diff --git a/crates/ec-h264/src/deblock.rs b/crates/ec-h264/src/deblock.rs index 85a9067d..283ecc05 100644 --- a/crates/ec-h264/src/deblock.rs +++ b/crates/ec-h264/src/deblock.rs @@ -2,6 +2,8 @@ //! macroblock is intra, so boundary strength is 4 on macroblock edges and 3 //! inside (8.7.2.1) — no motion-vector or reference comparisons yet. +use crate::dpb::{FRAME, PicPlane, Picture, SliceParams}; +use crate::entropy::{FLAG_DECODED, FLAG_INTER, FLAG_PCM, FLAG_TRANS8X8}; use crate::sample::Sample; use crate::tables::{ALPHA, BETA, CHROMA_QP, TC0}; @@ -356,3 +358,506 @@ mod tests { assert!(line[3] != 60 || line[4] != 74); } } + +/// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all +/// vertical edges then all horizontal edges per macroblock, then chroma. +// `e` and `j` are edge and segment positions inside the macroblock, used to +// index the plane as well as the strength arrays; iterating the arrays would +// hide which geometry each one names. +#[allow(clippy::needless_range_loop)] +pub(crate) fn deblock_picture(pic: &mut Picture) { + let mb_w = pic.mb_w; + let bd = pic.bd; + let max = (1i32 << bd) - 1; + let qp_bd = 6 * (bd as i32 - 8); + let cmb_h = pic.cmb_h; + let cat = pic.cat; + let lcomps = if cat == 3 { 3 } else { 1 }; + for mb_y in 0..pic.mb_h { + for mb_x in 0..mb_w { + let addr = mb_y * mb_w + mb_x; + if pic.mb_flags[addr] & FLAG_DECODED == 0 { + continue; + } + let sid = pic.mb_slice[addr]; + let sp = pic.slices[sid as usize]; + if sp.disable_deblock_idc == 1 { + continue; + } + let decoded = |a: usize| pic.mb_flags[a] & FLAG_DECODED != 0; + let cross_ok = |a: usize| sp.disable_deblock_idc != 2 || pic.mb_slice[a] == sid; + let filter_left = mb_x > 0 && decoded(addr - 1) && cross_ok(addr - 1); + let filter_top = mb_y > 0 && decoded(addr - mb_w) && cross_ok(addr - mb_w); + // Deblocking QP: 0 for I_PCM macroblocks (8.7.2). + let qp_of = |a: usize| -> i32 { + if pic.mb_flags[a] & FLAG_PCM != 0 { + 0 + } else { + i32::from(pic.mb_qp[a]) + } + }; + // 8.7: an 8x8-transform macroblock has no transform edge at luma + // 4 or 12, so those internal edges are not filtered. Chroma is + // unaffected for 4:2:0 (its internal edge sits on luma edge 8). + let internal = + |e: usize| e.is_multiple_of(2) || pic.mb_flags[addr] & FLAG_TRANS8X8 == 0; + + // Boundary strengths, per 4-sample segment of each edge (8.7.2.1). + // + // Both sides of an internal edge live in this macroblock, so the + // whole 8.7.2.1 ladder is decided once for all 24 of them: an intra + // macroblock gives 3 everywhere, and an inter macroblock with no + // luma coefficients and one motion vector over the whole 16x16 + // gives 0 everywhere. Only the two macroblock edges then need the + // per-segment derivation. + let mut bs_v = [[0u8; 4]; 4]; + let mut bs_h = [[0u8; 4]; 4]; + let cur_intra = pic.mb_flags[addr] & FLAG_INTER == 0; + let internal_uniform = if cur_intra { + Some(3) + } else if pic.mb_cbp[addr] == 0 && uniform_motion(pic, mb_x, mb_y) { + Some(0) + } else { + None + }; + for k in 0..4 { + if filter_left { + bs_v[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, true); + } + if filter_top { + bs_h[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, false); + } + } + for e in 1..4 { + match internal_uniform { + Some(bs) => { + bs_v[e] = [bs; 4]; + bs_h[e] = [bs; 4]; + } + None => { + for k in 0..4 { + bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true); + bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false); + } + } + } + } + + // ---- luma (and Cb/Cr, coded like luma, for ChromaArrayType 3) ---- + for comp in 0..lcomps { + let pl: &mut PicPlane = match comp { + 0 => &mut pic.y, + 1 => &mut pic.cb, + _ => &mut pic.cr, + }; + let stride = pl.stride; + let base = pl.at(mb_x * 16, mb_y * 16); + let qpf = |a: usize| -> i32 { + if comp == 0 { + qp_of(a) + } else { + let s = pic.slices[pic.mb_slice[a] as usize]; + let off = if comp == 1 { + s.cb_qp_offset + } else { + s.cr_qp_offset + }; + let q = if pic.mb_flags[a] & FLAG_PCM != 0 { + 0 + } else { + i32::from(pic.mb_qp[a]) + }; + chroma_qp(q, off, qp_bd) + } + }; + let qp_q = qpf(addr); + // Lossless macroblocks keep their samples (8.7.2.2). + let lossless = |a: usize| { + pic.bypass_enabled + && pic.mb_flags[a] & FLAG_PCM == 0 + && i32::from(pic.mb_qp[a]) + qp_bd == 0 + }; + let (p_ll_v, q_ll) = (filter_left && lossless(addr - 1), lossless(addr)); + let snap_v = (p_ll_v || (filter_left && q_ll)) + .then(|| snap_edge(&pl.data, base, stride, true)); + // Vertical edges (filter across columns), left to right. + for e in 0..4 { + if e == 0 && !filter_left { + continue; + } + if !internal(e) { + continue; + } + let qp_p = if e == 0 { qpf(addr - 1) } else { qp_q }; + let qp_avg = (qp_p + qp_q + 1) >> 1; + // Vertical edges stay scalar: a gather/scatter SIMD + // variant measured slower than this loop (strided + // per-lane loads dominate). + for j in 0..4 { + let bs = bs_v[e][j]; + if bs == 0 { + continue; + } + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd); + if params.alpha == 0 || params.beta == 0 { + continue; + } + for k in 0..4 { + let row = j * 4 + k; + filter_luma_line( + &mut pl.data, + max, + base + row * stride + e * 4, + 1, + ¶ms, + ); + } + } + } + if let Some(sv) = &snap_v { + restore_edge(&mut pl.data, sv, base, stride, true, p_ll_v, q_ll); + } + let p_ll_h = filter_top && lossless(addr - mb_w); + let snap_h = (p_ll_h || (filter_top && q_ll)) + .then(|| snap_edge(&pl.data, base, stride, false)); + // Horizontal edges, top to bottom. + for e in 0..4 { + if e == 0 && !filter_top { + continue; + } + if !internal(e) { + continue; + } + let qp_p = if e == 0 { qpf(addr - mb_w) } else { qp_q }; + let qp_avg = (qp_p + qp_q + 1) >> 1; + let bs = bs_h[e]; + let uniform = bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3]; + if uniform { + if bs[0] == 0 { + continue; + } + let params = + edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0], bd); + if params.alpha == 0 || params.beta == 0 { + continue; + } + // Eight rows around the edge are contiguous, so the + // whole 16-sample edge filters in one pass. + S::filter_luma_h_edge16( + &mut pl.data, + max, + base + e * 4 * stride, + stride, + ¶ms, + ); + continue; + } + for j in 0..4 { + if bs[j] == 0 { + continue; + } + let params = + edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[j], bd); + if params.alpha == 0 || params.beta == 0 { + continue; + } + for k in 0..4 { + filter_luma_line( + &mut pl.data, + max, + base + e * 4 * stride + j * 4 + k, + stride, + ¶ms, + ); + } + } + } + if let Some(sh) = &snap_h { + restore_edge(&mut pl.data, sh, base, stride, false, p_ll_h, q_ll); + } + } + + // ---- chroma (Cb, Cr) ---- + for comp in 0..if matches!(cat, 1 | 2) { 2 } else { 0 } { + let (plane, off_sel): (&mut PicPlane, fn(&SliceParams) -> i32) = if comp == 0 { + (&mut pic.cb, |s| s.cb_qp_offset) + } else { + (&mut pic.cr, |s| s.cr_qp_offset) + }; + let stride = plane.stride; + let c422 = cat == 2; + let base = plane.origin + (mb_y * cmb_h) * stride + mb_x * 8; + // Chroma QP per side: each macroblock's luma QP mapped with + // the offset of ITS OWN slice's PPS (8.7.2). + let cqp = |a: usize| -> i32 { + let s = pic.slices[pic.mb_slice[a] as usize]; + if pic.mb_flags[a] & FLAG_PCM != 0 { + chroma_qp(0, off_sel(&s), qp_bd) + } else { + chroma_qp(i32::from(pic.mb_qp[a]), off_sel(&s), qp_bd) + } + }; + let cq_q = cqp(addr); + // A chroma edge inherits the boundary strength of the luma edge + // it sits on: chroma sample k maps to luma sample 2k, so a + // chroma 4-sample run spans two luma 4x4 block rows. + for e in 0..2 { + if e == 0 && !filter_left { + continue; + } + let cq_p = if e == 0 { cqp(addr - 1) } else { cq_q }; + let qp_avg = (cq_p + cq_q + 1) >> 1; + for k in 0..cmb_h { + let bs = bs_v[e * 2][k >> if c422 { 2 } else { 1 }]; + if bs == 0 { + continue; + } + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd); + if params.alpha == 0 || params.beta == 0 { + continue; + } + filter_chroma_line( + &mut plane.data, + max, + base + k * stride + e * 4, + 1, + ¶ms, + ); + } + } + // 4:2:2 chroma is as tall as luma: its horizontal 4x4 transform + // edges sit at rows 0, 4, 8 and 12, each on the boundary + // strength of the luma edge on the same row. + for e in 0..if c422 { 4 } else { 2 } { + if e == 0 && !filter_top { + continue; + } + let cq_p = if e == 0 { cqp(addr - mb_w) } else { cq_q }; + let qp_avg = (cq_p + cq_q + 1) >> 1; + let bs = bs_h[if c422 { e } else { e * 2 }]; + if bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3] { + if bs[0] == 0 { + continue; + } + let params = + edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0], bd); + if params.alpha == 0 || params.beta == 0 { + continue; + } + // The four rows around the edge are contiguous, so the + // whole eight-sample edge filters in one pass. + S::filter_chroma_h_edge8( + &mut plane.data, + max, + base + e * 4 * stride, + stride, + ¶ms, + ); + continue; + } + for k in 0..8 { + let bs = bs[k / 2]; + if bs == 0 { + continue; + } + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd); + if params.alpha == 0 || params.beta == 0 { + continue; + } + filter_chroma_line( + &mut plane.data, + max, + base + e * 4 * stride + k, + stride, + ¶ms, + ); + } + } + } + } + } +} + +/// Copy the 8 samples across a macroblock edge (4 each side) along its 16 +/// samples, so a lossless side can be put back after the filter ran. +fn snap_edge(data: &[S], base: usize, stride: usize, vertical: bool) -> Vec { + let mut v = Vec::with_capacity(128); + for i in 0..16 { + for d in 0..8 { + v.push(if vertical { + data[base + i * stride + d - 4] + } else { + data[base + d * stride + i - 4 * stride] + }); + } + } + v +} + +fn restore_edge( + data: &mut [S], + snap: &[S], + base: usize, + stride: usize, + vertical: bool, + p: bool, + q: bool, +) { + for i in 0..16 { + for d in 0..8 { + if (d < 4 && !p) || (d >= 4 && !q) { + continue; + } + let idx = if vertical { + base + i * stride + d - 4 + } else { + base + d * stride + i - 4 * stride + }; + data[idx] = snap[i * 8 + d]; + } + } +} + +/// True when every 4x4 block of this macroblock predicts from the same +/// pictures with the same motion, so no internal edge can reach the motion +/// clauses of 8.7.2.1. +fn uniform_motion(pic: &Picture, mb_x: usize, mb_y: usize) -> bool { + let w4 = pic.mb_w * 4; + let first = mb_y * 4 * w4 + mb_x * 4; + let (mv, id) = (pic.mv[first], pic.ref_id[first]); + (0..4).all(|by| { + let row = first + by * w4; + (0..4).all(|bx| pic.mv[row + bx] == mv && pic.ref_id[row + bx] == id) + }) +} + +/// What clause 8.7.2.1 needs from the 4x4 block on one side of a luma edge. +#[derive(Clone, Copy)] +pub(crate) struct BsSide { + /// The containing macroblock is intra: strength 4 on macroblock edges and + /// 3 on internal ones, regardless of motion or levels. + pub(crate) intra: bool, + /// The transform block containing this sample has non-zero levels. + pub(crate) coded: bool, + /// MvLX of the block, `[list][component]`. + pub(crate) mv: [[i16; 2]; 2], + /// RefIdxLX of the block as list identities (`Picture::id`), -1 unused. + pub(crate) refs: [i32; 2], +} + +/// Boundary strength between the 4x4 blocks on the two sides of a luma edge +/// (clause 8.7.2.1). `mb_edge` selects the macroblock-edge strengths 4/3. +pub(crate) fn bs_between(p: &BsSide, q: &BsSide, mb_edge: bool, field: bool, vertical: bool) -> u8 { + if p.intra || q.intra { + // A horizontal edge of a field picture is never strength 4 (8.7.2.1). + return if mb_edge && (vertical || !field) { + 4 + } else { + 3 + }; + } + if p.coded || q.coded { + return 2; + } + let (pr, qr) = (p.refs, q.refs); + let pn = u8::from(pr[0] >= 0) + u8::from(pr[1] >= 0); + let qn = u8::from(qr[0] >= 0) + u8::from(qr[1] >= 0); + if pn != qn { + return 1; + } + let (pm, qm) = (p.mv, q.mv); + // The vertical limit is 4 quarter frame samples: 2 in field units. + let ylim = if field { 2 } else { 4 }; + let differs = |a: [i16; 2], b: [i16; 2]| { + (i32::from(a[0]) - i32::from(b[0])).abs() >= 4 + || (i32::from(a[1]) - i32::from(b[1])).abs() >= ylim + }; + if pn == 1 { + let pl = usize::from(pr[0] < 0); + let ql = usize::from(qr[0] < 0); + if pr[pl] != qr[ql] { + return 1; + } + return u8::from(differs(pm[pl], qm[ql])); + } + if pn == 0 { + return 0; + } + // Two motion vectors each: compare the two partitions by which pictures + // they reference, not by list position (NOTE 1 of 8.7.2.1). + let same_set = (pr[0] == qr[0] && pr[1] == qr[1]) || (pr[0] == qr[1] && pr[1] == qr[0]); + if !same_set { + return 1; + } + if pr[0] != pr[1] { + return if pr[0] == qr[0] { + u8::from(differs(pm[0], qm[0]) || differs(pm[1], qm[1])) + } else { + u8::from(differs(pm[0], qm[1]) || differs(pm[1], qm[0])) + }; + } + // Both lists name the same picture: either pairing agreeing is enough. + let straight = !differs(pm[0], qm[0]) && !differs(pm[1], qm[1]); + let crossed = !differs(pm[0], qm[1]) && !differs(pm[1], qm[0]); + u8::from(!(straight || crossed)) +} + +/// One side of a luma edge from picture state: the decoder path, both sides +/// final macroblocks. The encoder's inter trial uses this for the +/// already-coded neighbour and builds its candidate side itself. +pub(crate) fn bs_side(pic: &Picture, bx: usize, by: usize) -> BsSide { + let w4 = pic.mb_w * 4; + let mb = (by / 4) * pic.mb_w + bx / 4; + BsSide { + intra: pic.mb_flags[mb] & FLAG_INTER == 0, + coded: bs_coded(pic, mb, bx, by), + mv: pic.mv[by * w4 + bx], + refs: pic.ref_id[by * w4 + bx], + } +} + +/// "The transform block containing the sample has non-zero levels": for an +/// 8x8-transform macroblock that is the whole 8x8, whose four 4x4 slots +/// carry per-slot counts under CAVLC (7.3.5.3.1 splits it into four blocks). +fn bs_coded(pic: &Picture, mb: usize, bx: usize, by: usize) -> bool { + let w4 = pic.mb_w * 4; + if pic.mb_flags[mb] & FLAG_TRANS8X8 == 0 { + return pic.nz_y[by * w4 + bx] != 0; + } + let (ox, oy) = (bx & !1, by & !1); + pic.nz_y[oy * w4 + ox] != 0 + || pic.nz_y[oy * w4 + ox + 1] != 0 + || pic.nz_y[(oy + 1) * w4 + ox] != 0 + || pic.nz_y[(oy + 1) * w4 + ox + 1] != 0 +} + +/// Boundary strength of one 4-sample luma edge segment (clause 8.7.2.1). +/// +/// `edge` 0..4 selects the vertical (`vertical`) or horizontal edge inside the +/// macroblock, `seg` the 4-sample run along it. Edge 0 is the macroblock edge. +fn boundary_strength( + pic: &Picture, + mb_x: usize, + mb_y: usize, + edge: usize, + seg: usize, + vertical: bool, +) -> u8 { + let (qbx, qby) = if vertical { + (mb_x * 4 + edge, mb_y * 4 + seg) + } else { + (mb_x * 4 + seg, mb_y * 4 + edge) + }; + let (pbx, pby) = if vertical { + (qbx - 1, qby) + } else { + (qbx, qby - 1) + }; + bs_between( + &bs_side(pic, pbx, pby), + &bs_side(pic, qbx, qby), + edge == 0, + pic.structure != FRAME, + vertical, + ) +} diff --git a/crates/ec-h264/src/deblock_mbaff.rs b/crates/ec-h264/src/deblock_mbaff.rs index b820780b..fef065c3 100644 --- a/crates/ec-h264/src/deblock_mbaff.rs +++ b/crates/ec-h264/src/deblock_mbaff.rs @@ -19,7 +19,7 @@ //! progressive filter stays the one the speed budget is spent on. use crate::deblock::{chroma_qp, edge_params, filter_chroma_line, filter_luma_line}; -use crate::decoder::{BsSide, bs_between, bs_side}; +use crate::deblock::{BsSide, bs_between, bs_side}; use crate::dpb::{PicPlane, Picture, SliceParams}; use crate::entropy::{FLAG_DECODED, FLAG_PCM, FLAG_TRANS8X8}; use crate::sample::Sample; diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index be578999..05163272 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -19,6 +19,7 @@ //! caller that wants pictures as they are decoded. use std::collections::VecDeque; +use std::sync::Arc; use ec_core::BitReader; use ec_core::error::{Error, Result}; @@ -29,32 +30,32 @@ use ec_h264_syntax::{ SliceType, Sps, WeightEntry, unescape_rbsp, }; -use crate::deblock::{chroma_qp, edge_params, filter_chroma_line, filter_luma_line}; +use crate::deblock::{chroma_qp, deblock_picture}; use crate::dpb::{ - BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, Dpb, FRAME, Mark, NO_SLICE, + BLK_DIRECT, BLK_SKIP, BOTTOM, CODED_AFRM, Dpb, FRAME, Mark, NO_SLICE, PicInfo, PicPlane, Picture, RefList, SliceParams, TOP, }; use crate::entropy::{ BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, FLAG_SKIP, FLAG_TRANS8X8, MbCtx, MbInfo, MbaffA, }; -use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma}; +use crate::direct::{predict_direct, predict_direct_8x8}; +use crate::inter::Weights; use crate::mbaff::{self, MbPos}; use crate::mv::{ - B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, neighbour_mvd, + B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, neighbour_mvd, predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd, }; use crate::pred::{ - Nbr4, Nbr8, PlaneWindow, add_residual_4x4, add_residual_8x8, add_residual_dpcm, filter_nbr8, - pred_4x4, pred_8x8, pred_16x16, pred_chroma_8x8_halves, pred_chroma_8x16, + Nbr4, Nbr8, PlaneWindow, add_residual_4x4, add_residual_dpcm, pred_chroma_8x8_halves, + pred_chroma_8x16, }; +use crate::residual::residual_luma_style; use crate::sample::Sample; use crate::tables::BLK4_POS; use crate::transform::{ CHROMA_DC_422_RASTER, LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, - chroma_dc_transform_422, dequant_4x4, dequant_8x8, inverse_transform_4x4, - inverse_transform_8x8, luma_dc_transform, unfield, unfield_8x8, unfield_ac15, unzigzag, - unzigzag_8x8, unzigzag_ac15, + chroma_dc_transform_422, dequant_4x4, inverse_transform_4x4, unfield_ac15, unzigzag_ac15, }; /// Where a 4x4 block's top-right neighbour samples come from, per @@ -105,8 +106,8 @@ pub enum OutputOrder { /// The decode core, generic over the sample type of the pictures it holds. pub(crate) struct Core { - sps_map: Vec>, - pps_map: Vec>, + sps_map: Vec>>, + pps_map: Vec>>, rbsp: Vec, /// The picture being decoded, held out of the buffer pool. cur: Picture, @@ -635,7 +636,7 @@ impl Core { let sps = sps?; let id = sps.id; self.dpb.configure(&sps); - self.sps_map[id as usize] = Some(sps); + self.sps_map[id as usize] = Some(Arc::new(sps)); self.active_pps = None; self.last_sps = Some(id); Ok(NalOutcome::ParameterSet) @@ -643,11 +644,11 @@ impl Core { NalUnitType::Pps => { let mut rbsp = core::mem::take(&mut self.rbsp); unescape_rbsp(payload, &mut rbsp); - let pps = Pps::parse(&rbsp, |id| self.sps_map[id as usize].as_ref()); + let pps = Pps::parse(&rbsp, |id| self.sps_map[id as usize].as_deref()); self.rbsp = rbsp; let pps = pps?; let id = pps.id as usize; - self.pps_map[id] = Some(pps); + self.pps_map[id] = Some(Arc::new(pps)); // A re-sent PPS may carry other scaling lists: rebuild the level scales. self.active_pps = None; Ok(NalOutcome::ParameterSet) @@ -691,7 +692,7 @@ impl Core { let output_ok = !(self.cur_ref_padded && self.cur.poc < recovery_poc); let sps_id = self.cur.sps_id as usize; let sps = self.sps_map[sps_id] - .take() + .clone() .ok_or_else(|| Error::corrupt("active SPS vanished"))?; let pic = core::mem::take(&mut self.cur); let marking = self.has_marking.then_some(&self.cur_marking); @@ -702,7 +703,6 @@ impl Core { self.dpb .store(pic, &sps, &self.cur_info, marking, output_ok) }; - self.sps_map[sps_id] = Some(sps); stored?; if self.dpb.interlaced { // The picture a caller asks for is the frame store, which a field @@ -826,14 +826,11 @@ impl Core { copy(&pic.cr, cx_c, cy_c, cw_c, ch_c), ]; let mut frame = VideoFrame::try_new( - match (pic.cat, S::IS_8) { - (3, true) => PixelFormat::I444, - (3, false) => PixelFormat::I410, - (2, true) => PixelFormat::I422, - (2, false) => PixelFormat::I210, - (_, true) => PixelFormat::I420, - (_, false) => PixelFormat::I010, - }, + S::FORMATS[match pic.cat { + 3 => 0, + 2 => 1, + _ => 2, + }], w as u32, h as u32, planes, @@ -869,14 +866,13 @@ impl Core { return Err(Error::corrupt("pic_parameter_set_id > 255")); } let pps = self.pps_map[pps_id as usize] - .as_ref() + .clone() .ok_or_else(|| Error::corrupt("slice refers to an unknown PPS"))?; let sps = self.sps_map[pps.sps_id as usize] - .as_ref() + .clone() .ok_or_else(|| Error::corrupt("PPS refers to an unknown SPS"))?; - - check_supported::(sps, pps, slice_type_code, self.wide)?; - let sh = SliceHeader::parse(rbsp, header, sps, pps)?; + let sh = SliceHeader::parse(rbsp, header, &sps, &pps)?; + check_supported::(&sps, &pps, slice_type_code, self.wide)?; if self.has_picture && !self.cur.complete { let same_picture = self.cur_key == Some(PicKey::of(&sh, header)); // A picture starts again at macroblock 0 once macroblock 0 is @@ -892,16 +888,7 @@ impl Core { // Redundant coded slices (7.4.3) repeat primary data: ignored. return Ok(NalOutcome::Skipped); } - // Borrow the parameter sets out of their slots for the duration of the - // slice: cloning them per slice would allocate, and a decode loop that - // allocates per slice is the thing the whole layout is built to avoid. - let sps_slot = pps.sps_id as usize; - let sps = self.sps_map[sps_slot].take().expect("checked above"); - let pps = self.pps_map[pps_id as usize].take().expect("checked above"); - let outcome = self.decode_slice_data(&sps, &pps, &sh, header, rbsp, first_mb); - self.sps_map[sps_slot] = Some(sps); - self.pps_map[pps_id as usize] = Some(pps); - outcome + self.decode_slice_data(&sps, &pps, &sh, header, rbsp, first_mb) } #[allow(clippy::too_many_arguments)] @@ -1560,71 +1547,71 @@ fn check_supported( /// See [`SliceCtx::geo`]. Chroma rows are half of each luma row value. #[derive(Clone, Copy)] -struct Geo { - src_y: usize, - dst_y: usize, - dst_cy: usize, - mul: usize, +pub(crate) struct Geo { + pub(crate) src_y: usize, + pub(crate) dst_y: usize, + pub(crate) dst_cy: usize, + pub(crate) mul: usize, } impl Geo { /// Picture row of luma row `r` of the macroblock. #[inline] - fn y(&self, r: usize) -> usize { + pub(crate) fn y(&self, r: usize) -> usize { self.dst_y + r * self.mul } /// Picture row of chroma row `r` of the macroblock. #[inline] - fn cy(&self, r: usize) -> usize { + pub(crate) fn cy(&self, r: usize) -> usize { self.dst_cy + r * self.mul } } /// Mutable per-slice decode state. pub(crate) struct SliceCtx { - slice_id: u16, - slice_type: SliceType, - qp: i32, - cb_qp_offset: i32, - cr_qp_offset: i32, + pub(crate) slice_id: u16, + pub(crate) slice_type: SliceType, + pub(crate) qp: i32, + pub(crate) cb_qp_offset: i32, + pub(crate) cr_qp_offset: i32, /// Chroma rows per macroblock: 8 (4:2:0) or 16 (4:2:2). - cmb_h: usize, + pub(crate) cmb_h: usize, /// ChromaArrayType of the picture being decoded. - cat: u8, - transform_8x8_mode: bool, - constrained_intra_pred: bool, + pub(crate) cat: u8, + pub(crate) transform_8x8_mode: bool, + pub(crate) constrained_intra_pred: bool, /// ctxIdxInc for the next macroblock's first mb_qp_delta bin: set when the /// macroblock just decoded coded a non-zero mb_qp_delta (9.3.3.1.1.5). - qp_delta_inc: u8, + pub(crate) qp_delta_inc: u8, /// `RefPicList0` and `RefPicList1` as decoded picture buffer indices. - lists: [RefList; 2], - num_ref_idx: [usize; 2], - direct_spatial: bool, - direct_8x8_inference: bool, - weighted_pred: bool, - weighted_bipred_idc: u8, - weights: Option, + pub(crate) lists: [RefList; 2], + pub(crate) num_ref_idx: [usize; 2], + pub(crate) direct_spatial: bool, + pub(crate) direct_8x8_inference: bool, + pub(crate) weighted_pred: bool, + pub(crate) weighted_bipred_idc: u8, + pub(crate) weights: Option, /// `PicOrderCnt( CurrPic )`. - poc: i32, + pub(crate) poc: i32, /// `TopFieldOrderCnt` and `BottomFieldOrderCnt` of the current picture. - fpoc: [i32; 2], + pub(crate) fpoc: [i32; 2], /// Structure of the picture being decoded: [`FRAME`], [`TOP`] or [`BOTTOM`]. - structure: u8, + pub(crate) structure: u8, /// Parity of the macroblock being decoded when it is a field macroblock /// ([`TOP`] or [`BOTTOM`]), [`FRAME`] for a frame macroblock. In a field /// picture this is the picture's own parity. - mb_parity: u8, + pub(crate) mb_parity: u8, /// Where the macroblock being decoded sits when the picture is an MBAFF /// frame (`pos.active`); inert otherwise. - pos: MbPos, + pub(crate) pos: MbPos, } impl SliceCtx { /// `PicOrderCnt` of the current picture, or of the field of the current /// macroblock's parity for a field macroblock of an MBAFF frame (8.4.1.2.3, 8.4.2.3.1). #[inline] - fn cur_poc(&self) -> i32 { + pub(crate) fn cur_poc(&self) -> i32 { if self.pos.active && self.pos.field { self.fpoc[usize::from(self.mb_parity == BOTTOM)] } else { @@ -1632,14 +1619,14 @@ impl SliceCtx { } } - fn is_b(&self) -> bool { + pub(crate) fn is_b(&self) -> bool { self.slice_type == SliceType::B } /// The reference picture `RefPicListX[idx]` points at: a frame, or one /// field of a stored frame. #[inline(always)] - fn reference<'a, S: Sample>( + pub(crate) fn reference<'a, S: Sample>( &self, refs: &'a [Picture], list: usize, @@ -1664,7 +1651,7 @@ impl SliceCtx { /// [`SliceCtx::reference`] for a field macroblock of an MBAFF frame. #[inline(never)] - fn field_mb_reference<'a, S: Sample>( + pub(crate) fn field_mb_reference<'a, S: Sample>( &self, refs: &'a [Picture], list: usize, @@ -1683,7 +1670,7 @@ impl SliceCtx { /// True while decoding a field picture or a field macroblock. #[inline] - fn is_field(&self) -> bool { + pub(crate) fn is_field(&self) -> bool { self.mb_parity != FRAME } @@ -1691,7 +1678,7 @@ impl SliceCtx { /// row of its first luma row (motion compensation reads fields at field /// row positions), the picture row it is written at, and the row step. #[inline] - fn geo(&self, mb_y: usize) -> Geo { + pub(crate) fn geo(&self, mb_y: usize) -> Geo { if self.pos.active && self.pos.field { Geo { src_y: (mb_y / 2) * 16, @@ -1713,7 +1700,7 @@ impl SliceCtx { /// a prediction from `rp`: fields of opposite parity sit half a field line /// apart, which is a quarter of a chroma sample. #[inline] - fn chroma_dy(&self, rp: &Picture) -> i16 { + pub(crate) fn chroma_dy(&self, rp: &Picture) -> i16 { if self.cat != 1 { // Tables 8-9 and 8-10 apply to ChromaArrayType 1 only. return 0; @@ -1729,12 +1716,12 @@ impl SliceCtx { /// component of every partition resolves to [`Weights::DEFAULT`] without /// the per-component lookup: neither weighted prediction (P) nor /// weighted/bi-prediction (B) is signalled. - fn no_weights(&self) -> bool { + pub(crate) fn no_weights(&self) -> bool { self.weighted_bipred_idc == 0 && !self.weighted_pred } /// Prediction weights of one component (clause 8.4.3). - fn weights_for( + pub(crate) fn weights_for( &self, refs: &[Picture], comp: usize, @@ -1931,7 +1918,7 @@ pub(crate) fn luma_nz_pair( /// The count grid of colour component `comp` laid out like the luma one: `nz_y`, /// or for 4:4:4 the Cb / Cr grids, which are coded like luma. #[inline] -fn nz_grid(pic: &Picture, comp: usize) -> &[u8] { +pub(crate) fn nz_grid(pic: &Picture, comp: usize) -> &[u8] { if comp == 0 { &pic.nz_y } else { @@ -1940,7 +1927,7 @@ fn nz_grid(pic: &Picture, comp: usize) -> &[u8] { } #[inline] -fn nz_grid_mut(pic: &mut Picture, comp: usize) -> &mut [u8] { +pub(crate) fn nz_grid_mut(pic: &mut Picture, comp: usize) -> &mut [u8] { if comp == 0 { &mut pic.nz_y } else { @@ -1950,7 +1937,7 @@ fn nz_grid_mut(pic: &mut Picture, comp: usize) -> &mut [u8] { /// [`luma_nz_pair`] over an explicit count grid (`mb_w * 4` wide). #[inline] -fn nz_pair_in( +pub(crate) fn nz_pair_in( pic: &Picture, grid: &[u8], n: &MbNeighbors, @@ -1975,7 +1962,7 @@ fn nz_pair_in( /// (9.3.3.1.1.9, ctxBlockCat 5, 9, 13): a neighbouring macroblock that did not /// use the 8x8 transform has no 8x8 block there, which counts as "not coded" /// (I_PCM counts as coded). -fn nz_pair_8x8( +pub(crate) fn nz_pair_8x8( pic: &Picture, comp: usize, n: &MbNeighbors, @@ -2095,13 +2082,13 @@ fn build_mb_ctx( /// Motion data parsed for one macroblock, before prediction derivation. #[derive(Clone, Copy)] -struct MbMotion { +pub(crate) struct MbMotion { /// Sub-macroblock types of a P_8x8 / B_8x8 macroblock. - sub: [SubShape; 4], + pub(crate) sub: [SubShape; 4], /// `ref_idx_lX[ mbPartIdx ]`, -1 when the partition does not use the list. - ref_idx: [[i8; 4]; 2], + pub(crate) ref_idx: [[i8; 4]; 2], /// `mvd_lX[ mbPartIdx ][ subMbPartIdx ]`, indexed by 4x4 raster position. - mvd: [[[i16; 2]; 16]; 2], + pub(crate) mvd: [[[i16; 2]; 16]; 2], } /// Decode one macroblock (spec 7.3.5, 7.4.5) and reconstruct it. `ctx.qp` @@ -2408,30 +2395,30 @@ fn fill_chroma_nz(pic: &mut Picture, mb_x: usize, mb_y: usize, val } /// Everything the shared residual path needs after prediction is decided. -struct MbFinish { +pub(crate) struct MbFinish { /// Neighbour availability for *prediction*, which honours /// constrained_intra_pred_flag. The residual contexts use the plain /// availability instead — clause 9.2.1 and 9.3.3.1.1.9 only exclude an /// inter neighbour there when slice data partitioning is in use, and this /// decoder refuses partitioned slices outright. - pred_nbr: MbNeighbors, - is_i16: bool, - i16_mode: u8, - cbp_luma: u8, - cbp_chroma: u8, - modes: [u8; 16], + pub(crate) pred_nbr: MbNeighbors, + pub(crate) is_i16: bool, + pub(crate) i16_mode: u8, + pub(crate) cbp_luma: u8, + pub(crate) cbp_chroma: u8, + pub(crate) modes: [u8; 16], /// Intra8x8PredMode per 8x8 block, when `trans8x8` and `intra`. - modes8: [u8; 4], + pub(crate) modes8: [u8; 4], /// transform_size_8x8_flag: the luma residual is four 8x8 transform blocks. - trans8x8: bool, - chroma_mode: u8, - intra: bool, - flags: u8, + pub(crate) trans8x8: bool, + pub(crate) chroma_mode: u8, + pub(crate) intra: bool, + pub(crate) flags: u8, } /// The plane of colour component `comp` (0 Y, 1 Cb, 2 Cr). #[inline] -fn plane_mut(pic: &mut Picture, comp: usize) -> &mut PicPlane { +pub(crate) fn plane_mut(pic: &mut Picture, comp: usize) -> &mut PicPlane { match comp { 0 => &mut pic.y, 1 => &mut pic.cb, @@ -2440,7 +2427,7 @@ fn plane_mut(pic: &mut Picture, comp: usize) -> &mut PicPlane { } #[inline] -fn plane_ref(pic: &Picture, comp: usize) -> &PicPlane { +pub(crate) fn plane_ref(pic: &Picture, comp: usize) -> &PicPlane { match comp { 0 => &pic.y, 1 => &pic.cb, @@ -2448,305 +2435,6 @@ fn plane_ref(pic: &Picture, comp: usize) -> &PicPlane { } } -/// `residual_luma( )` (7.3.5.3.1) of one colour component plus its -/// reconstruction (8.5): the luma residual, and for ChromaArrayType 3 the Cb -/// and Cr residual too, which is coded and reconstructed exactly like luma -/// (against the plane of `comp`, with `qp` its QP', and `ls` / `ls8` its -/// scaling lists). -/// -/// Bitstream order equals reconstruction dependency order, so each block -/// reconstructs the moment its levels are parsed. `bypass` is -/// TransformBypassModeFlag: the levels are the residual (8.5.15). -#[allow(clippy::needless_range_loop, clippy::too_many_arguments)] -fn residual_luma_style( - pic: &mut Picture, - r: &mut Entropy<'_>, - nbr: &MbNeighbors, - m: &MbFinish, - mb_x: usize, - mb_y: usize, - comp: usize, - ls: &LevelScale4x4, - ls8: &LevelScale8x8, - qp: i32, - bypass: bool, - fld: bool, - geo: Geo, - dc_cbf: &mut u8, -) -> Result<()> { - let bd = pic.bd; - let max = (1i32 << bd) - 1; - let w4 = pic.mb_w * 4; - let (bx0, by0) = (mb_x * 4, mb_y * 4); - let mul = geo.mul; - let cbp_luma = m.cbp_luma; - let c = comp as u8; - let cat3 = pic.cat == 3; - let mut scan = [0i32; 16]; - let mut raster = [0i32; 16]; - let mut resid = [0i32; 16]; - if m.is_i16 { - { - let pl = plane_mut(pic, comp); - let mut w = PlaneWindow { - origin: pl.at(mb_x * 16, geo.y(0)), - stride: pl.stride * mul, - data: &mut pl.data, - }; - pred_16x16(m.i16_mode, bd, &mut w, m.pred_nbr.b, m.pred_nbr.a); - } - // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale. - let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx0, by0); - let dc_tc = r.residual_block_c(&mut scan, BlockCat::LumaDc, c, na, nb)?; - *dc_cbf |= u8::from(dc_tc != 0) << comp; - if fld { - unfield(&scan, &mut raster); - } else { - unzigzag(&scan, &mut raster); - } - if !bypass { - luma_dc_transform(&mut raster, ls, qp); - } - let dc = raster; - // Lossless horizontal / vertical prediction accumulates the residual - // over the whole macroblock, so every block takes part. - let dpcm = bypass && m.i16_mode < 2; - let horizontal = m.i16_mode == 1; - for blk in 0..16 { - let (dx, dy) = BLK4_POS[blk]; - let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); - let tc = if cbp_luma != 0 { - let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx, by); - r.residual_block_c(&mut scan, BlockCat::LumaAc, c, na, nb)? - } else { - 0 - }; - nz_grid_mut(pic, comp)[by * w4 + bx] = tc; - let dc_blk = dc[dy as usize * 4 + dx as usize]; - if tc == 0 && dc_blk == 0 && !dpcm { - continue; // prediction already in place - } - if tc > 0 { - if fld { - unfield_ac15(&scan, &mut raster); - } else { - unzigzag_ac15(&scan, &mut raster); - } - if !bypass { - dequant_4x4(&mut raster, ls, qp, true); - } - } else { - raster = [0; 16]; // DC-only block - } - raster[0] = dc_blk; - let pl = plane_mut(pic, comp); - let origin = pl.at(mb_x * 16 + dx as usize * 4, geo.y(dy as usize * 4)); - let stride = pl.stride * mul; - if bypass { - if dpcm { - let first = if horizontal { dx == 0 } else { dy == 0 }; - add_residual_dpcm( - &mut pl.data, - bd, - stride, - origin, - 4, - 4, - &raster, - horizontal, - first, - ); - } else { - add_residual_4x4(&mut pl.data, bd, stride, origin, &raster); - } - } else { - inverse_transform_4x4(&raster, &mut resid); - add_residual_4x4(&mut pl.data, bd, stride, origin, &resid); - } - } - } else if m.trans8x8 { - // 8x8 transform (8.5.13): predict, parse and reconstruct one 8x8 block - // at a time, because an Intra_8x8 block predicts from the reconstructed - // samples of the blocks before it. - let mut scan8 = [0i32; 64]; - let mut raster8 = [0i32; 64]; - let mut resid8 = [0i32; 64]; - for blk8 in 0..4 { - let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, geo.y((blk8 / 2) * 8)); - let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); - let origin = plane_ref(pic, comp).at(x, y); - let stride = plane_ref(pic, comp).stride * mul; - if m.intra { - let n = filter_nbr8(&gather_nbr8_in( - &plane_ref(pic, comp).data, - &m.pred_nbr, - blk8, - origin, - stride, - )); - let mut p = [S::default(); 64]; - pred_8x8(m.modes8[blk8], bd, &n, &mut p); - let pl = plane_mut(pic, comp); - for ry in 0..8 { - let row = origin + ry * stride; - pl.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]); - } - } - if cbp_luma & (1 << blk8) == 0 { - let grid = nz_grid_mut(pic, comp); - for dy in 0..2 { - let base = (by + dy) * w4 + bx; - grid[base..base + 2].fill(0); - } - continue; - } - let tc = if r.is_cabac() { - // ctxBlockCat 5: one 64-coefficient block, and every 4x4 slot - // of it reports the block's own count to the neighbours - // (9.3.3.1.1.9 resolves them to the 8x8 transform block). Only - // ChromaArrayType 3 sends a coded_block_flag for it. - let cbf = cat3.then(|| nz_pair_8x8(pic, comp, nbr, bx, by)); - let tc = r.residual_block_8x8(&mut scan8, c, cbf)?; - let grid = nz_grid_mut(pic, comp); - for dy in 0..2 { - let base = (by + dy) * w4 + bx; - grid[base..base + 2].fill(tc.min(16)); - } - tc - } else { - // CAVLC codes the same 64 coefficients as four interleaved 4x4 - // blocks (7.3.5.3.1), each with its own nC neighbourhood. - let mut tc = 0u8; - for i4 in 0..4 { - let (dx, dy) = BLK4_POS[blk8 * 4 + i4]; - let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize); - let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, sx, sy); - let n = r.residual_block_c(&mut scan, BlockCat::Luma4x4, c, na, nb)?; - nz_grid_mut(pic, comp)[sy * w4 + sx] = n; - tc += n; - for i in 0..16 { - scan8[4 * i + i4] = scan[i]; - } - } - tc - }; - if tc == 0 { - continue; - } - if fld { - unfield_8x8(&scan8, &mut raster8); - } else { - unzigzag_8x8(&scan8, &mut raster8); - } - let pl = plane_mut(pic, comp); - if bypass { - if m.intra && m.modes8[blk8] < 2 { - add_residual_dpcm( - &mut pl.data, - bd, - stride, - origin, - 8, - 8, - &raster8, - m.modes8[blk8] == 1, - true, - ); - } else { - add_residual_8x8(&mut pl.data, bd, stride, origin, &raster8); - } - } else { - dequant_8x8(&mut raster8, ls8, qp); - inverse_transform_8x8(&raster8, &mut resid8); - add_residual_8x8(&mut pl.data, bd, stride, origin, &resid8); - } - } - } else { - for blk in 0..16 { - let (dx, dy) = BLK4_POS[blk]; - let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); - let tc = if cbp_luma & (1 << (blk >> 2)) != 0 { - let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx, by); - r.residual_block_c(&mut scan, BlockCat::Luma4x4, c, na, nb)? - } else { - 0 - }; - nz_grid_mut(pic, comp)[by * w4 + bx] = tc; - let (x, y) = (mb_x * 16 + dx as usize * 4, geo.y(dy as usize * 4)); - let origin = plane_ref(pic, comp).at(x, y); - let stride = plane_ref(pic, comp).stride * mul; - if m.intra { - let n = - gather_nbr4_in(&plane_ref(pic, comp).data, &m.pred_nbr, blk, origin, stride); - let mut p = [S::default(); 16]; - pred_4x4(m.modes[blk], bd, &n, &mut p); - let pl = plane_mut(pic, comp); - if tc == 0 { - // Pure prediction: copy the 16 samples in. - for ry in 0..4 { - let row = origin + ry * stride; - pl.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); - } - continue; - } - if fld { - unfield(&scan, &mut raster); - } else { - unzigzag(&scan, &mut raster); - } - if bypass { - for ry in 0..4 { - let row = origin + ry * stride; - pl.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); - } - if m.modes[blk] < 2 { - add_residual_dpcm( - &mut pl.data, - bd, - stride, - origin, - 4, - 4, - &raster, - m.modes[blk] == 1, - true, - ); - } else { - add_residual_4x4(&mut pl.data, bd, stride, origin, &raster); - } - continue; - } - dequant_4x4(&mut raster, ls, qp, false); - inverse_transform_4x4(&raster, &mut resid); - for ry in 0..4 { - let row = origin + ry * stride; - for rx in 0..4 { - let v = p[ry * 4 + rx].to_i32() + resid[ry * 4 + rx]; - pl.data[row + rx] = S::clip(v, max); - } - } - } else { - if tc == 0 { - continue; // motion-compensated prediction already in place - } - if fld { - unfield(&scan, &mut raster); - } else { - unzigzag(&scan, &mut raster); - } - let pl = plane_mut(pic, comp); - if bypass { - add_residual_4x4(&mut pl.data, bd, stride, origin, &raster); - } else { - dequant_4x4(&mut raster, ls, qp, false); - inverse_transform_4x4(&raster, &mut resid); - add_residual_4x4(&mut pl.data, bd, stride, origin, &resid); - } - } - } - } - Ok(()) -} /// The residual half of a macroblock (7.3.5.3 + 8.5), shared by the intra and /// inter paths. @@ -3347,831 +3035,6 @@ fn predict_p_skip( ) } -/// B_Skip / B_Direct_16x16 (clause 8.4.1.2) over the whole macroblock. -fn predict_direct( - pic: &mut Picture, - refs: &[Picture], - ctx: &SliceCtx, - mvc: &mut MvCtx, - skip: bool, -) -> Result<()> { - for quad in 0..4 { - direct_quadrant(pic, refs, ctx, mvc, quad, skip)?; - } - Ok(()) -} - -/// B_Direct_8x8 for one 8x8 sub-macroblock. -fn predict_direct_8x8( - pic: &mut Picture, - refs: &[Picture], - ctx: &SliceCtx, - mvc: &mut MvCtx, - part: usize, -) -> Result<()> { - direct_quadrant(pic, refs, ctx, mvc, part, false) -} - -/// One 8x8 quadrant of a direct-mode macroblock. With -/// `direct_8x8_inference_flag` the whole quadrant shares the motion of its -/// outer corner 4x4 block; without it each 4x4 block is derived on its own. -fn direct_quadrant( - pic: &mut Picture, - refs: &[Picture], - ctx: &SliceCtx, - mvc: &mut MvCtx, - quad: usize, - skip: bool, -) -> Result<()> { - let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); - let (qx, qy) = (quad % 2 * 2, quad / 2 * 2); - let flags = BLK_DIRECT | if skip { BLK_SKIP } else { 0 }; - if ctx.direct_8x8_inference { - // 8.4.1.2.1: luma4x4BlkIdx = 5 * mbPartIdx, i.e. the quadrant's own - // outer corner of the macroblock. - let corner = (quad % 2 * 3, quad / 2 * 3); - let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, corner)?; - for dy in 0..2 { - for dx in 0..2 { - write_block(pic, mvc, qx + dx, qy + dy, mv, ref_idx, ref_id, flags); - } - } - S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx) - } else { - // Each 4x4 block derives its own motion, but they usually come out - // equal: interpolation is position-invariant, so one 8x8 compensation - // of the shared vector produces the same samples as four 4x4 ones and - // pays the per-partition setup once instead of four times. - let mut motion = [([[0i16; 2]; 2], [0i8; 2]); 4]; - for dy in 0..2 { - for dx in 0..2 { - let (px, py) = (qx + dx, qy + dy); - let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, (px, py))?; - write_block(pic, mvc, px, py, mv, ref_idx, ref_id, flags); - motion[dy * 2 + dx] = (mv, ref_idx); - } - } - if motion.iter().all(|m| *m == motion[0]) { - let (mv, ref_idx) = motion[0]; - return S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx); - } - for dy in 0..2 { - for dx in 0..2 { - let (mv, ref_idx) = motion[dy * 2 + dx]; - S::compensate( - pic, - refs, - ctx, - mb_x, - mb_y, - qx + dx, - qy + dy, - 1, - 1, - mv, - ref_idx, - )?; - } - } - Ok(()) - } -} - -/// Motion of one direct-mode 4x4 block: `(mvLX, refIdxLX, reference picture -/// identity)`, spatial (8.4.1.2.2) or temporal (8.4.1.2.3). -#[allow(clippy::type_complexity)] -fn direct_block( - pic: &Picture, - refs: &[Picture], - ctx: &SliceCtx, - mvc: &MvCtx, - at: (usize, usize), -) -> Result<([[i16; 2]; 2], [i8; 2], [i32; 2])> { - // The co-located block, in both modes (8.4.1.2.1): its list 0 motion, or - // its list 1 motion when list 0 is unused. `col_ref_idx` is refIdxCol — - // an index into the co-located picture's own reference list, not ours. - let (col_ref_id, col_mv, col_ref_idx, vscale) = colocated(ctx, refs, mvc, at); - let col = ctx.reference(refs, 1, 0); - - if ctx.direct_spatial { - // Reference indices from the macroblock's own neighbours, once. - let mut ref_idx = [-1i8; 2]; - let mut mvp = [[0i16; 2]; 2]; - for list in 0..2 { - let n = mvc.neighbours(pic, 0, 0, 4, list); - ref_idx[list] = min_positive(n[0].ref_idx, min_positive(n[1].ref_idx, n[2].ref_idx)); - mvp[list] = predict_mv(&n, ref_idx[list], 4, 4, 0); - } - let zero_prediction = ref_idx[0] < 0 && ref_idx[1] < 0; - if zero_prediction { - ref_idx = [0, 0]; - } - // colZeroFlag (8.4.1.2.2): the co-located block sits still on a - // short-term picture, referencing that picture's own list entry 0. The - // index is the one belonging to the list 8.4.1.2.1 picked — reading - // "either list is 0" instead lets a bi-predicted co-located block whose - // list 1 index happens to be 0 zero a motion vector it must not, which - // only shows on a B picture used as the co-located one. - let col_short = col.is_some_and(|c| c.mark == Mark::Short); - let col_zero = col_short - && col_ref_id >= 0 - && col_ref_idx == 0 - && (-1..=1).contains(&col_mv[0]) - && (-1..=1).contains(&col_mv[1]); - let mut mv = [[0i16; 2]; 2]; - let mut ref_id = [-1i32; 2]; - for list in 0..2 { - if ref_idx[list] < 0 { - continue; - } - ref_id[list] = ctx - .reference(refs, list, ref_idx[list]) - .map(|p| p.id) - .unwrap_or(-1); - if zero_prediction || (ref_idx[list] == 0 && col_zero) { - mv[list] = [0; 2]; - } else { - mv[list] = mvp[list]; - } - } - return Ok((mv, ref_idx, ref_id)); - } - - // Temporal direct (8.4.1.2.3). - let ref_idx0 = if col_ref_id < 0 { - 0 - } else { - map_col_to_list0(ctx, refs, col_ref_id, vscale) - }; - let col_mv = match vscale { - // 8-195 and 8-196: "/" truncates toward zero. - COL_FRM_TO_FLD => [col_mv[0], col_mv[1] / 2], - COL_FLD_TO_FRM => [col_mv[0], col_mv[1].wrapping_mul(2)], - _ => col_mv, - }; - let pic0 = ctx.reference(refs, 0, ref_idx0); - let pic1 = ctx.reference(refs, 1, 0); - let ref_id = [ - pic0.map(|p| p.id).unwrap_or(-1), - pic1.map(|p| p.id).unwrap_or(-1), - ]; - let (Some(p0), Some(p1)) = (pic0, pic1) else { - return Ok(([[0; 2]; 2], [ref_idx0, 0], ref_id)); - }; - let td = (p1.poc - p0.poc).clamp(-128, 127); - if p0.mark == Mark::Long || td == 0 { - return Ok(([col_mv, [0; 2]], [ref_idx0, 0], ref_id)); - } - let tb = (ctx.cur_poc() - p0.poc).clamp(-128, 127); - let tx = (16384 + (td / 2).abs()) / td; - let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023); - let mv0 = [ - ((dist * i32::from(col_mv[0]) + 128) >> 8) as i16, - ((dist * i32::from(col_mv[1]) + 128) >> 8) as i16, - ]; - let mv1 = [mv0[0] - col_mv[0], mv0[1] - col_mv[1]]; - Ok(([mv0, mv1], [ref_idx0, 0], ref_id)) -} - -/// `MapColToList0` (8.4.1.2.3): the lowest RefPicList0 index that names the -/// picture the co-located block referenced. -fn map_col_to_list0( - ctx: &SliceCtx, - refs: &[Picture], - col_ref_id: i32, - vscale: u8, -) -> i8 { - // Picture ids step by 4: a field id is its frame's id + 1 + parity. - let field_mb = ctx.pos.active && ctx.pos.field; - let want = match vscale { - // The field of the referenced frame with the current picture's (or - // macroblock's) parity. - COL_FRM_TO_FLD => col_ref_id + i32::from(ctx.mb_parity), - // A field macroblock of an MBAFF frame names the field of the frame - // the co-located field macroblock referenced that has its own parity. - _ if field_mb && MBAFF_ONE_TO_ONE_SAME_PARITY => { - (col_ref_id & !3) + i32::from(ctx.mb_parity) - } - _ => col_ref_id, - }; - let n = if field_mb { - 2 * ctx.lists[0].len() - } else { - ctx.lists[0].len() - }; - for i in 0..n { - let hit = ctx.reference(refs, 0, i as i8).is_some_and(|p| { - if vscale == COL_FLD_TO_FRM { - p.id == col_ref_id & !3 - } else { - p.id == want - } - }); - if hit { - return i as i8; - } - } - 0 -} - -/// Whether a field macroblock of an MBAFF frame whose co-located block is a -/// field macroblock maps the referenced field to the field of the same parity -/// as itself (true) or to that very field (false). -const MBAFF_ONE_TO_ONE_SAME_PARITY: bool = false; - -/// `vertMvScale` of 8.4.1.2.1. -const COL_ONE_TO_ONE: u8 = 0; -const COL_FRM_TO_FLD: u8 = 1; -const COL_FLD_TO_FRM: u8 = 2; - -/// [`colocated`] for a frame macroblock or field macroblock of an MBAFF frame. -#[inline(never)] -fn colocated_mbaff( - ctx: &SliceCtx, - refs: &[Picture], - mvc: &MvCtx, - at: (usize, usize), -) -> (i32, [i16; 2], i8, u8) { - const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE); - let Some((k, _)) = ctx.lists[1].get_ref(0) else { - return NONE; - }; - let Some(store) = refs.get(k) else { - return NONE; - }; - let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); - let w = store.mb_w.max(1); - let (c, bx, by, vs) = { - let field_mb = ctx.pos.field; - let bot = mb_y & 1; - let top = mb_y & !1; - // The field of a complementary pair, or of an MBAFF frame's field - // macroblock pair, a frame macroblock takes its co-located block from. - let by_poc = - usize::from((store.fpoc[0] - ctx.poc).abs() >= (store.fpoc[1] - ctx.poc).abs()); - if store.coding == CODED_FLD { - let p = if field_mb { bot } else { by_poc }; - let Some(f) = store.fields.get(p) else { - return NONE; - }; - if field_mb { - (f, mb_x * 4 + at.0, (mb_y / 2) * 4 + at.1, COL_ONE_TO_ONE) - } else { - // mbAddrCol5 and yM = 8 * (CurrMbAddr % 2) + 4 * (yCol / 8). - let by = (mb_y / 2) * 4 + 2 * bot + at.1 / 2; - (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) - } - } else { - let col_field = store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) != 0; - match (field_mb, col_field) { - (false, false) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE), - (false, true) => { - let slot = top + by_poc; - let by = slot * 4 + 2 * bot + at.1 / 2; - (store, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) - } - (true, false) => { - let slot = top + at.1 / 2; - let by = slot * 4 + (2 * at.1) % 4; - (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) - } - (true, true) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE), - } - } - }; - let idx = by * c.mb_w.max(1) * 4 + bx; - if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 { - let list = usize::from(c.ref_id[idx][0] < 0); - ( - c.ref_id[idx][list], - c.mv[idx][list], - c.ref_idx[idx][list], - vs, - ) - } else { - (-1, [0; 2], -1, vs) - } -} - -/// The co-located block of 8.4.1.2.1 for the 4x4 block `at` of the current -/// macroblock: `(refPicCol identity, mvCol, refIdxCol, vertMvScale)`; the -/// identity is -1 for an intra block. -fn colocated( - ctx: &SliceCtx, - refs: &[Picture], - mvc: &MvCtx, - at: (usize, usize), -) -> (i32, [i16; 2], i8, u8) { - const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE); - let Some((k, _)) = ctx.lists[1].get_ref(0) else { - return NONE; - }; - let Some(store) = refs.get(k) else { - return NONE; - }; - if ctx.pos.active { - return colocated_mbaff(ctx, refs, mvc, at); - } - let Some(cur) = ctx.reference(refs, 1, 0) else { - return NONE; - }; - let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); - let w = store.mb_w.max(1); - // Table 8-6 and Table 8-8. `mb_y` is a slot row for an MBAFF frame (the - // pair is `mb_y / 2`, the macroblock of the pair `mb_y % 2`). - let (c, bx, by, vs) = if ctx.structure != FRAME { - if store.coding == CODED_FLD { - (cur, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE) - } else if store.coding == CODED_AFRM { - let top = 2 * mb_y; - if store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) == 0 { - // mbAddrCol6 = 2 * CurrMbAddr + (yCol / 8), yM = (2 * yCol) % 16. - let by = (top + at.1 / 2) * 4 + (2 * at.1) % 4; - (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) - } else { - // mbAddrCol7 = 2 * CurrMbAddr + bottom_field_flag. - let slot = top + usize::from(ctx.structure == BOTTOM); - (store, mb_x * 4 + at.0, slot * 4 + at.1, COL_ONE_TO_ONE) - } - } else { - // mbAddrCol1 and yM = (2 * yCol) % 16. - let by = (2 * mb_y + at.1 / 2) * 4 + (2 * at.1) % 4; - (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) - } - } else if store.coding == CODED_FLD { - let top = (store.fpoc[0] - ctx.poc).abs(); - let bottom = (store.fpoc[1] - ctx.poc).abs(); - let p = usize::from(top >= bottom); - let Some(f) = store.fields.get(p) else { - return NONE; - }; - // mbAddrCol4 and yM = 8 * ((CurrMbAddr / PicWidthInMbs) % 2) + 4 * (yCol / 8). - let by = (mb_y / 2) * 4 + 2 * (mb_y % 2) + at.1 / 2; - (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) - } else { - (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE) - }; - let idx = by * c.mb_w.max(1) * 4 + bx; - if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 { - let list = usize::from(c.ref_id[idx][0] < 0); - ( - c.ref_id[idx][list], - c.mv[idx][list], - c.ref_idx[idx][list], - vs, - ) - } else { - (-1, [0; 2], -1, vs) - } -} - -/// The motion vectors chroma prediction uses: the luma vectors, with the -/// vertical offset of 8.4.1.4 added when a field predicts from a field of the -/// opposite parity. -#[inline] -fn chroma_mvs( - ctx: &SliceCtx, - refs: &[Picture], - ref_idx: [i8; 2], - mv: [[i16; 2]; 2], -) -> [[i16; 2]; 2] { - let mut out = mv; - if ctx.cat == 2 { - // 4:2:2 chroma is full height: the vertical vector stays in quarter - // samples of the chroma plane, which the eighth-sample interpolator - // reads as twice the value. - for l in out.iter_mut() { - l[1] = l[1].wrapping_mul(2); - } - } else if ctx.is_field() { - for l in 0..2 { - if let Some(rp) = ctx.reference(refs, l, ref_idx[l]) { - out[l][1] = out[l][1].wrapping_add(ctx.chroma_dy(rp)); - } - } - } - out -} - -/// The reference plane (`0` luma, `1` Cb, `2` Cr) list `list` predicts from. -#[inline(always)] -fn ref_plane<'a>( - ctx: &SliceCtx, - refs: &'a [Picture], - ref_idx: [i8; 2], - list: usize, - comp: usize, -) -> Result> { - let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| { - Error::corrupt("reference index names a picture the buffer does not hold") - })?; - let src = match comp { - 0 => &rp.y, - 1 => &rp.cb, - _ => &rp.cr, - }; - Ok(RefPlane { - data: &src.data, - stride: src.stride, - origin: src.origin, - width: src.width, - height: src.height, - pad: src.pad, - }) -} - -/// Motion compensation of one partition (clause 8.4.2): interpolate each list's -/// prediction, then combine them by the weighting of 8.4.2.3 and write the -/// result straight into the picture, where the residual is added on top. -/// -/// `(px, py)` and `(pw, ph)` are in 4x4 blocks within the macroblock. -#[allow(clippy::too_many_arguments)] -pub(crate) fn compensate8( - pic: &mut Picture, - refs: &[Picture], - ctx: &SliceCtx, - mb_x: usize, - mb_y: usize, - px: usize, - py: usize, - pw: usize, - ph: usize, - mv: [[i16; 2]; 2], - ref_idx: [i8; 2], -) -> Result<()> { - let use0 = ref_idx[0] >= 0; - let use1 = ref_idx[1] >= 0; - if !use0 && !use1 { - return Ok(()); - } - let geo = ctx.geo(mb_y); - let x0 = (mb_x * 16 + px * 4) as i32; - let y0 = (geo.src_y + py * 4) as i32; - let (w, h) = (pw * 4, ph * 4); - // A stream carrying no weighted prediction at all resolves every - // component to the identity weighting without the per-component lookup. - let plain = ctx.no_weights(); - // ChromaArrayType 3 predicts Cb and Cr with the luma interpolation, on - // their own planes and weights. - let ncomp = if ctx.cat == 3 { 3 } else { 1 }; - for comp in 0..ncomp { - let wt = if plain { - Weights::DEFAULT - } else { - ctx.weights_for(refs, comp, ref_idx[0], ref_idx[1], use0, use1) - }; - // 8.4.2.3.1 over one list is the identity, so the interpolation of that - // one list IS the prediction: it is written straight into the picture at - // the picture's own pitch. Over both lists the combined prediction is the - // rounded byte average of the two clipped ones, so list 0 interpolates - // into the picture and list 1 averages on top of it (Put::Avg) — no - // temporaries, no combining pass, no copy back. - let direct = wt.is_default(); - let stride = plane_ref(pic, comp).stride * geo.mul; - let origin = plane_ref(pic, comp).at(x0 as usize, geo.y(py * 4)); - // Weighted bi-prediction fuses the same way: the combining formula is - // per-sample, so list 0 lands in the picture and list 1 combines on top - // of it (Put::AvgW) with 8.4.2.3.2's exact integers. - let weighted_put = if !direct && use0 && use1 { - Some(crate::inter::Put::AvgW { - w0: wt.w[0], - w1: wt.w[1], - shift: (wt.log_wd + 1) as u32, - round: 1 << wt.log_wd, - off: (wt.o[0] + wt.o[1] + 1) >> 1, - }) - } else { - None - }; - if direct && use0 && use1 { - let plane = ref_plane(ctx, refs, ref_idx, 0, comp)?; - mc_luma( - &plane, - x0, - y0, - mv[0], - w, - h, - stride, - &mut plane_mut(pic, comp).data[origin..], - crate::inter::Put::Set, - ); - let plane = ref_plane(ctx, refs, ref_idx, 1, comp)?; - mc_luma( - &plane, - x0, - y0, - mv[1], - w, - h, - stride, - &mut plane_mut(pic, comp).data[origin..], - crate::inter::Put::Avg, - ); - } else if direct { - // No scratch buffer is declared on this path at all: the scratch is - // zeroed on entry, and most partitions of a P slice come through here. - let list = usize::from(!use0); - let plane = ref_plane(ctx, refs, ref_idx, list, comp)?; - mc_luma( - &plane, - x0, - y0, - mv[list], - w, - h, - stride, - &mut plane_mut(pic, comp).data[origin..], - crate::inter::Put::Set, - ); - } else if let Some(put) = weighted_put { - let plane = ref_plane(ctx, refs, ref_idx, 0, comp)?; - mc_luma( - &plane, - x0, - y0, - mv[0], - w, - h, - stride, - &mut plane_mut(pic, comp).data[origin..], - crate::inter::Put::Set, - ); - let plane = ref_plane(ctx, refs, ref_idx, 1, comp)?; - mc_luma( - &plane, - x0, - y0, - mv[1], - w, - h, - stride, - &mut plane_mut(pic, comp).data[origin..], - put, - ); - } else { - let mut part = [[0u8; 256]; 2]; - for list in 0..2 { - if ref_idx[list] < 0 { - continue; - } - let plane = ref_plane(ctx, refs, ref_idx, list, comp)?; - mc_luma( - &plane, - x0, - y0, - mv[list], - w, - h, - w, - &mut part[list], - crate::inter::Put::Set, - ); - } - let mut out = [0u8; 256]; - let (p0, p1) = part.split_at(1); - combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h); - for row in 0..h { - let dst = origin + row * stride; - plane_mut(pic, comp).data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]); - } - } - } - - // Chroma (8.4.1.4): for 4:2:0 frame coding the chroma vector is the luma - // vector, read as eighth-sample units over the half-resolution plane. - if ctx.cat == 0 || ctx.cat == 3 { - return Ok(()); - } - let cmv = chroma_mvs(ctx, refs, ref_idx, mv); - let c422 = ctx.cat == 2; - let (cw, ch) = (w / 2, if c422 { h } else { h / 2 }); - let (cx0, cy0) = (x0 / 2, if c422 { y0 } else { y0 / 2 }); - let crow = if c422 { py * 4 } else { py * 2 }; - for comp in 0..2 { - let wt = if plain { - Weights::DEFAULT - } else { - ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1) - }; - let direct = wt.is_default(); - // The combining weights are per-component syntax (luma and chroma - // carry their own denoms, weights and offsets), so this component's - // fused mode is built from ITS OWN lookup — never the luma one. - let weighted_put = if !direct && use0 && use1 { - Some(crate::inter::Put::AvgW { - w0: wt.w[0], - w1: wt.w[1], - shift: (wt.log_wd + 1) as u32, - round: 1 << wt.log_wd, - off: (wt.o[0] + wt.o[1] + 1) >> 1, - }) - } else { - None - }; - let plane_out = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; - let stride = plane_out.stride * geo.mul; - let origin = plane_out.at(cx0 as usize, geo.cy(crow)); - if direct && use0 && use1 { - let plane = ref_plane(ctx, refs, ref_idx, 0, 1 + comp)?; - mc_chroma( - &plane, - cx0, - cy0, - cmv[0], - cw, - ch, - stride, - &mut plane_out.data[origin..], - crate::inter::Put::Set, - ); - let plane = ref_plane(ctx, refs, ref_idx, 1, 1 + comp)?; - mc_chroma( - &plane, - cx0, - cy0, - cmv[1], - cw, - ch, - stride, - &mut plane_out.data[origin..], - crate::inter::Put::Avg, - ); - } else if let Some(put) = weighted_put { - let plane = ref_plane(ctx, refs, ref_idx, 0, 1 + comp)?; - mc_chroma( - &plane, - cx0, - cy0, - cmv[0], - cw, - ch, - stride, - &mut plane_out.data[origin..], - crate::inter::Put::Set, - ); - let plane = ref_plane(ctx, refs, ref_idx, 1, 1 + comp)?; - mc_chroma( - &plane, - cx0, - cy0, - cmv[1], - cw, - ch, - stride, - &mut plane_out.data[origin..], - put, - ); - } else if direct { - let list = usize::from(!use0); - let plane = ref_plane(ctx, refs, ref_idx, list, 1 + comp)?; - mc_chroma( - &plane, - cx0, - cy0, - cmv[list], - cw, - ch, - stride, - &mut plane_out.data[origin..], - crate::inter::Put::Set, - ); - } else { - let mut cpart = [[0u8; 128]; 2]; - for list in 0..2 { - if ref_idx[list] < 0 { - continue; - } - let plane = ref_plane(ctx, refs, ref_idx, list, 1 + comp)?; - mc_chroma( - &plane, - cx0, - cy0, - cmv[list], - cw, - ch, - cw, - &mut cpart[list], - crate::inter::Put::Set, - ); - } - let mut cout = [0u8; 128]; - let (c0, c1) = cpart.split_at(1); - combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch); - for row in 0..ch { - let dst = origin + row * stride; - plane_out.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]); - } - } - } - Ok(()) -} - -/// Motion compensation of one partition over `u16` planes: the same clause -/// 8.4.2 process as [`compensate8`], computed per sample from the equations. -/// Weighted prediction offsets scale by `1 << (BitDepth - 8)` (8-298, 8-299). -#[allow(clippy::too_many_arguments)] -pub(crate) fn compensate16( - pic: &mut Picture, - refs: &[Picture], - ctx: &SliceCtx, - mb_x: usize, - mb_y: usize, - px: usize, - py: usize, - pw: usize, - ph: usize, - mv: [[i16; 2]; 2], - ref_idx: [i8; 2], -) -> Result<()> { - let use0 = ref_idx[0] >= 0; - let use1 = ref_idx[1] >= 0; - if !use0 && !use1 { - return Ok(()); - } - let bd = pic.bd; - let max = (1i32 << bd) - 1; - let geo = ctx.geo(mb_y); - let x0 = (mb_x * 16 + px * 4) as i32; - let y0 = (geo.src_y + py * 4) as i32; - let plain = ctx.no_weights(); - let cmv = chroma_mvs(ctx, refs, ref_idx, mv); - let cat = pic.cat; - let ncomp = if cat == 0 { 1 } else { 3 }; - for comp in 0..ncomp { - let c422 = cat == 2; - let (w, h, cx, cy) = if comp == 0 || cat == 3 { - (pw * 4, ph * 4, x0, y0) - } else if c422 { - (pw * 2, ph * 4, x0 / 2, y0) - } else { - (pw * 2, ph * 2, x0 / 2, y0 / 2) - }; - let mut wt = if plain { - Weights::DEFAULT - } else { - ctx.weights_for(refs, comp, ref_idx[0], ref_idx[1], use0, use1) - }; - wt.o[0] <<= bd - 8; - wt.o[1] <<= bd - 8; - let mut pred = [[0i32; 256]; 2]; - for list in 0..2 { - if ref_idx[list] < 0 { - continue; - } - let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| { - Error::corrupt("reference index names a picture the buffer does not hold") - })?; - match comp { - 0 => crate::inter16::luma_pred(&rp.y, cx, cy, mv[list], w, h, max, &mut pred[list]), - 1 if cat == 3 => { - crate::inter16::luma_pred(&rp.cb, cx, cy, mv[list], w, h, max, &mut pred[list]) - } - _ if cat == 3 => { - crate::inter16::luma_pred(&rp.cr, cx, cy, mv[list], w, h, max, &mut pred[list]) - } - 1 => crate::inter16::chroma_pred(&rp.cb, cx, cy, cmv[list], w, h, &mut pred[list]), - _ => crate::inter16::chroma_pred(&rp.cr, cx, cy, cmv[list], w, h, &mut pred[list]), - } - } - let plane = match comp { - 0 => &mut pic.y, - 1 => &mut pic.cb, - _ => &mut pic.cr, - }; - let stride = plane.stride * geo.mul; - let origin = if comp == 0 || cat == 3 { - plane.at(cx as usize, geo.y(py * 4)) - } else { - plane.at(cx as usize, geo.cy(if c422 { py * 4 } else { py * 2 })) - }; - let round1 = if wt.log_wd >= 1 { - 1 << (wt.log_wd - 1) - } else { - 0 - }; - for row in 0..h { - for col in 0..w { - let i = row * w + col; - let v = if use0 && use1 { - // 8-301 / 8-300 (default weights reduce to the rounded mean). - ((pred[0][i] * wt.w[0] + pred[1][i] * wt.w[1] + (1 << wt.log_wd)) - >> (wt.log_wd + 1)) - + ((wt.o[0] + wt.o[1] + 1) >> 1) - } else { - let k = usize::from(!use0); - if wt.log_wd >= 1 { - ((pred[k][i] * wt.w[k] + round1) >> wt.log_wd) + wt.o[k] - } else { - pred[k][i] * wt.w[k] + wt.o[k] - } - }; - plane.data[origin + row * stride + col] = v.clamp(0, max) as u16; - } - } - } - Ok(()) -} /// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2), /// including the top-right substitution rule. @@ -4312,513 +3175,12 @@ pub(crate) fn gather_nbr8_in( } } -/// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all -/// vertical edges then all horizontal edges per macroblock, then chroma. -// `e` and `j` are edge and segment positions inside the macroblock, used to -// index the plane as well as the strength arrays; iterating the arrays would -// hide which geometry each one names. -#[allow(clippy::needless_range_loop)] -pub(crate) fn deblock_picture(pic: &mut Picture) { - let mb_w = pic.mb_w; - let bd = pic.bd; - let max = (1i32 << bd) - 1; - let qp_bd = 6 * (bd as i32 - 8); - let cmb_h = pic.cmb_h; - let cat = pic.cat; - let lcomps = if cat == 3 { 3 } else { 1 }; - for mb_y in 0..pic.mb_h { - for mb_x in 0..mb_w { - let addr = mb_y * mb_w + mb_x; - if pic.mb_flags[addr] & FLAG_DECODED == 0 { - continue; - } - let sid = pic.mb_slice[addr]; - let sp = pic.slices[sid as usize]; - if sp.disable_deblock_idc == 1 { - continue; - } - let decoded = |a: usize| pic.mb_flags[a] & FLAG_DECODED != 0; - let cross_ok = |a: usize| sp.disable_deblock_idc != 2 || pic.mb_slice[a] == sid; - let filter_left = mb_x > 0 && decoded(addr - 1) && cross_ok(addr - 1); - let filter_top = mb_y > 0 && decoded(addr - mb_w) && cross_ok(addr - mb_w); - // Deblocking QP: 0 for I_PCM macroblocks (8.7.2). - let qp_of = |a: usize| -> i32 { - if pic.mb_flags[a] & FLAG_PCM != 0 { - 0 - } else { - i32::from(pic.mb_qp[a]) - } - }; - // 8.7: an 8x8-transform macroblock has no transform edge at luma - // 4 or 12, so those internal edges are not filtered. Chroma is - // unaffected for 4:2:0 (its internal edge sits on luma edge 8). - let internal = - |e: usize| e.is_multiple_of(2) || pic.mb_flags[addr] & FLAG_TRANS8X8 == 0; - - // Boundary strengths, per 4-sample segment of each edge (8.7.2.1). - // - // Both sides of an internal edge live in this macroblock, so the - // whole 8.7.2.1 ladder is decided once for all 24 of them: an intra - // macroblock gives 3 everywhere, and an inter macroblock with no - // luma coefficients and one motion vector over the whole 16x16 - // gives 0 everywhere. Only the two macroblock edges then need the - // per-segment derivation. - let mut bs_v = [[0u8; 4]; 4]; - let mut bs_h = [[0u8; 4]; 4]; - let cur_intra = pic.mb_flags[addr] & FLAG_INTER == 0; - let internal_uniform = if cur_intra { - Some(3) - } else if pic.mb_cbp[addr] == 0 && uniform_motion(pic, mb_x, mb_y) { - Some(0) - } else { - None - }; - for k in 0..4 { - if filter_left { - bs_v[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, true); - } - if filter_top { - bs_h[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, false); - } - } - for e in 1..4 { - match internal_uniform { - Some(bs) => { - bs_v[e] = [bs; 4]; - bs_h[e] = [bs; 4]; - } - None => { - for k in 0..4 { - bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true); - bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false); - } - } - } - } - - // ---- luma (and Cb/Cr, coded like luma, for ChromaArrayType 3) ---- - for comp in 0..lcomps { - let pl: &mut PicPlane = match comp { - 0 => &mut pic.y, - 1 => &mut pic.cb, - _ => &mut pic.cr, - }; - let stride = pl.stride; - let base = pl.at(mb_x * 16, mb_y * 16); - let qpf = |a: usize| -> i32 { - if comp == 0 { - qp_of(a) - } else { - let s = pic.slices[pic.mb_slice[a] as usize]; - let off = if comp == 1 { - s.cb_qp_offset - } else { - s.cr_qp_offset - }; - let q = if pic.mb_flags[a] & FLAG_PCM != 0 { - 0 - } else { - i32::from(pic.mb_qp[a]) - }; - chroma_qp(q, off, qp_bd) - } - }; - let qp_q = qpf(addr); - // Lossless macroblocks keep their samples (8.7.2.2). - let lossless = |a: usize| { - pic.bypass_enabled - && pic.mb_flags[a] & FLAG_PCM == 0 - && i32::from(pic.mb_qp[a]) + qp_bd == 0 - }; - let (p_ll_v, q_ll) = (filter_left && lossless(addr - 1), lossless(addr)); - let snap_v = (p_ll_v || (filter_left && q_ll)) - .then(|| snap_edge(&pl.data, base, stride, true)); - // Vertical edges (filter across columns), left to right. - for e in 0..4 { - if e == 0 && !filter_left { - continue; - } - if !internal(e) { - continue; - } - let qp_p = if e == 0 { qpf(addr - 1) } else { qp_q }; - let qp_avg = (qp_p + qp_q + 1) >> 1; - // Vertical edges stay scalar: a gather/scatter SIMD - // variant measured slower than this loop (strided - // per-lane loads dominate). - for j in 0..4 { - let bs = bs_v[e][j]; - if bs == 0 { - continue; - } - let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd); - if params.alpha == 0 || params.beta == 0 { - continue; - } - for k in 0..4 { - let row = j * 4 + k; - filter_luma_line( - &mut pl.data, - max, - base + row * stride + e * 4, - 1, - ¶ms, - ); - } - } - } - if let Some(sv) = &snap_v { - restore_edge(&mut pl.data, sv, base, stride, true, p_ll_v, q_ll); - } - let p_ll_h = filter_top && lossless(addr - mb_w); - let snap_h = (p_ll_h || (filter_top && q_ll)) - .then(|| snap_edge(&pl.data, base, stride, false)); - // Horizontal edges, top to bottom. - for e in 0..4 { - if e == 0 && !filter_top { - continue; - } - if !internal(e) { - continue; - } - let qp_p = if e == 0 { qpf(addr - mb_w) } else { qp_q }; - let qp_avg = (qp_p + qp_q + 1) >> 1; - let bs = bs_h[e]; - let uniform = bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3]; - if uniform { - if bs[0] == 0 { - continue; - } - let params = - edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0], bd); - if params.alpha == 0 || params.beta == 0 { - continue; - } - // Eight rows around the edge are contiguous, so the - // whole 16-sample edge filters in one pass. - S::filter_luma_h_edge16( - &mut pl.data, - max, - base + e * 4 * stride, - stride, - ¶ms, - ); - continue; - } - for j in 0..4 { - if bs[j] == 0 { - continue; - } - let params = - edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[j], bd); - if params.alpha == 0 || params.beta == 0 { - continue; - } - for k in 0..4 { - filter_luma_line( - &mut pl.data, - max, - base + e * 4 * stride + j * 4 + k, - stride, - ¶ms, - ); - } - } - } - if let Some(sh) = &snap_h { - restore_edge(&mut pl.data, sh, base, stride, false, p_ll_h, q_ll); - } - } - - // ---- chroma (Cb, Cr) ---- - for comp in 0..if matches!(cat, 1 | 2) { 2 } else { 0 } { - let (plane, off_sel): (&mut PicPlane, fn(&SliceParams) -> i32) = if comp == 0 { - (&mut pic.cb, |s| s.cb_qp_offset) - } else { - (&mut pic.cr, |s| s.cr_qp_offset) - }; - let stride = plane.stride; - let c422 = cat == 2; - let base = plane.origin + (mb_y * cmb_h) * stride + mb_x * 8; - // Chroma QP per side: each macroblock's luma QP mapped with - // the offset of ITS OWN slice's PPS (8.7.2). - let cqp = |a: usize| -> i32 { - let s = pic.slices[pic.mb_slice[a] as usize]; - if pic.mb_flags[a] & FLAG_PCM != 0 { - chroma_qp(0, off_sel(&s), qp_bd) - } else { - chroma_qp(i32::from(pic.mb_qp[a]), off_sel(&s), qp_bd) - } - }; - let cq_q = cqp(addr); - // A chroma edge inherits the boundary strength of the luma edge - // it sits on: chroma sample k maps to luma sample 2k, so a - // chroma 4-sample run spans two luma 4x4 block rows. - for e in 0..2 { - if e == 0 && !filter_left { - continue; - } - let cq_p = if e == 0 { cqp(addr - 1) } else { cq_q }; - let qp_avg = (cq_p + cq_q + 1) >> 1; - for k in 0..cmb_h { - let bs = bs_v[e * 2][k >> if c422 { 2 } else { 1 }]; - if bs == 0 { - continue; - } - let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd); - if params.alpha == 0 || params.beta == 0 { - continue; - } - filter_chroma_line( - &mut plane.data, - max, - base + k * stride + e * 4, - 1, - ¶ms, - ); - } - } - // 4:2:2 chroma is as tall as luma: its horizontal 4x4 transform - // edges sit at rows 0, 4, 8 and 12, each on the boundary - // strength of the luma edge on the same row. - for e in 0..if c422 { 4 } else { 2 } { - if e == 0 && !filter_top { - continue; - } - let cq_p = if e == 0 { cqp(addr - mb_w) } else { cq_q }; - let qp_avg = (cq_p + cq_q + 1) >> 1; - let bs = bs_h[if c422 { e } else { e * 2 }]; - if bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3] { - if bs[0] == 0 { - continue; - } - let params = - edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0], bd); - if params.alpha == 0 || params.beta == 0 { - continue; - } - // The four rows around the edge are contiguous, so the - // whole eight-sample edge filters in one pass. - S::filter_chroma_h_edge8( - &mut plane.data, - max, - base + e * 4 * stride, - stride, - ¶ms, - ); - continue; - } - for k in 0..8 { - let bs = bs[k / 2]; - if bs == 0 { - continue; - } - let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd); - if params.alpha == 0 || params.beta == 0 { - continue; - } - filter_chroma_line( - &mut plane.data, - max, - base + e * 4 * stride + k, - stride, - ¶ms, - ); - } - } - } - } - } -} - -/// Copy the 8 samples across a macroblock edge (4 each side) along its 16 -/// samples, so a lossless side can be put back after the filter ran. -fn snap_edge(data: &[S], base: usize, stride: usize, vertical: bool) -> Vec { - let mut v = Vec::with_capacity(128); - for i in 0..16 { - for d in 0..8 { - v.push(if vertical { - data[base + i * stride + d - 4] - } else { - data[base + d * stride + i - 4 * stride] - }); - } - } - v -} - -fn restore_edge( - data: &mut [S], - snap: &[S], - base: usize, - stride: usize, - vertical: bool, - p: bool, - q: bool, -) { - for i in 0..16 { - for d in 0..8 { - if (d < 4 && !p) || (d >= 4 && !q) { - continue; - } - let idx = if vertical { - base + i * stride + d - 4 - } else { - base + d * stride + i - 4 * stride - }; - data[idx] = snap[i * 8 + d]; - } - } -} - -/// True when every 4x4 block of this macroblock predicts from the same -/// pictures with the same motion, so no internal edge can reach the motion -/// clauses of 8.7.2.1. -fn uniform_motion(pic: &Picture, mb_x: usize, mb_y: usize) -> bool { - let w4 = pic.mb_w * 4; - let first = mb_y * 4 * w4 + mb_x * 4; - let (mv, id) = (pic.mv[first], pic.ref_id[first]); - (0..4).all(|by| { - let row = first + by * w4; - (0..4).all(|bx| pic.mv[row + bx] == mv && pic.ref_id[row + bx] == id) - }) -} - -/// What clause 8.7.2.1 needs from the 4x4 block on one side of a luma edge. -#[derive(Clone, Copy)] -pub(crate) struct BsSide { - /// The containing macroblock is intra: strength 4 on macroblock edges and - /// 3 on internal ones, regardless of motion or levels. - pub(crate) intra: bool, - /// The transform block containing this sample has non-zero levels. - pub(crate) coded: bool, - /// MvLX of the block, `[list][component]`. - pub(crate) mv: [[i16; 2]; 2], - /// RefIdxLX of the block as list identities (`Picture::id`), -1 unused. - pub(crate) refs: [i32; 2], -} - -/// Boundary strength between the 4x4 blocks on the two sides of a luma edge -/// (clause 8.7.2.1). `mb_edge` selects the macroblock-edge strengths 4/3. -pub(crate) fn bs_between(p: &BsSide, q: &BsSide, mb_edge: bool, field: bool, vertical: bool) -> u8 { - if p.intra || q.intra { - // A horizontal edge of a field picture is never strength 4 (8.7.2.1). - return if mb_edge && (vertical || !field) { - 4 - } else { - 3 - }; - } - if p.coded || q.coded { - return 2; - } - let (pr, qr) = (p.refs, q.refs); - let pn = u8::from(pr[0] >= 0) + u8::from(pr[1] >= 0); - let qn = u8::from(qr[0] >= 0) + u8::from(qr[1] >= 0); - if pn != qn { - return 1; - } - let (pm, qm) = (p.mv, q.mv); - // The vertical limit is 4 quarter frame samples: 2 in field units. - let ylim = if field { 2 } else { 4 }; - let differs = |a: [i16; 2], b: [i16; 2]| { - (i32::from(a[0]) - i32::from(b[0])).abs() >= 4 - || (i32::from(a[1]) - i32::from(b[1])).abs() >= ylim - }; - if pn == 1 { - let pl = usize::from(pr[0] < 0); - let ql = usize::from(qr[0] < 0); - if pr[pl] != qr[ql] { - return 1; - } - return u8::from(differs(pm[pl], qm[ql])); - } - if pn == 0 { - return 0; - } - // Two motion vectors each: compare the two partitions by which pictures - // they reference, not by list position (NOTE 1 of 8.7.2.1). - let same_set = (pr[0] == qr[0] && pr[1] == qr[1]) || (pr[0] == qr[1] && pr[1] == qr[0]); - if !same_set { - return 1; - } - if pr[0] != pr[1] { - return if pr[0] == qr[0] { - u8::from(differs(pm[0], qm[0]) || differs(pm[1], qm[1])) - } else { - u8::from(differs(pm[0], qm[1]) || differs(pm[1], qm[0])) - }; - } - // Both lists name the same picture: either pairing agreeing is enough. - let straight = !differs(pm[0], qm[0]) && !differs(pm[1], qm[1]); - let crossed = !differs(pm[0], qm[1]) && !differs(pm[1], qm[0]); - u8::from(!(straight || crossed)) -} - -/// One side of a luma edge from picture state: the decoder path, both sides -/// final macroblocks. The encoder's inter trial uses this for the -/// already-coded neighbour and builds its candidate side itself. -pub(crate) fn bs_side(pic: &Picture, bx: usize, by: usize) -> BsSide { - let w4 = pic.mb_w * 4; - let mb = (by / 4) * pic.mb_w + bx / 4; - BsSide { - intra: pic.mb_flags[mb] & FLAG_INTER == 0, - coded: bs_coded(pic, mb, bx, by), - mv: pic.mv[by * w4 + bx], - refs: pic.ref_id[by * w4 + bx], - } -} - -/// "The transform block containing the sample has non-zero levels": for an -/// 8x8-transform macroblock that is the whole 8x8, whose four 4x4 slots -/// carry per-slot counts under CAVLC (7.3.5.3.1 splits it into four blocks). -fn bs_coded(pic: &Picture, mb: usize, bx: usize, by: usize) -> bool { - let w4 = pic.mb_w * 4; - if pic.mb_flags[mb] & FLAG_TRANS8X8 == 0 { - return pic.nz_y[by * w4 + bx] != 0; - } - let (ox, oy) = (bx & !1, by & !1); - pic.nz_y[oy * w4 + ox] != 0 - || pic.nz_y[oy * w4 + ox + 1] != 0 - || pic.nz_y[(oy + 1) * w4 + ox] != 0 - || pic.nz_y[(oy + 1) * w4 + ox + 1] != 0 -} - -/// Boundary strength of one 4-sample luma edge segment (clause 8.7.2.1). -/// -/// `edge` 0..4 selects the vertical (`vertical`) or horizontal edge inside the -/// macroblock, `seg` the 4-sample run along it. Edge 0 is the macroblock edge. -fn boundary_strength( - pic: &Picture, - mb_x: usize, - mb_y: usize, - edge: usize, - seg: usize, - vertical: bool, -) -> u8 { - let (qbx, qby) = if vertical { - (mb_x * 4 + edge, mb_y * 4 + seg) - } else { - (mb_x * 4 + seg, mb_y * 4 + edge) - }; - let (pbx, pby) = if vertical { - (qbx - 1, qby) - } else { - (qbx, qby - 1) - }; - bs_between( - &bs_side(pic, pbx, pby), - &bs_side(pic, qbx, qby), - edge == 0, - pic.structure != FRAME, - vertical, - ) -} #[cfg(test)] mod tests { use super::*; use crate::dpb::RefList; + use crate::mc::compensate8; use ec_h264_syntax::{PredWeightTable, WeightEntry}; /// A picture whose visible samples are a fixed ramp, borders replicated. diff --git a/crates/ec-h264/src/direct.rs b/crates/ec-h264/src/direct.rs new file mode 100644 index 00000000..fd7b65d1 --- /dev/null +++ b/crates/ec-h264/src/direct.rs @@ -0,0 +1,387 @@ +use ec_core::error::Result; + +use crate::decoder::SliceCtx; +use crate::dpb::{ + BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, FRAME, Mark, Picture, +}; +use crate::mv::{MvCtx, min_positive, predict_mv, write_block}; +use crate::sample::Sample; + +/// B_Skip / B_Direct_16x16 (clause 8.4.1.2) over the whole macroblock. +pub(crate) fn predict_direct( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &mut MvCtx, + skip: bool, +) -> Result<()> { + for quad in 0..4 { + direct_quadrant(pic, refs, ctx, mvc, quad, skip)?; + } + Ok(()) +} + +/// B_Direct_8x8 for one 8x8 sub-macroblock. +pub(crate) fn predict_direct_8x8( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &mut MvCtx, + part: usize, +) -> Result<()> { + direct_quadrant(pic, refs, ctx, mvc, part, false) +} + +/// One 8x8 quadrant of a direct-mode macroblock. With +/// `direct_8x8_inference_flag` the whole quadrant shares the motion of its +/// outer corner 4x4 block; without it each 4x4 block is derived on its own. +fn direct_quadrant( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &mut MvCtx, + quad: usize, + skip: bool, +) -> Result<()> { + let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); + let (qx, qy) = (quad % 2 * 2, quad / 2 * 2); + let flags = BLK_DIRECT | if skip { BLK_SKIP } else { 0 }; + if ctx.direct_8x8_inference { + // 8.4.1.2.1: luma4x4BlkIdx = 5 * mbPartIdx, i.e. the quadrant's own + // outer corner of the macroblock. + let corner = (quad % 2 * 3, quad / 2 * 3); + let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, corner)?; + for dy in 0..2 { + for dx in 0..2 { + write_block(pic, mvc, qx + dx, qy + dy, mv, ref_idx, ref_id, flags); + } + } + S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx) + } else { + // Each 4x4 block derives its own motion, but they usually come out + // equal: interpolation is position-invariant, so one 8x8 compensation + // of the shared vector produces the same samples as four 4x4 ones and + // pays the per-partition setup once instead of four times. + let mut motion = [([[0i16; 2]; 2], [0i8; 2]); 4]; + for dy in 0..2 { + for dx in 0..2 { + let (px, py) = (qx + dx, qy + dy); + let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, (px, py))?; + write_block(pic, mvc, px, py, mv, ref_idx, ref_id, flags); + motion[dy * 2 + dx] = (mv, ref_idx); + } + } + if motion.iter().all(|m| *m == motion[0]) { + let (mv, ref_idx) = motion[0]; + return S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx); + } + for dy in 0..2 { + for dx in 0..2 { + let (mv, ref_idx) = motion[dy * 2 + dx]; + S::compensate( + pic, + refs, + ctx, + mb_x, + mb_y, + qx + dx, + qy + dy, + 1, + 1, + mv, + ref_idx, + )?; + } + } + Ok(()) + } +} + +/// Motion of one direct-mode 4x4 block: `(mvLX, refIdxLX, reference picture +/// identity)`, spatial (8.4.1.2.2) or temporal (8.4.1.2.3). +#[allow(clippy::type_complexity)] +fn direct_block( + pic: &Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &MvCtx, + at: (usize, usize), +) -> Result<([[i16; 2]; 2], [i8; 2], [i32; 2])> { + // The co-located block, in both modes (8.4.1.2.1): its list 0 motion, or + // its list 1 motion when list 0 is unused. `col_ref_idx` is refIdxCol — + // an index into the co-located picture's own reference list, not ours. + let (col_ref_id, col_mv, col_ref_idx, vscale) = colocated(ctx, refs, mvc, at); + let col = ctx.reference(refs, 1, 0); + + if ctx.direct_spatial { + // Reference indices from the macroblock's own neighbours, once. + let mut ref_idx = [-1i8; 2]; + let mut mvp = [[0i16; 2]; 2]; + for list in 0..2 { + let n = mvc.neighbours(pic, 0, 0, 4, list); + ref_idx[list] = min_positive(n[0].ref_idx, min_positive(n[1].ref_idx, n[2].ref_idx)); + mvp[list] = predict_mv(&n, ref_idx[list], 4, 4, 0); + } + let zero_prediction = ref_idx[0] < 0 && ref_idx[1] < 0; + if zero_prediction { + ref_idx = [0, 0]; + } + // colZeroFlag (8.4.1.2.2): the co-located block sits still on a + // short-term picture, referencing that picture's own list entry 0. The + // index is the one belonging to the list 8.4.1.2.1 picked — reading + // "either list is 0" instead lets a bi-predicted co-located block whose + // list 1 index happens to be 0 zero a motion vector it must not, which + // only shows on a B picture used as the co-located one. + let col_short = col.is_some_and(|c| c.mark == Mark::Short); + let col_zero = col_short + && col_ref_id >= 0 + && col_ref_idx == 0 + && (-1..=1).contains(&col_mv[0]) + && (-1..=1).contains(&col_mv[1]); + let mut mv = [[0i16; 2]; 2]; + let mut ref_id = [-1i32; 2]; + for list in 0..2 { + if ref_idx[list] < 0 { + continue; + } + ref_id[list] = ctx + .reference(refs, list, ref_idx[list]) + .map(|p| p.id) + .unwrap_or(-1); + if zero_prediction || (ref_idx[list] == 0 && col_zero) { + mv[list] = [0; 2]; + } else { + mv[list] = mvp[list]; + } + } + return Ok((mv, ref_idx, ref_id)); + } + + // Temporal direct (8.4.1.2.3). + let ref_idx0 = if col_ref_id < 0 { + 0 + } else { + map_col_to_list0(ctx, refs, col_ref_id, vscale) + }; + let col_mv = match vscale { + // 8-195 and 8-196: "/" truncates toward zero. + COL_FRM_TO_FLD => [col_mv[0], col_mv[1] / 2], + COL_FLD_TO_FRM => [col_mv[0], col_mv[1].wrapping_mul(2)], + _ => col_mv, + }; + let pic0 = ctx.reference(refs, 0, ref_idx0); + let pic1 = ctx.reference(refs, 1, 0); + let ref_id = [ + pic0.map(|p| p.id).unwrap_or(-1), + pic1.map(|p| p.id).unwrap_or(-1), + ]; + let (Some(p0), Some(p1)) = (pic0, pic1) else { + return Ok(([[0; 2]; 2], [ref_idx0, 0], ref_id)); + }; + let td = (p1.poc - p0.poc).clamp(-128, 127); + if p0.mark == Mark::Long || td == 0 { + return Ok(([col_mv, [0; 2]], [ref_idx0, 0], ref_id)); + } + let tb = (ctx.cur_poc() - p0.poc).clamp(-128, 127); + let tx = (16384 + (td / 2).abs()) / td; + let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023); + let mv0 = [ + ((dist * i32::from(col_mv[0]) + 128) >> 8) as i16, + ((dist * i32::from(col_mv[1]) + 128) >> 8) as i16, + ]; + let mv1 = [mv0[0] - col_mv[0], mv0[1] - col_mv[1]]; + Ok(([mv0, mv1], [ref_idx0, 0], ref_id)) +} + +/// `MapColToList0` (8.4.1.2.3): the lowest RefPicList0 index that names the +/// picture the co-located block referenced. +fn map_col_to_list0( + ctx: &SliceCtx, + refs: &[Picture], + col_ref_id: i32, + vscale: u8, +) -> i8 { + // Picture ids step by 4: a field id is its frame's id + 1 + parity. + let field_mb = ctx.pos.active && ctx.pos.field; + let want = match vscale { + // The field of the referenced frame with the current picture's (or + // macroblock's) parity. + COL_FRM_TO_FLD => col_ref_id + i32::from(ctx.mb_parity), + // A field macroblock of an MBAFF frame names the field of the frame + // the co-located field macroblock referenced that has its own parity. + _ if field_mb && MBAFF_ONE_TO_ONE_SAME_PARITY => { + (col_ref_id & !3) + i32::from(ctx.mb_parity) + } + _ => col_ref_id, + }; + let n = if field_mb { + 2 * ctx.lists[0].len() + } else { + ctx.lists[0].len() + }; + for i in 0..n { + let hit = ctx.reference(refs, 0, i as i8).is_some_and(|p| { + if vscale == COL_FLD_TO_FRM { + p.id == col_ref_id & !3 + } else { + p.id == want + } + }); + if hit { + return i as i8; + } + } + 0 +} + +/// Whether a field macroblock of an MBAFF frame whose co-located block is a +/// field macroblock maps the referenced field to the field of the same parity +/// as itself (true) or to that very field (false). +const MBAFF_ONE_TO_ONE_SAME_PARITY: bool = false; + +/// `vertMvScale` of 8.4.1.2.1. +const COL_ONE_TO_ONE: u8 = 0; +const COL_FRM_TO_FLD: u8 = 1; +const COL_FLD_TO_FRM: u8 = 2; + +/// [`colocated`] for a frame macroblock or field macroblock of an MBAFF frame. +#[inline(never)] +fn colocated_mbaff( + ctx: &SliceCtx, + refs: &[Picture], + mvc: &MvCtx, + at: (usize, usize), +) -> (i32, [i16; 2], i8, u8) { + const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE); + let Some((k, _)) = ctx.lists[1].get_ref(0) else { + return NONE; + }; + let Some(store) = refs.get(k) else { + return NONE; + }; + let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); + let w = store.mb_w.max(1); + let (c, bx, by, vs) = { + let field_mb = ctx.pos.field; + let bot = mb_y & 1; + let top = mb_y & !1; + // The field of a complementary pair, or of an MBAFF frame's field + // macroblock pair, a frame macroblock takes its co-located block from. + let by_poc = + usize::from((store.fpoc[0] - ctx.poc).abs() >= (store.fpoc[1] - ctx.poc).abs()); + if store.coding == CODED_FLD { + let p = if field_mb { bot } else { by_poc }; + let Some(f) = store.fields.get(p) else { + return NONE; + }; + if field_mb { + (f, mb_x * 4 + at.0, (mb_y / 2) * 4 + at.1, COL_ONE_TO_ONE) + } else { + // mbAddrCol5 and yM = 8 * (CurrMbAddr % 2) + 4 * (yCol / 8). + let by = (mb_y / 2) * 4 + 2 * bot + at.1 / 2; + (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) + } + } else { + let col_field = store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) != 0; + match (field_mb, col_field) { + (false, false) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE), + (false, true) => { + let slot = top + by_poc; + let by = slot * 4 + 2 * bot + at.1 / 2; + (store, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) + } + (true, false) => { + let slot = top + at.1 / 2; + let by = slot * 4 + (2 * at.1) % 4; + (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) + } + (true, true) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE), + } + } + }; + let idx = by * c.mb_w.max(1) * 4 + bx; + if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 { + let list = usize::from(c.ref_id[idx][0] < 0); + ( + c.ref_id[idx][list], + c.mv[idx][list], + c.ref_idx[idx][list], + vs, + ) + } else { + (-1, [0; 2], -1, vs) + } +} + +/// The co-located block of 8.4.1.2.1 for the 4x4 block `at` of the current +/// macroblock: `(refPicCol identity, mvCol, refIdxCol, vertMvScale)`; the +/// identity is -1 for an intra block. +fn colocated( + ctx: &SliceCtx, + refs: &[Picture], + mvc: &MvCtx, + at: (usize, usize), +) -> (i32, [i16; 2], i8, u8) { + const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE); + let Some((k, _)) = ctx.lists[1].get_ref(0) else { + return NONE; + }; + let Some(store) = refs.get(k) else { + return NONE; + }; + if ctx.pos.active { + return colocated_mbaff(ctx, refs, mvc, at); + } + let Some(cur) = ctx.reference(refs, 1, 0) else { + return NONE; + }; + let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); + let w = store.mb_w.max(1); + // Table 8-6 and Table 8-8. `mb_y` is a slot row for an MBAFF frame (the + // pair is `mb_y / 2`, the macroblock of the pair `mb_y % 2`). + let (c, bx, by, vs) = if ctx.structure != FRAME { + if store.coding == CODED_FLD { + (cur, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE) + } else if store.coding == CODED_AFRM { + let top = 2 * mb_y; + if store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) == 0 { + // mbAddrCol6 = 2 * CurrMbAddr + (yCol / 8), yM = (2 * yCol) % 16. + let by = (top + at.1 / 2) * 4 + (2 * at.1) % 4; + (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) + } else { + // mbAddrCol7 = 2 * CurrMbAddr + bottom_field_flag. + let slot = top + usize::from(ctx.structure == BOTTOM); + (store, mb_x * 4 + at.0, slot * 4 + at.1, COL_ONE_TO_ONE) + } + } else { + // mbAddrCol1 and yM = (2 * yCol) % 16. + let by = (2 * mb_y + at.1 / 2) * 4 + (2 * at.1) % 4; + (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD) + } + } else if store.coding == CODED_FLD { + let top = (store.fpoc[0] - ctx.poc).abs(); + let bottom = (store.fpoc[1] - ctx.poc).abs(); + let p = usize::from(top >= bottom); + let Some(f) = store.fields.get(p) else { + return NONE; + }; + // mbAddrCol4 and yM = 8 * ((CurrMbAddr / PicWidthInMbs) % 2) + 4 * (yCol / 8). + let by = (mb_y / 2) * 4 + 2 * (mb_y % 2) + at.1 / 2; + (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM) + } else { + (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE) + }; + let idx = by * c.mb_w.max(1) * 4 + bx; + if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 { + let list = usize::from(c.ref_id[idx][0] < 0); + ( + c.ref_id[idx][list], + c.mv[idx][list], + c.ref_idx[idx][list], + vs, + ) + } else { + (-1, [0; 2], -1, vs) + } +} + diff --git a/crates/ec-h264/src/enc/analysis.rs b/crates/ec-h264/src/enc/analysis.rs new file mode 100644 index 00000000..dcf4e226 --- /dev/null +++ b/crates/ec-h264/src/enc/analysis.rs @@ -0,0 +1,141 @@ +use super::mb; +use super::mb::Source; + +/// Everything one band worker needs. +/// Mean absolute neighbour difference of one plane, horizontal and vertical +/// averaged, over the `w` by `h` samples at the top left of `plane`. +pub(super) fn mean_gradient(plane: &[u8], stride: usize, w: usize, h: usize) -> f64 { + let (mut sum, mut n) = (0u64, 0u64); + for y in 0..h { + let row = &plane[y * stride..y * stride + w]; + for x in 1..w { + sum += u64::from(row[x].abs_diff(row[x - 1])); + n += 1; + } + if y > 0 { + let prev = &plane[(y - 1) * stride..(y - 1) * stride + w]; + for x in 0..w { + sum += u64::from(row[x].abs_diff(prev[x])); + n += 1; + } + } + } + if n == 0 { 0.0 } else { sum as f64 / n as f64 } +} + +/// `chroma_qp_index_offset` for a source, from how textured its chroma is +/// relative to its luma. +/// +/// A negative offset spends bits on chroma that luma would otherwise take. +/// That pays when the chroma planes are flat — screen capture, phone video, +/// anything with large constant-hue areas — because their few edges are what +/// the eye reads, and it loses on film, whose chroma carries as much detail as +/// its luma and whose luma is the better place for the same bits. The +/// separating statistic is the mean absolute sample gradient of the chroma +/// planes over that of luma, measured on the first source picture. +/// BD-PSNR-YUV against x264, GOP 10, QP 22/26/30/34, `Preset::Balanced`, over +/// nine clips of the user's library, offset 0 against offset -2: +/// +/// ```text +/// chroma/luma gradient 0 -> -2 (dB) +/// 0.013 +0.019 +/// 0.092 +0.181 +/// 0.094 +0.228 +/// 0.098 +0.014 +/// 0.118 +0.081 +/// 0.122 +0.045 +/// 0.128 +0.065 +/// 0.286 +0.011 +/// 0.911 -0.158 +/// ``` +/// +/// Every clip whose chroma is flatter than its luma gains; the one film clip, +/// whose chroma gradient is nearly its luma's, loses. The threshold sits in +/// the middle of the gap the data leaves. +pub(super) fn chroma_qp_offset_for_source(src: &Source, width: u32, height: u32) -> i32 { + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w / 2, h / 2); + let luma = mean_gradient(&src.y, src.stride, w, h); + if luma <= 0.0 { + return 0; + } + let chroma = (mean_gradient(&src.u, src.c_stride, cw, ch) + + mean_gradient(&src.v, src.c_stride, cw, ch)) + / 2.0; + if chroma / luma < CHROMA_FLAT_RATIO { + CHROMA_FLAT_QP_OFFSET + } else { + 0 + } +} + +/// Chroma is "flat" below this share of the luma gradient. +pub(super) const CHROMA_FLAT_RATIO: f64 = 0.5; + +/// The offset flat chroma is coded with. +pub(super) const CHROMA_FLAT_QP_OFFSET: i32 = -2; + +/// The Fast-preset speed settings: the defaults, with `EC_H264_INTRA_GATE` +/// (a number) and `EC_H264_SKIP_I8` (any value but 0 skips Intra_8x8) as +/// sweep overrides. Read once per band, so they cost nothing per macroblock. +pub(super) fn fast_knobs() -> mb::FastKnobs { + let mut k = mb::FastKnobs::default(); + if let Some(g) = std::env::var("EC_H264_INTRA_GATE") + .ok() + .and_then(|v| v.parse().ok()) + { + k.intra_gate = g; + } + if let Ok(v) = std::env::var("EC_H264_SKIP_I8") { + k.skip_i8 = v != "0"; + } + if let Some(v) = std::env::var("EC_H264_ME_SUB") + .ok() + .and_then(|v| v.parse().ok()) + { + k.me_sub = v; + } + if let Ok(v) = std::env::var("EC_H264_ME_SATD") { + k.me_satd = v != "0"; + } + if let Some(v) = std::env::var("EC_H264_INTER_TX") + .ok() + .and_then(|v| v.parse().ok()) + { + k.inter_tx = v; + } + if let Ok(v) = std::env::var("EC_H264_LAZY_I16") { + k.lazy_i16 = v != "0"; + } + if let Some(v) = std::env::var("EC_H264_EARLY_SKIP") + .ok() + .and_then(|v| v.parse().ok()) + { + k.early_skip = v; + } + if let Some(v) = std::env::var("EC_H264_TX8_NZ") + .ok() + .and_then(|v| v.parse().ok()) + { + k.tx8_nz_limit = v; + } + if let Ok(v) = std::env::var("EC_H264_P_SKIP_I8") { + k.p_skip_i8 = v != "0"; + } + k +} + +/// Standard Lagrangian multiplier in the squared-error domain. +pub(crate) fn lambda_ssd(qp: i32) -> f64 { + 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() +} + +/// Lagrangian multiplier. Production uses the established byte-stable ladder; +/// the ablation feature can select the standard squared-error multiplier. +pub(super) fn lambda_for(qp: i32, standard: bool) -> f64 { + if standard { + lambda_ssd(qp) + } else { + (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0) + } +} diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index e72c47c9..cacec2bc 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -12,38 +12,33 @@ // the arrays instead would hide which geometry each loop names. #![allow(clippy::needless_range_loop)] +mod inter; +mod intra; +mod me; +mod residual; + +use self::inter::*; +use self::intra::*; +use self::me::*; +use self::residual::*; + use ec_h264_syntax::SliceType; -use wide::{i16x8, i16x16}; +use wide::{i16x16}; -use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line}; use crate::decoder::{ - MbNeighbors, chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, + mb_neighbors, }; -use crate::dpb::{BLK_SKIP, Picture, Plane8}; +use crate::dpb::{Picture, Plane8}; use crate::entropy::{ - BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8, - MbCtx, MbInfo, + FLAG_SKIP, MbCtx, MbInfo, }; -use crate::inter::{Put, RefPlane, integer_origin, mc_chroma, mc_luma}; -use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd}; -use crate::pred::{ - PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16, - pred_chroma_8x8, -}; -use crate::tables::{BLK4_POS, CHROMA_QP}; +use crate::tables::{CHROMA_QP}; use crate::transform::{ - LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8, - inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, - unzigzag_ac15, -}; + LevelScale4x4, LevelScale8x8, }; -use super::quant::{ - forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, - quant_4x4_offset, quant_8x8, quant_8x8_offset, quant_chroma_dc, quant_luma_dc, -}; use super::{ - entropy::{EncEntropy, sub_block_4x4}, + entropy::{EncEntropy}, lambda_ssd, }; @@ -187,144 +182,6 @@ impl Default for Levels { } } -/// 4x4 Hadamard sum of absolute transformed differences between the source at -/// `(sx, sy)` and a 4x4 prediction. -// Tried (lane-h264perf r2): a transpose-based i32x4 vectorization of this -// butterfly, bit-identical, but cycles-flat-to-worse under perf stat -// (22.958B -> 23.042B cycles over 10 reps despite fewer instructions -// retired) -- reverted, dead end; see ledger. -fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 { - // Differences are at most 255 in magnitude and the 2-D Hadamard sums 16 of - // them, so every intermediate fits an i16. - let mut d = [[0i16; 4]; 4]; - for (y, row) in d.iter_mut().enumerate() { - let s = &src[(sy + y) * sstride + sx..][..4]; - let p = &pred[y * pstride..][..4]; - for x in 0..4 { - row[x] = i16::from(s[x]) - i16::from(p[x]); - } - } - // Vertical butterflies, lane-wise over the four columns. - let mut v = [[0i16; 4]; 4]; - for x in 0..4 { - let (a, b, c, e) = (d[0][x], d[1][x], d[2][x], d[3][x]); - let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e); - v[0][x] = s0 + s1; - v[1][x] = s0 - s1; - v[2][x] = s2 + s3; - v[3][x] = s2 - s3; - } - // Horizontal butterflies per row, then the absolute sum. - let mut sum = 0i32; - for row in &v { - let (a, b, c, e) = (row[0], row[1], row[2], row[3]); - let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e); - sum += i32::from((s0 + s1).abs()) - + i32::from((s0 - s1).abs()) - + i32::from((s2 + s3).abs()) - + i32::from((s2 - s3).abs()); - } - (sum + 2) >> 2 -} - -/// SATD of a whole 16x16 luma macroblock against the prediction already in the -/// picture plane. -fn satd16( - src: &[u8], - sstride: usize, - sx: usize, - sy: usize, - plane: &[u8], - pstride: usize, - po: usize, -) -> i32 { - satd_block(src, sstride, sx, sy, plane, pstride, po, 16, 16) -} - -/// The same over a `w` x `h` partition. -#[allow(clippy::too_many_arguments)] -fn satd_block( - src: &[u8], - sstride: usize, - sx: usize, - sy: usize, - plane: &[u8], - pstride: usize, - po: usize, - w: usize, - h: usize, -) -> i32 { - let mut sum = 0; - for by in 0..h / 4 { - for bx in 0..w / 4 { - sum += satd4( - src, - sstride, - sx + bx * 4, - sy + by * 4, - &plane[po + by * 4 * pstride + bx * 4..], - pstride, - ); - } - } - sum -} - -/// Sum of absolute differences of a `w` x `h` block against a prediction with -/// its own pitch. This is the motion search's inner loop and nothing else in -/// the encoder is called as often, so a full-width row goes through one vector. -#[allow(clippy::too_many_arguments)] -fn sad( - src: &[u8], - sstride: usize, - sx: usize, - sy: usize, - pred: &[u8], - pstride: usize, - w: usize, - h: usize, -) -> i32 { - if w == 16 { - let mut acc = i16x16::ZERO; - for y in 0..h { - let a = load16(src, (sy + y) * sstride + sx); - let b = load16(pred, y * pstride); - acc += (a - b).abs(); - } - return acc.to_array().iter().map(|&v| i32::from(v)).sum(); - } - let mut sum = 0; - for y in 0..h { - let s = &src[(sy + y) * sstride + sx..]; - let p = &pred[y * pstride..]; - for x in 0..w { - sum += (i32::from(s[x]) - i32::from(p[x])).abs(); - } - } - sum -} - -/// Sum and maximum of the absolute differences between the 16x16 source block -/// at `(sx, sy)` and a 16-wide prediction. -fn sad_max16(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8]) -> (i32, i32) { - let mut acc = i16x16::ZERO; - let mut mx = i16x16::ZERO; - for y in 0..16 { - let a = load16(src, (sy + y) * sstride + sx); - let b = load16(pred, y * 16); - let d = (a - b).abs(); - acc += d; - mx = mx.max(d); - } - let sum = acc.to_array().iter().map(|&v| i32::from(v)).sum(); - let max = mx - .to_array() - .iter() - .map(|&v| i32::from(v)) - .max() - .unwrap_or(0); - (sum, max) -} /// Sixteen samples widened to 16-bit lanes; the tail past the slice is zero, /// which only a caller reading past the plane could reach. @@ -367,21 +224,6 @@ fn modes_allowed(have_top: bool, have_left: bool, have_tl: bool) -> [bool; 9] { ] } -#[inline] -fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 { - (motion_lambda(e) * bits).round() as i32 -} - -/// The multiplier `motion_rate` applies, for loops that price many vectors. -#[inline] -fn motion_lambda(e: &MbEnc<'_>) -> f64 { - if e.transform_8x8 { - e.lambda.sqrt() - } else { - e.lambda - } -} - /// Everything one macroblock's coding writes into the picture, kept so that a /// branch can be coded, measured and undone. struct MbState { @@ -643,3141 +485,3 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy } } -/// The Intra_16x16 mode this macroblock would use. Intra_16x16 against -/// Intra_4x4 is decided later, on real rate and real distortion (see -/// [`encode_intra_mb`]). -struct IntraCost { - i16_mode: u8, - /// SATD of the Intra_16x16 mode above: the cheap intra estimate that - /// `Preset::Fast` gates the full intra branch on. - satd: i32, - /// True when Intra_4x4 may be used at all for this picture and preset. - allow_i4: bool, -} - -/// Best Intra_16x16 mode by SATD, leaving nothing behind in the plane that a -/// later branch does not overwrite. -fn intra_pre_cost( - pic: &mut Picture, - e: &MbEnc<'_>, - nbr: &MbNeighbors, - mb_x: usize, - mb_y: usize, - modes: &[u8], -) -> IntraCost { - let (sx, sy) = (mb_x * 16, mb_y * 16); - let stride = pic.y.stride; - let origin = pic.y.at(sx, sy); - let mut best = (i32::MAX, 2u8); - for &mode in modes { - let ok = match mode { - 0 => nbr.b, - 1 => nbr.a, - 3 => nbr.a && nbr.b && nbr.d, - _ => true, - }; - if !ok { - continue; - } - let mut win = PlaneWindow { - data: &mut pic.y.data, - stride, - origin, - }; - pred_16x16(mode, 8, &mut win, nbr.b, nbr.a); - let cost = satd16(&e.src.y, e.src.stride, sx, sy, &pic.y.data, stride, origin); - if cost < best.0 { - best = (cost, mode); - } - } - IntraCost { - i16_mode: best.1, - satd: best.0, - // Intra_4x4 is tried in P pictures too, at every preset. Re-measured - // once the intra-versus-inter decision became a real one (BD-PSNR - // against x264, GOP 10, QP 22/26/30/34): restricting it to I pictures - // reads -1.613 dB on the film clip and -0.508 on the screen capture, - // where allowing it everywhere reads -0.728 and -0.500. It stays on - // everywhere. Under the old prediction-domain decision the screen - // capture preferred the restriction by a third of a dB; coding both - // branches for real removed that disagreement. - allow_i4: true, - } -} - -/// How much of a motion vector's signalling the search pays for. Half, which -/// is not the true rate: swept on consecutive pictures (BD-PSNR against x264, -/// GOP 10), 0.25/0.5/1.0/2.0 read -1.074/-1.043/-1.225/-1.618 on the film clip -/// and -0.676/-0.661/-0.795/-1.201 on the screen capture. Charging the whole -/// rate is worse than charging half on both contents, and the curve is flat -/// below a half and falls away above it. -const MV_BITS_WEIGHT: f64 = 0.5; - -/// Cap on whole-sample walk iterations per partition at `Preset::Fast`. -const FAST_ME_PASSES: usize = 3; - -/// The offsets the whole-sample search steps through, in units of the current -/// step size. -/// -/// A square, not a cross. The cross this used to be could only walk along an -/// axis, so a diagonally moving macroblock had to be reached in two steps -/// through a point that was worse than both -- and a step search stops at the -/// first point it cannot improve on. Adding the four diagonals is worth 0.032 -/// dB BD-PSNR-YUV on the film clip and 0.041 on the screen capture for twice -/// the candidates in the whole-sample stage, which is the cheap stage: it reads -/// the reference in place and never interpolates. -/// -/// The step the walk starts from was swept with it, at 4, 8 and 16 whole -/// samples: -0.580/-0.580/-0.593 dB on the film clip and -0.474/-0.493/-0.529 -/// on the screen capture. Four is screen capture's optimum and inside film's -/// flat part -- a wider opening step is not a wider search here, it just lands -/// the walk further from the seeds, which are already the answer most of the -/// time. -const ME_PATTERN: [(i16, i16); 8] = [ - (1, 0), - (-1, 0), - (0, 1), - (0, -1), - (1, 1), - (-1, -1), - (1, -1), - (-1, 1), -]; - -/// What the search charges P_8x8 for its own signalling, against the six bits -/// a 16x8 or 8x16 is charged: an mb_type that is one bin longer plus four -/// sub_mb_type bins, before the four predictors' own mvd. -/// -/// Swept at `Preset::Balanced` -- the only preset that searches shapes at all -/// -- on consecutive pictures against x264. Off, 6, 12 and 20 bits read -/// -0.382/-0.379/-0.377/-0.378 dB BD-PSNR on the film clip and -/// -0.369/-0.364/-0.353/-0.356 on the screen capture: both contents put the -/// optimum at twelve, and quarters are worth 0.005 dB on camera content and -/// 0.016 on screen capture. -/// -/// Re-swept once each partition was searched against its own predictor rather -/// than the macroblock's, because that changes what a split is worth: 6, 12 -/// and 20 read -0.342/-0.343/-0.346 dB on the film clip and -/// -0.322/-0.314/-0.324 on the screen capture. Twelve survives the new path. -const QUAD_BITS: f64 = 12.0; - -/// The same charge for a 16x8 or 8x16: one extra mb_type bin over P_16x16, -/// with no sub_mb_type behind it. -/// -/// Swept on the per-partition-predictor path at 3, 6 and 10 bits: -/// -0.329/-0.343/-0.358 dB on the film clip and -0.310/-0.314/-0.326 on the -/// screen capture. Both contents want the halves charged half of what the old -/// whole-macroblock predictor made them look worth -- with each half searched -/// against its own predictor its mvd is genuinely cheaper, so the search no -/// longer has to be talked out of splitting. -const HALF_BITS: f64 = 3.0; - -/// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum PShape { - /// P_L0_16x16. - Whole, - /// P_L0_L0_16x8: a top and a bottom half. - Horizontal, - /// P_L0_L0_8x16: a left and a right half. - Vertical, - /// P_8x8 with four P_L0_8x8 sub-partitions: a quarter each. - Quad, -} - -impl PShape { - /// mb_type of Table 7-13. - fn mb_type(self) -> u32 { - match self { - PShape::Whole => 0, - PShape::Horizontal => 1, - PShape::Vertical => 2, - PShape::Quad => 3, - } - } - - fn parts(self) -> usize { - match self { - PShape::Whole => 1, - PShape::Horizontal | PShape::Vertical => 2, - PShape::Quad => 4, - } - } - - /// Partition `part`'s origin in 4x4 blocks and its size in luma samples. - fn geometry(self, part: usize) -> ((usize, usize), (usize, usize)) { - match self { - PShape::Whole => ((0, 0), (16, 16)), - PShape::Horizontal => ((0, part * 2), (16, 8)), - PShape::Vertical => ((part * 2, 0), (8, 16)), - PShape::Quad => (((part % 2) * 2, (part / 2) * 2), (8, 8)), - } - } - - /// Which partition covers the 4x4 block at `(x, y)` in macroblock - /// coordinates, or `None` when the block is outside the macroblock. - fn part_of(self, x: i32, y: i32) -> Option { - if !(0..4).contains(&x) || !(0..4).contains(&y) { - return None; - } - let (x, y) = (x as usize, y as usize); - Some(match self { - PShape::Whole => 0, - PShape::Horizontal => y / 2, - PShape::Vertical => x / 2, - PShape::Quad => (y / 2) * 2 + x / 2, - }) - } - - /// `MbPartWidth`/`MbPartHeight` in 4x4 blocks, which select the - /// directional shortcuts of 8.4.1.3. - fn part_blocks(self) -> (usize, usize) { - match self { - PShape::Whole => (4, 4), - PShape::Horizontal => (4, 2), - PShape::Vertical => (2, 4), - PShape::Quad => (2, 2), - } - } -} - -/// How much the two chroma planes weigh against luma in the inter decision. -/// -/// Swept at 0, 0.25, 0.5, 1 and 2, read on BD-PSNR-YUV because a luma-only -/// metric cannot price a term whose whole purpose is chroma: the film clip -/// reads -0.653/-0.622/-0.612/-0.615/-0.626 dB and the screen capture -/// -0.517/-0.521/-0.515/-0.521/-0.546. A half is film's optimum and inside -/// screen capture's flat part; zero reproduces the chroma-blind decision -/// exactly, which is how the sweep proved the term was reaching the search. -/// -/// It is worth 0.041 dB on the film clip and nothing on the screen capture -- -/// small enough to name what it rules out. Our chroma trails x264 by 0.5-0.9 dB -/// per plane at every QP, and it is not because the vector was chosen without -/// looking: weighting chroma up lifts chroma PSNR monotonically, and past a -/// half the bits it spends cost more than the chroma it buys. -const CHROMA_ME_WEIGHT: f64 = 0.5; - -/// How many inter candidates the macroblock decision codes before choosing, -/// most promising first. One is the SATD winner alone, which is what this used -/// to do; five is every shape the search costed plus P_Skip. BD-PSNR-YUV -/// against x264 at GOP 10 over QP 22/26/30/34, at `Preset::Balanced`: -/// -/// ```text -/// film 3840x1608 screen 2560x1440 -/// 1 candidate -0.580 -0.474 -/// 2 -0.521 -0.459 -/// 3 -0.513 -0.447 -/// 5 -0.504 -0.406 -/// ``` -/// -/// monotone in the count with no turnover, so the decision is taken at the -/// full list. The SATD total that used to rank the shapes is a -/// prediction-domain estimate that never sees the residual it causes. -const SHAPE_RD_CANDIDATES: usize = 5; - -/// The inter decision for a P macroblock. -#[derive(Clone, Copy)] -struct InterChoice { - /// The candidate's SATD cost (luma plus chroma) as the shape search ranked it; - /// zero where the search did not rank it. - satd: i32, - shape: PShape, - /// One motion vector per partition. - mv: [[i16; 2]; 4], - /// The P_Skip motion vector of 8.4.1.1. - skip_mv: [i16; 2], - /// The skip candidate is at least as good as the searched one. - prefer_skip: bool, - /// The prediction is so close to the source that the macroblock is coded - /// as P_Skip without costing a residual (`Preset::Fast` only). - force_skip: bool, -} - -/// Motion search plus the skip candidate. -fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec { - let reference = e.reference.expect("a P slice has a reference"); - let ctx = MvCtx { - mb_x, - mb_y, - slice_id: e.slice_id, - written: 0, - pos: Default::default(), - }; - let n = ctx.neighbours(pic, 0, 0, 4, 0); - let mvp = predict_mv(&n, 0, 4, 4, 0); - // P_Skip (8.4.1.1): zero when either neighbour is missing or is itself a - // zero-motion reference-0 partition. - let a = ctx.at(pic, mb_x as i32 * 4 - 1, mb_y as i32 * 4, 0); - let b = ctx.at(pic, mb_x as i32 * 4, mb_y as i32 * 4 - 1, 0); - let zero = |nb: &crate::mv::Nb| nb.ref_idx == 0 && nb.mv == [0, 0]; - let skip_mv = if !a.avail || !b.avail || zero(&a) || zero(&b) { - [0, 0] - } else { - mvp - }; - - let plane = RefPlane { - data: &reference.y.data, - stride: reference.y.stride, - origin: reference.y.origin, - width: reference.y.width, - height: reference.y.height, - pad: reference.y.pad, - }; - let (sx, sy) = (mb_x * 16, mb_y * 16); - let sw = e.src.stride; - - // What the two chroma planes cost under a candidate vector, in the same - // SATD domain the luma search ranks in. The search itself cannot afford - // this -- it runs on SAD over a whole neighbourhood -- but the handful of - // candidates that survive to the shape decision can, and until they did, - // no decision in this encoder had ever looked at chroma: the vector, the - // shape and the skip flag were all chosen on luma alone and chroma was - // coded against whatever came out. Measured per plane against x264 that - // showed up as a uniform 0.5-0.9 dB chroma deficit at every QP while we - // spent more bits, which is a prediction that was never asked about. - let cplanes = [&reference.cb, &reference.cr]; - let chroma_satd = |px: usize, py: usize, w: usize, h: usize, mv: [i16; 2]| -> i32 { - if CHROMA_ME_WEIGHT == 0.0 { - return 0; - } - let mut buf = [0u8; 64]; - let mut sum = 0; - for comp in 0..2 { - let src = cplanes[comp]; - let rp = RefPlane { - data: &src.data, - stride: src.stride, - origin: src.origin, - width: src.width, - height: src.height, - pad: src.pad, - }; - let (cw, ch) = (w / 2, h / 2); - mc_chroma( - &rp, - (sx + px) as i32 / 2, - (sy + py) as i32 / 2, - mv, - cw, - ch, - cw, - &mut buf, - crate::inter::Put::Set, - ); - let plane = if comp == 0 { &e.src.u } else { &e.src.v }; - sum += satd_block( - plane, - e.src.c_stride, - (sx + px) / 2, - (sy + py) / 2, - &buf, - cw, - 0, - cw, - ch, - ); - } - (f64::from(sum) * CHROMA_ME_WEIGHT) as i32 - }; - - // Early skip: a prediction at the P_Skip vector that already sits inside - // the quantiser's dead zone codes nothing, so neither the search nor a - // residual is worth the time. Judged on luma SAD, the largest single - // difference and the chroma SATD, all against the quantiser step. - if e.preset == Preset::Fast && e.fast.early_skip > 0 { - let qstep = ((f64::from(e.qp) - 4.0) / 6.0).exp2(); - let k = f64::from(e.fast.early_skip) / 100.0; - let mut buf = [0u8; 256]; - mc_luma( - &plane, - sx as i32, - sy as i32, - skip_mv, - 16, - 16, - 16, - &mut buf, - Put::Set, - ); - let (sad_luma, max_luma) = sad_max16(&e.src.y, sw, sx, sy, &buf); - if f64::from(sad_luma) <= 256.0 * k * qstep && f64::from(max_luma) <= 4.0 * k * qstep + 2.0 - { - let c = chroma_satd(0, 0, 16, 16, skip_mv); - if f64::from(c) <= 64.0 * k * qstep * 4.0 { - return vec![InterChoice { - satd: 0, - shape: PShape::Whole, - mv: [skip_mv; 4], - skip_mv, - prefer_skip: true, - force_skip: true, - }]; - } - } - } - - let range = match e.preset { - Preset::Fast => 16i16, - Preset::Balanced => 48, - }; - - // One search over a `w` x `h` partition at `(px, py)` samples inside the - // macroblock, seeded with the candidate vectors of its neighbourhood. - let mlam = motion_lambda(e); - let search = |px: usize, py: usize, w: usize, h: usize, mvp: [i16; 2], seeds: &[[i16; 2]]| { - let (x0, y0) = (sx + px, sy + py); - let mut buf = [0u8; 256]; - // Whole-sample candidates read the reference plane in place; only the - // sub-sample refinement pays for interpolation. The search runs on SAD, - // which is what a search can afford; the winner is re-costed on SATD - // because the intra candidates are SATD and the two scales differ. - let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 { - let bits = (mlam - * f64::from( - se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1])), - ) - * MV_BITS_WEIGHT) - .round() as i32; - if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 { - let o = integer_origin( - &plane, - x0 as i32 + (mv[0] >> 2) as i32, - y0 as i32 + (mv[1] >> 2) as i32, - w, - h, - ); - return sad(&e.src.y, sw, x0, y0, &plane.data[o..], plane.stride, w, h) + bits; - } - mc_luma( - &plane, - x0 as i32, - y0 as i32, - mv, - w, - h, - w, - &mut buf, - crate::inter::Put::Set, - ); - let d = if satd { - satd_block(&e.src.y, sw, x0, y0, &buf, w, 0, w, h) - } else { - sad(&e.src.y, sw, x0, y0, &buf, w, w, h) - }; - d + bits - }; - - let fast = e.preset == Preset::Fast; - let mut best = ([0i16; 2], i32::MAX); - for (i, &cand) in seeds.iter().enumerate() { - if seeds[..i].contains(&cand) { - continue; - } - let c = cost_of(cand, false); - if c < best.1 { - best = (cand, c); - } - } - // Every partition is searched. This used to stop at a seed whose cost - // was already under half a level a sample, on the reasoning that the - // prediction fit and the search is the encoder's hot loop. Swept on - // consecutive pictures (BD-PSNR against x264, GOP 10) the threshold is - // monotonically harmful: 0/0.25/0.5/1.0 levels a sample read - // -0.586/-0.587/-0.593/-0.617 dB on the film clip and - // -0.466/-0.470/-0.468/-0.476 on the screen capture. A seed that fits - // is exactly where a little more refinement is cheap. - { - // Fast opens at two whole samples: the seeds already carry the - // neighbours' motion, so the walk only has to settle around them. - let mut step = if fast { 2i16 * 4 } else { 4i16 * 4 }; - let mut passes = 0; - while step >= 4 { - let mut improved = true; - while improved { - improved = false; - passes += 1; - if fast && passes > FAST_ME_PASSES { - break; - } - for (dx, dy) in ME_PATTERN { - let (dx, dy) = (dx * step, dy * step); - let cand = [best.0[0] + dx, best.0[1] + dy]; - if (cand[0] - mvp[0]).abs() > range * 4 - || (cand[1] - mvp[1]).abs() > range * 4 - { - continue; - } - let c = cost_of(cand, false); - if c < best.1 { - best = (cand, c); - improved = true; - } - } - } - step /= 2; - } - // Sub-sample refinement runs on SATD, not SAD: interpolation - // smooths, and a sum of absolute differences reads the smoothing - // as a better match where a transform-domain cost does not. Worth - // 0.06 dB BD-PSNR on the film clip and 0.04 dB on the screen - // capture. The whole-sample winner is re-costed in the same domain - // first so the two halves of the search compare. - let sub_satd = !fast || e.fast.me_satd; - best.1 = cost_of(best.0, sub_satd); - // Balanced iterates both sub-sample steps to convergence. Fast - // looks at each ring of eight once. - let rings: &[i16] = if !fast { - &[2, 1] - } else { - match e.fast.me_sub { - 0 => &[], - 1 => &[2], - _ => &[2, 1], - } - }; - if fast && e.fast.me_sub == 1 { - // The four half-sample neighbours on the axes, then only the - // diagonal the two winning axes point at. - let base = best; - let mut axis = [(base.0, base.1); 2]; - for (k, dirs) in [[(2i16, 0i16), (-2, 0)], [(0, 2), (0, -2)]] - .into_iter() - .enumerate() - { - for (dx, dy) in dirs { - let cand = [base.0[0] + dx, base.0[1] + dy]; - let c = cost_of(cand, sub_satd); - if c < axis[k].1 { - axis[k] = (cand, c); - } - } - } - let both = axis[0].1 < base.1 && axis[1].1 < base.1; - if both { - let cand = [axis[0].0[0], axis[1].0[1]]; - let c = cost_of(cand, sub_satd); - if c < best.1 { - best = (cand, c); - } - } - for a in axis { - if a.1 < best.1 { - best = a; - } - } - } - let rings: &[i16] = if fast && e.fast.me_sub == 1 { - &[] - } else { - rings - }; - for &step in rings { - let mut improved = true; - while improved { - improved = false; - for (dx, dy) in [ - (step, 0), - (-step, 0), - (0, step), - (0, -step), - (step, step), - (-step, -step), - (step, -step), - (-step, step), - ] { - let cand = [best.0[0] + dx, best.0[1] + dy]; - let c = cost_of(cand, sub_satd); - if c < best.1 { - best = (cand, c); - improved = !fast; - } - } - } - } - } - ( - best.0, - if !fast || e.fast.me_satd { - best.1 - } else { - cost_of(best.0, true) - }, - ) - }; - - let seeds = [mvp, skip_mv, [0, 0], n[0].mv, n[1].mv, n[2].mv]; - let (mv16, cost16) = search(0, 0, 16, 16, mvp, &seeds); - let cost16 = cost16 + chroma_satd(0, 0, 16, 16, mv16); - let skip_cost = { - let mut buf = [0u8; 256]; - mc_luma( - &plane, - sx as i32, - sy as i32, - skip_mv, - 16, - 16, - 16, - &mut buf, - Put::Set, - ); - // P_Skip's rebate is the signalling it genuinely saves. Re-measured on - // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip - // and -0.741/-0.696 on the screen capture -- the two contents disagree - // by less than the step between them, so this is the flat part. Six - // costs 0.14 dB and twelve costs 0.42. - // - // The Intra_4x4 discount above was swept with it: 0.65/0.75/0.85/1.0 - // read -1.216/-1.154/-1.182/-1.373 on film and -0.970/-0.696/-0.591/ - // -0.562 on screen capture, so three quarters is film's optimum and - // inside screen capture's flat part. - satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) + chroma_satd(0, 0, 16, 16, skip_mv) - - motion_rate(e, 2.0) - }; - - let mut best = (PShape::Whole, [mv16; 4], cost16); - // Every shape the search costed, kept so the macroblock decision can rank - // them on coded cost instead of on this SATD total (see `encode_mb`). - let mut evaluated = vec![(PShape::Whole, [mv16; 4])]; - // Halves, seeded with the whole-macroblock winner. The predictor used here - // is the whole-macroblock one rather than each half's own: the real - // predictors are derived in coding order when the choice is made, and this - // only has to rank the shapes. A macroblock the 16x16 search already fits - // is left alone — splitting it could only spend bits. - // - // Measured: two more searches per macroblock buy 0.1-0.2 dB on screen - // capture and nothing on camera content, for roughly twice the search - // time. That is a Balanced trade, not a Fast one. - // The threshold is a floor that real content clears everywhere: swept at - // 0, 0.5, 1 and 2 levels a sample it moves neither clip's BD-PSNR by a - // thousandth of a decibel, so on these sources the halves are always - // searched. It stays as a guard for content flat enough to make the two - // extra searches pure cost. - if e.preset == Preset::Balanced && cost16 > 16 * 16 { - for shape in [PShape::Horizontal, PShape::Vertical, PShape::Quad] { - // What the shape itself costs to signal: its mb_type, plus one - // sub_mb_type per quarter when it is P_8x8. - let mut total = motion_rate( - e, - if shape == PShape::Quad { - QUAD_BITS - } else { - HALF_BITS - }, - ); - let mut mvs = [[0i16; 2]; 4]; - let (pw, ph) = shape.part_blocks(); - for part in 0..shape.parts() { - let ((bx, by), (w, h)) = shape.geometry(part); - // Each partition is searched against the predictor it will - // actually be coded with (8.4.1.3), not against the whole - // macroblock's: the partitions before it in this macroblock - // are already chosen, so the neighbourhood the predictor reads - // can be completed from `mvs`. - let mut n = ctx.neighbours(pic, bx, by, pw, 0); - let inside = |x: i32, y: i32, nb: &mut crate::mv::Nb| { - if let Some(p) = shape.part_of(x, y).filter(|&p| p < part) { - *nb = crate::mv::Nb { - avail: true, - mv: mvs[p], - ref_idx: 0, - }; - } - }; - inside(bx as i32 - 1, by as i32, &mut n[0]); - inside(bx as i32, by as i32 - 1, &mut n[1]); - let cx = bx as i32 + pw as i32; - if shape.part_of(cx, by as i32 - 1).is_some() { - inside(cx, by as i32 - 1, &mut n[2]); - } else if !n[2].avail { - inside(bx as i32 - 1, by as i32 - 1, &mut n[2]); - } - let part_mvp = predict_mv(&n, 0, pw, ph, part); - let seeds = [mv16, part_mvp, mvp, skip_mv, [0, 0]]; - let (mv, cost) = search(bx * 4, by * 4, w, h, part_mvp, &seeds); - mvs[part] = mv; - total += cost + chroma_satd(bx * 4, by * 4, w, h, mv); - } - evaluated.push((shape, mvs)); - if total < best.2 { - best = (shape, mvs, total); - } - } - } - - // How often each shape actually wins. Behind an environment switch because - // it answers a question the rate gate cannot: a partition sweep that reads - // flat is either a flat knob or a path nothing enters, and only a count - // tells the two apart. It found the second -- at `Preset::Fast`, which is - // what the x264 comparison runs by default, no macroblock is ever split. - if std::env::var_os("EC_H264_SHAPE_STATS").is_some() { - static N: [std::sync::atomic::AtomicUsize; 4] = [ - std::sync::atomic::AtomicUsize::new(0), - std::sync::atomic::AtomicUsize::new(0), - std::sync::atomic::AtomicUsize::new(0), - std::sync::atomic::AtomicUsize::new(0), - ]; - let i = match best.0 { - PShape::Whole => 0, - PShape::Horizontal => 1, - PShape::Vertical => 2, - PShape::Quad => 3, - }; - let v = N[i].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; - let tot: usize = N - .iter() - .map(|n| n.load(std::sync::atomic::Ordering::Relaxed)) - .sum(); - if tot.is_multiple_of(20000) { - eprintln!( - "SHAPES whole={} horiz={} vert={} quad={} (last {i} -> {v})", - N[0].load(std::sync::atomic::Ordering::Relaxed), - N[1].load(std::sync::atomic::Ordering::Relaxed), - N[2].load(std::sync::atomic::Ordering::Relaxed), - N[3].load(std::sync::atomic::Ordering::Relaxed), - ); - } - } - let winner = InterChoice { - satd: best.2, - shape: best.0, - mv: best.1, - skip_mv, - prefer_skip: best.0 == PShape::Whole && skip_cost <= best.2, - force_skip: false, - }; - // The SATD winner first, then the shapes it beat, then the skip candidate - // when the winner is not already it. The caller codes as many of these as - // its preset allows and keeps the one with the smallest coded cost. - let mut cands = vec![winner]; - for (shape, mv) in evaluated { - if shape != winner.shape || winner.prefer_skip { - cands.push(InterChoice { - satd: 0, - shape, - mv, - skip_mv, - prefer_skip: false, - force_skip: false, - }); - } - } - if !winner.prefer_skip { - cands.push(InterChoice { - satd: skip_cost, - shape: PShape::Whole, - mv: [skip_mv; 4], - skip_mv, - prefer_skip: true, - force_skip: false, - }); - } - cands -} - -/// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock, -/// prediction already in the plane. -#[allow(clippy::too_many_arguments)] -fn code_luma_4x4( - pic: &mut Picture, - e: &MbEnc<'_>, - w: &EncEntropy, - mb_x: usize, - mb_y: usize, - qp: i32, - intra: bool, - lv: &mut Levels, -) { - let stride = pic.y.stride; - // An inter macroblock's blocks are reconstructed only after the whole - // macroblock has been quantised, because [`decimate_score`] can still take - // a block away. Intra blocks reconstruct as they go: the next block in the - // macroblock predicts from them. - let mut pending: [Option<[i32; 16]>; 16] = [None; 16]; - // Per 8x8 group, what coding its blocks buys and what it costs, for the - // group-level test below. A block with no levels contributes nothing to - // either side: its source energy stays in the reconstruction whatever the - // group decides. - let mut ssd_zero = [0i64; 4]; - let mut ssd_coded = [0i64; 4]; - let mut rate = [0f64; 4]; - for blk in 0..16 { - let (dx, dy) = BLK4_POS[blk]; - let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); - let origin = pic.y.at(x, y); - let mut d = [0i32; 16]; - for ry in 0..4 { - for rx in 0..4 { - d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) - - i32::from(pic.y.data[origin + ry * stride + rx]); - } - } - let source = d; - forward_4x4(&mut d); - let rdoq = !intra && w.is_cabac(); - let mut nz = if rdoq { - quant_4x4_offset(&d, qp, RDOQ_DEAD_ZONE, false, &mut lv.luma[blk]) - } else { - quant_4x4(&d, qp, intra, false, &mut lv.luma[blk]) - }; - if rdoq && nz != 0 { - nz = rdoq_4x4( - e, - w, - &source, - &mut lv.luma[blk], - qp, - BlockCat::Luma4x4, - false, - ); - } - lv.luma_nz[blk] = nz; - if nz == 0 { - continue; - } - let mut raster = [0i32; 16]; - unzigzag(&lv.luma[blk], &mut raster); - dequant_4x4(&mut raster, &e.ls, qp, false); - let mut resid = [0i32; 16]; - inverse_transform_4x4(&raster, &mut resid); - // Is the block worth its bits? A block whose residual barely moves the - // reconstruction is pure quantisation churn; dropping it is the cheap - // half of rate-distortion optimised quantisation, and the half that - // pays. Intra blocks are left alone: their reconstruction is what the - // next block in the macroblock predicts from. - if !rdoq - && !intra - && !worth_coding( - &source, - &resid, - &lv.luma[blk], - zero_block_lambda(e, qp, e.transform_8x8), - ) - { - lv.luma[blk] = [0; 16]; - lv.luma_nz[blk] = 0; - continue; - } - if intra { - lv.cbp_luma |= 1 << (blk >> 2); - add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid); - } else { - for i in 0..16 { - let z = i64::from(source[i]); - let c = i64::from(source[i] - resid[i]); - ssd_zero[blk >> 2] += z * z; - ssd_coded[blk >> 2] += c * c; - } - rate[blk >> 2] += - match w.residual_block_cost(&lv.luma[blk], BlockCat::Luma4x4, Some(1), Some(1)) { - // CABAC's own arithmetic cost for the levels, which is what - // the group is really deciding about. It arrives in 256ths of - // a bit. - Some(bits) => f64::from(bits) / 256.0, - None => block_bits(&lv.luma[blk]) as f64, - }; - pending[blk] = Some(resid); - } - } - if intra { - return; - } - // A block that survives its own rate-distortion test can still be the last - // coefficient standing in its 8x8 group, and then it is paying a - // coded_block_pattern bit as well as its levels. x264 decides that with a - // count of how tightly the levels cluster at the front of the scan - // (`decimate`), thresholded at four per group; swept here, that count - // wants opposite settings on the two contents -- monotonically off on - // camera grain, monotonically harder on screen capture -- because it is a - // heuristic standing in for a rate-distortion test the encoder can just - // do. So do it: a group is coded only if its blocks buy more squared error - // than their levels plus the pattern bit are worth, at the same lambda the - // per-block test uses. - // With an exact rate the lambda needs no correction factor: the group test - // uses the mode decision's own lambda where the rate is CABAC's, and falls - // back to the per-block test's discounted one where it is an estimate. - let lambda = if w.is_cabac() { - GROUP_LAMBDA * lambda_ssd(qp) - } else { - zero_block_lambda(e, qp, e.transform_8x8) - }; - for g in 0..4 { - if rate[g] == 0.0 { - continue; - } - if ssd_coded[g] as f64 + lambda * (rate[g] + CBP_BIT) < ssd_zero[g] as f64 { - continue; - } - for blk in g * 4..g * 4 + 4 { - lv.luma[blk] = [0; 16]; - lv.luma_nz[blk] = 0; - pending[blk] = None; - } - } - for blk in 0..16 { - let Some(resid) = pending[blk] else { continue }; - let (dx, dy) = BLK4_POS[blk]; - let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); - let origin = pic.y.at(x, y); - lv.cbp_luma |= 1 << (blk >> 2); - add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid); - } -} - -/// What a group of four luma blocks pays in coded_block_pattern to be coded -/// at all, in bits, on top of its own levels. -/// -/// This charge and [`GROUP_LAMBDA`] move the group test along the same axis -- -/// both make dropping a group likelier -- so only one of them is worth tuning. -/// Swept at 0, 6, 12 and 24 bits it reads -0.317/-0.335/-0.379/-0.472 dB on -/// the film clip against -0.295/-0.212/-0.191/-0.185 on the screen capture: -/// the same trade the lambda makes, at a worse exchange rate. It stays at a -/// plausible six. -const CBP_BIT: f64 = 6.0; - -/// What chroma pays to take its coded_block_pattern from one to two, in bits, -/// on top of the levels: the pattern bins themselves plus a coded_block_flag -/// for every AC block that then has to say it is empty. -/// -/// Swept at 0, 4, 8, 16, 32 and 64 bits, read on the all-plane PSNR because a -/// luma-only one cannot see what this decision spends: -0.688/-0.681/-0.659/ -/// -0.653/-0.670/-0.742 dB BD on the film clip and -0.537/-0.527/-0.530/ -/// -0.517/-0.524/-0.522 on the screen capture. Both turn over at sixteen. The -/// same sweep read on luma alone climbs all the way to +0.079 dB at 64, -/// because past the turn the test is buying luma bits by throwing chroma -/// away -- which is exactly the trade an all-plane metric exists to catch. -const CBP_CHROMA_BIT: f64 = 16.0; - -/// How much of the mode-decision lambda the group test uses. -/// -/// The 8x8 transform path was swept the same way and does not want this test -/// at all: at 0, 0.3 and 0.6 the `transform_8x8` gate reads +0.620/+0.624/ -/// +0.608 dB on the film clip and +0.007/+0.007/+0.009 on the screen capture, -/// all inside its noise. One 8x8 block is a whole coded_block_pattern group, -/// so its own zero test already decides what this one would, and `rdoq_8x8` -/// drops it outright when the levels do not survive. -/// -/// Swept at 0.25, 0.5, 0.6, 0.75, 0.9, 1.0 and 2.0 on both real clips: -/// -0.315/-0.314/-0.321/-0.335/-0.354/-0.372/-0.575 dB on the 3840x1608 film -/// clip and -0.297/-0.267/-0.252/-0.212/-0.202/-0.193/-0.277 on the 2560x1440 -/// screen capture. Screen capture has an interior optimum around one -- which -/// the same test on an estimated rate did not, it only ever wanted more -- and -/// camera grain wants less, because a grain block that scores as noise is -/// carrying signal the eye is measuring. Six tenths is the most the film clip -/// takes without losing ground, and it is worth 0.06 dB on screen capture. -const GROUP_LAMBDA: f64 = 0.6; - -/// How much of the squared-error lambda the chroma DC zero test uses. -/// -/// BD-PSNR-YUV against x264 at GOP 10 over QP 22/26/30/34, `Preset::Balanced`, -/// with the test off against a ladder of multipliers: -/// -/// ```text -/// film screen phone handheld -/// off -0.504 -0.227 -0.300 -0.886 -/// 0.25 -0.506 -0.227 -/// 0.5 -0.500 -0.220 -0.297 -0.884 -/// 0.75 -0.500 -0.223 -/// 1.0 -0.518 -0.246 -/// 2.0 -0.708 -0.566 -/// ``` -/// -/// Zeroing on squared error alone (a multiplier of 0) never fires, so the rate -/// term is the whole test; above the peak it throws away chroma the picture -/// needs. -const CHROMA_DC_LAMBDA: f64 = 0.5; - -/// Squared error of coding `levels`, in the pixels the block reconstructs to. -fn block_ssd(e: &MbEnc<'_>, source: &[i32; 16], levels: &[i32; 16], qp: i32, skip_dc: bool) -> i64 { - let mut raster = [0i32; 16]; - if skip_dc { - unzigzag_ac15(levels, &mut raster); - } else { - unzigzag(levels, &mut raster); - } - dequant_4x4(&mut raster, &e.ls, qp, skip_dc); - let mut resid = [0i32; 16]; - inverse_transform_4x4(&raster, &mut resid); - let mut ssd = 0i64; - for i in 0..16 { - let d = i64::from(source[i] - resid[i]); - ssd += d * d; - } - ssd -} - -/// How much of the mode-decision lambda rate-distortion quantisation uses. -/// -/// The bits here are the coder's own, not an estimate, so there is no -/// over-estimate to correct for and the scale starts at 1. Swept over 0.5, -/// 1.0, 1.25, 1.5 and 2.0 against x264 on a 3840x1608 film clip and a -/// 2560x1440 screen capture: the two disagree, film reading -0.607 dB at 0.5 -/// and -0.680 at 1.5 while screen capture reads -0.620 and -0.444, and 1.0 is -/// the crossing point that costs neither (-0.628 and -0.471). Table in -/// `lanes/h264x264-r2.report.md`. -const RDOQ_LAMBDA: f64 = 1.0; - -/// The dead zone rate-distortion quantisation starts from, as a divisor of the -/// quantiser step: 2 is round-to-nearest. The plain inter path uses 6, which -/// has already thrown away the levels this search would weigh -- a search -/// bounded by the heuristic it replaces measures the heuristic. This is the -/// half of the change that pays: 1/6 -> 1/2 under the same search is worth -/// 0.102 dB on the film clip and 0.301 on the synthetic gate. 1/3 and 1/4 read -/// -0.647 and -0.677 dB where 1/2 reads -0.630. -const RDOQ_DEAD_ZONE: i32 = 2; - -/// The largest level the search offers a smaller magnitude to. A big level is -/// carrying real signal and never wins by shrinking; bounding the search is -/// what keeps it free. Unbounded it tripled the synthetic clip's encode time -/// (1.08 s -> 3.53 s) for the same BD-PSNR; at 2 the run is 1.09 s. Swept over -/// 1, 2 and 3: -4.062/-0.623/-0.496, -4.073/-0.628/-0.471 and -/// -4.065/-0.629/-0.477 dB on synthetic, film and screen capture. -const RDOQ_MAX_LEVEL: i32 = 2; - -/// The rounding the chroma AC path keeps under the search: the inter dead zone -/// it already had. Luma wanted the wider 1/2 rounding once a search could take -/// levels back down (`RDOQ_DEAD_ZONE`); chroma does not. Measured on the two -/// clips at the settled luma constants, BD-PSNR against x264: 1/2 rounding -/// -0.653 film / -0.482 screen capture, 1/4 -0.623 / -0.472, 1/3 -0.644 / -/// -0.481, and the 1/6 kept here -0.593 / -0.468 -- against -0.628 / -0.471 -/// with no chroma search at all. Chroma AC is sparse enough at these -/// quantisers that offering more levels costs more bits than the search takes -/// back; what pays is only the pruning. -const RDOQ_CHROMA_DEAD_ZONE: i32 = 6; - -/// The rounding the 8x8 luma path keeps under the search. It answers the way -/// 4x4 luma did, not the way chroma did: measured as BD-PSNR of the opt-in -/// `transform_8x8` flag against flag-off, which isolates this path because the -/// flag-off curve does not run through it. Film 3840x1608 / screen capture -/// 2560x1440, no search +0.535 / +0.042, 1/6 +0.551 / --, 1/3 +0.605 / +0.075, -/// and the 1/2 kept here +0.619 / +0.067. The 8x8 blocks carry enough -/// coefficients for the extra levels to pay for themselves, as 4x4 luma's do. -const RDOQ8_DEAD_ZONE: i32 = 2; - -/// Rate-distortion quantisation of one inter luma block: each level is offered -/// the two cheaper magnitudes below it, and takes one when the squared error it -/// gives up costs less than the bits it saves. -/// -/// The rate is the CABAC coder's own price for the whole block against the -/// context state as it stands, so dropping a level is priced with the -/// significance map that follows from it — which is where most of the saving -/// is. Intra blocks stay out: their reconstruction is what the next block in -/// the macroblock predicts from, so a level changed here would move a -/// prediction the decision cannot see. -#[allow(clippy::too_many_arguments)] -fn rdoq_4x4( - e: &MbEnc<'_>, - w: &EncEntropy, - source: &[i32; 16], - levels: &mut [i32; 16], - qp: i32, - cat: BlockCat, - skip_dc: bool, -) -> u8 { - let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else { - return levels.iter().filter(|&&l| l != 0).count() as u8; - }; - let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0; - let mut cost = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits); - // Highest scanning position first: dropping the last significant level is - // what shortens the significance map, so it is tried while the levels - // above it are still gone. - for pos in (0..cat.max_num_coeff()).rev() { - let level = levels[pos]; - if level == 0 { - continue; - } - let mag = level.abs(); - if mag > RDOQ_MAX_LEVEL { - continue; - } - let mut tried = mag; - for candidate in [mag - 1, 0] { - if candidate == tried { - continue; - } - tried = candidate; - let keep = levels[pos]; - levels[pos] = candidate * level.signum(); - let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else { - unreachable!("CAVLC returned early"); - }; - let trial = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits); - if trial < cost { - cost = trial; - } else { - levels[pos] = keep; - } - } - } - // And the block as a whole: zeroing it drops the coded_block_pattern bit as - // well as every level, which no single-coefficient step can see. This is - // the same decision `worth_coding` makes for the paths without an exact - // rate, made here with one. - let zero_bits = w - .residual_block_cost(&[0; 16], cat, Some(1), Some(1)) - .expect("CABAC"); - let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum(); - if ssd_zero as f64 + lambda * f64::from(zero_bits) <= cost { - *levels = [0; 16]; - return 0; - } - levels.iter().filter(|&&l| l != 0).count() as u8 -} - -/// How much of the mode-decision lambda the zero-block test uses. -/// -/// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what -/// CAVLC spends and an over-estimate of what CABAC spends; the multiplier -/// brings the rate term back to the coder actually in force. Measured over -/// 0.0, 0.4 and 1.0 on 1080p camera and screen-capture clips: 0.4 is the only -/// one that gains on screen content (+0.13 to +0.39 dB at matched bitrate) -/// without costing camera content. -const ZERO_BLOCK_LAMBDA: f64 = 0.4; - -fn zero_block_lambda(e: &MbEnc<'_>, qp: i32, transform_8x8: bool) -> f64 { - if transform_8x8 { - e.lambda - } else { - ZERO_BLOCK_LAMBDA * lambda_ssd(qp) - } -} - -/// The rate-distortion test behind the per-block zero decision: coding the -/// block has to buy more squared error than its bits are worth. -fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], lambda: f64) -> bool { - let mut ssd_zero = 0i64; - let mut ssd_coded = 0i64; - for i in 0..source.len() { - let z = i64::from(source[i]); - let c = i64::from(source[i] - resid[i]); - ssd_zero += z * z; - ssd_coded += c * c; - } - ssd_coded as f64 + lambda * (block_bits(levels) as f64) < ssd_zero as f64 -} - -/// Predict and code the luma of an Intra_16x16 macroblock. -#[allow(clippy::too_many_arguments)] -fn code_i16_luma( - pic: &mut Picture, - e: &MbEnc<'_>, - mb_x: usize, - mb_y: usize, - qp: i32, - mode: u8, - nbr: &MbNeighbors, - lv: &mut Levels, -) { - let w4 = pic.mb_w * 4; - for dy in 0..4 { - let base = (mb_y * 4 + dy) * w4 + mb_x * 4; - pic.i4_modes[base..base + 4].fill(2); - } - let stride = pic.y.stride; - let origin = pic.y.at(mb_x * 16, mb_y * 16); - let mut win = PlaneWindow { - data: &mut pic.y.data, - stride, - origin, - }; - pred_16x16(mode, 8, &mut win, nbr.b, nbr.a); - code_luma_i16(pic, e, mb_x, mb_y, qp, lv); -} - -/// The Intra_16x16 luma path (8.5.10 in reverse then forward again). -fn code_luma_i16( - pic: &mut Picture, - e: &MbEnc<'_>, - mb_x: usize, - mb_y: usize, - qp: i32, - lv: &mut Levels, -) { - let stride = pic.y.stride; - let mut dc = [0i32; 16]; - let mut ac = [[0i32; 16]; 16]; - for blk in 0..16 { - let (dx, dy) = BLK4_POS[blk]; - let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); - let origin = pic.y.at(x, y); - let mut d = [0i32; 16]; - for ry in 0..4 { - for rx in 0..4 { - d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) - - i32::from(pic.y.data[origin + ry * stride + rx]); - } - } - forward_4x4(&mut d); - dc[dy as usize * 4 + dx as usize] = d[0]; - let nz = quant_4x4(&d, qp, true, true, &mut lv.luma[blk]); - lv.luma_nz[blk] = nz; - ac[blk] = lv.luma[blk]; - if nz > 0 { - lv.cbp_luma = 15; - } - } - if lv.cbp_luma == 0 { - for blk in 0..16 { - lv.luma[blk] = [0; 16]; - lv.luma_nz[blk] = 0; - } - } - forward_hadamard_4x4(&mut dc); - quant_luma_dc(&dc, qp, &mut lv.dc); - - // Reconstruct exactly as the decoder does: DC through 8.5.10, then each - // block's AC with the DC substituted at raster position 0. - let mut raster = [0i32; 16]; - unzigzag(&lv.dc, &mut raster); - luma_dc_transform(&mut raster, &e.ls, qp); - let dc_recon = raster; - for blk in 0..16 { - let (dx, dy) = BLK4_POS[blk]; - let dc_blk = dc_recon[dy as usize * 4 + dx as usize]; - let tc = lv.luma_nz[blk]; - if tc == 0 && dc_blk == 0 { - continue; - } - let mut raster = [0i32; 16]; - if tc > 0 { - unzigzag_ac15(&ac[blk], &mut raster); - dequant_4x4(&mut raster, &e.ls, qp, true); - } - raster[0] = dc_blk; - let mut resid = [0i32; 16]; - inverse_transform_4x4(&raster, &mut resid); - let origin = pic - .y - .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); - add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid); - } -} - -/// Chroma residual for both components (8.5.11 + the AC path). -#[allow(clippy::too_many_arguments)] -fn code_chroma( - pic: &mut Picture, - e: &MbEnc<'_>, - w: &EncEntropy, - mb_x: usize, - mb_y: usize, - qp_y: i32, - intra: bool, - lv: &mut Levels, -) { - let qp_c = chroma_qp(qp_y, e.cqo); - let mut dc_lists = [[0i32; 4]; 2]; - let mut ac = [[[0i32; 16]; 4]; 2]; - let mut srcs = [[[0i32; 16]; 4]; 2]; - let mut any_ac = false; - for comp in 0..2 { - let (plane, src) = if comp == 0 { - (&pic.cb, &e.src.u) - } else { - (&pic.cr, &e.src.v) - }; - let stride = plane.stride; - for blk in 0..4 { - let (x, y) = (mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4); - let origin = plane.at(x, y); - let mut d = [0i32; 16]; - for ry in 0..4 { - for rx in 0..4 { - d[ry * 4 + rx] = i32::from(src[(y + ry) * e.src.c_stride + x + rx]) - - i32::from(plane.data[origin + ry * stride + rx]); - } - } - let source = d; - srcs[comp][blk] = d; - forward_4x4(&mut d); - dc_lists[comp][blk] = d[0]; - let rdoq = !intra && w.is_cabac(); - let mut nz = if rdoq { - quant_4x4_offset(&d, qp_c, RDOQ_CHROMA_DEAD_ZONE, true, &mut ac[comp][blk]) - } else { - quant_4x4(&d, qp_c, intra, true, &mut ac[comp][blk]) - }; - if rdoq && nz > 0 { - nz = rdoq_4x4( - e, - w, - &source, - &mut ac[comp][blk], - qp_c, - BlockCat::ChromaAc, - true, - ); - } else if nz > 0 { - // The same zero decision as luma, against the AC part alone: - // the DC of this block travels through the 2x2 Hadamard and is - // decided with the other three. - let mut raster = [0i32; 16]; - unzigzag_ac15(&ac[comp][blk], &mut raster); - dequant_4x4(&mut raster, &e.ls, qp_c, true); - let mut resid = [0i32; 16]; - inverse_transform_4x4(&raster, &mut resid); - if !worth_coding( - &source, - &resid, - &ac[comp][blk], - zero_block_lambda(e, qp_c, e.transform_8x8), - ) { - ac[comp][blk] = [0; 16]; - nz = 0; - } - } - lv.chroma_nz[comp][blk] = nz; - if nz > 0 { - any_ac = true; - } - } - } - // The chroma pattern is one decision for all eight AC blocks: a single - // surviving block takes coded_block_pattern from one to two, and every - // other block then has to code a coded_block_flag to say it is empty. So - // the same group test luma runs over four blocks runs here over all eight, - // against the same lambda. - if any_ac { - let (mut ssd_zero, mut ssd_coded, mut rate) = (0i64, 0i64, 0f64); - for comp in 0..2 { - for blk in 0..4 { - let source = &srcs[comp][blk]; - let mut resid = [0i32; 16]; - if lv.chroma_nz[comp][blk] > 0 { - let mut raster = [0i32; 16]; - unzigzag_ac15(&ac[comp][blk], &mut raster); - dequant_4x4(&mut raster, &e.ls, qp_c, true); - inverse_transform_4x4(&raster, &mut resid); - rate += match w.residual_block_cost( - &ac[comp][blk], - BlockCat::ChromaAc, - Some(1), - Some(1), - ) { - Some(bits) => f64::from(bits) / 256.0, - None => block_bits(&ac[comp][blk]) as f64, - }; - } - for i in 0..16 { - let z = i64::from(source[i]); - let c = i64::from(source[i] - resid[i]); - ssd_zero += z * z; - ssd_coded += c * c; - } - } - } - let lambda = if w.is_cabac() { - GROUP_LAMBDA * lambda_ssd(qp_c) - } else { - zero_block_lambda(e, qp_c, false) - }; - if ssd_coded as f64 + lambda * (rate + CBP_CHROMA_BIT) >= ssd_zero as f64 { - ac = [[[0; 16]; 4]; 2]; - lv.chroma_nz = [[0; 4]; 2]; - any_ac = false; - } - } - // The chroma DC block had no zero test at all: whatever the quantiser - // produced was coded. Its four coefficients spread over all 64 samples of - // the component, and with only DC in the block the inverse transform gives - // every sample the same (dc + 32) >> 6, so the squared error zeroing costs - // is exact in one pass over the AC residual that is already reconstructed - // here. - let mut any_dc = false; - for comp in 0..2 { - forward_hadamard_2x2(&mut dc_lists[comp]); - let mut nz = quant_chroma_dc(&dc_lists[comp], qp_c, intra, &mut lv.chroma_dc[comp]); - if nz > 0 { - let mut dc = [ - lv.chroma_dc[comp][0], - lv.chroma_dc[comp][1], - lv.chroma_dc[comp][2], - lv.chroma_dc[comp][3], - ]; - chroma_dc_transform_420(&mut dc, &e.ls, qp_c); - let mut delta = 0i64; - for blk in 0..4 { - let mut resid = [0i32; 16]; - if any_ac && lv.chroma_nz[comp][blk] > 0 { - let mut raster = [0i32; 16]; - unzigzag_ac15(&ac[comp][blk], &mut raster); - dequant_4x4(&mut raster, &e.ls, qp_c, true); - inverse_transform_4x4(&raster, &mut resid); - } - let c = i64::from((dc[blk] + 32) >> 6); - let err: i64 = (0..16) - .map(|i| i64::from(srcs[comp][blk][i] - resid[i])) - .sum(); - delta += 16 * c * c - 2 * c * err; - } - let rate = match w.residual_block_cost( - &lv.chroma_dc[comp], - BlockCat::ChromaDc(comp as u8), - Some(1), - Some(1), - ) { - Some(bits) => f64::from(bits) / 256.0, - None => block_bits(&lv.chroma_dc[comp]) as f64, - }; - if delta as f64 + CHROMA_DC_LAMBDA * lambda_ssd(qp_c) * rate >= 0.0 { - lv.chroma_dc[comp] = [0; 16]; - nz = 0; - } - } - if nz > 0 { - any_dc = true; - } - } - lv.cbp_chroma = if any_ac { - 2 - } else if any_dc { - 1 - } else { - 0 - }; - if lv.cbp_chroma < 2 { - lv.chroma_nz = [[0; 4]; 2]; - } else { - lv.chroma = ac; - } - if lv.cbp_chroma == 0 { - return; - } - for comp in 0..2 { - let mut dc = [ - lv.chroma_dc[comp][0], - lv.chroma_dc[comp][1], - lv.chroma_dc[comp][2], - lv.chroma_dc[comp][3], - ]; - chroma_dc_transform_420(&mut dc, &e.ls, qp_c); - let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; - let stride = plane.stride; - for blk in 0..4 { - let tc = lv.chroma_nz[comp][blk]; - if tc == 0 && dc[blk] == 0 { - continue; - } - let mut raster = [0i32; 16]; - if tc > 0 { - unzigzag_ac15(&lv.chroma[comp][blk], &mut raster); - dequant_4x4(&mut raster, &e.ls, qp_c, true); - } - raster[0] = dc[blk]; - let mut resid = [0i32; 16]; - inverse_transform_4x4(&raster, &mut resid); - let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4); - add_residual_4x4(&mut plane.data, 8, stride, origin, &resid); - } - } -} - -/// Code the luma of an Intra_4x4 macroblock: per block, choose the prediction -/// mode against the *reconstructed* neighbours and reconstruct it immediately, -/// because the next block predicts from it. Returns the chosen modes and the -/// modes they were predicted to be. -/// How many SATD survivors the Intra_4x4 mode decision re-costs with real -/// quantisation before choosing. -const I4_RD_CANDIDATES: usize = 3; - -fn code_intra_4x4( - pic: &mut Picture, - e: &MbEnc<'_>, - mb_x: usize, - mb_y: usize, - qp: i32, - nbr: &MbNeighbors, - lv: &mut Levels, -) -> ([u8; 16], [u8; 16]) { - let w4 = pic.mb_w * 4; - let (bx0, by0) = (mb_x * 4, mb_y * 4); - let mut modes = [2u8; 16]; - let mut pred_modes = [2u8; 16]; - for blk in 0..16 { - let (dx, dy) = BLK4_POS[blk]; - let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); - let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); - let left_avail = if dx == 0 { nbr.a } else { true }; - let top_avail = if dy == 0 { nbr.b } else { true }; - let predicted = if left_avail && top_avail { - pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx]) - } else { - 2 - }; - pred_modes[blk] = predicted; - let n = gather_nbr4(pic, nbr, blk, x, y); - let have_tl = match (dx, dy) { - (0, 0) => nbr.d, - (0, _) => nbr.a, - (_, 0) => nbr.b, - _ => true, - }; - let allowed = modes_allowed(n.have_top, n.have_left, have_tl); - let mut best = (i32::MAX, predicted.min(2)); - let mut p = [0u8; 16]; - let mut ranked = [(i32::MAX, 2u8); 9]; - for mode in 0..9u8 { - if !allowed[mode as usize] { - continue; - } - pred_4x4(mode, 8, &n, &mut p); - let bits = if mode == predicted { 1 } else { 4 }; - let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + motion_rate(e, f64::from(bits)); - ranked[mode as usize] = (c, mode); - if c < best.0 { - best = (c, mode); - } - } - let mut mode = best.1; - // SATD ranks the modes; the survivors are re-costed with the - // quantisation actually in force, because a mode that predicts a - // little worse can quantise to far fewer levels. Measured against - // x264 with `bd_psnr_vs_x264` on a 3840x1608 film clip and a 2560x1440 - // screen capture: +0.129 and +0.088 dB all-intra, +0.062 and +0.043 dB - // at GOP 10, for 3-4% encode time. Three survivors is where it - // saturates -- all nine landed within 0.002 dB of three, for 7% more - // encode time. - { - ranked.sort_unstable(); - let keep = I4_RD_CANDIDATES; - // The same over-count [`ZERO_BLOCK_LAMBDA`] corrects for: with the - // full rate term this search loses 0.065 dB instead of gaining, - // and it loses more the more candidates it sees. - let lambda = ZERO_BLOCK_LAMBDA - * if e.transform_8x8 { - e.lambda - } else { - lambda_ssd(qp) - }; - let mut best_rd = f64::MAX; - for &(c, cand) in ranked.iter().take(keep) { - if c == i32::MAX { - break; - } - pred_4x4(cand, 8, &n, &mut p); - let mut d = [0i32; 16]; - for ry in 0..4 { - for rx in 0..4 { - d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) - - i32::from(p[ry * 4 + rx]); - } - } - let src = d; - forward_4x4(&mut d); - let mut levels = [0i32; 16]; - let nz = quant_4x4(&d, qp, true, false, &mut levels); - let mut resid = [0i32; 16]; - if nz > 0 { - let mut raster = [0i32; 16]; - unzigzag(&levels, &mut raster); - dequant_4x4(&mut raster, &e.ls, qp, false); - inverse_transform_4x4(&raster, &mut resid); - } - let mut ssd = 0i64; - for i in 0..16 { - let err = i64::from(src[i] - resid[i]); - ssd += err * err; - } - let mode_bits = if cand == predicted { 1 } else { 4 }; - let bits = block_bits(&levels) + mode_bits; - let cost = ssd as f64 + lambda * bits as f64; - if cost < best_rd { - best_rd = cost; - mode = cand; - } - } - } - modes[blk] = mode; - pic.i4_modes[by * w4 + bx] = mode; - // Prediction into the plane, then residual and reconstruction. - pred_4x4(mode, 8, &n, &mut p); - let stride = pic.y.stride; - let origin = pic.y.at(x, y); - for ry in 0..4 { - let row = origin + ry * stride; - pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); - } - let mut d = [0i32; 16]; - for ry in 0..4 { - for rx in 0..4 { - d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) - - i32::from(p[ry * 4 + rx]); - } - } - forward_4x4(&mut d); - let nz = quant_4x4(&d, qp, true, false, &mut lv.luma[blk]); - lv.luma_nz[blk] = nz; - if nz > 0 { - lv.cbp_luma |= 1 << (blk >> 2); - let mut raster = [0i32; 16]; - unzigzag(&lv.luma[blk], &mut raster); - dequant_4x4(&mut raster, &e.ls, qp, false); - let mut resid = [0i32; 16]; - inverse_transform_4x4(&raster, &mut resid); - add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid); - } - } - (modes, pred_modes) -} - -/// Predicted Intra_8x8 mode of `blk8` (8.3.2.1): the decoder's rule, read -/// from the 4x4 slots every size writes its mode into. -fn predicted_mode8(pic: &Picture, nbr: &MbNeighbors, bx: usize, by: usize, blk8: usize) -> u8 { - let w4 = pic.mb_w * 4; - let left_avail = if blk8.is_multiple_of(2) { nbr.a } else { true }; - let top_avail = if blk8 < 2 { nbr.b } else { true }; - if left_avail && top_avail { - pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx]) - } else { - 2 - } -} - -/// Residual of one 8x8 luma block against the prediction already in the -/// plane: forward transform, quantise, and — when anything survives — -/// reconstruct with the decoder's own inverse. Returns the non-zero count. -#[allow(clippy::too_many_arguments)] -fn code_block_8x8( - pic: &mut Picture, - e: &MbEnc<'_>, - w: &EncEntropy, - x: usize, - y: usize, - qp: i32, - intra: bool, - out: &mut [i32; 64], -) -> u8 { - let stride = pic.y.stride; - let origin = pic.y.at(x, y); - let mut d = [0i32; 64]; - for ry in 0..8 { - for rx in 0..8 { - d[ry * 8 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) - - i32::from(pic.y.data[origin + ry * stride + rx]); - } - } - let rdoq = !intra && w.is_cabac(); - let fwd = forward_8x8(&d); - let mut nz = if rdoq { - quant_8x8_offset(&fwd, &e.ls8, qp, RDOQ8_DEAD_ZONE, out) - } else { - quant_8x8(&fwd, &e.ls8, qp, intra, out) - }; - if nz == 0 { - return 0; - } - if rdoq { - nz = rdoq_8x8(e, w, &d, out, qp); - if nz == 0 { - return 0; - } - } - let mut raster = [0i32; 64]; - unzigzag_8x8(out, &mut raster); - dequant_8x8(&mut raster, &e.ls8, qp); - let mut resid = [0i32; 64]; - inverse_transform_8x8(&raster, &mut resid); - if !rdoq && !intra && !worth_coding(&d, &resid, out, zero_block_lambda(e, qp, e.transform_8x8)) - { - *out = [0; 64]; - return 0; - } - add_residual_8x8(&mut pic.y.data, 8, stride, origin, &resid); - nz -} - -/// Code the luma of an Intra_8x8 macroblock, the 8x8 sibling of -/// [`code_intra_4x4`]: neighbours are the decoder's filtered reference -/// samples, and every 4x4 mode slot of a block carries its mode. -#[allow(clippy::too_many_arguments)] -fn code_intra_8x8( - pic: &mut Picture, - e: &MbEnc<'_>, - w: &EncEntropy, - mb_x: usize, - mb_y: usize, - qp: i32, - nbr: &MbNeighbors, - lv: &mut Levels, -) -> ([u8; 4], [u8; 4]) { - let w4 = pic.mb_w * 4; - let mut modes = [2u8; 4]; - let mut pred_modes = [2u8; 4]; - lv.trans8 = true; - for blk8 in 0..4 { - let (bx, by) = (mb_x * 4 + (blk8 % 2) * 2, mb_y * 4 + (blk8 / 2) * 2); - let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8); - let predicted = predicted_mode8(pic, nbr, bx, by, blk8); - pred_modes[blk8] = predicted; - let n = filter_nbr8(&gather_nbr8(pic, nbr, blk8, x, y)); - let allowed = modes_allowed(n.have_top, n.have_left, n.have_tl); - let mut p = [0u8; 64]; - { - let (mode, coded, recon) = - i8_mode_by_rd(pic, e, w, x, y, qp, &n, &allowed, predicted, &mut p); - let stride = pic.y.stride; - let origin = pic.y.at(x, y); - for ry in 0..8 { - let row = origin + ry * stride; - pic.y.data[row..row + 8].copy_from_slice(&recon[ry * 8..ry * 8 + 8]); - } - lv.luma8[blk8] = coded.0; - if coded.1 { - lv.cbp_luma |= 1 << blk8; - } - modes[blk8] = mode; - for dy in 0..2 { - let base = (by + dy) * w4 + bx; - pic.i4_modes[base..base + 2].fill(mode); - } - } - } - (modes, pred_modes) -} - -/// The inter residual under the 8x8 transform, prediction already in the -/// plane: the sibling of [`code_luma_4x4`]. -fn code_luma_8x8( - pic: &mut Picture, - e: &MbEnc<'_>, - w: &EncEntropy, - mb_x: usize, - mb_y: usize, - qp: i32, - lv: &mut Levels, -) { - lv.trans8 = true; - for blk8 in 0..4 { - let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8); - if code_block_8x8(pic, e, w, x, y, qp, false, &mut lv.luma8[blk8]) > 0 { - lv.cbp_luma |= 1 << blk8; - } - } -} - -/// Squared error of coding `levels` as an 8x8 block, in its pixels. -fn block_ssd_8x8(e: &MbEnc<'_>, source: &[i32; 64], levels: &[i32; 64], qp: i32) -> i64 { - let mut raster = [0i32; 64]; - unzigzag_8x8(levels, &mut raster); - dequant_8x8(&mut raster, &e.ls8, qp); - let mut resid = [0i32; 64]; - inverse_transform_8x8(&raster, &mut resid); - let mut ssd = 0i64; - for k in 0..64 { - let d = i64::from(source[k]) - i64::from(resid[k]); - ssd += d * d; - } - ssd -} - -/// [`rdoq_4x4`] for the 8x8 transform: the same walk down the scan against the -/// CABAC coder's own price, with the 8x8 block's own contexts. -fn rdoq_8x8( - e: &MbEnc<'_>, - w: &EncEntropy, - source: &[i32; 64], - levels: &mut [i32; 64], - qp: i32, -) -> u8 { - let Some(bits) = w.residual_block_8x8_cost(levels) else { - return levels.iter().filter(|&&l| l != 0).count() as u8; - }; - let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0; - let mut cost = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits); - for pos in (0..64).rev() { - let level = levels[pos]; - if level == 0 { - continue; - } - let mag = level.abs(); - if mag > RDOQ_MAX_LEVEL { - continue; - } - let mut tried = mag; - for candidate in [mag - 1, 0] { - if candidate == tried { - continue; - } - tried = candidate; - let keep = levels[pos]; - levels[pos] = candidate * level.signum(); - let bits = w - .residual_block_8x8_cost(levels) - .expect("CAVLC returned early"); - let trial = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits); - if trial < cost { - cost = trial; - } else { - levels[pos] = keep; - break; - } - } - } - // The whole block against nothing, on the same exact price. - let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum(); - if ssd_zero as f64 <= cost { - *levels = [0; 64]; - return 0; - } - levels.iter().filter(|&&l| l != 0).count() as u8 -} - -/// Squared error of the luma macroblock against the source. -fn ssd_luma(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { - let stride = pic.y.stride; - let origin = pic.y.at(mb_x * 16, mb_y * 16); - let mut sum = 0i64; - for row in 0..16 { - let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16; - for x in 0..16 { - let d = i64::from(e.src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]); - sum += d * d; - } - } - sum -} - -/// Copy the luma macroblock out of the plane, and back in. -fn save_luma(pic: &Picture, mb_x: usize, mb_y: usize, out: &mut [u8; 256]) { - let stride = pic.y.stride; - let origin = pic.y.at(mb_x * 16, mb_y * 16); - for row in 0..16 { - out[row * 16..row * 16 + 16].copy_from_slice(&pic.y.data[origin + row * stride..][..16]); - } -} - -fn restore_luma(pic: &mut Picture, mb_x: usize, mb_y: usize, src: &[u8; 256]) { - let stride = pic.y.stride; - let origin = pic.y.at(mb_x * 16, mb_y * 16); - for row in 0..16 { - pic.y.data[origin + row * stride..][..16].copy_from_slice(&src[row * 16..row * 16 + 16]); - } -} - -fn rough_intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 { - let mut bits = estimate_luma_bits(lv); - match i4 { - Some((modes, pred)) => { - bits += 6; - for blk in 0..modes.len() { - bits += if modes[blk] == pred[blk] { 1 } else { 4 }; - } - } - None => bits += 8, - } - bits -} - -fn entropy_bits(w: &EncEntropy, write: impl FnOnce(&mut EncEntropy)) -> i64 { - let mut probe = w.probe_copy(); - let before = probe.bit_len(); - write(&mut probe); - (probe.bit_len() - before) as i64 -} - -fn cost_luma_nz_pair( - pic: &Picture, - nbr: &MbNeighbors, - local: &[u8; 16], - bx0: usize, - by0: usize, - bx: usize, - by: usize, -) -> (Option, Option) { - let w4 = pic.mb_w * 4; - let left_avail = if bx.is_multiple_of(4) { nbr.a } else { true }; - let top_avail = if by.is_multiple_of(4) { nbr.b } else { true }; - let left = (left_avail && bx > 0).then(|| { - if bx > bx0 { - local[(by - by0) * 4 + (bx - bx0 - 1)] - } else { - pic.nz_y[by * w4 + bx - 1] - } - }); - let top = (top_avail && by > 0).then(|| { - if by > by0 { - local[(by - by0 - 1) * 4 + (bx - bx0)] - } else { - pic.nz_y[(by - 1) * w4 + bx] - } - }); - (left, top) -} - -fn write_luma_for_cost( - pic: &Picture, - nbr: &MbNeighbors, - w: &mut EncEntropy, - mb_x: usize, - mb_y: usize, - lv: &Levels, - is_i16: bool, -) { - let (bx0, by0) = (mb_x * 4, mb_y * 4); - let mut nz = [0u8; 16]; - if is_i16 { - let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx0, by0); - nz[0] = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb); - } - if lv.trans8 { - for blk8 in 0..4 { - let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); - if lv.cbp_luma & (1 << blk8) == 0 { - continue; - } - if w.is_cabac() { - let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None); - for dy in 0..2 { - let base = (by - by0 + dy) * 4 + bx - bx0; - nz[base..base + 2].fill(tc.min(16)); - } - } else { - for i4 in 0..4 { - let (dx, dy) = BLK4_POS[blk8 * 4 + i4]; - let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize); - let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, sx, sy); - let sub = sub_block_4x4(&lv.luma8[blk8], i4); - nz[(sy - by0) * 4 + (sx - bx0)] = - w.residual_block(&sub, BlockCat::Luma4x4, na, nb); - } - } - } - return; - } - for blk in 0..16 { - let (dx, dy) = BLK4_POS[blk]; - let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); - let group = 1 << (blk >> 2); - let coded_block = if is_i16 { - lv.cbp_luma != 0 - } else { - lv.cbp_luma & group != 0 - }; - if coded_block { - let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx, by); - let (levels, cat) = if is_i16 { - (&lv.luma[blk][..15], BlockCat::LumaAc) - } else { - (&lv.luma[blk][..16], BlockCat::Luma4x4) - }; - nz[(by - by0) * 4 + (bx - bx0)] = w.residual_block(levels, cat, na, nb); - } - } -} -#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly -fn cost_chroma_nz_pair( - pic: &Picture, - nbr: &MbNeighbors, - local: &[[u8; 4]; 2], - comp: usize, - cx0: usize, - cy0: usize, - cx: usize, - cy: usize, -) -> (Option, Option) { - let w2 = pic.mb_w * 2; - let left_avail = if cx.is_multiple_of(2) { nbr.a } else { true }; - let top_avail = if cy.is_multiple_of(2) { nbr.b } else { true }; - let left = (left_avail && cx > 0).then(|| { - if cx > cx0 { - local[comp][(cy - cy0) * 2 + (cx - cx0 - 1)] - } else { - pic.nz_c[comp][cy * w2 + cx - 1] - } - }); - let top = (top_avail && cy > 0).then(|| { - if cy > cy0 { - local[comp][(cy - cy0 - 1) * 2 + (cx - cx0)] - } else { - pic.nz_c[comp][(cy - 1) * w2 + cx] - } - }); - (left, top) -} - -fn write_chroma_for_cost( - pic: &Picture, - nbr: &MbNeighbors, - w: &mut EncEntropy, - mb_x: usize, - mb_y: usize, - lv: &Levels, -) { - if lv.cbp_chroma != 0 { - for comp in 0..2 { - w.residual_block( - &lv.chroma_dc[comp][..4], - BlockCat::ChromaDc(comp as u8), - None, - None, - ); - } - } - if lv.cbp_chroma != 2 { - return; - } - let (cx0, cy0) = (mb_x * 2, mb_y * 2); - let mut nz = [[0u8; 4]; 2]; - for comp in 0..2 { - for blk in 0..4 { - let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); - let (na, nb) = cost_chroma_nz_pair(pic, nbr, &nz, comp, cx0, cy0, cx, cy); - nz[comp][blk] = - w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb); - } - } -} - -#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly -fn intra_mb_bits( - pic: &Picture, - e: &MbEnc<'_>, - w: &EncEntropy, - mb_addr: usize, - nbr: &MbNeighbors, - lv: &Levels, - i4: Option<(&[u8], &[u8])>, - i16_mode: u8, - chroma_mode: u8, -) -> i64 { - let use_i4 = i4.is_some(); - let p_slice = e.slice_type == SliceType::P; - let offset = if p_slice { 5 } else { 0 }; - let intra_type = if use_i4 { - 0 - } else { - 1 + u32::from(i16_mode) - + 4 * u32::from(lv.cbp_chroma) - + if lv.cbp_luma != 0 { 12 } else { 0 } - }; - entropy_bits(w, |cw| { - cw.begin_mb(&e.mb_ctx); - cw.coded_mb(p_slice, e.skip_inc); - cw.set_intra(true); - cw.mb_type(p_slice, intra_type + offset); - if let Some((modes, pred)) = i4 { - if e.transform_8x8 { - cw.transform_size_8x8_flag(lv.trans8); - } - for blk in 0..modes.len() { - let rem = if modes[blk] == pred[blk] { - None - } else if modes[blk] > pred[blk] { - Some(modes[blk] - 1) - } else { - Some(modes[blk]) - }; - cw.intra4x4_pred_mode(rem); - } - } - cw.intra_chroma_pred_mode(chroma_mode); - if use_i4 { - cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true); - } - let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || !use_i4; - if coded { - cw.mb_qp_delta(e.target_qp - e.qp); - } - let mb_x = mb_addr % pic.mb_w; - let mb_y = mb_addr / pic.mb_w; - write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, !use_i4); - write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv); - }) -} - -#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly -fn inter_mb_bits( - pic: &Picture, - e: &MbEnc<'_>, - w: &EncEntropy, - mb_addr: usize, - nbr: &MbNeighbors, - shape: PShape, - mvd: &[[i16; 2]; 4], - inc: &[[usize; 2]; 4], - lv: &Levels, -) -> i64 { - entropy_bits(w, |cw| { - cw.begin_mb(&e.mb_ctx); - cw.coded_mb(true, e.skip_inc); - cw.set_intra(false); - cw.mb_type(true, shape.mb_type()); - if shape == PShape::Quad { - for _ in 0..4 { - cw.sub_mb_type_p(0); // P_L0_8x8 - } - } - for part in 0..shape.parts() { - for comp in 0..2 { - cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp])); - } - } - cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false); - if lv.cbp_luma != 0 && e.transform_8x8 { - cw.transform_size_8x8_flag(lv.trans8); - } - if lv.cbp_luma != 0 || lv.cbp_chroma != 0 { - cw.mb_qp_delta(e.target_qp - e.qp); - let mb_x = mb_addr % pic.mb_w; - let mb_y = mb_addr / pic.mb_w; - write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, false); - write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv); - } - }) -} - -/// Code an intra macroblock, choosing Intra_16x16 against Intra_4x4 on real -/// rate and real distortion. -/// -/// A SATD estimate of the 4x4 form has to predict from the source samples -/// inside the macroblock — the reconstruction it would predict from does not -/// exist until the mode is chosen — and on flat or text-heavy pictures that -/// estimate misjudges which form wins. Coding both and measuring is worth -/// more than it costs: it is 1.1 dB on screen capture at matched bitrate. -fn encode_intra_mb( - pic: &mut Picture, - e: &mut MbEnc<'_>, - w: &mut EncEntropy, - mb_addr: usize, - nbr: MbNeighbors, - cost: IntraCost, -) { - let mb_x = mb_addr % pic.mb_w; - let mb_y = mb_addr / pic.mb_w; - let w4 = pic.mb_w * 4; - let (bx0, by0) = (mb_x * 4, mb_y * 4); - let qp = e.target_qp; - write_intra_mb(pic, mb_x, mb_y); - let mut lv: Levels; - let mut modes = [2u8; 16]; - let mut pred_modes = [2u8; 16]; - let mut modes8 = [2u8; 4]; - let mut pred_modes8 = [2u8; 4]; - let mut use_i4 = false; - let mut chroma_lv = Levels::default(); - let chroma_mode = choose_chroma_mode_rd(pic, e, w, &nbr, mb_x, mb_y, qp, &mut chroma_lv); - let mut use_i8 = false; - - if cost.allow_i4 { - let mut lv4 = chroma_lv.clone(); - let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4); - let cost4 = if e.transform_8x8 { - let bits = intra_mb_bits( - pic, - e, - w, - mb_addr, - &nbr, - &lv4, - Some((&m4, &p4)), - cost.i16_mode, - chroma_mode, - ); - ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64 - + e.lambda * bits as f64 - } else { - ssd_luma(pic, e, mb_x, mb_y) as f64 - + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f64 - }; - let mut recon4 = [0u8; 256]; - save_luma(pic, mb_x, mb_y, &mut recon4); - let mut modes4 = [2u8; 16]; - for blk in 0..16 { - let (dx, dy) = BLK4_POS[blk]; - modes4[blk] = pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize]; - } - - // Intra_8x8 on the same terms, when the PPS allows it. - let mut lv8 = chroma_lv.clone(); - let mut recon8 = [0u8; 256]; - let skip8 = e.preset == Preset::Fast - && (e.fast.skip_i8 || (e.fast.p_skip_i8 && e.slice_type == SliceType::P)); - let cost8 = if e.transform_8x8 && !skip8 { - let (m8, p8) = code_intra_8x8(pic, e, w, mb_x, mb_y, qp, &nbr, &mut lv8); - modes8 = m8; - pred_modes8 = p8; - save_luma(pic, mb_x, mb_y, &mut recon8); - let bits = intra_mb_bits( - pic, - e, - w, - mb_addr, - &nbr, - &lv8, - Some((&m8, &p8)), - cost.i16_mode, - chroma_mode, - ); - ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, true, intra_bs) as f64 - + e.lambda * bits as f64 - } else { - f64::INFINITY - }; - - let mut lv16 = chroma_lv; - code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16); - let cost16 = if e.transform_8x8 { - let bits = intra_mb_bits( - pic, - e, - w, - mb_addr, - &nbr, - &lv16, - None, - cost.i16_mode, - chroma_mode, - ); - ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64 - + e.lambda * bits as f64 - } else { - ssd_luma(pic, e, mb_x, mb_y) as f64 - + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64 - }; - - if cost8 <= cost4 && cost8 <= cost16 { - use_i4 = true; - use_i8 = true; - restore_luma(pic, mb_x, mb_y, &recon8); - for blk8 in 0..4 { - for dy in 0..2 { - let base = (by0 + (blk8 / 2) * 2 + dy) * w4 + bx0 + (blk8 % 2) * 2; - pic.i4_modes[base..base + 2].fill(modes8[blk8]); - } - } - lv = lv8; - } else if cost4 <= cost16 { - use_i4 = true; - restore_luma(pic, mb_x, mb_y, &recon4); - for blk in 0..16 { - let (dx, dy) = BLK4_POS[blk]; - pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize] = modes4[blk]; - } - lv = lv4; - modes = m4; - pred_modes = p4; - } else { - lv = lv16; - } - } else { - lv = chroma_lv; - code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv); - } - - // ---- syntax ---- - w.begin_mb(&e.mb_ctx); - w.coded_mb(e.slice_type == SliceType::P, e.skip_inc); - w.set_intra(true); - let intra_type = if use_i4 { - 0 - } else { - 1 + u32::from(cost.i16_mode) - + 4 * u32::from(lv.cbp_chroma) - + if lv.cbp_luma != 0 { 12 } else { 0 } - }; - let p_slice = e.slice_type == SliceType::P; - let offset = if p_slice { 5 } else { 0 }; - w.mb_type(p_slice, intra_type + offset); - if use_i4 { - if e.transform_8x8 { - w.transform_size_8x8_flag(use_i8); - } - // prev_intra8x8_pred_mode_flag / rem_intra8x8_pred_mode share the 4x4 - // elements' binarisation and contexts (9.3.2.2, Table 9-34). - let (modes, pred_modes): (&[u8], &[u8]) = if use_i8 { - (&modes8, &pred_modes8) - } else { - (&modes, &pred_modes) - }; - for blk in 0..modes.len() { - let rem = if modes[blk] == pred_modes[blk] { - None - } else if modes[blk] > pred_modes[blk] { - Some(modes[blk] - 1) - } else { - Some(modes[blk]) - }; - w.intra4x4_pred_mode(rem); - } - } - w.intra_chroma_pred_mode(chroma_mode); - if use_i4 { - w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true); - } - finish_mb( - pic, - e, - w, - mb_addr, - &nbr, - &lv, - MbRecord { - intra: true, - is_i16: !use_i4, - chroma_mode, - qp, - }, - ); -} - -/// Eight samples widened to 16-bit lanes; the tail past the slice is zero, -/// which only a caller reading past the plane could reach. -#[inline] -fn load8(data: &[u8], at: usize) -> i16x8 { - let mut a = [0i16; 8]; - if let Some(row) = data.get(at..at + 8) { - for (o, &b) in a.iter_mut().zip(row) { - *o = i16::from(b); - } - } - i16x8::from(a) -} - -/// Squared error of the whole macroblock against the source, luma and chroma: -/// the distortion term of the skip decision. -/// -/// Each row's 16 (luma) or 8 (chroma) per-pixel differences fit in `i16` -/// (range `-255..=255`), and `dot` widens the pairwise products to `i32` -/// before summing, so this is the exact same integer value as scalar -/// `i64::from(d) * i64::from(d)` per pixel, just batched a row at a time and -/// summed into the `i64` accumulator in a different (still overflow-free, -/// so exact) order. -fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { - let mut sum = 0i64; - let stride = pic.y.stride; - let origin = pic.y.at(mb_x * 16, mb_y * 16); - for row in 0..16 { - let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16; - let d = load16(&e.src.y, s) - load16(&pic.y.data, origin + row * stride); - sum += d - .dot(d) - .to_array() - .iter() - .map(|&v| i64::from(v)) - .sum::(); - } - for comp in 0..2 { - let (plane, src) = if comp == 0 { - (&pic.cb, &e.src.u) - } else { - (&pic.cr, &e.src.v) - }; - let stride = plane.stride; - let origin = plane.at(mb_x * 8, mb_y * 8); - for row in 0..8 { - let s = (mb_y * 8 + row) * e.src.c_stride + mb_x * 8; - let d = load8(src, s) - load8(&plane.data, origin + row * stride); - sum += d - .dot(d) - .to_array() - .iter() - .map(|&v| i64::from(v)) - .sum::(); - } - } - sum -} - -/// [`ssd_mb`] with the luma half measured after the loop filter this -/// macroblock's reconstruction will get. `bs(edge, seg, vertical)` is the -/// boundary strength of one 4-sample edge segment — edge 0 the macroblock -/// edge, edges 1..3 the internal edges at offsets 4/8/12 — as the decoder -/// will derive it, so an intra candidate passes its forced 4/3 and an inter -/// candidate its own coded/motion strengths. A transform-8x8 macroblock has -/// no transform edge at luma offsets 4 and 12, so those stay unfiltered, -/// exactly as the decoder's `internal` gate decides it. Neighbours share -/// this slice's qp with the zero offsets the encoder writes, so every edge -/// is parameterised by the trial qp alone. The right and bottom edges -/// belong to macroblocks coded later and cannot be known here; the aprons -/// are the pre-filter neighbour samples, which is everything that exists at -/// decision time. The chroma half is left pre-filter: chroma never takes -/// the 8x8 transform, so it cannot separate the candidates. -/// -/// The 8x8-vs-4x4 trials are judged by this and not by [`ssd_mb`] because the -/// two candidates meet different edge sets under the same loop filter: a -/// pre-filter SSD prices the 4x4 candidate as if its extra filtered edges -/// cost nothing. -fn ssd_mb_deblocked( - pic: &Picture, - e: &MbEnc<'_>, - mb_x: usize, - mb_y: usize, - nbr: &MbNeighbors, - trans8: bool, - bs: impl Fn(usize, usize, bool) -> u8, -) -> i64 { - // The macroblock at (A, A) plus 4-sample left and top aprons: a bS-4 - // edge reads p3 and rewrites p2 on its far side. - const A: usize = 4; - const S: usize = A + 16; - let mut scratch = [0u8; S * S]; - let stride = pic.y.stride; - let origin = pic.y.at(mb_x * 16, mb_y * 16); - for row in 0..16 { - let src = origin + row * stride; - let dst = (A + row) * S + A; - scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]); - } - if nbr.a { - for row in 0..16 { - let src = origin + row * stride - A; - let dst = (A + row) * S; - scratch[dst..dst + A].copy_from_slice(&pic.y.data[src..src + A]); - } - } - if nbr.b { - for row in 0..A { - let src = origin - (A - row) * stride; - let dst = row * S + A; - scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]); - } - } - // Vertical edges left to right, then horizontal top to bottom, the order - // of 8.7.1: each edge filters what the earlier edges left behind. Each - // 4-sample segment carries its own strength, as in the decoder. - let qp = e.target_qp; - for edge in 0..4 { - let x = edge * 4; - if (edge == 0 && !nbr.a) || (trans8 && x != 0 && x != 8) { - continue; - } - for seg in 0..4 { - let s = bs(edge, seg, true); - if s == 0 { - continue; - } - let ep = edge_params(qp, 0, 0, s, 8); - for row in seg * 4..seg * 4 + 4 { - filter_luma_line(&mut scratch, 255, (A + row) * S + A + x, 1, &ep); - } - } - } - for edge in 0..4 { - let y = edge * 4; - if (edge == 0 && !nbr.b) || (trans8 && y != 0 && y != 8) { - continue; - } - let seg_bs = [ - bs(edge, 0, false), - bs(edge, 1, false), - bs(edge, 2, false), - bs(edge, 3, false), - ]; - if seg_bs[0] == seg_bs[1] && seg_bs[1] == seg_bs[2] && seg_bs[2] == seg_bs[3] { - if seg_bs[0] != 0 { - let ep = edge_params(qp, 0, 0, seg_bs[0], 8); - filter_luma_h_edge16(&mut scratch, (A + y) * S + A, S, &ep); - } - continue; - } - for seg in 0..4 { - if seg_bs[seg] == 0 { - continue; - } - let ep = edge_params(qp, 0, 0, seg_bs[seg], 8); - for col in seg * 4..seg * 4 + 4 { - filter_luma_line(&mut scratch, 255, (A + y) * S + A + col, S, &ep); - } - } - } - let mut sum = ssd_mb(pic, e, mb_x, mb_y) - ssd_luma(pic, e, mb_x, mb_y); - for row in 0..16 { - let src = (mb_y * 16 + row) * e.src.stride + mb_x * 16; - for x in 0..16 { - let d = i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]); - sum += d * d; - } - } - sum -} - -/// Boundary strengths an intra candidate forces (8.7.2.1): 4 on its -/// macroblock edges, 3 on the internal luma edges. -fn intra_bs(edge: usize, _seg: usize, _vertical: bool) -> u8 { - if edge == 0 { 4 } else { 3 } -} - -/// Rough bit cost of a macroblock's luma residual. -fn estimate_luma_bits(lv: &Levels) -> i64 { - let mut bits = 0; - if lv.trans8 { - for blk8 in 0..4 { - if lv.cbp_luma & (1 << blk8) != 0 { - // A level's position costs two more bits in a 64-coefficient - // significance map than in a 16-coefficient one; measured - // against the coded size on the text clip, without this the - // estimate undercharges Intra_8x8 by ~44 bits a macroblock. - let b = &lv.luma8[blk8]; - bits += block_bits(b) + 2 * b.iter().filter(|&&l| l != 0).count() as i64; - } - } - return bits; - } - for blk in 0..16 { - if lv.cbp_luma & (1 << (blk >> 2)) != 0 { - bits += block_bits(&lv.luma[blk]); - } - } - if lv.cbp_luma == 15 { - // Intra_16x16 also carries the DC block. - bits += block_bits(&lv.dc); - } - bits -} - -/// Bits one residual block costs, to the accuracy a mode decision needs. -fn block_bits(b: &[i32]) -> i64 { - let mut n = 0i64; - for &l in b { - if l != 0 { - n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1; - } - } - if n > 0 { n + 6 } else { 2 } -} - -/// Rough bit cost of a macroblock's residual, for the skip decision: a level -/// costs its magnitude's exp-Golomb-ish width, a coded block its token. -fn estimate_bits(lv: &Levels) -> i64 { - let mut bits = 10 + estimate_luma_bits(lv); - if lv.cbp_chroma != 0 { - for comp in 0..2 { - bits += block_bits(&lv.chroma_dc[comp][..4]); - if lv.cbp_chroma == 2 { - for blk in 0..4 { - bits += block_bits(&lv.chroma[comp][blk][..15]); - } - } - } - } - bits -} - -/// Motion-compensate one partition into the picture planes. -fn compensate_part( - pic: &mut Picture, - reference: &Picture, - mb_x: usize, - mb_y: usize, - (bx, by): (usize, usize), - (w, h): (usize, usize), - mv: [i16; 2], -) { - let (x0, y0) = ((mb_x * 16 + bx * 4) as i32, (mb_y * 16 + by * 4) as i32); - let plane = RefPlane { - data: &reference.y.data, - stride: reference.y.stride, - origin: reference.y.origin, - width: reference.y.width, - height: reference.y.height, - pad: reference.y.pad, - }; - let stride = pic.y.stride; - let origin = pic.y.at(mb_x * 16 + bx * 4, mb_y * 16 + by * 4); - mc_luma( - &plane, - x0, - y0, - mv, - w, - h, - stride, - &mut pic.y.data[origin..], - Put::Set, - ); - for comp in 0..2 { - let src = if comp == 0 { - &reference.cb - } else { - &reference.cr - }; - let plane = RefPlane { - data: &src.data, - stride: src.stride, - origin: src.origin, - width: src.width, - height: src.height, - pad: src.pad, - }; - let dst = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; - let stride = dst.stride; - let origin = dst.at(mb_x * 8 + bx * 2, mb_y * 8 + by * 2); - mc_chroma( - &plane, - x0 / 2, - y0 / 2, - mv, - w / 2, - h / 2, - stride, - &mut dst.data[origin..], - Put::Set, - ); - } -} - -/// Code a P macroblock: skip, one 16x16 partition, two halves or four -/// quarters. -fn encode_inter_mb( - pic: &mut Picture, - e: &mut MbEnc<'_>, - w: &mut EncEntropy, - mb_addr: usize, - nbr: MbNeighbors, - choice: InterChoice, -) { - let mb_x = mb_addr % pic.mb_w; - let mb_y = mb_addr / pic.mb_w; - let reference = e.reference.expect("a P macroblock has a reference"); - let ref_id = reference.id; - let qp = e.target_qp; - let shape = if choice.prefer_skip { - PShape::Whole - } else { - choice.shape - }; - - // Motion vectors, their predictors and the reconstruction, partition by - // partition and in coding order: a partition's predictor reads the motion - // of the partitions before it (8.4.1.3), so the order is not free. - let mut ctx = MvCtx { - mb_x, - mb_y, - slice_id: e.slice_id, - written: 0, - pos: Default::default(), - }; - let (part_w, part_h) = shape.part_blocks(); - let mut mvd = [[0i16; 2]; 4]; - let mut inc = [[0usize; 2]; 4]; - for part in 0..shape.parts() { - let ((bx, by), (pw, ph)) = shape.geometry(part); - let mv = if choice.prefer_skip { - choice.skip_mv - } else { - choice.mv[part] - }; - let n = ctx.neighbours(pic, bx, by, part_w, 0); - let mvp = predict_mv(&n, 0, part_w, part_h, part); - // ctxIdxInc from the neighbouring partitions' absolute mvd - // (9.3.3.1.1.7), read before this partition writes its own. - let (gx, gy) = ((mb_x * 4 + bx) as i32, (mb_y * 4 + by) as i32); - for comp in 0..2 { - let sum = neighbour_mvd(pic, &ctx, gx - 1, gy, 0)[comp] - + neighbour_mvd(pic, &ctx, gx, gy - 1, 0)[comp]; - inc[part][comp] = if sum > 32 { - 2 - } else if sum > 2 { - 1 - } else { - 0 - }; - } - mvd[part] = [mv[0] - mvp[0], mv[1] - mvp[1]]; - compensate_part(pic, reference, mb_x, mb_y, (bx, by), (pw, ph), mv); - for py in by..by + ph / 4 { - for px in bx..bx + pw / 4 { - write_block( - pic, - &mut ctx, - px, - py, - [mv, [0, 0]], - [0, -1], - [ref_id, -1], - 0, - ); - write_mvd(pic, mb_x, mb_y, px, py, 0, mvd[part]); - } - } - } - - // Skipping is only *available* on the P_Skip vector of a whole macroblock, - // and only worth taking when the residual it drops is worth less than the - // bits it saves: on static content a macroblock whose residual is pure - // quantisation churn costs bits every picture and improves nothing. - let may_skip = choice.prefer_skip; - let (lv, skip) = if choice.force_skip { - (Levels::default(), true) - } else { - let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y)); - let mut chroma_lv = Levels::default(); - code_chroma(pic, e, w, mb_x, mb_y, qp, false, &mut chroma_lv); - let mut lv = chroma_lv.clone(); - let tx_mode = if e.preset == Preset::Fast { - e.fast.inter_tx - } else { - 0 - }; - if e.transform_8x8 && tx_mode == 1 { - code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv); - } else if e.transform_8x8 && tx_mode != 2 { - // Both transform sizes on the same prediction; the cheaper - // rate-distortion cost is coded. - let mut pred = [0u8; 256]; - save_luma(pic, mb_x, mb_y, &mut pred); - let mut lv4 = chroma_lv.clone(); - code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv4); - // At Fast the 8x8 trial is only worth its time when the 4x4 coding - // left a few levels in a smooth residual: an empty one cannot be - // beaten and a dense one rarely is. - let nz4: u32 = lv4.luma_nz.iter().map(|&n| u32::from(n)).sum(); - if tx_mode == 3 && (lv4.cbp_luma == 0 || nz4 > e.fast.tx8_nz_limit) { - lv = lv4; - } else { - let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4); - let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 as f64; - let mut recon4 = [0u8; 256]; - save_luma(pic, mb_x, mb_y, &mut recon4); - restore_luma(pic, mb_x, mb_y, &pred); - let mut lv8 = chroma_lv; - code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv8); - let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8); - let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64; - if cost8 < cost4 { - lv = lv8; - } else { - lv = lv4; - restore_luma(pic, mb_x, mb_y, &recon4); - } - } - } else { - code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv); - } - let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0; - let skip = match ssd_skip { - None => false, - Some(_) if empty => true, - Some(ssd_skip) => { - let coded = if e.transform_8x8 { - let bits = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv); - ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 - } else { - ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64 - }; - if ssd_skip as f64 <= coded { - // Put the prediction back: the residual has been added to it. - compensate_part(pic, reference, mb_x, mb_y, (0, 0), (16, 16), choice.skip_mv); - true - } else { - false - } - } - }; - (lv, skip) - }; - - let w4 = pic.mb_w * 4; - if skip { - for py in 0..4 { - for px in 0..4 { - let idx = (mb_y * 4 + py) * w4 + mb_x * 4 + px; - pic.blk[idx] = BLK_SKIP; - pic.mvd_abs[idx] = [0; 4]; - } - } - for dy in 0..4 { - let base = (mb_y * 4 + dy) * w4 + mb_x * 4; - pic.nz_y[base..base + 4].fill(0); - pic.i4_modes[base..base + 4].fill(2); - } - for comp in 0..2 { - for dy in 0..2 { - let base = (mb_y * 2 + dy) * pic.mb_w * 2 + mb_x * 2; - pic.nz_c[comp][base..base + 2].fill(0); - } - } - pic.mb_qp[mb_addr] = e.qp as i8; - pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_INTER | FLAG_SKIP; - pic.mb_cbp[mb_addr] = 0; - pic.mb_dc_cbf[mb_addr] = 0; - pic.mb_slice[mb_addr] = e.slice_id; - pic.decoded_mbs += 1; - e.qp_delta_inc = 0; - w.skipped_mb(e.skip_inc); - return; - } - for dy in 0..4 { - let base = (mb_y * 4 + dy) * w4 + mb_x * 4; - pic.i4_modes[base..base + 4].fill(2); - } - - // ---- syntax ---- - w.begin_mb(&e.mb_ctx); - w.coded_mb(true, e.skip_inc); - w.set_intra(false); - w.mb_type(true, shape.mb_type()); - if shape == PShape::Quad { - for _ in 0..4 { - w.sub_mb_type_p(0); // P_L0_8x8 - } - } - // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded. - for part in 0..shape.parts() { - for comp in 0..2 { - w.mvd(comp, inc[part][comp], i32::from(mvd[part][comp])); - } - } - w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false); - // Every shape this encoder emits is 8x8-aligned, so the decoder reads the - // flag whenever luma is coded. - if lv.cbp_luma != 0 && e.transform_8x8 { - w.transform_size_8x8_flag(lv.trans8); - } - finish_mb( - pic, - e, - w, - mb_addr, - &nbr, - &lv, - MbRecord { - intra: false, - is_i16: false, - chroma_mode: 0, - qp, - }, - ); -} - -/// What the residual writer needs to know about the macroblock it closes. -struct MbRecord { - intra: bool, - is_i16: bool, - chroma_mode: u8, - /// The QP the residual was quantised at. - qp: i32, -} - -/// mb_qp_delta, the residual blocks and the per-macroblock metadata: the -/// writing half of [`crate::decoder::finish_macroblock`]. -fn finish_mb( - pic: &mut Picture, - e: &mut MbEnc<'_>, - w: &mut EncEntropy, - mb_addr: usize, - nbr: &MbNeighbors, - lv: &Levels, - m: MbRecord, -) { - let mb_x = mb_addr % pic.mb_w; - let mb_y = mb_addr / pic.mb_w; - let w4 = pic.mb_w * 4; - let w2 = pic.mb_w * 2; - let (bx0, by0) = (mb_x * 4, mb_y * 4); - let (cx0, cy0) = (mb_x * 2, mb_y * 2); - - let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || m.is_i16; - let qp_y = if coded { - let delta = m.qp - e.qp; - w.mb_qp_delta(delta); - e.qp_delta_inc = u8::from(delta != 0); - e.qp = m.qp; - m.qp - } else { - // No residual: the QP prediction chain is untouched (7.4.5), and the - // deblocking filter uses the chain value. - e.qp_delta_inc = 0; - e.qp - }; - pic.mb_qp[mb_addr] = qp_y as i8; - pic.mb_flags[mb_addr] = FLAG_DECODED - | if m.is_i16 { FLAG_I16 } else { 0 } - | if m.intra { 0 } else { FLAG_INTER } - // The flag only reaches the stream when the decoder reads it (7.3.5). - | if lv.trans8 && (m.intra || lv.cbp_luma != 0) { - FLAG_TRANS8X8 - } else { - 0 - } - | if m.intra && m.chroma_mode != 0 { - FLAG_CHROMA_PRED - } else { - 0 - }; - pic.mb_cbp[mb_addr] = lv.cbp_luma | (lv.cbp_chroma << 4); - pic.mb_slice[mb_addr] = e.slice_id; - pic.decoded_mbs += 1; - - let mut dc_cbf = 0u8; - // Luma DC (Intra_16x16 only), then the luma blocks in Z-order. - if m.is_i16 { - let (na, nb) = luma_nz_pair(pic, nbr, bx0, by0); - let tc = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb); - dc_cbf |= u8::from(tc != 0); - } - if lv.trans8 { - // The decoder's 8x8 branch: CABAC codes one cat-5 block and reports - // its count in every 4x4 slot; CAVLC codes four interleaved 4x4 - // blocks, each with its own nC and count. - for blk8 in 0..4 { - let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); - if lv.cbp_luma & (1 << blk8) == 0 { - for dy in 0..2 { - let base = (by + dy) * w4 + bx; - pic.nz_y[base..base + 2].fill(0); - } - } else if w.is_cabac() { - let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None); - for dy in 0..2 { - let base = (by + dy) * w4 + bx; - pic.nz_y[base..base + 2].fill(tc.min(16)); - } - } else { - for i4 in 0..4 { - let (dx, dy) = BLK4_POS[blk8 * 4 + i4]; - let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize); - let (na, nb) = luma_nz_pair(pic, nbr, sx, sy); - let sub = sub_block_4x4(&lv.luma8[blk8], i4); - pic.nz_y[sy * w4 + sx] = w.residual_block(&sub, BlockCat::Luma4x4, na, nb); - } - } - } - } - for blk in 0..16 { - if lv.trans8 { - break; - } - let (dx, dy) = BLK4_POS[blk]; - let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); - let group = 1 << (blk >> 2); - let coded_block = if m.is_i16 { - lv.cbp_luma != 0 - } else { - lv.cbp_luma & group != 0 - }; - let tc = if coded_block { - let (na, nb) = luma_nz_pair(pic, nbr, bx, by); - let (levels, cat) = if m.is_i16 { - (&lv.luma[blk][..15], BlockCat::LumaAc) - } else { - (&lv.luma[blk][..16], BlockCat::Luma4x4) - }; - w.residual_block(levels, cat, na, nb) - } else { - 0 - }; - pic.nz_y[by * w4 + bx] = tc; - } - // Chroma DC then chroma AC, in bitstream order. - if lv.cbp_chroma != 0 { - for comp in 0..2 { - let tc = w.residual_block( - &lv.chroma_dc[comp][..4], - BlockCat::ChromaDc(comp as u8), - None, - None, - ); - dc_cbf |= u8::from(tc != 0) << (1 + comp); - } - } - for comp in 0..2 { - for blk in 0..4 { - let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); - let tc = if lv.cbp_chroma == 2 { - let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy); - w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb) - } else { - 0 - }; - pic.nz_c[comp][cy * w2 + cx] = tc; - } - } - pic.mb_dc_cbf[mb_addr] = dc_cbf; -} - -/// Chroma prediction mode by rate-distortion: every available mode is coded -/// through the real chroma path and scored on reconstructed SSD plus the bits -/// its levels and its own name actually cost. The SATD-plus-mode-bits chooser -/// this replaced picked the mode before the quantiser had a say, which reads -/// as a chroma deficit at matched luma: measured with `bd_psnr_vs_x264` -/// against x264 `-preset medium`, BD-PSNR-YUV, GOP 10, 24 pictures: -/// -/// | clip | SATD | RD | -/// |---|---|---| -/// | 3840x1608 film | -0.500 dB | -0.443 dB | -/// | 2560x1440 screen capture | -0.220 dB | -0.146 dB | -/// | 2560x1440 screen capture, second scene | -0.571 dB | -0.538 dB | -/// | 1080p phone clip | -1.122 dB | -1.084 dB | -/// | 720p web clip | -0.606 dB | -0.572 dB | -/// -/// Luma is unmoved (film -0.065 -> -0.070 dB) and the encode time does not -/// change measurably: only intra macroblocks pay, and only four trials of the -/// chroma path each. -#[allow(clippy::too_many_arguments)] -fn choose_chroma_mode_rd( - pic: &mut Picture, - e: &MbEnc<'_>, - w: &EncEntropy, - nbr: &MbNeighbors, - mb_x: usize, - mb_y: usize, - qp: i32, - out: &mut Levels, -) -> u8 { - let qp_c = chroma_qp(qp, e.cqo); - let lambda = lambda_ssd(qp_c); - let mut best: Option<(f64, u8, Levels, [[u8; 64]; 2])> = None; - for mode in [0u8, 1, 2, 3] { - let ok = match mode { - 1 => nbr.a, - 2 => nbr.b, - 3 => nbr.a && nbr.b && nbr.d, - _ => true, - }; - if !ok { - continue; - } - for comp in 0..2 { - let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; - let stride = plane.stride; - let origin = plane.at(mb_x * 8, mb_y * 8); - let mut win = PlaneWindow { - data: &mut plane.data, - stride, - origin, - }; - pred_chroma_8x8(mode, 8, &mut win, nbr.b, nbr.a); - } - let mut lv = Levels::default(); - code_chroma(pic, e, w, mb_x, mb_y, qp, true, &mut lv); - let mut ssd = 0i64; - let mut recon = [[0u8; 64]; 2]; - for comp in 0..2 { - let (plane, src) = if comp == 0 { - (&pic.cb, &e.src.u) - } else { - (&pic.cr, &e.src.v) - }; - let origin = plane.at(mb_x * 8, mb_y * 8); - for ry in 0..8 { - for rx in 0..8 { - let r = plane.data[origin + ry * plane.stride + rx]; - recon[comp][ry * 8 + rx] = r; - let d = i64::from(src[(mb_y * 8 + ry) * e.src.c_stride + mb_x * 8 + rx]) - - i64::from(r); - ssd += d * d; - } - } - } - let mut bits = match mode { - 0 => 1.0, - 3 => 5.0, - _ => 3.0, - }; - for comp in 0..2 { - bits += match w.residual_block_cost( - &lv.chroma_dc[comp], - BlockCat::ChromaDc(comp as u8), - Some(1), - Some(1), - ) { - Some(b) => f64::from(b) / 256.0, - None => block_bits(&lv.chroma_dc[comp]) as f64, - }; - for blk in 0..4 { - bits += match w.residual_block_cost( - &lv.chroma[comp][blk], - BlockCat::ChromaAc, - Some(1), - Some(1), - ) { - Some(b) => f64::from(b) / 256.0, - None => block_bits(&lv.chroma[comp][blk]) as f64, - }; - } - } - let cost = ssd as f64 + lambda * bits; - if best.as_ref().is_none_or(|b| cost < b.0) { - best = Some((cost, mode, lv, recon)); - } - } - let (_, mode, lv, recon) = best.expect("chroma DC prediction is always available"); - for comp in 0..2 { - let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; - let stride = plane.stride; - let origin = plane.at(mb_x * 8, mb_y * 8); - for ry in 0..8 { - for rx in 0..8 { - plane.data[origin + ry * stride + rx] = recon[comp][ry * 8 + rx]; - } - } - } - *out = lv; - mode -} - -/// The mode decision of [`code_intra_8x8`]: for every allowed mode, predict, -/// code the 8x8 residual at the real QP and score `SSD + lambda * bits`, then -/// keep the cheapest. The SATD chooser this replaced scored the prediction -/// residual before the quantiser had a say, so it optimised a proxy. -/// -/// Returns the winning mode, its coded levels with whether the block has any, -/// and the reconstructed 8x8 to write back. Measured on BD-PSNR against x264 -/// with the 8x8 transform on, GOP 10, 24 consecutive pictures, luma / YUV: -/// • 3840x1608 film: +0.475 / -0.068 -> +0.512 / -0.035 -/// • 1138x640 web: +0.040 / -0.031 -> +0.076 / +0.003 -/// • 854x480 web: +0.070 / +0.047 -> +0.132 / +0.108 -/// • 2560x1440 screen: -0.206 / -0.199 -> -0.215 / -0.207 -/// Three clips of four gain; the screen capture loses 0.008 dB. Encode time -/// moves from 12 s to 13 s on the 854x480 clip. -#[allow(clippy::too_many_arguments)] -fn i8_mode_by_rd( - pic: &mut Picture, - e: &MbEnc<'_>, - w: &EncEntropy, - x: usize, - y: usize, - qp: i32, - n: &crate::pred::Nbr8, - allowed: &[bool; 9], - predicted: u8, - p: &mut [u8; 64], -) -> (u8, ([i32; 64], bool), [u8; 64]) { - let lambda = lambda_ssd(qp); - let stride = pic.y.stride; - let origin = pic.y.at(x, y); - type Best = Option<(f64, u8, [i32; 64], bool, [u8; 64])>; - let mut best: Best = None; - for mode in 0..9u8 { - if !allowed[mode as usize] { - continue; - } - pred_8x8(mode, 8, n, p); - for ry in 0..8 { - let row = origin + ry * stride; - pic.y.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]); - } - let mut levels = [0i32; 64]; - let nz = code_block_8x8(pic, e, w, x, y, qp, true, &mut levels); - let mut ssd = 0i64; - let mut recon = [0u8; 64]; - for ry in 0..8 { - let row = origin + ry * stride; - for rx in 0..8 { - let r = pic.y.data[row + rx]; - recon[ry * 8 + rx] = r; - let d = i64::from(e.src.y[(y + ry) * e.src.stride + x + rx]) - i64::from(r); - ssd += d * d; - } - } - let mut bits = if mode == predicted { 1.0 } else { 4.0 }; - if nz > 0 { - // `Luma8x8` has no coded_block_flag of its own — the CBP carries it - // — so it needs the 8x8 cost path, not the cbf-indexed one. - bits += match w.residual_block_8x8_cost(&levels) { - Some(b) => f64::from(b) / 256.0, - None => block_bits(&levels) as f64, - }; - } - let cost = ssd as f64 + lambda * bits; - if best.as_ref().is_none_or(|b| cost < b.0) { - best = Some((cost, mode, levels, nz > 0, recon)); - } - } - let (_, mode, levels, coded, recon) = - best.expect("Intra_8x8 always has at least the DC mode available"); - (mode, (levels, coded), recon) -} diff --git a/crates/ec-h264/src/enc/mb/inter.rs b/crates/ec-h264/src/enc/mb/inter.rs new file mode 100644 index 00000000..3725f573 --- /dev/null +++ b/crates/ec-h264/src/enc/mb/inter.rs @@ -0,0 +1,346 @@ +#![allow(clippy::needless_range_loop)] + + +use crate::decoder::{ + MbNeighbors, }; +use crate::dpb::{BLK_SKIP, Picture}; +use crate::entropy::{ + FLAG_DECODED, FLAG_INTER, FLAG_SKIP, }; +use crate::inter::{Put, RefPlane, mc_chroma, mc_luma}; +use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_mvd}; + + +use crate::enc::{ + entropy::{EncEntropy}, + lambda_ssd, +}; +use super::*; + +#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly +pub(super) fn inter_mb_bits( + pic: &Picture, + e: &MbEnc<'_>, + w: &EncEntropy, + mb_addr: usize, + nbr: &MbNeighbors, + shape: PShape, + mvd: &[[i16; 2]; 4], + inc: &[[usize; 2]; 4], + lv: &Levels, +) -> i64 { + entropy_bits(w, |cw| { + cw.begin_mb(&e.mb_ctx); + cw.coded_mb(true, e.skip_inc); + cw.set_intra(false); + cw.mb_type(true, shape.mb_type()); + if shape == PShape::Quad { + for _ in 0..4 { + cw.sub_mb_type_p(0); // P_L0_8x8 + } + } + for part in 0..shape.parts() { + for comp in 0..2 { + cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp])); + } + } + cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false); + if lv.cbp_luma != 0 && e.transform_8x8 { + cw.transform_size_8x8_flag(lv.trans8); + } + if lv.cbp_luma != 0 || lv.cbp_chroma != 0 { + cw.mb_qp_delta(e.target_qp - e.qp); + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, false); + write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv); + } + }) +} + +/// Motion-compensate one partition into the picture planes. +pub(super) fn compensate_part( + pic: &mut Picture, + reference: &Picture, + mb_x: usize, + mb_y: usize, + (bx, by): (usize, usize), + (w, h): (usize, usize), + mv: [i16; 2], +) { + let (x0, y0) = ((mb_x * 16 + bx * 4) as i32, (mb_y * 16 + by * 4) as i32); + let plane = RefPlane { + data: &reference.y.data, + stride: reference.y.stride, + origin: reference.y.origin, + width: reference.y.width, + height: reference.y.height, + pad: reference.y.pad, + }; + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16 + bx * 4, mb_y * 16 + by * 4); + mc_luma( + &plane, + x0, + y0, + mv, + w, + h, + stride, + &mut pic.y.data[origin..], + Put::Set, + ); + for comp in 0..2 { + let src = if comp == 0 { + &reference.cb + } else { + &reference.cr + }; + let plane = RefPlane { + data: &src.data, + stride: src.stride, + origin: src.origin, + width: src.width, + height: src.height, + pad: src.pad, + }; + let dst = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = dst.stride; + let origin = dst.at(mb_x * 8 + bx * 2, mb_y * 8 + by * 2); + mc_chroma( + &plane, + x0 / 2, + y0 / 2, + mv, + w / 2, + h / 2, + stride, + &mut dst.data[origin..], + Put::Set, + ); + } +} + +/// Code a P macroblock: skip, one 16x16 partition, two halves or four +/// quarters. +pub(super) fn encode_inter_mb( + pic: &mut Picture, + e: &mut MbEnc<'_>, + w: &mut EncEntropy, + mb_addr: usize, + nbr: MbNeighbors, + choice: InterChoice, +) { + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + let reference = e.reference.expect("a P macroblock has a reference"); + let ref_id = reference.id; + let qp = e.target_qp; + let shape = if choice.prefer_skip { + PShape::Whole + } else { + choice.shape + }; + + // Motion vectors, their predictors and the reconstruction, partition by + // partition and in coding order: a partition's predictor reads the motion + // of the partitions before it (8.4.1.3), so the order is not free. + let mut ctx = MvCtx { + mb_x, + mb_y, + slice_id: e.slice_id, + written: 0, + pos: Default::default(), + }; + let (part_w, part_h) = shape.part_blocks(); + let mut mvd = [[0i16; 2]; 4]; + let mut inc = [[0usize; 2]; 4]; + for part in 0..shape.parts() { + let ((bx, by), (pw, ph)) = shape.geometry(part); + let mv = if choice.prefer_skip { + choice.skip_mv + } else { + choice.mv[part] + }; + let n = ctx.neighbours(pic, bx, by, part_w, 0); + let mvp = predict_mv(&n, 0, part_w, part_h, part); + // ctxIdxInc from the neighbouring partitions' absolute mvd + // (9.3.3.1.1.7), read before this partition writes its own. + let (gx, gy) = ((mb_x * 4 + bx) as i32, (mb_y * 4 + by) as i32); + for comp in 0..2 { + let sum = neighbour_mvd(pic, &ctx, gx - 1, gy, 0)[comp] + + neighbour_mvd(pic, &ctx, gx, gy - 1, 0)[comp]; + inc[part][comp] = if sum > 32 { + 2 + } else if sum > 2 { + 1 + } else { + 0 + }; + } + mvd[part] = [mv[0] - mvp[0], mv[1] - mvp[1]]; + compensate_part(pic, reference, mb_x, mb_y, (bx, by), (pw, ph), mv); + for py in by..by + ph / 4 { + for px in bx..bx + pw / 4 { + write_block( + pic, + &mut ctx, + px, + py, + [mv, [0, 0]], + [0, -1], + [ref_id, -1], + 0, + ); + write_mvd(pic, mb_x, mb_y, px, py, 0, mvd[part]); + } + } + } + + // Skipping is only *available* on the P_Skip vector of a whole macroblock, + // and only worth taking when the residual it drops is worth less than the + // bits it saves: on static content a macroblock whose residual is pure + // quantisation churn costs bits every picture and improves nothing. + let may_skip = choice.prefer_skip; + let (lv, skip) = if choice.force_skip { + (Levels::default(), true) + } else { + let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y)); + let mut chroma_lv = Levels::default(); + code_chroma(pic, e, w, mb_x, mb_y, qp, false, &mut chroma_lv); + let mut lv = chroma_lv.clone(); + let tx_mode = if e.preset == Preset::Fast { + e.fast.inter_tx + } else { + 0 + }; + if e.transform_8x8 && tx_mode == 1 { + code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv); + } else if e.transform_8x8 && tx_mode != 2 { + // Both transform sizes on the same prediction; the cheaper + // rate-distortion cost is coded. + let mut pred = [0u8; 256]; + save_luma(pic, mb_x, mb_y, &mut pred); + let mut lv4 = chroma_lv.clone(); + code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv4); + // At Fast the 8x8 trial is only worth its time when the 4x4 coding + // left a few levels in a smooth residual: an empty one cannot be + // beaten and a dense one rarely is. + let nz4: u32 = lv4.luma_nz.iter().map(|&n| u32::from(n)).sum(); + if tx_mode == 3 && (lv4.cbp_luma == 0 || nz4 > e.fast.tx8_nz_limit) { + lv = lv4; + } else { + let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4); + let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 as f64; + let mut recon4 = [0u8; 256]; + save_luma(pic, mb_x, mb_y, &mut recon4); + restore_luma(pic, mb_x, mb_y, &pred); + let mut lv8 = chroma_lv; + code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv8); + let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8); + let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64; + if cost8 < cost4 { + lv = lv8; + } else { + lv = lv4; + restore_luma(pic, mb_x, mb_y, &recon4); + } + } + } else { + code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv); + } + let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0; + let skip = match ssd_skip { + None => false, + Some(_) if empty => true, + Some(ssd_skip) => { + let coded = if e.transform_8x8 { + let bits = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv); + ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 + } else { + ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64 + }; + if ssd_skip as f64 <= coded { + // Put the prediction back: the residual has been added to it. + compensate_part(pic, reference, mb_x, mb_y, (0, 0), (16, 16), choice.skip_mv); + true + } else { + false + } + } + }; + (lv, skip) + }; + + let w4 = pic.mb_w * 4; + if skip { + for py in 0..4 { + for px in 0..4 { + let idx = (mb_y * 4 + py) * w4 + mb_x * 4 + px; + pic.blk[idx] = BLK_SKIP; + pic.mvd_abs[idx] = [0; 4]; + } + } + for dy in 0..4 { + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; + pic.nz_y[base..base + 4].fill(0); + pic.i4_modes[base..base + 4].fill(2); + } + for comp in 0..2 { + for dy in 0..2 { + let base = (mb_y * 2 + dy) * pic.mb_w * 2 + mb_x * 2; + pic.nz_c[comp][base..base + 2].fill(0); + } + } + pic.mb_qp[mb_addr] = e.qp as i8; + pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_INTER | FLAG_SKIP; + pic.mb_cbp[mb_addr] = 0; + pic.mb_dc_cbf[mb_addr] = 0; + pic.mb_slice[mb_addr] = e.slice_id; + pic.decoded_mbs += 1; + e.qp_delta_inc = 0; + w.skipped_mb(e.skip_inc); + return; + } + for dy in 0..4 { + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; + pic.i4_modes[base..base + 4].fill(2); + } + + // ---- syntax ---- + w.begin_mb(&e.mb_ctx); + w.coded_mb(true, e.skip_inc); + w.set_intra(false); + w.mb_type(true, shape.mb_type()); + if shape == PShape::Quad { + for _ in 0..4 { + w.sub_mb_type_p(0); // P_L0_8x8 + } + } + // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded. + for part in 0..shape.parts() { + for comp in 0..2 { + w.mvd(comp, inc[part][comp], i32::from(mvd[part][comp])); + } + } + w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false); + // Every shape this encoder emits is 8x8-aligned, so the decoder reads the + // flag whenever luma is coded. + if lv.cbp_luma != 0 && e.transform_8x8 { + w.transform_size_8x8_flag(lv.trans8); + } + finish_mb( + pic, + e, + w, + mb_addr, + &nbr, + &lv, + MbRecord { + intra: false, + is_i16: false, + chroma_mode: 0, + qp, + }, + ); +} + diff --git a/crates/ec-h264/src/enc/mb/intra.rs b/crates/ec-h264/src/enc/mb/intra.rs new file mode 100644 index 00000000..6ccf7b85 --- /dev/null +++ b/crates/ec-h264/src/enc/mb/intra.rs @@ -0,0 +1,800 @@ +#![allow(clippy::needless_range_loop)] + +use ec_h264_syntax::SliceType; + +use crate::decoder::{ + MbNeighbors, gather_nbr4, gather_nbr8, }; +use crate::dpb::{Picture}; +use crate::entropy::{ + BlockCat, }; +use crate::mv::{write_intra_mb}; +use crate::pred::{ + PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16, + pred_chroma_8x8, +}; +use crate::tables::{BLK4_POS}; +use crate::transform::{ + dequant_4x4, dequant_8x8, + inverse_transform_4x4, inverse_transform_8x8, unzigzag, unzigzag_8x8, + }; + +use crate::enc::quant::{ + forward_4x4, forward_8x8, quant_4x4, + quant_8x8, quant_8x8_offset, }; + +use crate::enc::{ + entropy::{EncEntropy}, + lambda_ssd, +}; +use super::*; + +/// The Intra_16x16 mode this macroblock would use. Intra_16x16 against +/// Intra_4x4 is decided later, on real rate and real distortion (see +/// [`encode_intra_mb`]). +pub(super) struct IntraCost { + pub(super) i16_mode: u8, + /// SATD of the Intra_16x16 mode above: the cheap intra estimate that + /// `Preset::Fast` gates the full intra branch on. + pub(super) satd: i32, + /// True when Intra_4x4 may be used at all for this picture and preset. + pub(super) allow_i4: bool, +} + +/// Best Intra_16x16 mode by SATD, leaving nothing behind in the plane that a +/// later branch does not overwrite. +pub(super) fn intra_pre_cost( + pic: &mut Picture, + e: &MbEnc<'_>, + nbr: &MbNeighbors, + mb_x: usize, + mb_y: usize, + modes: &[u8], +) -> IntraCost { + let (sx, sy) = (mb_x * 16, mb_y * 16); + let stride = pic.y.stride; + let origin = pic.y.at(sx, sy); + let mut best = (i32::MAX, 2u8); + for &mode in modes { + let ok = match mode { + 0 => nbr.b, + 1 => nbr.a, + 3 => nbr.a && nbr.b && nbr.d, + _ => true, + }; + if !ok { + continue; + } + let mut win = PlaneWindow { + data: &mut pic.y.data, + stride, + origin, + }; + pred_16x16(mode, 8, &mut win, nbr.b, nbr.a); + let cost = satd16(&e.src.y, e.src.stride, sx, sy, &pic.y.data, stride, origin); + if cost < best.0 { + best = (cost, mode); + } + } + IntraCost { + i16_mode: best.1, + satd: best.0, + // Intra_4x4 is tried in P pictures too, at every preset. Re-measured + // once the intra-versus-inter decision became a real one (BD-PSNR + // against x264, GOP 10, QP 22/26/30/34): restricting it to I pictures + // reads -1.613 dB on the film clip and -0.508 on the screen capture, + // where allowing it everywhere reads -0.728 and -0.500. It stays on + // everywhere. Under the old prediction-domain decision the screen + // capture preferred the restriction by a third of a dB; coding both + // branches for real removed that disagreement. + allow_i4: true, + } +} + +/// Code the luma of an Intra_4x4 macroblock: per block, choose the prediction +/// mode against the *reconstructed* neighbours and reconstruct it immediately, +/// because the next block predicts from it. Returns the chosen modes and the +/// modes they were predicted to be. +/// How many SATD survivors the Intra_4x4 mode decision re-costs with real +/// quantisation before choosing. +pub(super) const I4_RD_CANDIDATES: usize = 3; + +pub(super) fn code_intra_4x4( + pic: &mut Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + qp: i32, + nbr: &MbNeighbors, + lv: &mut Levels, +) -> ([u8; 16], [u8; 16]) { + let w4 = pic.mb_w * 4; + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let mut modes = [2u8; 16]; + let mut pred_modes = [2u8; 16]; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + let left_avail = if dx == 0 { nbr.a } else { true }; + let top_avail = if dy == 0 { nbr.b } else { true }; + let predicted = if left_avail && top_avail { + pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx]) + } else { + 2 + }; + pred_modes[blk] = predicted; + let n = gather_nbr4(pic, nbr, blk, x, y); + let have_tl = match (dx, dy) { + (0, 0) => nbr.d, + (0, _) => nbr.a, + (_, 0) => nbr.b, + _ => true, + }; + let allowed = modes_allowed(n.have_top, n.have_left, have_tl); + let mut best = (i32::MAX, predicted.min(2)); + let mut p = [0u8; 16]; + let mut ranked = [(i32::MAX, 2u8); 9]; + for mode in 0..9u8 { + if !allowed[mode as usize] { + continue; + } + pred_4x4(mode, 8, &n, &mut p); + let bits = if mode == predicted { 1 } else { 4 }; + let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + motion_rate(e, f64::from(bits)); + ranked[mode as usize] = (c, mode); + if c < best.0 { + best = (c, mode); + } + } + let mut mode = best.1; + // SATD ranks the modes; the survivors are re-costed with the + // quantisation actually in force, because a mode that predicts a + // little worse can quantise to far fewer levels. Measured against + // x264 with `bd_psnr_vs_x264` on a 3840x1608 film clip and a 2560x1440 + // screen capture: +0.129 and +0.088 dB all-intra, +0.062 and +0.043 dB + // at GOP 10, for 3-4% encode time. Three survivors is where it + // saturates -- all nine landed within 0.002 dB of three, for 7% more + // encode time. + { + ranked.sort_unstable(); + let keep = I4_RD_CANDIDATES; + // The same over-count [`ZERO_BLOCK_LAMBDA`] corrects for: with the + // full rate term this search loses 0.065 dB instead of gaining, + // and it loses more the more candidates it sees. + let lambda = ZERO_BLOCK_LAMBDA + * if e.transform_8x8 { + e.lambda + } else { + lambda_ssd(qp) + }; + let mut best_rd = f64::MAX; + for &(c, cand) in ranked.iter().take(keep) { + if c == i32::MAX { + break; + } + pred_4x4(cand, 8, &n, &mut p); + let mut d = [0i32; 16]; + for ry in 0..4 { + for rx in 0..4 { + d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) + - i32::from(p[ry * 4 + rx]); + } + } + let src = d; + forward_4x4(&mut d); + let mut levels = [0i32; 16]; + let nz = quant_4x4(&d, qp, true, false, &mut levels); + let mut resid = [0i32; 16]; + if nz > 0 { + let mut raster = [0i32; 16]; + unzigzag(&levels, &mut raster); + dequant_4x4(&mut raster, &e.ls, qp, false); + inverse_transform_4x4(&raster, &mut resid); + } + let mut ssd = 0i64; + for i in 0..16 { + let err = i64::from(src[i] - resid[i]); + ssd += err * err; + } + let mode_bits = if cand == predicted { 1 } else { 4 }; + let bits = block_bits(&levels) + mode_bits; + let cost = ssd as f64 + lambda * bits as f64; + if cost < best_rd { + best_rd = cost; + mode = cand; + } + } + } + modes[blk] = mode; + pic.i4_modes[by * w4 + bx] = mode; + // Prediction into the plane, then residual and reconstruction. + pred_4x4(mode, 8, &n, &mut p); + let stride = pic.y.stride; + let origin = pic.y.at(x, y); + for ry in 0..4 { + let row = origin + ry * stride; + pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); + } + let mut d = [0i32; 16]; + for ry in 0..4 { + for rx in 0..4 { + d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) + - i32::from(p[ry * 4 + rx]); + } + } + forward_4x4(&mut d); + let nz = quant_4x4(&d, qp, true, false, &mut lv.luma[blk]); + lv.luma_nz[blk] = nz; + if nz > 0 { + lv.cbp_luma |= 1 << (blk >> 2); + let mut raster = [0i32; 16]; + unzigzag(&lv.luma[blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp, false); + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid); + } + } + (modes, pred_modes) +} + +/// Predicted Intra_8x8 mode of `blk8` (8.3.2.1): the decoder's rule, read +/// from the 4x4 slots every size writes its mode into. +pub(super) fn predicted_mode8(pic: &Picture, nbr: &MbNeighbors, bx: usize, by: usize, blk8: usize) -> u8 { + let w4 = pic.mb_w * 4; + let left_avail = if blk8.is_multiple_of(2) { nbr.a } else { true }; + let top_avail = if blk8 < 2 { nbr.b } else { true }; + if left_avail && top_avail { + pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx]) + } else { + 2 + } +} + +/// Residual of one 8x8 luma block against the prediction already in the +/// plane: forward transform, quantise, and — when anything survives — +/// reconstruct with the decoder's own inverse. Returns the non-zero count. +#[allow(clippy::too_many_arguments)] +pub(super) fn code_block_8x8( + pic: &mut Picture, + e: &MbEnc<'_>, + w: &EncEntropy, + x: usize, + y: usize, + qp: i32, + intra: bool, + out: &mut [i32; 64], +) -> u8 { + let stride = pic.y.stride; + let origin = pic.y.at(x, y); + let mut d = [0i32; 64]; + for ry in 0..8 { + for rx in 0..8 { + d[ry * 8 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) + - i32::from(pic.y.data[origin + ry * stride + rx]); + } + } + let rdoq = !intra && w.is_cabac(); + let fwd = forward_8x8(&d); + let mut nz = if rdoq { + quant_8x8_offset(&fwd, &e.ls8, qp, RDOQ8_DEAD_ZONE, out) + } else { + quant_8x8(&fwd, &e.ls8, qp, intra, out) + }; + if nz == 0 { + return 0; + } + if rdoq { + nz = rdoq_8x8(e, w, &d, out, qp); + if nz == 0 { + return 0; + } + } + let mut raster = [0i32; 64]; + unzigzag_8x8(out, &mut raster); + dequant_8x8(&mut raster, &e.ls8, qp); + let mut resid = [0i32; 64]; + inverse_transform_8x8(&raster, &mut resid); + if !rdoq && !intra && !worth_coding(&d, &resid, out, zero_block_lambda(e, qp, e.transform_8x8)) + { + *out = [0; 64]; + return 0; + } + add_residual_8x8(&mut pic.y.data, 8, stride, origin, &resid); + nz +} + +/// Code the luma of an Intra_8x8 macroblock, the 8x8 sibling of +/// [`code_intra_4x4`]: neighbours are the decoder's filtered reference +/// samples, and every 4x4 mode slot of a block carries its mode. +#[allow(clippy::too_many_arguments)] +pub(super) fn code_intra_8x8( + pic: &mut Picture, + e: &MbEnc<'_>, + w: &EncEntropy, + mb_x: usize, + mb_y: usize, + qp: i32, + nbr: &MbNeighbors, + lv: &mut Levels, +) -> ([u8; 4], [u8; 4]) { + let w4 = pic.mb_w * 4; + let mut modes = [2u8; 4]; + let mut pred_modes = [2u8; 4]; + lv.trans8 = true; + for blk8 in 0..4 { + let (bx, by) = (mb_x * 4 + (blk8 % 2) * 2, mb_y * 4 + (blk8 / 2) * 2); + let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8); + let predicted = predicted_mode8(pic, nbr, bx, by, blk8); + pred_modes[blk8] = predicted; + let n = filter_nbr8(&gather_nbr8(pic, nbr, blk8, x, y)); + let allowed = modes_allowed(n.have_top, n.have_left, n.have_tl); + let mut p = [0u8; 64]; + { + let (mode, coded, recon) = + i8_mode_by_rd(pic, e, w, x, y, qp, &n, &allowed, predicted, &mut p); + let stride = pic.y.stride; + let origin = pic.y.at(x, y); + for ry in 0..8 { + let row = origin + ry * stride; + pic.y.data[row..row + 8].copy_from_slice(&recon[ry * 8..ry * 8 + 8]); + } + lv.luma8[blk8] = coded.0; + if coded.1 { + lv.cbp_luma |= 1 << blk8; + } + modes[blk8] = mode; + for dy in 0..2 { + let base = (by + dy) * w4 + bx; + pic.i4_modes[base..base + 2].fill(mode); + } + } + } + (modes, pred_modes) +} + +#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly +pub(super) fn intra_mb_bits( + pic: &Picture, + e: &MbEnc<'_>, + w: &EncEntropy, + mb_addr: usize, + nbr: &MbNeighbors, + lv: &Levels, + i4: Option<(&[u8], &[u8])>, + i16_mode: u8, + chroma_mode: u8, +) -> i64 { + let use_i4 = i4.is_some(); + let p_slice = e.slice_type == SliceType::P; + let offset = if p_slice { 5 } else { 0 }; + let intra_type = if use_i4 { + 0 + } else { + 1 + u32::from(i16_mode) + + 4 * u32::from(lv.cbp_chroma) + + if lv.cbp_luma != 0 { 12 } else { 0 } + }; + entropy_bits(w, |cw| { + cw.begin_mb(&e.mb_ctx); + cw.coded_mb(p_slice, e.skip_inc); + cw.set_intra(true); + cw.mb_type(p_slice, intra_type + offset); + if let Some((modes, pred)) = i4 { + if e.transform_8x8 { + cw.transform_size_8x8_flag(lv.trans8); + } + for blk in 0..modes.len() { + let rem = if modes[blk] == pred[blk] { + None + } else if modes[blk] > pred[blk] { + Some(modes[blk] - 1) + } else { + Some(modes[blk]) + }; + cw.intra4x4_pred_mode(rem); + } + } + cw.intra_chroma_pred_mode(chroma_mode); + if use_i4 { + cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true); + } + let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || !use_i4; + if coded { + cw.mb_qp_delta(e.target_qp - e.qp); + } + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, !use_i4); + write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv); + }) +} + +/// Code an intra macroblock, choosing Intra_16x16 against Intra_4x4 on real +/// rate and real distortion. +/// +/// A SATD estimate of the 4x4 form has to predict from the source samples +/// inside the macroblock — the reconstruction it would predict from does not +/// exist until the mode is chosen — and on flat or text-heavy pictures that +/// estimate misjudges which form wins. Coding both and measuring is worth +/// more than it costs: it is 1.1 dB on screen capture at matched bitrate. +pub(super) fn encode_intra_mb( + pic: &mut Picture, + e: &mut MbEnc<'_>, + w: &mut EncEntropy, + mb_addr: usize, + nbr: MbNeighbors, + cost: IntraCost, +) { + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + let w4 = pic.mb_w * 4; + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let qp = e.target_qp; + write_intra_mb(pic, mb_x, mb_y); + let mut lv: Levels; + let mut modes = [2u8; 16]; + let mut pred_modes = [2u8; 16]; + let mut modes8 = [2u8; 4]; + let mut pred_modes8 = [2u8; 4]; + let mut use_i4 = false; + let mut chroma_lv = Levels::default(); + let chroma_mode = choose_chroma_mode_rd(pic, e, w, &nbr, mb_x, mb_y, qp, &mut chroma_lv); + let mut use_i8 = false; + + if cost.allow_i4 { + let mut lv4 = chroma_lv.clone(); + let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4); + let cost4 = if e.transform_8x8 { + let bits = intra_mb_bits( + pic, + e, + w, + mb_addr, + &nbr, + &lv4, + Some((&m4, &p4)), + cost.i16_mode, + chroma_mode, + ); + ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64 + + e.lambda * bits as f64 + } else { + ssd_luma(pic, e, mb_x, mb_y) as f64 + + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f64 + }; + let mut recon4 = [0u8; 256]; + save_luma(pic, mb_x, mb_y, &mut recon4); + let mut modes4 = [2u8; 16]; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + modes4[blk] = pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize]; + } + + // Intra_8x8 on the same terms, when the PPS allows it. + let mut lv8 = chroma_lv.clone(); + let mut recon8 = [0u8; 256]; + let skip8 = e.preset == Preset::Fast + && (e.fast.skip_i8 || (e.fast.p_skip_i8 && e.slice_type == SliceType::P)); + let cost8 = if e.transform_8x8 && !skip8 { + let (m8, p8) = code_intra_8x8(pic, e, w, mb_x, mb_y, qp, &nbr, &mut lv8); + modes8 = m8; + pred_modes8 = p8; + save_luma(pic, mb_x, mb_y, &mut recon8); + let bits = intra_mb_bits( + pic, + e, + w, + mb_addr, + &nbr, + &lv8, + Some((&m8, &p8)), + cost.i16_mode, + chroma_mode, + ); + ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, true, intra_bs) as f64 + + e.lambda * bits as f64 + } else { + f64::INFINITY + }; + + let mut lv16 = chroma_lv; + code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16); + let cost16 = if e.transform_8x8 { + let bits = intra_mb_bits( + pic, + e, + w, + mb_addr, + &nbr, + &lv16, + None, + cost.i16_mode, + chroma_mode, + ); + ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64 + + e.lambda * bits as f64 + } else { + ssd_luma(pic, e, mb_x, mb_y) as f64 + + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64 + }; + + if cost8 <= cost4 && cost8 <= cost16 { + use_i4 = true; + use_i8 = true; + restore_luma(pic, mb_x, mb_y, &recon8); + for blk8 in 0..4 { + for dy in 0..2 { + let base = (by0 + (blk8 / 2) * 2 + dy) * w4 + bx0 + (blk8 % 2) * 2; + pic.i4_modes[base..base + 2].fill(modes8[blk8]); + } + } + lv = lv8; + } else if cost4 <= cost16 { + use_i4 = true; + restore_luma(pic, mb_x, mb_y, &recon4); + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize] = modes4[blk]; + } + lv = lv4; + modes = m4; + pred_modes = p4; + } else { + lv = lv16; + } + } else { + lv = chroma_lv; + code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv); + } + + // ---- syntax ---- + w.begin_mb(&e.mb_ctx); + w.coded_mb(e.slice_type == SliceType::P, e.skip_inc); + w.set_intra(true); + let intra_type = if use_i4 { + 0 + } else { + 1 + u32::from(cost.i16_mode) + + 4 * u32::from(lv.cbp_chroma) + + if lv.cbp_luma != 0 { 12 } else { 0 } + }; + let p_slice = e.slice_type == SliceType::P; + let offset = if p_slice { 5 } else { 0 }; + w.mb_type(p_slice, intra_type + offset); + if use_i4 { + if e.transform_8x8 { + w.transform_size_8x8_flag(use_i8); + } + // prev_intra8x8_pred_mode_flag / rem_intra8x8_pred_mode share the 4x4 + // elements' binarisation and contexts (9.3.2.2, Table 9-34). + let (modes, pred_modes): (&[u8], &[u8]) = if use_i8 { + (&modes8, &pred_modes8) + } else { + (&modes, &pred_modes) + }; + for blk in 0..modes.len() { + let rem = if modes[blk] == pred_modes[blk] { + None + } else if modes[blk] > pred_modes[blk] { + Some(modes[blk] - 1) + } else { + Some(modes[blk]) + }; + w.intra4x4_pred_mode(rem); + } + } + w.intra_chroma_pred_mode(chroma_mode); + if use_i4 { + w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true); + } + finish_mb( + pic, + e, + w, + mb_addr, + &nbr, + &lv, + MbRecord { + intra: true, + is_i16: !use_i4, + chroma_mode, + qp, + }, + ); +} + +/// Chroma prediction mode by rate-distortion: every available mode is coded +/// through the real chroma path and scored on reconstructed SSD plus the bits +/// its levels and its own name actually cost. The SATD-plus-mode-bits chooser +/// this replaced picked the mode before the quantiser had a say, which reads +/// as a chroma deficit at matched luma: measured with `bd_psnr_vs_x264` +/// against x264 `-preset medium`, BD-PSNR-YUV, GOP 10, 24 pictures: +/// +/// | clip | SATD | RD | +/// |---|---|---| +/// | 3840x1608 film | -0.500 dB | -0.443 dB | +/// | 2560x1440 screen capture | -0.220 dB | -0.146 dB | +/// | 2560x1440 screen capture, second scene | -0.571 dB | -0.538 dB | +/// | 1080p phone clip | -1.122 dB | -1.084 dB | +/// | 720p web clip | -0.606 dB | -0.572 dB | +/// +/// Luma is unmoved (film -0.065 -> -0.070 dB) and the encode time does not +/// change measurably: only intra macroblocks pay, and only four trials of the +/// chroma path each. +#[allow(clippy::too_many_arguments)] +pub(super) fn choose_chroma_mode_rd( + pic: &mut Picture, + e: &MbEnc<'_>, + w: &EncEntropy, + nbr: &MbNeighbors, + mb_x: usize, + mb_y: usize, + qp: i32, + out: &mut Levels, +) -> u8 { + let qp_c = chroma_qp(qp, e.cqo); + let lambda = lambda_ssd(qp_c); + let mut best: Option<(f64, u8, Levels, [[u8; 64]; 2])> = None; + for mode in [0u8, 1, 2, 3] { + let ok = match mode { + 1 => nbr.a, + 2 => nbr.b, + 3 => nbr.a && nbr.b && nbr.d, + _ => true, + }; + if !ok { + continue; + } + for comp in 0..2 { + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = plane.stride; + let origin = plane.at(mb_x * 8, mb_y * 8); + let mut win = PlaneWindow { + data: &mut plane.data, + stride, + origin, + }; + pred_chroma_8x8(mode, 8, &mut win, nbr.b, nbr.a); + } + let mut lv = Levels::default(); + code_chroma(pic, e, w, mb_x, mb_y, qp, true, &mut lv); + let mut ssd = 0i64; + let mut recon = [[0u8; 64]; 2]; + for comp in 0..2 { + let (plane, src) = if comp == 0 { + (&pic.cb, &e.src.u) + } else { + (&pic.cr, &e.src.v) + }; + let origin = plane.at(mb_x * 8, mb_y * 8); + for ry in 0..8 { + for rx in 0..8 { + let r = plane.data[origin + ry * plane.stride + rx]; + recon[comp][ry * 8 + rx] = r; + let d = i64::from(src[(mb_y * 8 + ry) * e.src.c_stride + mb_x * 8 + rx]) + - i64::from(r); + ssd += d * d; + } + } + } + let mut bits = match mode { + 0 => 1.0, + 3 => 5.0, + _ => 3.0, + }; + for comp in 0..2 { + bits += match w.residual_block_cost( + &lv.chroma_dc[comp], + BlockCat::ChromaDc(comp as u8), + Some(1), + Some(1), + ) { + Some(b) => f64::from(b) / 256.0, + None => block_bits(&lv.chroma_dc[comp]) as f64, + }; + for blk in 0..4 { + bits += match w.residual_block_cost( + &lv.chroma[comp][blk], + BlockCat::ChromaAc, + Some(1), + Some(1), + ) { + Some(b) => f64::from(b) / 256.0, + None => block_bits(&lv.chroma[comp][blk]) as f64, + }; + } + } + let cost = ssd as f64 + lambda * bits; + if best.as_ref().is_none_or(|b| cost < b.0) { + best = Some((cost, mode, lv, recon)); + } + } + let (_, mode, lv, recon) = best.expect("chroma DC prediction is always available"); + for comp in 0..2 { + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = plane.stride; + let origin = plane.at(mb_x * 8, mb_y * 8); + for ry in 0..8 { + for rx in 0..8 { + plane.data[origin + ry * stride + rx] = recon[comp][ry * 8 + rx]; + } + } + } + *out = lv; + mode +} + +/// The mode decision of [`code_intra_8x8`]: for every allowed mode, predict, +/// code the 8x8 residual at the real QP and score `SSD + lambda * bits`, then +/// keep the cheapest. The SATD chooser this replaced scored the prediction +/// residual before the quantiser had a say, so it optimised a proxy. +/// +/// Returns the winning mode, its coded levels with whether the block has any, +/// and the reconstructed 8x8 to write back. Measured on BD-PSNR against x264 +/// with the 8x8 transform on, GOP 10, 24 consecutive pictures, luma / YUV: +/// • 3840x1608 film: +0.475 / -0.068 -> +0.512 / -0.035 +/// • 1138x640 web: +0.040 / -0.031 -> +0.076 / +0.003 +/// • 854x480 web: +0.070 / +0.047 -> +0.132 / +0.108 +/// • 2560x1440 screen: -0.206 / -0.199 -> -0.215 / -0.207 +/// Three clips of four gain; the screen capture loses 0.008 dB. Encode time +/// moves from 12 s to 13 s on the 854x480 clip. +#[allow(clippy::too_many_arguments)] +pub(super) fn i8_mode_by_rd( + pic: &mut Picture, + e: &MbEnc<'_>, + w: &EncEntropy, + x: usize, + y: usize, + qp: i32, + n: &crate::pred::Nbr8, + allowed: &[bool; 9], + predicted: u8, + p: &mut [u8; 64], +) -> (u8, ([i32; 64], bool), [u8; 64]) { + let lambda = lambda_ssd(qp); + let stride = pic.y.stride; + let origin = pic.y.at(x, y); + type Best = Option<(f64, u8, [i32; 64], bool, [u8; 64])>; + let mut best: Best = None; + for mode in 0..9u8 { + if !allowed[mode as usize] { + continue; + } + pred_8x8(mode, 8, n, p); + for ry in 0..8 { + let row = origin + ry * stride; + pic.y.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]); + } + let mut levels = [0i32; 64]; + let nz = code_block_8x8(pic, e, w, x, y, qp, true, &mut levels); + let mut ssd = 0i64; + let mut recon = [0u8; 64]; + for ry in 0..8 { + let row = origin + ry * stride; + for rx in 0..8 { + let r = pic.y.data[row + rx]; + recon[ry * 8 + rx] = r; + let d = i64::from(e.src.y[(y + ry) * e.src.stride + x + rx]) - i64::from(r); + ssd += d * d; + } + } + let mut bits = if mode == predicted { 1.0 } else { 4.0 }; + if nz > 0 { + // `Luma8x8` has no coded_block_flag of its own — the CBP carries it + // — so it needs the 8x8 cost path, not the cbf-indexed one. + bits += match w.residual_block_8x8_cost(&levels) { + Some(b) => f64::from(b) / 256.0, + None => block_bits(&levels) as f64, + }; + } + let cost = ssd as f64 + lambda * bits; + if best.as_ref().is_none_or(|b| cost < b.0) { + best = Some((cost, mode, levels, nz > 0, recon)); + } + } + let (_, mode, levels, coded, recon) = + best.expect("Intra_8x8 always has at least the DC mode available"); + (mode, (levels, coded), recon) +} + diff --git a/crates/ec-h264/src/enc/mb/me.rs b/crates/ec-h264/src/enc/mb/me.rs new file mode 100644 index 00000000..d32d8f36 --- /dev/null +++ b/crates/ec-h264/src/enc/mb/me.rs @@ -0,0 +1,836 @@ +#![allow(clippy::needless_range_loop)] + +use wide::{i16x16}; + +use crate::dpb::{Picture}; +use crate::inter::{Put, RefPlane, integer_origin, mc_chroma, mc_luma}; +use crate::mv::{MvCtx, predict_mv}; + + +use super::*; + +/// 4x4 Hadamard sum of absolute transformed differences between the source at +/// `(sx, sy)` and a 4x4 prediction. +// Tried (lane-h264perf r2): a transpose-based i32x4 vectorization of this +// butterfly, bit-identical, but cycles-flat-to-worse under perf stat +// (22.958B -> 23.042B cycles over 10 reps despite fewer instructions +// retired) -- reverted, dead end; see ledger. +pub(super) fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 { + // Differences are at most 255 in magnitude and the 2-D Hadamard sums 16 of + // them, so every intermediate fits an i16. + let mut d = [[0i16; 4]; 4]; + for (y, row) in d.iter_mut().enumerate() { + let s = &src[(sy + y) * sstride + sx..][..4]; + let p = &pred[y * pstride..][..4]; + for x in 0..4 { + row[x] = i16::from(s[x]) - i16::from(p[x]); + } + } + // Vertical butterflies, lane-wise over the four columns. + let mut v = [[0i16; 4]; 4]; + for x in 0..4 { + let (a, b, c, e) = (d[0][x], d[1][x], d[2][x], d[3][x]); + let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e); + v[0][x] = s0 + s1; + v[1][x] = s0 - s1; + v[2][x] = s2 + s3; + v[3][x] = s2 - s3; + } + // Horizontal butterflies per row, then the absolute sum. + let mut sum = 0i32; + for row in &v { + let (a, b, c, e) = (row[0], row[1], row[2], row[3]); + let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e); + sum += i32::from((s0 + s1).abs()) + + i32::from((s0 - s1).abs()) + + i32::from((s2 + s3).abs()) + + i32::from((s2 - s3).abs()); + } + (sum + 2) >> 2 +} + +/// SATD of a whole 16x16 luma macroblock against the prediction already in the +/// picture plane. +pub(super) fn satd16( + src: &[u8], + sstride: usize, + sx: usize, + sy: usize, + plane: &[u8], + pstride: usize, + po: usize, +) -> i32 { + satd_block(src, sstride, sx, sy, plane, pstride, po, 16, 16) +} + +/// The same over a `w` x `h` partition. +#[allow(clippy::too_many_arguments)] +pub(super) fn satd_block( + src: &[u8], + sstride: usize, + sx: usize, + sy: usize, + plane: &[u8], + pstride: usize, + po: usize, + w: usize, + h: usize, +) -> i32 { + let mut sum = 0; + for by in 0..h / 4 { + for bx in 0..w / 4 { + sum += satd4( + src, + sstride, + sx + bx * 4, + sy + by * 4, + &plane[po + by * 4 * pstride + bx * 4..], + pstride, + ); + } + } + sum +} + +/// Sum of absolute differences of a `w` x `h` block against a prediction with +/// its own pitch. This is the motion search's inner loop and nothing else in +/// the encoder is called as often, so a full-width row goes through one vector. +#[allow(clippy::too_many_arguments)] +pub(super) fn sad( + src: &[u8], + sstride: usize, + sx: usize, + sy: usize, + pred: &[u8], + pstride: usize, + w: usize, + h: usize, +) -> i32 { + if w == 16 { + let mut acc = i16x16::ZERO; + for y in 0..h { + let a = load16(src, (sy + y) * sstride + sx); + let b = load16(pred, y * pstride); + acc += (a - b).abs(); + } + return acc.to_array().iter().map(|&v| i32::from(v)).sum(); + } + let mut sum = 0; + for y in 0..h { + let s = &src[(sy + y) * sstride + sx..]; + let p = &pred[y * pstride..]; + for x in 0..w { + sum += (i32::from(s[x]) - i32::from(p[x])).abs(); + } + } + sum +} + +/// Sum and maximum of the absolute differences between the 16x16 source block +/// at `(sx, sy)` and a 16-wide prediction. +pub(super) fn sad_max16(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8]) -> (i32, i32) { + let mut acc = i16x16::ZERO; + let mut mx = i16x16::ZERO; + for y in 0..16 { + let a = load16(src, (sy + y) * sstride + sx); + let b = load16(pred, y * 16); + let d = (a - b).abs(); + acc += d; + mx = mx.max(d); + } + let sum = acc.to_array().iter().map(|&v| i32::from(v)).sum(); + let max = mx + .to_array() + .iter() + .map(|&v| i32::from(v)) + .max() + .unwrap_or(0); + (sum, max) +} + +#[inline] +pub(super) fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 { + (motion_lambda(e) * bits).round() as i32 +} + +/// The multiplier `motion_rate` applies, for loops that price many vectors. +#[inline] +pub(super) fn motion_lambda(e: &MbEnc<'_>) -> f64 { + if e.transform_8x8 { + e.lambda.sqrt() + } else { + e.lambda + } +} + +/// How much of a motion vector's signalling the search pays for. Half, which +/// is not the true rate: swept on consecutive pictures (BD-PSNR against x264, +/// GOP 10), 0.25/0.5/1.0/2.0 read -1.074/-1.043/-1.225/-1.618 on the film clip +/// and -0.676/-0.661/-0.795/-1.201 on the screen capture. Charging the whole +/// rate is worse than charging half on both contents, and the curve is flat +/// below a half and falls away above it. +pub(super) const MV_BITS_WEIGHT: f64 = 0.5; + +/// Cap on whole-sample walk iterations per partition at `Preset::Fast`. +pub(super) const FAST_ME_PASSES: usize = 3; + +/// The offsets the whole-sample search steps through, in units of the current +/// step size. +/// +/// A square, not a cross. The cross this used to be could only walk along an +/// axis, so a diagonally moving macroblock had to be reached in two steps +/// through a point that was worse than both -- and a step search stops at the +/// first point it cannot improve on. Adding the four diagonals is worth 0.032 +/// dB BD-PSNR-YUV on the film clip and 0.041 on the screen capture for twice +/// the candidates in the whole-sample stage, which is the cheap stage: it reads +/// the reference in place and never interpolates. +/// +/// The step the walk starts from was swept with it, at 4, 8 and 16 whole +/// samples: -0.580/-0.580/-0.593 dB on the film clip and -0.474/-0.493/-0.529 +/// on the screen capture. Four is screen capture's optimum and inside film's +/// flat part -- a wider opening step is not a wider search here, it just lands +/// the walk further from the seeds, which are already the answer most of the +/// time. +pub(super) const ME_PATTERN: [(i16, i16); 8] = [ + (1, 0), + (-1, 0), + (0, 1), + (0, -1), + (1, 1), + (-1, -1), + (1, -1), + (-1, 1), +]; + +/// What the search charges P_8x8 for its own signalling, against the six bits +/// a 16x8 or 8x16 is charged: an mb_type that is one bin longer plus four +/// sub_mb_type bins, before the four predictors' own mvd. +/// +/// Swept at `Preset::Balanced` -- the only preset that searches shapes at all +/// -- on consecutive pictures against x264. Off, 6, 12 and 20 bits read +/// -0.382/-0.379/-0.377/-0.378 dB BD-PSNR on the film clip and +/// -0.369/-0.364/-0.353/-0.356 on the screen capture: both contents put the +/// optimum at twelve, and quarters are worth 0.005 dB on camera content and +/// 0.016 on screen capture. +/// +/// Re-swept once each partition was searched against its own predictor rather +/// than the macroblock's, because that changes what a split is worth: 6, 12 +/// and 20 read -0.342/-0.343/-0.346 dB on the film clip and +/// -0.322/-0.314/-0.324 on the screen capture. Twelve survives the new path. +pub(super) const QUAD_BITS: f64 = 12.0; + +/// The same charge for a 16x8 or 8x16: one extra mb_type bin over P_16x16, +/// with no sub_mb_type behind it. +/// +/// Swept on the per-partition-predictor path at 3, 6 and 10 bits: +/// -0.329/-0.343/-0.358 dB on the film clip and -0.310/-0.314/-0.326 on the +/// screen capture. Both contents want the halves charged half of what the old +/// whole-macroblock predictor made them look worth -- with each half searched +/// against its own predictor its mvd is genuinely cheaper, so the search no +/// longer has to be talked out of splitting. +pub(super) const HALF_BITS: f64 = 3.0; + +/// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum PShape { + /// P_L0_16x16. + Whole, + /// P_L0_L0_16x8: a top and a bottom half. + Horizontal, + /// P_L0_L0_8x16: a left and a right half. + Vertical, + /// P_8x8 with four P_L0_8x8 sub-partitions: a quarter each. + Quad, +} + +impl PShape { + /// mb_type of Table 7-13. + pub(super) fn mb_type(self) -> u32 { + match self { + PShape::Whole => 0, + PShape::Horizontal => 1, + PShape::Vertical => 2, + PShape::Quad => 3, + } + } + + pub(super) fn parts(self) -> usize { + match self { + PShape::Whole => 1, + PShape::Horizontal | PShape::Vertical => 2, + PShape::Quad => 4, + } + } + + /// Partition `part`'s origin in 4x4 blocks and its size in luma samples. + pub(super) fn geometry(self, part: usize) -> ((usize, usize), (usize, usize)) { + match self { + PShape::Whole => ((0, 0), (16, 16)), + PShape::Horizontal => ((0, part * 2), (16, 8)), + PShape::Vertical => ((part * 2, 0), (8, 16)), + PShape::Quad => (((part % 2) * 2, (part / 2) * 2), (8, 8)), + } + } + + /// Which partition covers the 4x4 block at `(x, y)` in macroblock + /// coordinates, or `None` when the block is outside the macroblock. + pub(super) fn part_of(self, x: i32, y: i32) -> Option { + if !(0..4).contains(&x) || !(0..4).contains(&y) { + return None; + } + let (x, y) = (x as usize, y as usize); + Some(match self { + PShape::Whole => 0, + PShape::Horizontal => y / 2, + PShape::Vertical => x / 2, + PShape::Quad => (y / 2) * 2 + x / 2, + }) + } + + /// `MbPartWidth`/`MbPartHeight` in 4x4 blocks, which select the + /// directional shortcuts of 8.4.1.3. + pub(super) fn part_blocks(self) -> (usize, usize) { + match self { + PShape::Whole => (4, 4), + PShape::Horizontal => (4, 2), + PShape::Vertical => (2, 4), + PShape::Quad => (2, 2), + } + } +} + +/// How much the two chroma planes weigh against luma in the inter decision. +/// +/// Swept at 0, 0.25, 0.5, 1 and 2, read on BD-PSNR-YUV because a luma-only +/// metric cannot price a term whose whole purpose is chroma: the film clip +/// reads -0.653/-0.622/-0.612/-0.615/-0.626 dB and the screen capture +/// -0.517/-0.521/-0.515/-0.521/-0.546. A half is film's optimum and inside +/// screen capture's flat part; zero reproduces the chroma-blind decision +/// exactly, which is how the sweep proved the term was reaching the search. +/// +/// It is worth 0.041 dB on the film clip and nothing on the screen capture -- +/// small enough to name what it rules out. Our chroma trails x264 by 0.5-0.9 dB +/// per plane at every QP, and it is not because the vector was chosen without +/// looking: weighting chroma up lifts chroma PSNR monotonically, and past a +/// half the bits it spends cost more than the chroma it buys. +pub(super) const CHROMA_ME_WEIGHT: f64 = 0.5; + +/// How many inter candidates the macroblock decision codes before choosing, +/// most promising first. One is the SATD winner alone, which is what this used +/// to do; five is every shape the search costed plus P_Skip. BD-PSNR-YUV +/// against x264 at GOP 10 over QP 22/26/30/34, at `Preset::Balanced`: +/// +/// ```text +/// film 3840x1608 screen 2560x1440 +/// 1 candidate -0.580 -0.474 +/// 2 -0.521 -0.459 +/// 3 -0.513 -0.447 +/// 5 -0.504 -0.406 +/// ``` +/// +/// monotone in the count with no turnover, so the decision is taken at the +/// full list. The SATD total that used to rank the shapes is a +/// prediction-domain estimate that never sees the residual it causes. +pub(super) const SHAPE_RD_CANDIDATES: usize = 5; + +/// The inter decision for a P macroblock. +#[derive(Clone, Copy)] +pub(super) struct InterChoice { + /// The candidate's SATD cost (luma plus chroma) as the shape search ranked it; + /// zero where the search did not rank it. + pub(super) satd: i32, + pub(super) shape: PShape, + /// One motion vector per partition. + pub(super) mv: [[i16; 2]; 4], + /// The P_Skip motion vector of 8.4.1.1. + pub(super) skip_mv: [i16; 2], + /// The skip candidate is at least as good as the searched one. + pub(super) prefer_skip: bool, + /// The prediction is so close to the source that the macroblock is coded + /// as P_Skip without costing a residual (`Preset::Fast` only). + pub(super) force_skip: bool, +} + +/// Motion search plus the skip candidate. +pub(super) fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec { + let reference = e.reference.expect("a P slice has a reference"); + let ctx = MvCtx { + mb_x, + mb_y, + slice_id: e.slice_id, + written: 0, + pos: Default::default(), + }; + let n = ctx.neighbours(pic, 0, 0, 4, 0); + let mvp = predict_mv(&n, 0, 4, 4, 0); + // P_Skip (8.4.1.1): zero when either neighbour is missing or is itself a + // zero-motion reference-0 partition. + let a = ctx.at(pic, mb_x as i32 * 4 - 1, mb_y as i32 * 4, 0); + let b = ctx.at(pic, mb_x as i32 * 4, mb_y as i32 * 4 - 1, 0); + let zero = |nb: &crate::mv::Nb| nb.ref_idx == 0 && nb.mv == [0, 0]; + let skip_mv = if !a.avail || !b.avail || zero(&a) || zero(&b) { + [0, 0] + } else { + mvp + }; + + let plane = RefPlane { + data: &reference.y.data, + stride: reference.y.stride, + origin: reference.y.origin, + width: reference.y.width, + height: reference.y.height, + pad: reference.y.pad, + }; + let (sx, sy) = (mb_x * 16, mb_y * 16); + let sw = e.src.stride; + + // What the two chroma planes cost under a candidate vector, in the same + // SATD domain the luma search ranks in. The search itself cannot afford + // this -- it runs on SAD over a whole neighbourhood -- but the handful of + // candidates that survive to the shape decision can, and until they did, + // no decision in this encoder had ever looked at chroma: the vector, the + // shape and the skip flag were all chosen on luma alone and chroma was + // coded against whatever came out. Measured per plane against x264 that + // showed up as a uniform 0.5-0.9 dB chroma deficit at every QP while we + // spent more bits, which is a prediction that was never asked about. + let cplanes = [&reference.cb, &reference.cr]; + let chroma_satd = |px: usize, py: usize, w: usize, h: usize, mv: [i16; 2]| -> i32 { + if CHROMA_ME_WEIGHT == 0.0 { + return 0; + } + let mut buf = [0u8; 64]; + let mut sum = 0; + for comp in 0..2 { + let src = cplanes[comp]; + let rp = RefPlane { + data: &src.data, + stride: src.stride, + origin: src.origin, + width: src.width, + height: src.height, + pad: src.pad, + }; + let (cw, ch) = (w / 2, h / 2); + mc_chroma( + &rp, + (sx + px) as i32 / 2, + (sy + py) as i32 / 2, + mv, + cw, + ch, + cw, + &mut buf, + crate::inter::Put::Set, + ); + let plane = if comp == 0 { &e.src.u } else { &e.src.v }; + sum += satd_block( + plane, + e.src.c_stride, + (sx + px) / 2, + (sy + py) / 2, + &buf, + cw, + 0, + cw, + ch, + ); + } + (f64::from(sum) * CHROMA_ME_WEIGHT) as i32 + }; + + // Early skip: a prediction at the P_Skip vector that already sits inside + // the quantiser's dead zone codes nothing, so neither the search nor a + // residual is worth the time. Judged on luma SAD, the largest single + // difference and the chroma SATD, all against the quantiser step. + if e.preset == Preset::Fast && e.fast.early_skip > 0 { + let qstep = ((f64::from(e.qp) - 4.0) / 6.0).exp2(); + let k = f64::from(e.fast.early_skip) / 100.0; + let mut buf = [0u8; 256]; + mc_luma( + &plane, + sx as i32, + sy as i32, + skip_mv, + 16, + 16, + 16, + &mut buf, + Put::Set, + ); + let (sad_luma, max_luma) = sad_max16(&e.src.y, sw, sx, sy, &buf); + if f64::from(sad_luma) <= 256.0 * k * qstep && f64::from(max_luma) <= 4.0 * k * qstep + 2.0 + { + let c = chroma_satd(0, 0, 16, 16, skip_mv); + if f64::from(c) <= 64.0 * k * qstep * 4.0 { + return vec![InterChoice { + satd: 0, + shape: PShape::Whole, + mv: [skip_mv; 4], + skip_mv, + prefer_skip: true, + force_skip: true, + }]; + } + } + } + + let range = match e.preset { + Preset::Fast => 16i16, + Preset::Balanced => 48, + }; + + // One search over a `w` x `h` partition at `(px, py)` samples inside the + // macroblock, seeded with the candidate vectors of its neighbourhood. + let mlam = motion_lambda(e); + let search = |px: usize, py: usize, w: usize, h: usize, mvp: [i16; 2], seeds: &[[i16; 2]]| { + let (x0, y0) = (sx + px, sy + py); + let mut buf = [0u8; 256]; + // Whole-sample candidates read the reference plane in place; only the + // sub-sample refinement pays for interpolation. The search runs on SAD, + // which is what a search can afford; the winner is re-costed on SATD + // because the intra candidates are SATD and the two scales differ. + let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 { + let bits = (mlam + * f64::from( + se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1])), + ) + * MV_BITS_WEIGHT) + .round() as i32; + if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 { + let o = integer_origin( + &plane, + x0 as i32 + (mv[0] >> 2) as i32, + y0 as i32 + (mv[1] >> 2) as i32, + w, + h, + ); + return sad(&e.src.y, sw, x0, y0, &plane.data[o..], plane.stride, w, h) + bits; + } + mc_luma( + &plane, + x0 as i32, + y0 as i32, + mv, + w, + h, + w, + &mut buf, + crate::inter::Put::Set, + ); + let d = if satd { + satd_block(&e.src.y, sw, x0, y0, &buf, w, 0, w, h) + } else { + sad(&e.src.y, sw, x0, y0, &buf, w, w, h) + }; + d + bits + }; + + let fast = e.preset == Preset::Fast; + let mut best = ([0i16; 2], i32::MAX); + for (i, &cand) in seeds.iter().enumerate() { + if seeds[..i].contains(&cand) { + continue; + } + let c = cost_of(cand, false); + if c < best.1 { + best = (cand, c); + } + } + // Every partition is searched. This used to stop at a seed whose cost + // was already under half a level a sample, on the reasoning that the + // prediction fit and the search is the encoder's hot loop. Swept on + // consecutive pictures (BD-PSNR against x264, GOP 10) the threshold is + // monotonically harmful: 0/0.25/0.5/1.0 levels a sample read + // -0.586/-0.587/-0.593/-0.617 dB on the film clip and + // -0.466/-0.470/-0.468/-0.476 on the screen capture. A seed that fits + // is exactly where a little more refinement is cheap. + { + // Fast opens at two whole samples: the seeds already carry the + // neighbours' motion, so the walk only has to settle around them. + let mut step = if fast { 2i16 * 4 } else { 4i16 * 4 }; + let mut passes = 0; + while step >= 4 { + let mut improved = true; + while improved { + improved = false; + passes += 1; + if fast && passes > FAST_ME_PASSES { + break; + } + for (dx, dy) in ME_PATTERN { + let (dx, dy) = (dx * step, dy * step); + let cand = [best.0[0] + dx, best.0[1] + dy]; + if (cand[0] - mvp[0]).abs() > range * 4 + || (cand[1] - mvp[1]).abs() > range * 4 + { + continue; + } + let c = cost_of(cand, false); + if c < best.1 { + best = (cand, c); + improved = true; + } + } + } + step /= 2; + } + // Sub-sample refinement runs on SATD, not SAD: interpolation + // smooths, and a sum of absolute differences reads the smoothing + // as a better match where a transform-domain cost does not. Worth + // 0.06 dB BD-PSNR on the film clip and 0.04 dB on the screen + // capture. The whole-sample winner is re-costed in the same domain + // first so the two halves of the search compare. + let sub_satd = !fast || e.fast.me_satd; + best.1 = cost_of(best.0, sub_satd); + // Balanced iterates both sub-sample steps to convergence. Fast + // looks at each ring of eight once. + let rings: &[i16] = if !fast { + &[2, 1] + } else { + match e.fast.me_sub { + 0 => &[], + 1 => &[2], + _ => &[2, 1], + } + }; + if fast && e.fast.me_sub == 1 { + // The four half-sample neighbours on the axes, then only the + // diagonal the two winning axes point at. + let base = best; + let mut axis = [(base.0, base.1); 2]; + for (k, dirs) in [[(2i16, 0i16), (-2, 0)], [(0, 2), (0, -2)]] + .into_iter() + .enumerate() + { + for (dx, dy) in dirs { + let cand = [base.0[0] + dx, base.0[1] + dy]; + let c = cost_of(cand, sub_satd); + if c < axis[k].1 { + axis[k] = (cand, c); + } + } + } + let both = axis[0].1 < base.1 && axis[1].1 < base.1; + if both { + let cand = [axis[0].0[0], axis[1].0[1]]; + let c = cost_of(cand, sub_satd); + if c < best.1 { + best = (cand, c); + } + } + for a in axis { + if a.1 < best.1 { + best = a; + } + } + } + let rings: &[i16] = if fast && e.fast.me_sub == 1 { + &[] + } else { + rings + }; + for &step in rings { + let mut improved = true; + while improved { + improved = false; + for (dx, dy) in [ + (step, 0), + (-step, 0), + (0, step), + (0, -step), + (step, step), + (-step, -step), + (step, -step), + (-step, step), + ] { + let cand = [best.0[0] + dx, best.0[1] + dy]; + let c = cost_of(cand, sub_satd); + if c < best.1 { + best = (cand, c); + improved = !fast; + } + } + } + } + } + ( + best.0, + if !fast || e.fast.me_satd { + best.1 + } else { + cost_of(best.0, true) + }, + ) + }; + + let seeds = [mvp, skip_mv, [0, 0], n[0].mv, n[1].mv, n[2].mv]; + let (mv16, cost16) = search(0, 0, 16, 16, mvp, &seeds); + let cost16 = cost16 + chroma_satd(0, 0, 16, 16, mv16); + let skip_cost = { + let mut buf = [0u8; 256]; + mc_luma( + &plane, + sx as i32, + sy as i32, + skip_mv, + 16, + 16, + 16, + &mut buf, + Put::Set, + ); + // P_Skip's rebate is the signalling it genuinely saves. Re-measured on + // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip + // and -0.741/-0.696 on the screen capture -- the two contents disagree + // by less than the step between them, so this is the flat part. Six + // costs 0.14 dB and twelve costs 0.42. + // + // The Intra_4x4 discount above was swept with it: 0.65/0.75/0.85/1.0 + // read -1.216/-1.154/-1.182/-1.373 on film and -0.970/-0.696/-0.591/ + // -0.562 on screen capture, so three quarters is film's optimum and + // inside screen capture's flat part. + satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) + chroma_satd(0, 0, 16, 16, skip_mv) + - motion_rate(e, 2.0) + }; + + let mut best = (PShape::Whole, [mv16; 4], cost16); + // Every shape the search costed, kept so the macroblock decision can rank + // them on coded cost instead of on this SATD total (see `encode_mb`). + let mut evaluated = vec![(PShape::Whole, [mv16; 4])]; + // Halves, seeded with the whole-macroblock winner. The predictor used here + // is the whole-macroblock one rather than each half's own: the real + // predictors are derived in coding order when the choice is made, and this + // only has to rank the shapes. A macroblock the 16x16 search already fits + // is left alone — splitting it could only spend bits. + // + // Measured: two more searches per macroblock buy 0.1-0.2 dB on screen + // capture and nothing on camera content, for roughly twice the search + // time. That is a Balanced trade, not a Fast one. + // The threshold is a floor that real content clears everywhere: swept at + // 0, 0.5, 1 and 2 levels a sample it moves neither clip's BD-PSNR by a + // thousandth of a decibel, so on these sources the halves are always + // searched. It stays as a guard for content flat enough to make the two + // extra searches pure cost. + if e.preset == Preset::Balanced && cost16 > 16 * 16 { + for shape in [PShape::Horizontal, PShape::Vertical, PShape::Quad] { + // What the shape itself costs to signal: its mb_type, plus one + // sub_mb_type per quarter when it is P_8x8. + let mut total = motion_rate( + e, + if shape == PShape::Quad { + QUAD_BITS + } else { + HALF_BITS + }, + ); + let mut mvs = [[0i16; 2]; 4]; + let (pw, ph) = shape.part_blocks(); + for part in 0..shape.parts() { + let ((bx, by), (w, h)) = shape.geometry(part); + // Each partition is searched against the predictor it will + // actually be coded with (8.4.1.3), not against the whole + // macroblock's: the partitions before it in this macroblock + // are already chosen, so the neighbourhood the predictor reads + // can be completed from `mvs`. + let mut n = ctx.neighbours(pic, bx, by, pw, 0); + let inside = |x: i32, y: i32, nb: &mut crate::mv::Nb| { + if let Some(p) = shape.part_of(x, y).filter(|&p| p < part) { + *nb = crate::mv::Nb { + avail: true, + mv: mvs[p], + ref_idx: 0, + }; + } + }; + inside(bx as i32 - 1, by as i32, &mut n[0]); + inside(bx as i32, by as i32 - 1, &mut n[1]); + let cx = bx as i32 + pw as i32; + if shape.part_of(cx, by as i32 - 1).is_some() { + inside(cx, by as i32 - 1, &mut n[2]); + } else if !n[2].avail { + inside(bx as i32 - 1, by as i32 - 1, &mut n[2]); + } + let part_mvp = predict_mv(&n, 0, pw, ph, part); + let seeds = [mv16, part_mvp, mvp, skip_mv, [0, 0]]; + let (mv, cost) = search(bx * 4, by * 4, w, h, part_mvp, &seeds); + mvs[part] = mv; + total += cost + chroma_satd(bx * 4, by * 4, w, h, mv); + } + evaluated.push((shape, mvs)); + if total < best.2 { + best = (shape, mvs, total); + } + } + } + + // How often each shape actually wins. Behind an environment switch because + // it answers a question the rate gate cannot: a partition sweep that reads + // flat is either a flat knob or a path nothing enters, and only a count + // tells the two apart. It found the second -- at `Preset::Fast`, which is + // what the x264 comparison runs by default, no macroblock is ever split. + if std::env::var_os("EC_H264_SHAPE_STATS").is_some() { + static N: [std::sync::atomic::AtomicUsize; 4] = [ + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + ]; + let i = match best.0 { + PShape::Whole => 0, + PShape::Horizontal => 1, + PShape::Vertical => 2, + PShape::Quad => 3, + }; + let v = N[i].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let tot: usize = N + .iter() + .map(|n| n.load(std::sync::atomic::Ordering::Relaxed)) + .sum(); + if tot.is_multiple_of(20000) { + eprintln!( + "SHAPES whole={} horiz={} vert={} quad={} (last {i} -> {v})", + N[0].load(std::sync::atomic::Ordering::Relaxed), + N[1].load(std::sync::atomic::Ordering::Relaxed), + N[2].load(std::sync::atomic::Ordering::Relaxed), + N[3].load(std::sync::atomic::Ordering::Relaxed), + ); + } + } + let winner = InterChoice { + satd: best.2, + shape: best.0, + mv: best.1, + skip_mv, + prefer_skip: best.0 == PShape::Whole && skip_cost <= best.2, + force_skip: false, + }; + // The SATD winner first, then the shapes it beat, then the skip candidate + // when the winner is not already it. The caller codes as many of these as + // its preset allows and keeps the one with the smallest coded cost. + let mut cands = vec![winner]; + for (shape, mv) in evaluated { + if shape != winner.shape || winner.prefer_skip { + cands.push(InterChoice { + satd: 0, + shape, + mv, + skip_mv, + prefer_skip: false, + force_skip: false, + }); + } + } + if !winner.prefer_skip { + cands.push(InterChoice { + satd: skip_cost, + shape: PShape::Whole, + mv: [skip_mv; 4], + skip_mv, + prefer_skip: true, + force_skip: false, + }); + } + cands +} + diff --git a/crates/ec-h264/src/enc/mb/residual.rs b/crates/ec-h264/src/enc/mb/residual.rs new file mode 100644 index 00000000..752cb12f --- /dev/null +++ b/crates/ec-h264/src/enc/mb/residual.rs @@ -0,0 +1,1403 @@ +#![allow(clippy::needless_range_loop)] + +use wide::{i16x8}; + +use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line}; +use crate::decoder::{ + MbNeighbors, chroma_nz_pair, luma_nz_pair, }; +use crate::dpb::{Picture}; +use crate::entropy::{ + BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_TRANS8X8, + }; +use crate::pred::{ + PlaneWindow, add_residual_4x4, pred_16x16, + }; +use crate::tables::{BLK4_POS}; +use crate::transform::{ + chroma_dc_transform_420, dequant_4x4, dequant_8x8, + inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, + unzigzag_ac15, +}; + +use crate::enc::quant::{ + forward_4x4, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, + quant_4x4_offset, quant_chroma_dc, quant_luma_dc, +}; + +use crate::enc::{ + entropy::{EncEntropy, sub_block_4x4}, + lambda_ssd, +}; +use super::*; + +/// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock, +/// prediction already in the plane. +#[allow(clippy::too_many_arguments)] +pub(super) fn code_luma_4x4( + pic: &mut Picture, + e: &MbEnc<'_>, + w: &EncEntropy, + mb_x: usize, + mb_y: usize, + qp: i32, + intra: bool, + lv: &mut Levels, +) { + let stride = pic.y.stride; + // An inter macroblock's blocks are reconstructed only after the whole + // macroblock has been quantised, because [`decimate_score`] can still take + // a block away. Intra blocks reconstruct as they go: the next block in the + // macroblock predicts from them. + let mut pending: [Option<[i32; 16]>; 16] = [None; 16]; + // Per 8x8 group, what coding its blocks buys and what it costs, for the + // group-level test below. A block with no levels contributes nothing to + // either side: its source energy stays in the reconstruction whatever the + // group decides. + let mut ssd_zero = [0i64; 4]; + let mut ssd_coded = [0i64; 4]; + let mut rate = [0f64; 4]; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + let origin = pic.y.at(x, y); + let mut d = [0i32; 16]; + for ry in 0..4 { + for rx in 0..4 { + d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) + - i32::from(pic.y.data[origin + ry * stride + rx]); + } + } + let source = d; + forward_4x4(&mut d); + let rdoq = !intra && w.is_cabac(); + let mut nz = if rdoq { + quant_4x4_offset(&d, qp, RDOQ_DEAD_ZONE, false, &mut lv.luma[blk]) + } else { + quant_4x4(&d, qp, intra, false, &mut lv.luma[blk]) + }; + if rdoq && nz != 0 { + nz = rdoq_4x4( + e, + w, + &source, + &mut lv.luma[blk], + qp, + BlockCat::Luma4x4, + false, + ); + } + lv.luma_nz[blk] = nz; + if nz == 0 { + continue; + } + let mut raster = [0i32; 16]; + unzigzag(&lv.luma[blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp, false); + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + // Is the block worth its bits? A block whose residual barely moves the + // reconstruction is pure quantisation churn; dropping it is the cheap + // half of rate-distortion optimised quantisation, and the half that + // pays. Intra blocks are left alone: their reconstruction is what the + // next block in the macroblock predicts from. + if !rdoq + && !intra + && !worth_coding( + &source, + &resid, + &lv.luma[blk], + zero_block_lambda(e, qp, e.transform_8x8), + ) + { + lv.luma[blk] = [0; 16]; + lv.luma_nz[blk] = 0; + continue; + } + if intra { + lv.cbp_luma |= 1 << (blk >> 2); + add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid); + } else { + for i in 0..16 { + let z = i64::from(source[i]); + let c = i64::from(source[i] - resid[i]); + ssd_zero[blk >> 2] += z * z; + ssd_coded[blk >> 2] += c * c; + } + rate[blk >> 2] += + match w.residual_block_cost(&lv.luma[blk], BlockCat::Luma4x4, Some(1), Some(1)) { + // CABAC's own arithmetic cost for the levels, which is what + // the group is really deciding about. It arrives in 256ths of + // a bit. + Some(bits) => f64::from(bits) / 256.0, + None => block_bits(&lv.luma[blk]) as f64, + }; + pending[blk] = Some(resid); + } + } + if intra { + return; + } + // A block that survives its own rate-distortion test can still be the last + // coefficient standing in its 8x8 group, and then it is paying a + // coded_block_pattern bit as well as its levels. x264 decides that with a + // count of how tightly the levels cluster at the front of the scan + // (`decimate`), thresholded at four per group; swept here, that count + // wants opposite settings on the two contents -- monotonically off on + // camera grain, monotonically harder on screen capture -- because it is a + // heuristic standing in for a rate-distortion test the encoder can just + // do. So do it: a group is coded only if its blocks buy more squared error + // than their levels plus the pattern bit are worth, at the same lambda the + // per-block test uses. + // With an exact rate the lambda needs no correction factor: the group test + // uses the mode decision's own lambda where the rate is CABAC's, and falls + // back to the per-block test's discounted one where it is an estimate. + let lambda = if w.is_cabac() { + GROUP_LAMBDA * lambda_ssd(qp) + } else { + zero_block_lambda(e, qp, e.transform_8x8) + }; + for g in 0..4 { + if rate[g] == 0.0 { + continue; + } + if ssd_coded[g] as f64 + lambda * (rate[g] + CBP_BIT) < ssd_zero[g] as f64 { + continue; + } + for blk in g * 4..g * 4 + 4 { + lv.luma[blk] = [0; 16]; + lv.luma_nz[blk] = 0; + pending[blk] = None; + } + } + for blk in 0..16 { + let Some(resid) = pending[blk] else { continue }; + let (dx, dy) = BLK4_POS[blk]; + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + let origin = pic.y.at(x, y); + lv.cbp_luma |= 1 << (blk >> 2); + add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid); + } +} + +/// What a group of four luma blocks pays in coded_block_pattern to be coded +/// at all, in bits, on top of its own levels. +/// +/// This charge and [`GROUP_LAMBDA`] move the group test along the same axis -- +/// both make dropping a group likelier -- so only one of them is worth tuning. +/// Swept at 0, 6, 12 and 24 bits it reads -0.317/-0.335/-0.379/-0.472 dB on +/// the film clip against -0.295/-0.212/-0.191/-0.185 on the screen capture: +/// the same trade the lambda makes, at a worse exchange rate. It stays at a +/// plausible six. +pub(super) const CBP_BIT: f64 = 6.0; + +/// What chroma pays to take its coded_block_pattern from one to two, in bits, +/// on top of the levels: the pattern bins themselves plus a coded_block_flag +/// for every AC block that then has to say it is empty. +/// +/// Swept at 0, 4, 8, 16, 32 and 64 bits, read on the all-plane PSNR because a +/// luma-only one cannot see what this decision spends: -0.688/-0.681/-0.659/ +/// -0.653/-0.670/-0.742 dB BD on the film clip and -0.537/-0.527/-0.530/ +/// -0.517/-0.524/-0.522 on the screen capture. Both turn over at sixteen. The +/// same sweep read on luma alone climbs all the way to +0.079 dB at 64, +/// because past the turn the test is buying luma bits by throwing chroma +/// away -- which is exactly the trade an all-plane metric exists to catch. +pub(super) const CBP_CHROMA_BIT: f64 = 16.0; + +/// How much of the mode-decision lambda the group test uses. +/// +/// The 8x8 transform path was swept the same way and does not want this test +/// at all: at 0, 0.3 and 0.6 the `transform_8x8` gate reads +0.620/+0.624/ +/// +0.608 dB on the film clip and +0.007/+0.007/+0.009 on the screen capture, +/// all inside its noise. One 8x8 block is a whole coded_block_pattern group, +/// so its own zero test already decides what this one would, and `rdoq_8x8` +/// drops it outright when the levels do not survive. +/// +/// Swept at 0.25, 0.5, 0.6, 0.75, 0.9, 1.0 and 2.0 on both real clips: +/// -0.315/-0.314/-0.321/-0.335/-0.354/-0.372/-0.575 dB on the 3840x1608 film +/// clip and -0.297/-0.267/-0.252/-0.212/-0.202/-0.193/-0.277 on the 2560x1440 +/// screen capture. Screen capture has an interior optimum around one -- which +/// the same test on an estimated rate did not, it only ever wanted more -- and +/// camera grain wants less, because a grain block that scores as noise is +/// carrying signal the eye is measuring. Six tenths is the most the film clip +/// takes without losing ground, and it is worth 0.06 dB on screen capture. +pub(super) const GROUP_LAMBDA: f64 = 0.6; + +/// How much of the squared-error lambda the chroma DC zero test uses. +/// +/// BD-PSNR-YUV against x264 at GOP 10 over QP 22/26/30/34, `Preset::Balanced`, +/// with the test off against a ladder of multipliers: +/// +/// ```text +/// film screen phone handheld +/// off -0.504 -0.227 -0.300 -0.886 +/// 0.25 -0.506 -0.227 +/// 0.5 -0.500 -0.220 -0.297 -0.884 +/// 0.75 -0.500 -0.223 +/// 1.0 -0.518 -0.246 +/// 2.0 -0.708 -0.566 +/// ``` +/// +/// Zeroing on squared error alone (a multiplier of 0) never fires, so the rate +/// term is the whole test; above the peak it throws away chroma the picture +/// needs. +pub(super) const CHROMA_DC_LAMBDA: f64 = 0.5; + +/// Squared error of coding `levels`, in the pixels the block reconstructs to. +pub(super) fn block_ssd(e: &MbEnc<'_>, source: &[i32; 16], levels: &[i32; 16], qp: i32, skip_dc: bool) -> i64 { + let mut raster = [0i32; 16]; + if skip_dc { + unzigzag_ac15(levels, &mut raster); + } else { + unzigzag(levels, &mut raster); + } + dequant_4x4(&mut raster, &e.ls, qp, skip_dc); + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + let mut ssd = 0i64; + for i in 0..16 { + let d = i64::from(source[i] - resid[i]); + ssd += d * d; + } + ssd +} + +/// How much of the mode-decision lambda rate-distortion quantisation uses. +/// +/// The bits here are the coder's own, not an estimate, so there is no +/// over-estimate to correct for and the scale starts at 1. Swept over 0.5, +/// 1.0, 1.25, 1.5 and 2.0 against x264 on a 3840x1608 film clip and a +/// 2560x1440 screen capture: the two disagree, film reading -0.607 dB at 0.5 +/// and -0.680 at 1.5 while screen capture reads -0.620 and -0.444, and 1.0 is +/// the crossing point that costs neither (-0.628 and -0.471). Table in +/// `lanes/h264x264-r2.report.md`. +pub(super) const RDOQ_LAMBDA: f64 = 1.0; + +/// The dead zone rate-distortion quantisation starts from, as a divisor of the +/// quantiser step: 2 is round-to-nearest. The plain inter path uses 6, which +/// has already thrown away the levels this search would weigh -- a search +/// bounded by the heuristic it replaces measures the heuristic. This is the +/// half of the change that pays: 1/6 -> 1/2 under the same search is worth +/// 0.102 dB on the film clip and 0.301 on the synthetic gate. 1/3 and 1/4 read +/// -0.647 and -0.677 dB where 1/2 reads -0.630. +pub(super) const RDOQ_DEAD_ZONE: i32 = 2; + +/// The largest level the search offers a smaller magnitude to. A big level is +/// carrying real signal and never wins by shrinking; bounding the search is +/// what keeps it free. Unbounded it tripled the synthetic clip's encode time +/// (1.08 s -> 3.53 s) for the same BD-PSNR; at 2 the run is 1.09 s. Swept over +/// 1, 2 and 3: -4.062/-0.623/-0.496, -4.073/-0.628/-0.471 and +/// -4.065/-0.629/-0.477 dB on synthetic, film and screen capture. +pub(super) const RDOQ_MAX_LEVEL: i32 = 2; + +/// The rounding the chroma AC path keeps under the search: the inter dead zone +/// it already had. Luma wanted the wider 1/2 rounding once a search could take +/// levels back down (`RDOQ_DEAD_ZONE`); chroma does not. Measured on the two +/// clips at the settled luma constants, BD-PSNR against x264: 1/2 rounding +/// -0.653 film / -0.482 screen capture, 1/4 -0.623 / -0.472, 1/3 -0.644 / +/// -0.481, and the 1/6 kept here -0.593 / -0.468 -- against -0.628 / -0.471 +/// with no chroma search at all. Chroma AC is sparse enough at these +/// quantisers that offering more levels costs more bits than the search takes +/// back; what pays is only the pruning. +pub(super) const RDOQ_CHROMA_DEAD_ZONE: i32 = 6; + +/// The rounding the 8x8 luma path keeps under the search. It answers the way +/// 4x4 luma did, not the way chroma did: measured as BD-PSNR of the opt-in +/// `transform_8x8` flag against flag-off, which isolates this path because the +/// flag-off curve does not run through it. Film 3840x1608 / screen capture +/// 2560x1440, no search +0.535 / +0.042, 1/6 +0.551 / --, 1/3 +0.605 / +0.075, +/// and the 1/2 kept here +0.619 / +0.067. The 8x8 blocks carry enough +/// coefficients for the extra levels to pay for themselves, as 4x4 luma's do. +pub(super) const RDOQ8_DEAD_ZONE: i32 = 2; + +/// Rate-distortion quantisation of one inter luma block: each level is offered +/// the two cheaper magnitudes below it, and takes one when the squared error it +/// gives up costs less than the bits it saves. +/// +/// The rate is the CABAC coder's own price for the whole block against the +/// context state as it stands, so dropping a level is priced with the +/// significance map that follows from it — which is where most of the saving +/// is. Intra blocks stay out: their reconstruction is what the next block in +/// the macroblock predicts from, so a level changed here would move a +/// prediction the decision cannot see. +#[allow(clippy::too_many_arguments)] +pub(super) fn rdoq_4x4( + e: &MbEnc<'_>, + w: &EncEntropy, + source: &[i32; 16], + levels: &mut [i32; 16], + qp: i32, + cat: BlockCat, + skip_dc: bool, +) -> u8 { + let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else { + return levels.iter().filter(|&&l| l != 0).count() as u8; + }; + let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0; + let mut cost = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits); + // Highest scanning position first: dropping the last significant level is + // what shortens the significance map, so it is tried while the levels + // above it are still gone. + for pos in (0..cat.max_num_coeff()).rev() { + let level = levels[pos]; + if level == 0 { + continue; + } + let mag = level.abs(); + if mag > RDOQ_MAX_LEVEL { + continue; + } + let mut tried = mag; + for candidate in [mag - 1, 0] { + if candidate == tried { + continue; + } + tried = candidate; + let keep = levels[pos]; + levels[pos] = candidate * level.signum(); + let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else { + unreachable!("CAVLC returned early"); + }; + let trial = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits); + if trial < cost { + cost = trial; + } else { + levels[pos] = keep; + } + } + } + // And the block as a whole: zeroing it drops the coded_block_pattern bit as + // well as every level, which no single-coefficient step can see. This is + // the same decision `worth_coding` makes for the paths without an exact + // rate, made here with one. + let zero_bits = w + .residual_block_cost(&[0; 16], cat, Some(1), Some(1)) + .expect("CABAC"); + let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum(); + if ssd_zero as f64 + lambda * f64::from(zero_bits) <= cost { + *levels = [0; 16]; + return 0; + } + levels.iter().filter(|&&l| l != 0).count() as u8 +} + +/// How much of the mode-decision lambda the zero-block test uses. +/// +/// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what +/// CAVLC spends and an over-estimate of what CABAC spends; the multiplier +/// brings the rate term back to the coder actually in force. Measured over +/// 0.0, 0.4 and 1.0 on 1080p camera and screen-capture clips: 0.4 is the only +/// one that gains on screen content (+0.13 to +0.39 dB at matched bitrate) +/// without costing camera content. +pub(super) const ZERO_BLOCK_LAMBDA: f64 = 0.4; + +pub(super) fn zero_block_lambda(e: &MbEnc<'_>, qp: i32, transform_8x8: bool) -> f64 { + if transform_8x8 { + e.lambda + } else { + ZERO_BLOCK_LAMBDA * lambda_ssd(qp) + } +} + +/// The rate-distortion test behind the per-block zero decision: coding the +/// block has to buy more squared error than its bits are worth. +pub(super) fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], lambda: f64) -> bool { + let mut ssd_zero = 0i64; + let mut ssd_coded = 0i64; + for i in 0..source.len() { + let z = i64::from(source[i]); + let c = i64::from(source[i] - resid[i]); + ssd_zero += z * z; + ssd_coded += c * c; + } + ssd_coded as f64 + lambda * (block_bits(levels) as f64) < ssd_zero as f64 +} + +/// Predict and code the luma of an Intra_16x16 macroblock. +#[allow(clippy::too_many_arguments)] +pub(super) fn code_i16_luma( + pic: &mut Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + qp: i32, + mode: u8, + nbr: &MbNeighbors, + lv: &mut Levels, +) { + let w4 = pic.mb_w * 4; + for dy in 0..4 { + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; + pic.i4_modes[base..base + 4].fill(2); + } + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + let mut win = PlaneWindow { + data: &mut pic.y.data, + stride, + origin, + }; + pred_16x16(mode, 8, &mut win, nbr.b, nbr.a); + code_luma_i16(pic, e, mb_x, mb_y, qp, lv); +} + +/// The Intra_16x16 luma path (8.5.10 in reverse then forward again). +pub(super) fn code_luma_i16( + pic: &mut Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + qp: i32, + lv: &mut Levels, +) { + let stride = pic.y.stride; + let mut dc = [0i32; 16]; + let mut ac = [[0i32; 16]; 16]; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + let origin = pic.y.at(x, y); + let mut d = [0i32; 16]; + for ry in 0..4 { + for rx in 0..4 { + d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) + - i32::from(pic.y.data[origin + ry * stride + rx]); + } + } + forward_4x4(&mut d); + dc[dy as usize * 4 + dx as usize] = d[0]; + let nz = quant_4x4(&d, qp, true, true, &mut lv.luma[blk]); + lv.luma_nz[blk] = nz; + ac[blk] = lv.luma[blk]; + if nz > 0 { + lv.cbp_luma = 15; + } + } + if lv.cbp_luma == 0 { + for blk in 0..16 { + lv.luma[blk] = [0; 16]; + lv.luma_nz[blk] = 0; + } + } + forward_hadamard_4x4(&mut dc); + quant_luma_dc(&dc, qp, &mut lv.dc); + + // Reconstruct exactly as the decoder does: DC through 8.5.10, then each + // block's AC with the DC substituted at raster position 0. + let mut raster = [0i32; 16]; + unzigzag(&lv.dc, &mut raster); + luma_dc_transform(&mut raster, &e.ls, qp); + let dc_recon = raster; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let dc_blk = dc_recon[dy as usize * 4 + dx as usize]; + let tc = lv.luma_nz[blk]; + if tc == 0 && dc_blk == 0 { + continue; + } + let mut raster = [0i32; 16]; + if tc > 0 { + unzigzag_ac15(&ac[blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp, true); + } + raster[0] = dc_blk; + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + let origin = pic + .y + .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); + add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid); + } +} + +/// Chroma residual for both components (8.5.11 + the AC path). +#[allow(clippy::too_many_arguments)] +pub(super) fn code_chroma( + pic: &mut Picture, + e: &MbEnc<'_>, + w: &EncEntropy, + mb_x: usize, + mb_y: usize, + qp_y: i32, + intra: bool, + lv: &mut Levels, +) { + let qp_c = chroma_qp(qp_y, e.cqo); + let mut dc_lists = [[0i32; 4]; 2]; + let mut ac = [[[0i32; 16]; 4]; 2]; + let mut srcs = [[[0i32; 16]; 4]; 2]; + let mut any_ac = false; + for comp in 0..2 { + let (plane, src) = if comp == 0 { + (&pic.cb, &e.src.u) + } else { + (&pic.cr, &e.src.v) + }; + let stride = plane.stride; + for blk in 0..4 { + let (x, y) = (mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4); + let origin = plane.at(x, y); + let mut d = [0i32; 16]; + for ry in 0..4 { + for rx in 0..4 { + d[ry * 4 + rx] = i32::from(src[(y + ry) * e.src.c_stride + x + rx]) + - i32::from(plane.data[origin + ry * stride + rx]); + } + } + let source = d; + srcs[comp][blk] = d; + forward_4x4(&mut d); + dc_lists[comp][blk] = d[0]; + let rdoq = !intra && w.is_cabac(); + let mut nz = if rdoq { + quant_4x4_offset(&d, qp_c, RDOQ_CHROMA_DEAD_ZONE, true, &mut ac[comp][blk]) + } else { + quant_4x4(&d, qp_c, intra, true, &mut ac[comp][blk]) + }; + if rdoq && nz > 0 { + nz = rdoq_4x4( + e, + w, + &source, + &mut ac[comp][blk], + qp_c, + BlockCat::ChromaAc, + true, + ); + } else if nz > 0 { + // The same zero decision as luma, against the AC part alone: + // the DC of this block travels through the 2x2 Hadamard and is + // decided with the other three. + let mut raster = [0i32; 16]; + unzigzag_ac15(&ac[comp][blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp_c, true); + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + if !worth_coding( + &source, + &resid, + &ac[comp][blk], + zero_block_lambda(e, qp_c, e.transform_8x8), + ) { + ac[comp][blk] = [0; 16]; + nz = 0; + } + } + lv.chroma_nz[comp][blk] = nz; + if nz > 0 { + any_ac = true; + } + } + } + // The chroma pattern is one decision for all eight AC blocks: a single + // surviving block takes coded_block_pattern from one to two, and every + // other block then has to code a coded_block_flag to say it is empty. So + // the same group test luma runs over four blocks runs here over all eight, + // against the same lambda. + if any_ac { + let (mut ssd_zero, mut ssd_coded, mut rate) = (0i64, 0i64, 0f64); + for comp in 0..2 { + for blk in 0..4 { + let source = &srcs[comp][blk]; + let mut resid = [0i32; 16]; + if lv.chroma_nz[comp][blk] > 0 { + let mut raster = [0i32; 16]; + unzigzag_ac15(&ac[comp][blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp_c, true); + inverse_transform_4x4(&raster, &mut resid); + rate += match w.residual_block_cost( + &ac[comp][blk], + BlockCat::ChromaAc, + Some(1), + Some(1), + ) { + Some(bits) => f64::from(bits) / 256.0, + None => block_bits(&ac[comp][blk]) as f64, + }; + } + for i in 0..16 { + let z = i64::from(source[i]); + let c = i64::from(source[i] - resid[i]); + ssd_zero += z * z; + ssd_coded += c * c; + } + } + } + let lambda = if w.is_cabac() { + GROUP_LAMBDA * lambda_ssd(qp_c) + } else { + zero_block_lambda(e, qp_c, false) + }; + if ssd_coded as f64 + lambda * (rate + CBP_CHROMA_BIT) >= ssd_zero as f64 { + ac = [[[0; 16]; 4]; 2]; + lv.chroma_nz = [[0; 4]; 2]; + any_ac = false; + } + } + // The chroma DC block had no zero test at all: whatever the quantiser + // produced was coded. Its four coefficients spread over all 64 samples of + // the component, and with only DC in the block the inverse transform gives + // every sample the same (dc + 32) >> 6, so the squared error zeroing costs + // is exact in one pass over the AC residual that is already reconstructed + // here. + let mut any_dc = false; + for comp in 0..2 { + forward_hadamard_2x2(&mut dc_lists[comp]); + let mut nz = quant_chroma_dc(&dc_lists[comp], qp_c, intra, &mut lv.chroma_dc[comp]); + if nz > 0 { + let mut dc = [ + lv.chroma_dc[comp][0], + lv.chroma_dc[comp][1], + lv.chroma_dc[comp][2], + lv.chroma_dc[comp][3], + ]; + chroma_dc_transform_420(&mut dc, &e.ls, qp_c); + let mut delta = 0i64; + for blk in 0..4 { + let mut resid = [0i32; 16]; + if any_ac && lv.chroma_nz[comp][blk] > 0 { + let mut raster = [0i32; 16]; + unzigzag_ac15(&ac[comp][blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp_c, true); + inverse_transform_4x4(&raster, &mut resid); + } + let c = i64::from((dc[blk] + 32) >> 6); + let err: i64 = (0..16) + .map(|i| i64::from(srcs[comp][blk][i] - resid[i])) + .sum(); + delta += 16 * c * c - 2 * c * err; + } + let rate = match w.residual_block_cost( + &lv.chroma_dc[comp], + BlockCat::ChromaDc(comp as u8), + Some(1), + Some(1), + ) { + Some(bits) => f64::from(bits) / 256.0, + None => block_bits(&lv.chroma_dc[comp]) as f64, + }; + if delta as f64 + CHROMA_DC_LAMBDA * lambda_ssd(qp_c) * rate >= 0.0 { + lv.chroma_dc[comp] = [0; 16]; + nz = 0; + } + } + if nz > 0 { + any_dc = true; + } + } + lv.cbp_chroma = if any_ac { + 2 + } else if any_dc { + 1 + } else { + 0 + }; + if lv.cbp_chroma < 2 { + lv.chroma_nz = [[0; 4]; 2]; + } else { + lv.chroma = ac; + } + if lv.cbp_chroma == 0 { + return; + } + for comp in 0..2 { + let mut dc = [ + lv.chroma_dc[comp][0], + lv.chroma_dc[comp][1], + lv.chroma_dc[comp][2], + lv.chroma_dc[comp][3], + ]; + chroma_dc_transform_420(&mut dc, &e.ls, qp_c); + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = plane.stride; + for blk in 0..4 { + let tc = lv.chroma_nz[comp][blk]; + if tc == 0 && dc[blk] == 0 { + continue; + } + let mut raster = [0i32; 16]; + if tc > 0 { + unzigzag_ac15(&lv.chroma[comp][blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp_c, true); + } + raster[0] = dc[blk]; + let mut resid = [0i32; 16]; + inverse_transform_4x4(&raster, &mut resid); + let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4); + add_residual_4x4(&mut plane.data, 8, stride, origin, &resid); + } + } +} + +/// The inter residual under the 8x8 transform, prediction already in the +/// plane: the sibling of [`code_luma_4x4`]. +pub(super) fn code_luma_8x8( + pic: &mut Picture, + e: &MbEnc<'_>, + w: &EncEntropy, + mb_x: usize, + mb_y: usize, + qp: i32, + lv: &mut Levels, +) { + lv.trans8 = true; + for blk8 in 0..4 { + let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8); + if code_block_8x8(pic, e, w, x, y, qp, false, &mut lv.luma8[blk8]) > 0 { + lv.cbp_luma |= 1 << blk8; + } + } +} + +/// Squared error of coding `levels` as an 8x8 block, in its pixels. +pub(super) fn block_ssd_8x8(e: &MbEnc<'_>, source: &[i32; 64], levels: &[i32; 64], qp: i32) -> i64 { + let mut raster = [0i32; 64]; + unzigzag_8x8(levels, &mut raster); + dequant_8x8(&mut raster, &e.ls8, qp); + let mut resid = [0i32; 64]; + inverse_transform_8x8(&raster, &mut resid); + let mut ssd = 0i64; + for k in 0..64 { + let d = i64::from(source[k]) - i64::from(resid[k]); + ssd += d * d; + } + ssd +} + +/// [`rdoq_4x4`] for the 8x8 transform: the same walk down the scan against the +/// CABAC coder's own price, with the 8x8 block's own contexts. +pub(super) fn rdoq_8x8( + e: &MbEnc<'_>, + w: &EncEntropy, + source: &[i32; 64], + levels: &mut [i32; 64], + qp: i32, +) -> u8 { + let Some(bits) = w.residual_block_8x8_cost(levels) else { + return levels.iter().filter(|&&l| l != 0).count() as u8; + }; + let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0; + let mut cost = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits); + for pos in (0..64).rev() { + let level = levels[pos]; + if level == 0 { + continue; + } + let mag = level.abs(); + if mag > RDOQ_MAX_LEVEL { + continue; + } + let mut tried = mag; + for candidate in [mag - 1, 0] { + if candidate == tried { + continue; + } + tried = candidate; + let keep = levels[pos]; + levels[pos] = candidate * level.signum(); + let bits = w + .residual_block_8x8_cost(levels) + .expect("CAVLC returned early"); + let trial = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits); + if trial < cost { + cost = trial; + } else { + levels[pos] = keep; + break; + } + } + } + // The whole block against nothing, on the same exact price. + let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum(); + if ssd_zero as f64 <= cost { + *levels = [0; 64]; + return 0; + } + levels.iter().filter(|&&l| l != 0).count() as u8 +} + +/// Squared error of the luma macroblock against the source. +pub(super) fn ssd_luma(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + let mut sum = 0i64; + for row in 0..16 { + let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16; + for x in 0..16 { + let d = i64::from(e.src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]); + sum += d * d; + } + } + sum +} + +/// Copy the luma macroblock out of the plane, and back in. +pub(super) fn save_luma(pic: &Picture, mb_x: usize, mb_y: usize, out: &mut [u8; 256]) { + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + for row in 0..16 { + out[row * 16..row * 16 + 16].copy_from_slice(&pic.y.data[origin + row * stride..][..16]); + } +} + +pub(super) fn restore_luma(pic: &mut Picture, mb_x: usize, mb_y: usize, src: &[u8; 256]) { + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + for row in 0..16 { + pic.y.data[origin + row * stride..][..16].copy_from_slice(&src[row * 16..row * 16 + 16]); + } +} + +pub(super) fn rough_intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 { + let mut bits = estimate_luma_bits(lv); + match i4 { + Some((modes, pred)) => { + bits += 6; + for blk in 0..modes.len() { + bits += if modes[blk] == pred[blk] { 1 } else { 4 }; + } + } + None => bits += 8, + } + bits +} + +pub(super) fn entropy_bits(w: &EncEntropy, write: impl FnOnce(&mut EncEntropy)) -> i64 { + let mut probe = w.probe_copy(); + let before = probe.bit_len(); + write(&mut probe); + (probe.bit_len() - before) as i64 +} + +pub(super) fn cost_luma_nz_pair( + pic: &Picture, + nbr: &MbNeighbors, + local: &[u8; 16], + bx0: usize, + by0: usize, + bx: usize, + by: usize, +) -> (Option, Option) { + let w4 = pic.mb_w * 4; + let left_avail = if bx.is_multiple_of(4) { nbr.a } else { true }; + let top_avail = if by.is_multiple_of(4) { nbr.b } else { true }; + let left = (left_avail && bx > 0).then(|| { + if bx > bx0 { + local[(by - by0) * 4 + (bx - bx0 - 1)] + } else { + pic.nz_y[by * w4 + bx - 1] + } + }); + let top = (top_avail && by > 0).then(|| { + if by > by0 { + local[(by - by0 - 1) * 4 + (bx - bx0)] + } else { + pic.nz_y[(by - 1) * w4 + bx] + } + }); + (left, top) +} + +pub(super) fn write_luma_for_cost( + pic: &Picture, + nbr: &MbNeighbors, + w: &mut EncEntropy, + mb_x: usize, + mb_y: usize, + lv: &Levels, + is_i16: bool, +) { + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let mut nz = [0u8; 16]; + if is_i16 { + let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx0, by0); + nz[0] = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb); + } + if lv.trans8 { + for blk8 in 0..4 { + let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); + if lv.cbp_luma & (1 << blk8) == 0 { + continue; + } + if w.is_cabac() { + let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None); + for dy in 0..2 { + let base = (by - by0 + dy) * 4 + bx - bx0; + nz[base..base + 2].fill(tc.min(16)); + } + } else { + for i4 in 0..4 { + let (dx, dy) = BLK4_POS[blk8 * 4 + i4]; + let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize); + let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, sx, sy); + let sub = sub_block_4x4(&lv.luma8[blk8], i4); + nz[(sy - by0) * 4 + (sx - bx0)] = + w.residual_block(&sub, BlockCat::Luma4x4, na, nb); + } + } + } + return; + } + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + let group = 1 << (blk >> 2); + let coded_block = if is_i16 { + lv.cbp_luma != 0 + } else { + lv.cbp_luma & group != 0 + }; + if coded_block { + let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx, by); + let (levels, cat) = if is_i16 { + (&lv.luma[blk][..15], BlockCat::LumaAc) + } else { + (&lv.luma[blk][..16], BlockCat::Luma4x4) + }; + nz[(by - by0) * 4 + (bx - bx0)] = w.residual_block(levels, cat, na, nb); + } + } +} + +#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly +pub(super) fn cost_chroma_nz_pair( + pic: &Picture, + nbr: &MbNeighbors, + local: &[[u8; 4]; 2], + comp: usize, + cx0: usize, + cy0: usize, + cx: usize, + cy: usize, +) -> (Option, Option) { + let w2 = pic.mb_w * 2; + let left_avail = if cx.is_multiple_of(2) { nbr.a } else { true }; + let top_avail = if cy.is_multiple_of(2) { nbr.b } else { true }; + let left = (left_avail && cx > 0).then(|| { + if cx > cx0 { + local[comp][(cy - cy0) * 2 + (cx - cx0 - 1)] + } else { + pic.nz_c[comp][cy * w2 + cx - 1] + } + }); + let top = (top_avail && cy > 0).then(|| { + if cy > cy0 { + local[comp][(cy - cy0 - 1) * 2 + (cx - cx0)] + } else { + pic.nz_c[comp][(cy - 1) * w2 + cx] + } + }); + (left, top) +} + +pub(super) fn write_chroma_for_cost( + pic: &Picture, + nbr: &MbNeighbors, + w: &mut EncEntropy, + mb_x: usize, + mb_y: usize, + lv: &Levels, +) { + if lv.cbp_chroma != 0 { + for comp in 0..2 { + w.residual_block( + &lv.chroma_dc[comp][..4], + BlockCat::ChromaDc(comp as u8), + None, + None, + ); + } + } + if lv.cbp_chroma != 2 { + return; + } + let (cx0, cy0) = (mb_x * 2, mb_y * 2); + let mut nz = [[0u8; 4]; 2]; + for comp in 0..2 { + for blk in 0..4 { + let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); + let (na, nb) = cost_chroma_nz_pair(pic, nbr, &nz, comp, cx0, cy0, cx, cy); + nz[comp][blk] = + w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb); + } + } +} + +/// Eight samples widened to 16-bit lanes; the tail past the slice is zero, +/// which only a caller reading past the plane could reach. +#[inline] +pub(super) fn load8(data: &[u8], at: usize) -> i16x8 { + let mut a = [0i16; 8]; + if let Some(row) = data.get(at..at + 8) { + for (o, &b) in a.iter_mut().zip(row) { + *o = i16::from(b); + } + } + i16x8::from(a) +} + +/// Squared error of the whole macroblock against the source, luma and chroma: +/// the distortion term of the skip decision. +/// +/// Each row's 16 (luma) or 8 (chroma) per-pixel differences fit in `i16` +/// (range `-255..=255`), and `dot` widens the pairwise products to `i32` +/// before summing, so this is the exact same integer value as scalar +/// `i64::from(d) * i64::from(d)` per pixel, just batched a row at a time and +/// summed into the `i64` accumulator in a different (still overflow-free, +/// so exact) order. +pub(super) fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { + let mut sum = 0i64; + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + for row in 0..16 { + let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16; + let d = load16(&e.src.y, s) - load16(&pic.y.data, origin + row * stride); + sum += d + .dot(d) + .to_array() + .iter() + .map(|&v| i64::from(v)) + .sum::(); + } + for comp in 0..2 { + let (plane, src) = if comp == 0 { + (&pic.cb, &e.src.u) + } else { + (&pic.cr, &e.src.v) + }; + let stride = plane.stride; + let origin = plane.at(mb_x * 8, mb_y * 8); + for row in 0..8 { + let s = (mb_y * 8 + row) * e.src.c_stride + mb_x * 8; + let d = load8(src, s) - load8(&plane.data, origin + row * stride); + sum += d + .dot(d) + .to_array() + .iter() + .map(|&v| i64::from(v)) + .sum::(); + } + } + sum +} + +/// [`ssd_mb`] with the luma half measured after the loop filter this +/// macroblock's reconstruction will get. `bs(edge, seg, vertical)` is the +/// boundary strength of one 4-sample edge segment — edge 0 the macroblock +/// edge, edges 1..3 the internal edges at offsets 4/8/12 — as the decoder +/// will derive it, so an intra candidate passes its forced 4/3 and an inter +/// candidate its own coded/motion strengths. A transform-8x8 macroblock has +/// no transform edge at luma offsets 4 and 12, so those stay unfiltered, +/// exactly as the decoder's `internal` gate decides it. Neighbours share +/// this slice's qp with the zero offsets the encoder writes, so every edge +/// is parameterised by the trial qp alone. The right and bottom edges +/// belong to macroblocks coded later and cannot be known here; the aprons +/// are the pre-filter neighbour samples, which is everything that exists at +/// decision time. The chroma half is left pre-filter: chroma never takes +/// the 8x8 transform, so it cannot separate the candidates. +/// +/// The 8x8-vs-4x4 trials are judged by this and not by [`ssd_mb`] because the +/// two candidates meet different edge sets under the same loop filter: a +/// pre-filter SSD prices the 4x4 candidate as if its extra filtered edges +/// cost nothing. +pub(super) fn ssd_mb_deblocked( + pic: &Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + nbr: &MbNeighbors, + trans8: bool, + bs: impl Fn(usize, usize, bool) -> u8, +) -> i64 { + // The macroblock at (A, A) plus 4-sample left and top aprons: a bS-4 + // edge reads p3 and rewrites p2 on its far side. + const A: usize = 4; + const S: usize = A + 16; + let mut scratch = [0u8; S * S]; + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + for row in 0..16 { + let src = origin + row * stride; + let dst = (A + row) * S + A; + scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]); + } + if nbr.a { + for row in 0..16 { + let src = origin + row * stride - A; + let dst = (A + row) * S; + scratch[dst..dst + A].copy_from_slice(&pic.y.data[src..src + A]); + } + } + if nbr.b { + for row in 0..A { + let src = origin - (A - row) * stride; + let dst = row * S + A; + scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]); + } + } + // Vertical edges left to right, then horizontal top to bottom, the order + // of 8.7.1: each edge filters what the earlier edges left behind. Each + // 4-sample segment carries its own strength, as in the decoder. + let qp = e.target_qp; + for edge in 0..4 { + let x = edge * 4; + if (edge == 0 && !nbr.a) || (trans8 && x != 0 && x != 8) { + continue; + } + for seg in 0..4 { + let s = bs(edge, seg, true); + if s == 0 { + continue; + } + let ep = edge_params(qp, 0, 0, s, 8); + for row in seg * 4..seg * 4 + 4 { + filter_luma_line(&mut scratch, 255, (A + row) * S + A + x, 1, &ep); + } + } + } + for edge in 0..4 { + let y = edge * 4; + if (edge == 0 && !nbr.b) || (trans8 && y != 0 && y != 8) { + continue; + } + let seg_bs = [ + bs(edge, 0, false), + bs(edge, 1, false), + bs(edge, 2, false), + bs(edge, 3, false), + ]; + if seg_bs[0] == seg_bs[1] && seg_bs[1] == seg_bs[2] && seg_bs[2] == seg_bs[3] { + if seg_bs[0] != 0 { + let ep = edge_params(qp, 0, 0, seg_bs[0], 8); + filter_luma_h_edge16(&mut scratch, (A + y) * S + A, S, &ep); + } + continue; + } + for seg in 0..4 { + if seg_bs[seg] == 0 { + continue; + } + let ep = edge_params(qp, 0, 0, seg_bs[seg], 8); + for col in seg * 4..seg * 4 + 4 { + filter_luma_line(&mut scratch, 255, (A + y) * S + A + col, S, &ep); + } + } + } + let mut sum = ssd_mb(pic, e, mb_x, mb_y) - ssd_luma(pic, e, mb_x, mb_y); + for row in 0..16 { + let src = (mb_y * 16 + row) * e.src.stride + mb_x * 16; + for x in 0..16 { + let d = i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]); + sum += d * d; + } + } + sum +} + +/// Boundary strengths an intra candidate forces (8.7.2.1): 4 on its +/// macroblock edges, 3 on the internal luma edges. +pub(super) fn intra_bs(edge: usize, _seg: usize, _vertical: bool) -> u8 { + if edge == 0 { 4 } else { 3 } +} + +/// Rough bit cost of a macroblock's luma residual. +pub(super) fn estimate_luma_bits(lv: &Levels) -> i64 { + let mut bits = 0; + if lv.trans8 { + for blk8 in 0..4 { + if lv.cbp_luma & (1 << blk8) != 0 { + // A level's position costs two more bits in a 64-coefficient + // significance map than in a 16-coefficient one; measured + // against the coded size on the text clip, without this the + // estimate undercharges Intra_8x8 by ~44 bits a macroblock. + let b = &lv.luma8[blk8]; + bits += block_bits(b) + 2 * b.iter().filter(|&&l| l != 0).count() as i64; + } + } + return bits; + } + for blk in 0..16 { + if lv.cbp_luma & (1 << (blk >> 2)) != 0 { + bits += block_bits(&lv.luma[blk]); + } + } + if lv.cbp_luma == 15 { + // Intra_16x16 also carries the DC block. + bits += block_bits(&lv.dc); + } + bits +} + +/// Bits one residual block costs, to the accuracy a mode decision needs. +pub(super) fn block_bits(b: &[i32]) -> i64 { + let mut n = 0i64; + for &l in b { + if l != 0 { + n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1; + } + } + if n > 0 { n + 6 } else { 2 } +} + +/// Rough bit cost of a macroblock's residual, for the skip decision: a level +/// costs its magnitude's exp-Golomb-ish width, a coded block its token. +pub(super) fn estimate_bits(lv: &Levels) -> i64 { + let mut bits = 10 + estimate_luma_bits(lv); + if lv.cbp_chroma != 0 { + for comp in 0..2 { + bits += block_bits(&lv.chroma_dc[comp][..4]); + if lv.cbp_chroma == 2 { + for blk in 0..4 { + bits += block_bits(&lv.chroma[comp][blk][..15]); + } + } + } + } + bits +} + +/// What the residual writer needs to know about the macroblock it closes. +pub(super) struct MbRecord { + pub(super) intra: bool, + pub(super) is_i16: bool, + pub(super) chroma_mode: u8, + /// The QP the residual was quantised at. + pub(super) qp: i32, +} + +/// mb_qp_delta, the residual blocks and the per-macroblock metadata: the +/// writing half of [`crate::decoder::finish_macroblock`]. +pub(super) fn finish_mb( + pic: &mut Picture, + e: &mut MbEnc<'_>, + w: &mut EncEntropy, + mb_addr: usize, + nbr: &MbNeighbors, + lv: &Levels, + m: MbRecord, +) { + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + let w4 = pic.mb_w * 4; + let w2 = pic.mb_w * 2; + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let (cx0, cy0) = (mb_x * 2, mb_y * 2); + + let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || m.is_i16; + let qp_y = if coded { + let delta = m.qp - e.qp; + w.mb_qp_delta(delta); + e.qp_delta_inc = u8::from(delta != 0); + e.qp = m.qp; + m.qp + } else { + // No residual: the QP prediction chain is untouched (7.4.5), and the + // deblocking filter uses the chain value. + e.qp_delta_inc = 0; + e.qp + }; + pic.mb_qp[mb_addr] = qp_y as i8; + pic.mb_flags[mb_addr] = FLAG_DECODED + | if m.is_i16 { FLAG_I16 } else { 0 } + | if m.intra { 0 } else { FLAG_INTER } + // The flag only reaches the stream when the decoder reads it (7.3.5). + | if lv.trans8 && (m.intra || lv.cbp_luma != 0) { + FLAG_TRANS8X8 + } else { + 0 + } + | if m.intra && m.chroma_mode != 0 { + FLAG_CHROMA_PRED + } else { + 0 + }; + pic.mb_cbp[mb_addr] = lv.cbp_luma | (lv.cbp_chroma << 4); + pic.mb_slice[mb_addr] = e.slice_id; + pic.decoded_mbs += 1; + + let mut dc_cbf = 0u8; + // Luma DC (Intra_16x16 only), then the luma blocks in Z-order. + if m.is_i16 { + let (na, nb) = luma_nz_pair(pic, nbr, bx0, by0); + let tc = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb); + dc_cbf |= u8::from(tc != 0); + } + if lv.trans8 { + // The decoder's 8x8 branch: CABAC codes one cat-5 block and reports + // its count in every 4x4 slot; CAVLC codes four interleaved 4x4 + // blocks, each with its own nC and count. + for blk8 in 0..4 { + let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); + if lv.cbp_luma & (1 << blk8) == 0 { + for dy in 0..2 { + let base = (by + dy) * w4 + bx; + pic.nz_y[base..base + 2].fill(0); + } + } else if w.is_cabac() { + let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None); + for dy in 0..2 { + let base = (by + dy) * w4 + bx; + pic.nz_y[base..base + 2].fill(tc.min(16)); + } + } else { + for i4 in 0..4 { + let (dx, dy) = BLK4_POS[blk8 * 4 + i4]; + let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize); + let (na, nb) = luma_nz_pair(pic, nbr, sx, sy); + let sub = sub_block_4x4(&lv.luma8[blk8], i4); + pic.nz_y[sy * w4 + sx] = w.residual_block(&sub, BlockCat::Luma4x4, na, nb); + } + } + } + } + for blk in 0..16 { + if lv.trans8 { + break; + } + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + let group = 1 << (blk >> 2); + let coded_block = if m.is_i16 { + lv.cbp_luma != 0 + } else { + lv.cbp_luma & group != 0 + }; + let tc = if coded_block { + let (na, nb) = luma_nz_pair(pic, nbr, bx, by); + let (levels, cat) = if m.is_i16 { + (&lv.luma[blk][..15], BlockCat::LumaAc) + } else { + (&lv.luma[blk][..16], BlockCat::Luma4x4) + }; + w.residual_block(levels, cat, na, nb) + } else { + 0 + }; + pic.nz_y[by * w4 + bx] = tc; + } + // Chroma DC then chroma AC, in bitstream order. + if lv.cbp_chroma != 0 { + for comp in 0..2 { + let tc = w.residual_block( + &lv.chroma_dc[comp][..4], + BlockCat::ChromaDc(comp as u8), + None, + None, + ); + dc_cbf |= u8::from(tc != 0) << (1 + comp); + } + } + for comp in 0..2 { + for blk in 0..4 { + let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); + let tc = if lv.cbp_chroma == 2 { + let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy); + w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb) + } else { + 0 + }; + pic.nz_c[comp][cy * w2 + cx] = tc; + } + } + pic.mb_dc_cbf[mb_addr] = dc_cbf; +} + diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs index 4c9e7a83..98769597 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -20,6 +20,7 @@ //! once over the whole picture, across slice boundaries exactly as a decoder //! runs it. No `unsafe`, no shared mutable state at all. +mod analysis; mod cabac_enc; mod entropy; mod headers; @@ -34,13 +35,14 @@ use ec_core::error::{Error, Result}; use ec_h264_syntax::nal::{NalUnitType, escape_rbsp}; use ec_h264_syntax::{SliceType, Sps}; -use crate::decoder::deblock_picture; +use crate::deblock::deblock_picture; use crate::dpb::{Picture, SliceParams as DeblockParams}; use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8}; use crate::transform::{LevelScale4x4, LevelScale8x8}; use entropy::EncEntropy; use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps}; +use analysis::{chroma_qp_offset_for_source, fast_knobs, lambda_for, lambda_ssd}; use mb::{MbEnc, Source, encode_mb}; use pool::BandPool; use rc::RateControl; @@ -304,7 +306,6 @@ impl Encoder { pub fn encode(&mut self, frame: &PictureView<'_>) -> Result { self.encode_with(frame, false) } - /// [`Encoder::encode`], coding the picture as an IDR when `force_keyframe` /// is set; the GOP restarts from it. pub fn encode_with( @@ -312,6 +313,12 @@ impl Encoder { frame: &PictureView<'_>, force_keyframe: bool, ) -> Result { + let step = self.begin_frame(frame, force_keyframe)?; + let outputs = self.code_bands(&step); + Ok(self.finish_frame(step, outputs)) + } + + fn begin_frame(&mut self, frame: &PictureView<'_>, force_keyframe: bool) -> Result { if frame.width != self.cfg.width || frame.height != self.cfg.height { return Err(Error::corrupt("frame size differs from the encoder's")); } @@ -333,13 +340,23 @@ impl Encoder { self.frame_num = 0; } let slice_type = if idr { SliceType::I } else { SliceType::P }; - let mb_w = self.sps.mb_width as usize; let mb_h = self.sps.mb_height as usize; let bands = split_bands(mb_h, self.threads); let picture_id = self.next_id; self.next_id = self.next_id.wrapping_add(1); + Ok(FrameStep { + idr, + qp, + slice_type, + mb_w, + mb_h, + bands, + picture_id, + }) + } + fn code_bands(&mut self, step: &FrameStep) -> Vec> { // Per-band coding. Every worker owns its picture and its bitstream; // the frame's shared inputs (source, reference, parameters) travel in // one `Arc`, and come back to the encoder once every band has answered. @@ -348,20 +365,20 @@ impl Encoder { cfg: self.cfg.clone(), rc: self.rc.clone(), src: std::mem::take(&mut self.src), - reference: (!idr).then(|| std::mem::take(&mut self.reference)), - bands: bands.clone(), - slice_type, + reference: (!step.idr).then(|| std::mem::take(&mut self.reference)), + bands: step.bands.clone(), + slice_type: step.slice_type, frame_num: self.frame_num, - idr, + idr: step.idr, idr_pic_id: self.idr_pic_id, - qp, - target: self.rc.frame_target(idr), - total_mbs: (mb_w * mb_h) as f64, + qp: step.qp, + target: self.rc.frame_target(step.idr), + total_mbs: (step.mb_w * step.mb_h) as f64, cqo: self.cqo, - mb_w, + mb_w: step.mb_w, }); - let mut answers = Vec::with_capacity(bands.len()); + let mut answers = Vec::with_capacity(step.bands.len()); if self.threads == 1 { // One band: coded on this thread, with no workers. let pic = std::mem::take(&mut self.workers[0]); @@ -369,7 +386,7 @@ impl Encoder { pic, shared: Arc::clone(&shared), band: 0, - picture_id, + picture_id: step.picture_id, })); } else { let threads = self.threads; @@ -383,15 +400,15 @@ impl Encoder { pic: std::mem::take(worker), shared: Arc::clone(&shared), band, - picture_id, + picture_id: step.picture_id, }, ); } - for band in 0..bands.len() { + for band in 0..step.bands.len() { answers.push(pool.collect(band)); } } - let mut outputs: Vec> = Vec::with_capacity(bands.len()); + let mut outputs: Vec> = Vec::with_capacity(step.bands.len()); for (band, answer) in answers.into_iter().enumerate() { outputs.push(answer.rbsp); self.workers[band] = answer.pic; @@ -404,13 +421,16 @@ impl Encoder { if let Some(reference) = shared.reference { self.reference = reference; } + outputs + } + fn finish_frame(&mut self, step: FrameStep, outputs: Vec>) -> EncodedPicture { // Stitch the bands into worker 0's picture, then filter the whole // picture the way a decoder does. let (first, rest) = self.workers.split_at_mut(1); let master = &mut first[0]; master.slices.clear(); - for _ in 0..bands.len() { + for _ in 0..step.bands.len() { master.slices.push(DeblockParams { disable_deblock_idc: 0, alpha_offset: 0, @@ -419,7 +439,7 @@ impl Encoder { cr_qp_offset: self.cqo, }); } - for (band, worker) in bands.iter().skip(1).zip(rest.iter()) { + for (band, worker) in step.bands.iter().skip(1).zip(rest.iter()) { merge_band(master, worker, *band); } for &f in &master.mb_flags { @@ -439,11 +459,11 @@ impl Encoder { // Assemble the access unit. let mut au = Vec::with_capacity(outputs.iter().map(Vec::len).sum::() + 64); - if idr { + if step.idr { au.extend_from_slice(&self.sps_nal); au.extend_from_slice(&self.pps_nal); } - let unit = if idr { + let unit = if step.idr { NalUnitType::SliceIdr } else { NalUnitType::Slice @@ -453,17 +473,17 @@ impl Encoder { } let bits = au.len() as u64 * 8; - self.rc.update(idr, qp, bits); + self.rc.update(step.idr, step.qp, bits); self.frames += 1; self.frame_num = (self.frame_num + 1) % (1 << headers::LOG2_MAX_FRAME_NUM); - if idr { + if step.idr { self.idr_pic_id ^= 1; } - Ok(EncodedPicture { + EncodedPicture { au, - key_frame: idr, - qp, - }) + key_frame: step.idr, + qp: step.qp, + } } /// Copy the caller's planes into whole-macroblock buffers, replicating the @@ -512,80 +532,16 @@ impl Encoder { } } -/// Everything one band worker needs. -/// Mean absolute neighbour difference of one plane, horizontal and vertical -/// averaged, over the `w` by `h` samples at the top left of `plane`. -fn mean_gradient(plane: &[u8], stride: usize, w: usize, h: usize) -> f64 { - let (mut sum, mut n) = (0u64, 0u64); - for y in 0..h { - let row = &plane[y * stride..y * stride + w]; - for x in 1..w { - sum += u64::from(row[x].abs_diff(row[x - 1])); - n += 1; - } - if y > 0 { - let prev = &plane[(y - 1) * stride..(y - 1) * stride + w]; - for x in 0..w { - sum += u64::from(row[x].abs_diff(prev[x])); - n += 1; - } - } - } - if n == 0 { 0.0 } else { sum as f64 / n as f64 } -} - -/// `chroma_qp_index_offset` for a source, from how textured its chroma is -/// relative to its luma. -/// -/// A negative offset spends bits on chroma that luma would otherwise take. -/// That pays when the chroma planes are flat — screen capture, phone video, -/// anything with large constant-hue areas — because their few edges are what -/// the eye reads, and it loses on film, whose chroma carries as much detail as -/// its luma and whose luma is the better place for the same bits. The -/// separating statistic is the mean absolute sample gradient of the chroma -/// planes over that of luma, measured on the first source picture. -/// BD-PSNR-YUV against x264, GOP 10, QP 22/26/30/34, `Preset::Balanced`, over -/// nine clips of the user's library, offset 0 against offset -2: -/// -/// ```text -/// chroma/luma gradient 0 -> -2 (dB) -/// 0.013 +0.019 -/// 0.092 +0.181 -/// 0.094 +0.228 -/// 0.098 +0.014 -/// 0.118 +0.081 -/// 0.122 +0.045 -/// 0.128 +0.065 -/// 0.286 +0.011 -/// 0.911 -0.158 -/// ``` -/// -/// Every clip whose chroma is flatter than its luma gains; the one film clip, -/// whose chroma gradient is nearly its luma's, loses. The threshold sits in -/// the middle of the gap the data leaves. -fn chroma_qp_offset_for_source(src: &Source, width: u32, height: u32) -> i32 { - let (w, h) = (width as usize, height as usize); - let (cw, ch) = (w / 2, h / 2); - let luma = mean_gradient(&src.y, src.stride, w, h); - if luma <= 0.0 { - return 0; - } - let chroma = (mean_gradient(&src.u, src.c_stride, cw, ch) - + mean_gradient(&src.v, src.c_stride, cw, ch)) - / 2.0; - if chroma / luma < CHROMA_FLAT_RATIO { - CHROMA_FLAT_QP_OFFSET - } else { - 0 - } +struct FrameStep { + idr: bool, + qp: i32, + slice_type: SliceType, + mb_w: usize, + mb_h: usize, + bands: Vec<(usize, usize)>, + picture_id: i32, } -/// Chroma is "flat" below this share of the luma gradient. -const CHROMA_FLAT_RATIO: f64 = 0.5; - -/// The offset flat chroma is coded with. -const CHROMA_FLAT_QP_OFFSET: i32 = -2; - /// What every band of one picture reads. The workers share it through an `Arc`. struct FrameShared { sps: Sps, @@ -740,71 +696,6 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { w.finish(job.slice_type == SliceType::P) } -/// The Fast-preset speed settings: the defaults, with `EC_H264_INTRA_GATE` -/// (a number) and `EC_H264_SKIP_I8` (any value but 0 skips Intra_8x8) as -/// sweep overrides. Read once per band, so they cost nothing per macroblock. -fn fast_knobs() -> mb::FastKnobs { - let mut k = mb::FastKnobs::default(); - if let Some(g) = std::env::var("EC_H264_INTRA_GATE") - .ok() - .and_then(|v| v.parse().ok()) - { - k.intra_gate = g; - } - if let Ok(v) = std::env::var("EC_H264_SKIP_I8") { - k.skip_i8 = v != "0"; - } - if let Some(v) = std::env::var("EC_H264_ME_SUB") - .ok() - .and_then(|v| v.parse().ok()) - { - k.me_sub = v; - } - if let Ok(v) = std::env::var("EC_H264_ME_SATD") { - k.me_satd = v != "0"; - } - if let Some(v) = std::env::var("EC_H264_INTER_TX") - .ok() - .and_then(|v| v.parse().ok()) - { - k.inter_tx = v; - } - if let Ok(v) = std::env::var("EC_H264_LAZY_I16") { - k.lazy_i16 = v != "0"; - } - if let Some(v) = std::env::var("EC_H264_EARLY_SKIP") - .ok() - .and_then(|v| v.parse().ok()) - { - k.early_skip = v; - } - if let Some(v) = std::env::var("EC_H264_TX8_NZ") - .ok() - .and_then(|v| v.parse().ok()) - { - k.tx8_nz_limit = v; - } - if let Ok(v) = std::env::var("EC_H264_P_SKIP_I8") { - k.p_skip_i8 = v != "0"; - } - k -} - -/// Standard Lagrangian multiplier in the squared-error domain. -pub(crate) fn lambda_ssd(qp: i32) -> f64 { - 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() -} - -/// Lagrangian multiplier. Production uses the established byte-stable ladder; -/// the ablation feature can select the standard squared-error multiplier. -fn lambda_for(qp: i32, standard: bool) -> f64 { - if standard { - lambda_ssd(qp) - } else { - (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0) - } -} - /// Split `mb_h` macroblock rows into at most `n` contiguous bands. fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> { let n = n.clamp(1, mb_h); @@ -927,6 +818,7 @@ fn rational_timing(fps: f64) -> (u32, u32) { #[cfg(test)] mod tests { use super::*; + use super::analysis::CHROMA_FLAT_QP_OFFSET; #[test] fn bands_cover_every_row_once() { diff --git a/crates/ec-h264/src/lib.rs b/crates/ec-h264/src/lib.rs index 5d5ae4cb..dc363d8e 100644 --- a/crates/ec-h264/src/lib.rs +++ b/crates/ec-h264/src/lib.rs @@ -43,6 +43,7 @@ mod cavlc; mod codec; mod deblock; mod deblock_mbaff; +mod direct; mod decoder; mod dpb; mod enc; @@ -51,8 +52,10 @@ mod fmo; mod inter; mod inter16; mod mbaff; +mod mc; mod mv; mod pred; +mod residual; mod sample; mod tables; mod transform; diff --git a/crates/ec-h264/src/mc.rs b/crates/ec-h264/src/mc.rs new file mode 100644 index 00000000..dc9fa210 --- /dev/null +++ b/crates/ec-h264/src/mc.rs @@ -0,0 +1,455 @@ +use ec_core::error::{Error, Result}; + +use crate::decoder::{SliceCtx, plane_mut, plane_ref}; +use crate::dpb::Picture; +use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma}; +use crate::sample::Sample; + + +/// The motion vectors chroma prediction uses: the luma vectors, with the +/// vertical offset of 8.4.1.4 added when a field predicts from a field of the +/// opposite parity. +#[inline] +fn chroma_mvs( + ctx: &SliceCtx, + refs: &[Picture], + ref_idx: [i8; 2], + mv: [[i16; 2]; 2], +) -> [[i16; 2]; 2] { + let mut out = mv; + if ctx.cat == 2 { + // 4:2:2 chroma is full height: the vertical vector stays in quarter + // samples of the chroma plane, which the eighth-sample interpolator + // reads as twice the value. + for l in out.iter_mut() { + l[1] = l[1].wrapping_mul(2); + } + } else if ctx.is_field() { + for l in 0..2 { + if let Some(rp) = ctx.reference(refs, l, ref_idx[l]) { + out[l][1] = out[l][1].wrapping_add(ctx.chroma_dy(rp)); + } + } + } + out +} + +/// The reference plane (`0` luma, `1` Cb, `2` Cr) list `list` predicts from. +#[inline(always)] +fn ref_plane<'a>( + ctx: &SliceCtx, + refs: &'a [Picture], + ref_idx: [i8; 2], + list: usize, + comp: usize, +) -> Result> { + let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| { + Error::corrupt("reference index names a picture the buffer does not hold") + })?; + let src = match comp { + 0 => &rp.y, + 1 => &rp.cb, + _ => &rp.cr, + }; + Ok(RefPlane { + data: &src.data, + stride: src.stride, + origin: src.origin, + width: src.width, + height: src.height, + pad: src.pad, + }) +} + +/// Motion compensation of one partition (clause 8.4.2): interpolate each list's +/// prediction, then combine them by the weighting of 8.4.2.3 and write the +/// result straight into the picture, where the residual is added on top. +/// +/// `(px, py)` and `(pw, ph)` are in 4x4 blocks within the macroblock. +#[allow(clippy::too_many_arguments)] +pub(crate) fn compensate8( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mb_x: usize, + mb_y: usize, + px: usize, + py: usize, + pw: usize, + ph: usize, + mv: [[i16; 2]; 2], + ref_idx: [i8; 2], +) -> Result<()> { + let use0 = ref_idx[0] >= 0; + let use1 = ref_idx[1] >= 0; + if !use0 && !use1 { + return Ok(()); + } + let geo = ctx.geo(mb_y); + let x0 = (mb_x * 16 + px * 4) as i32; + let y0 = (geo.src_y + py * 4) as i32; + let (w, h) = (pw * 4, ph * 4); + // A stream carrying no weighted prediction at all resolves every + // component to the identity weighting without the per-component lookup. + let plain = ctx.no_weights(); + // ChromaArrayType 3 predicts Cb and Cr with the luma interpolation, on + // their own planes and weights. + let ncomp = if ctx.cat == 3 { 3 } else { 1 }; + for comp in 0..ncomp { + let wt = if plain { + Weights::DEFAULT + } else { + ctx.weights_for(refs, comp, ref_idx[0], ref_idx[1], use0, use1) + }; + // 8.4.2.3.1 over one list is the identity, so the interpolation of that + // one list IS the prediction: it is written straight into the picture at + // the picture's own pitch. Over both lists the combined prediction is the + // rounded byte average of the two clipped ones, so list 0 interpolates + // into the picture and list 1 averages on top of it (Put::Avg) — no + // temporaries, no combining pass, no copy back. + let direct = wt.is_default(); + let stride = plane_ref(pic, comp).stride * geo.mul; + let origin = plane_ref(pic, comp).at(x0 as usize, geo.y(py * 4)); + // Weighted bi-prediction fuses the same way: the combining formula is + // per-sample, so list 0 lands in the picture and list 1 combines on top + // of it (Put::AvgW) with 8.4.2.3.2's exact integers. + let weighted_put = if !direct && use0 && use1 { + Some(crate::inter::Put::AvgW { + w0: wt.w[0], + w1: wt.w[1], + shift: (wt.log_wd + 1) as u32, + round: 1 << wt.log_wd, + off: (wt.o[0] + wt.o[1] + 1) >> 1, + }) + } else { + None + }; + if direct && use0 && use1 { + let plane = ref_plane(ctx, refs, ref_idx, 0, comp)?; + mc_luma( + &plane, + x0, + y0, + mv[0], + w, + h, + stride, + &mut plane_mut(pic, comp).data[origin..], + crate::inter::Put::Set, + ); + let plane = ref_plane(ctx, refs, ref_idx, 1, comp)?; + mc_luma( + &plane, + x0, + y0, + mv[1], + w, + h, + stride, + &mut plane_mut(pic, comp).data[origin..], + crate::inter::Put::Avg, + ); + } else if direct { + // No scratch buffer is declared on this path at all: the scratch is + // zeroed on entry, and most partitions of a P slice come through here. + let list = usize::from(!use0); + let plane = ref_plane(ctx, refs, ref_idx, list, comp)?; + mc_luma( + &plane, + x0, + y0, + mv[list], + w, + h, + stride, + &mut plane_mut(pic, comp).data[origin..], + crate::inter::Put::Set, + ); + } else if let Some(put) = weighted_put { + let plane = ref_plane(ctx, refs, ref_idx, 0, comp)?; + mc_luma( + &plane, + x0, + y0, + mv[0], + w, + h, + stride, + &mut plane_mut(pic, comp).data[origin..], + crate::inter::Put::Set, + ); + let plane = ref_plane(ctx, refs, ref_idx, 1, comp)?; + mc_luma( + &plane, + x0, + y0, + mv[1], + w, + h, + stride, + &mut plane_mut(pic, comp).data[origin..], + put, + ); + } else { + let mut part = [[0u8; 256]; 2]; + for list in 0..2 { + if ref_idx[list] < 0 { + continue; + } + let plane = ref_plane(ctx, refs, ref_idx, list, comp)?; + mc_luma( + &plane, + x0, + y0, + mv[list], + w, + h, + w, + &mut part[list], + crate::inter::Put::Set, + ); + } + let mut out = [0u8; 256]; + let (p0, p1) = part.split_at(1); + combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h); + for row in 0..h { + let dst = origin + row * stride; + plane_mut(pic, comp).data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]); + } + } + } + + // Chroma (8.4.1.4): for 4:2:0 frame coding the chroma vector is the luma + // vector, read as eighth-sample units over the half-resolution plane. + if ctx.cat == 0 || ctx.cat == 3 { + return Ok(()); + } + let cmv = chroma_mvs(ctx, refs, ref_idx, mv); + let c422 = ctx.cat == 2; + let (cw, ch) = (w / 2, if c422 { h } else { h / 2 }); + let (cx0, cy0) = (x0 / 2, if c422 { y0 } else { y0 / 2 }); + let crow = if c422 { py * 4 } else { py * 2 }; + for comp in 0..2 { + let wt = if plain { + Weights::DEFAULT + } else { + ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1) + }; + let direct = wt.is_default(); + // The combining weights are per-component syntax (luma and chroma + // carry their own denoms, weights and offsets), so this component's + // fused mode is built from ITS OWN lookup — never the luma one. + let weighted_put = if !direct && use0 && use1 { + Some(crate::inter::Put::AvgW { + w0: wt.w[0], + w1: wt.w[1], + shift: (wt.log_wd + 1) as u32, + round: 1 << wt.log_wd, + off: (wt.o[0] + wt.o[1] + 1) >> 1, + }) + } else { + None + }; + let plane_out = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = plane_out.stride * geo.mul; + let origin = plane_out.at(cx0 as usize, geo.cy(crow)); + if direct && use0 && use1 { + let plane = ref_plane(ctx, refs, ref_idx, 0, 1 + comp)?; + mc_chroma( + &plane, + cx0, + cy0, + cmv[0], + cw, + ch, + stride, + &mut plane_out.data[origin..], + crate::inter::Put::Set, + ); + let plane = ref_plane(ctx, refs, ref_idx, 1, 1 + comp)?; + mc_chroma( + &plane, + cx0, + cy0, + cmv[1], + cw, + ch, + stride, + &mut plane_out.data[origin..], + crate::inter::Put::Avg, + ); + } else if let Some(put) = weighted_put { + let plane = ref_plane(ctx, refs, ref_idx, 0, 1 + comp)?; + mc_chroma( + &plane, + cx0, + cy0, + cmv[0], + cw, + ch, + stride, + &mut plane_out.data[origin..], + crate::inter::Put::Set, + ); + let plane = ref_plane(ctx, refs, ref_idx, 1, 1 + comp)?; + mc_chroma( + &plane, + cx0, + cy0, + cmv[1], + cw, + ch, + stride, + &mut plane_out.data[origin..], + put, + ); + } else if direct { + let list = usize::from(!use0); + let plane = ref_plane(ctx, refs, ref_idx, list, 1 + comp)?; + mc_chroma( + &plane, + cx0, + cy0, + cmv[list], + cw, + ch, + stride, + &mut plane_out.data[origin..], + crate::inter::Put::Set, + ); + } else { + let mut cpart = [[0u8; 128]; 2]; + for list in 0..2 { + if ref_idx[list] < 0 { + continue; + } + let plane = ref_plane(ctx, refs, ref_idx, list, 1 + comp)?; + mc_chroma( + &plane, + cx0, + cy0, + cmv[list], + cw, + ch, + cw, + &mut cpart[list], + crate::inter::Put::Set, + ); + } + let mut cout = [0u8; 128]; + let (c0, c1) = cpart.split_at(1); + combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch); + for row in 0..ch { + let dst = origin + row * stride; + plane_out.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]); + } + } + } + Ok(()) +} + +/// Motion compensation of one partition over `u16` planes: the same clause +/// 8.4.2 process as [`compensate8`], computed per sample from the equations. +/// Weighted prediction offsets scale by `1 << (BitDepth - 8)` (8-298, 8-299). +#[allow(clippy::too_many_arguments)] +pub(crate) fn compensate16( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mb_x: usize, + mb_y: usize, + px: usize, + py: usize, + pw: usize, + ph: usize, + mv: [[i16; 2]; 2], + ref_idx: [i8; 2], +) -> Result<()> { + let use0 = ref_idx[0] >= 0; + let use1 = ref_idx[1] >= 0; + if !use0 && !use1 { + return Ok(()); + } + let bd = pic.bd; + let max = (1i32 << bd) - 1; + let geo = ctx.geo(mb_y); + let x0 = (mb_x * 16 + px * 4) as i32; + let y0 = (geo.src_y + py * 4) as i32; + let plain = ctx.no_weights(); + let cmv = chroma_mvs(ctx, refs, ref_idx, mv); + let cat = pic.cat; + let ncomp = if cat == 0 { 1 } else { 3 }; + for comp in 0..ncomp { + let c422 = cat == 2; + let (w, h, cx, cy) = if comp == 0 || cat == 3 { + (pw * 4, ph * 4, x0, y0) + } else if c422 { + (pw * 2, ph * 4, x0 / 2, y0) + } else { + (pw * 2, ph * 2, x0 / 2, y0 / 2) + }; + let mut wt = if plain { + Weights::DEFAULT + } else { + ctx.weights_for(refs, comp, ref_idx[0], ref_idx[1], use0, use1) + }; + wt.o[0] <<= bd - 8; + wt.o[1] <<= bd - 8; + let mut pred = [[0i32; 256]; 2]; + for list in 0..2 { + if ref_idx[list] < 0 { + continue; + } + let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| { + Error::corrupt("reference index names a picture the buffer does not hold") + })?; + match comp { + 0 => crate::inter16::luma_pred(&rp.y, cx, cy, mv[list], w, h, max, &mut pred[list]), + 1 if cat == 3 => { + crate::inter16::luma_pred(&rp.cb, cx, cy, mv[list], w, h, max, &mut pred[list]) + } + _ if cat == 3 => { + crate::inter16::luma_pred(&rp.cr, cx, cy, mv[list], w, h, max, &mut pred[list]) + } + 1 => crate::inter16::chroma_pred(&rp.cb, cx, cy, cmv[list], w, h, &mut pred[list]), + _ => crate::inter16::chroma_pred(&rp.cr, cx, cy, cmv[list], w, h, &mut pred[list]), + } + } + let plane = match comp { + 0 => &mut pic.y, + 1 => &mut pic.cb, + _ => &mut pic.cr, + }; + let stride = plane.stride * geo.mul; + let origin = if comp == 0 || cat == 3 { + plane.at(cx as usize, geo.y(py * 4)) + } else { + plane.at(cx as usize, geo.cy(if c422 { py * 4 } else { py * 2 })) + }; + let round1 = if wt.log_wd >= 1 { + 1 << (wt.log_wd - 1) + } else { + 0 + }; + for row in 0..h { + for col in 0..w { + let i = row * w + col; + let v = if use0 && use1 { + // 8-301 / 8-300 (default weights reduce to the rounded mean). + ((pred[0][i] * wt.w[0] + pred[1][i] * wt.w[1] + (1 << wt.log_wd)) + >> (wt.log_wd + 1)) + + ((wt.o[0] + wt.o[1] + 1) >> 1) + } else { + let k = usize::from(!use0); + if wt.log_wd >= 1 { + ((pred[k][i] * wt.w[k] + round1) >> wt.log_wd) + wt.o[k] + } else { + pred[k][i] * wt.w[k] + wt.o[k] + } + }; + plane.data[origin + row * stride + col] = v.clamp(0, max) as u16; + } + } + } + Ok(()) +} diff --git a/crates/ec-h264/src/residual.rs b/crates/ec-h264/src/residual.rs new file mode 100644 index 00000000..c4f7181d --- /dev/null +++ b/crates/ec-h264/src/residual.rs @@ -0,0 +1,320 @@ +use ec_core::error::Result; + +use crate::decoder::{ + Geo, MbFinish, MbNeighbors, gather_nbr4_in, gather_nbr8_in, nz_grid, nz_grid_mut, nz_pair_8x8, + nz_pair_in, + plane_mut, plane_ref, +}; +use crate::dpb::Picture; +use crate::entropy::{BlockCat, Entropy}; +use crate::pred::{ + PlaneWindow, add_residual_4x4, add_residual_8x8, add_residual_dpcm, filter_nbr8, pred_16x16, + pred_4x4, pred_8x8, +}; +use crate::sample::Sample; +use crate::tables::BLK4_POS; +use crate::transform::{ + LevelScale4x4, LevelScale8x8, dequant_4x4, dequant_8x8, inverse_transform_4x4, + inverse_transform_8x8, unfield, unfield_8x8, unfield_ac15, unzigzag, unzigzag_8x8, + luma_dc_transform, unzigzag_ac15, +}; + +/// `residual_luma( )` (7.3.5.3.1) of one colour component plus its +/// reconstruction (8.5): the luma residual, and for ChromaArrayType 3 the Cb +/// and Cr residual too, which is coded and reconstructed exactly like luma +/// (against the plane of `comp`, with `qp` its QP', and `ls` / `ls8` its +/// scaling lists). +/// +/// Bitstream order equals reconstruction dependency order, so each block +/// reconstructs the moment its levels are parsed. `bypass` is +/// TransformBypassModeFlag: the levels are the residual (8.5.15). +#[allow(clippy::needless_range_loop, clippy::too_many_arguments)] +pub(crate) fn residual_luma_style( + pic: &mut Picture, + r: &mut Entropy<'_>, + nbr: &MbNeighbors, + m: &MbFinish, + mb_x: usize, + mb_y: usize, + comp: usize, + ls: &LevelScale4x4, + ls8: &LevelScale8x8, + qp: i32, + bypass: bool, + fld: bool, + geo: Geo, + dc_cbf: &mut u8, +) -> Result<()> { + let bd = pic.bd; + let max = (1i32 << bd) - 1; + let w4 = pic.mb_w * 4; + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let mul = geo.mul; + let cbp_luma = m.cbp_luma; + let c = comp as u8; + let cat3 = pic.cat == 3; + let mut scan = [0i32; 16]; + let mut raster = [0i32; 16]; + let mut resid = [0i32; 16]; + if m.is_i16 { + { + let pl = plane_mut(pic, comp); + let mut w = PlaneWindow { + origin: pl.at(mb_x * 16, geo.y(0)), + stride: pl.stride * mul, + data: &mut pl.data, + }; + pred_16x16(m.i16_mode, bd, &mut w, m.pred_nbr.b, m.pred_nbr.a); + } + // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale. + let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx0, by0); + let dc_tc = r.residual_block_c(&mut scan, BlockCat::LumaDc, c, na, nb)?; + *dc_cbf |= u8::from(dc_tc != 0) << comp; + if fld { + unfield(&scan, &mut raster); + } else { + unzigzag(&scan, &mut raster); + } + if !bypass { + luma_dc_transform(&mut raster, ls, qp); + } + let dc = raster; + // Lossless horizontal / vertical prediction accumulates the residual + // over the whole macroblock, so every block takes part. + let dpcm = bypass && m.i16_mode < 2; + let horizontal = m.i16_mode == 1; + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + let tc = if cbp_luma != 0 { + let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx, by); + r.residual_block_c(&mut scan, BlockCat::LumaAc, c, na, nb)? + } else { + 0 + }; + nz_grid_mut(pic, comp)[by * w4 + bx] = tc; + let dc_blk = dc[dy as usize * 4 + dx as usize]; + if tc == 0 && dc_blk == 0 && !dpcm { + continue; // prediction already in place + } + if tc > 0 { + if fld { + unfield_ac15(&scan, &mut raster); + } else { + unzigzag_ac15(&scan, &mut raster); + } + if !bypass { + dequant_4x4(&mut raster, ls, qp, true); + } + } else { + raster = [0; 16]; // DC-only block + } + raster[0] = dc_blk; + let pl = plane_mut(pic, comp); + let origin = pl.at(mb_x * 16 + dx as usize * 4, geo.y(dy as usize * 4)); + let stride = pl.stride * mul; + if bypass { + if dpcm { + let first = if horizontal { dx == 0 } else { dy == 0 }; + add_residual_dpcm( + &mut pl.data, + bd, + stride, + origin, + 4, + 4, + &raster, + horizontal, + first, + ); + } else { + add_residual_4x4(&mut pl.data, bd, stride, origin, &raster); + } + } else { + inverse_transform_4x4(&raster, &mut resid); + add_residual_4x4(&mut pl.data, bd, stride, origin, &resid); + } + } + } else if m.trans8x8 { + // 8x8 transform (8.5.13): predict, parse and reconstruct one 8x8 block + // at a time, because an Intra_8x8 block predicts from the reconstructed + // samples of the blocks before it. + let mut scan8 = [0i32; 64]; + let mut raster8 = [0i32; 64]; + let mut resid8 = [0i32; 64]; + for blk8 in 0..4 { + let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, geo.y((blk8 / 2) * 8)); + let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); + let origin = plane_ref(pic, comp).at(x, y); + let stride = plane_ref(pic, comp).stride * mul; + if m.intra { + let n = filter_nbr8(&gather_nbr8_in( + &plane_ref(pic, comp).data, + &m.pred_nbr, + blk8, + origin, + stride, + )); + let mut p = [S::default(); 64]; + pred_8x8(m.modes8[blk8], bd, &n, &mut p); + let pl = plane_mut(pic, comp); + for ry in 0..8 { + let row = origin + ry * stride; + pl.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]); + } + } + if cbp_luma & (1 << blk8) == 0 { + let grid = nz_grid_mut(pic, comp); + for dy in 0..2 { + let base = (by + dy) * w4 + bx; + grid[base..base + 2].fill(0); + } + continue; + } + let tc = if r.is_cabac() { + // ctxBlockCat 5: one 64-coefficient block, and every 4x4 slot + // of it reports the block's own count to the neighbours + // (9.3.3.1.1.9 resolves them to the 8x8 transform block). Only + // ChromaArrayType 3 sends a coded_block_flag for it. + let cbf = cat3.then(|| nz_pair_8x8(pic, comp, nbr, bx, by)); + let tc = r.residual_block_8x8(&mut scan8, c, cbf)?; + let grid = nz_grid_mut(pic, comp); + for dy in 0..2 { + let base = (by + dy) * w4 + bx; + grid[base..base + 2].fill(tc.min(16)); + } + tc + } else { + // CAVLC codes the same 64 coefficients as four interleaved 4x4 + // blocks (7.3.5.3.1), each with its own nC neighbourhood. + let mut tc = 0u8; + for i4 in 0..4 { + let (dx, dy) = BLK4_POS[blk8 * 4 + i4]; + let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize); + let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, sx, sy); + let n = r.residual_block_c(&mut scan, BlockCat::Luma4x4, c, na, nb)?; + nz_grid_mut(pic, comp)[sy * w4 + sx] = n; + tc += n; + for i in 0..16 { + scan8[4 * i + i4] = scan[i]; + } + } + tc + }; + if tc == 0 { + continue; + } + if fld { + unfield_8x8(&scan8, &mut raster8); + } else { + unzigzag_8x8(&scan8, &mut raster8); + } + let pl = plane_mut(pic, comp); + if bypass { + if m.intra && m.modes8[blk8] < 2 { + add_residual_dpcm( + &mut pl.data, + bd, + stride, + origin, + 8, + 8, + &raster8, + m.modes8[blk8] == 1, + true, + ); + } else { + add_residual_8x8(&mut pl.data, bd, stride, origin, &raster8); + } + } else { + dequant_8x8(&mut raster8, ls8, qp); + inverse_transform_8x8(&raster8, &mut resid8); + add_residual_8x8(&mut pl.data, bd, stride, origin, &resid8); + } + } + } else { + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + let tc = if cbp_luma & (1 << (blk >> 2)) != 0 { + let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx, by); + r.residual_block_c(&mut scan, BlockCat::Luma4x4, c, na, nb)? + } else { + 0 + }; + nz_grid_mut(pic, comp)[by * w4 + bx] = tc; + let (x, y) = (mb_x * 16 + dx as usize * 4, geo.y(dy as usize * 4)); + let origin = plane_ref(pic, comp).at(x, y); + let stride = plane_ref(pic, comp).stride * mul; + if m.intra { + let n = + gather_nbr4_in(&plane_ref(pic, comp).data, &m.pred_nbr, blk, origin, stride); + let mut p = [S::default(); 16]; + pred_4x4(m.modes[blk], bd, &n, &mut p); + let pl = plane_mut(pic, comp); + if tc == 0 { + // Pure prediction: copy the 16 samples in. + for ry in 0..4 { + let row = origin + ry * stride; + pl.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); + } + continue; + } + if fld { + unfield(&scan, &mut raster); + } else { + unzigzag(&scan, &mut raster); + } + if bypass { + for ry in 0..4 { + let row = origin + ry * stride; + pl.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); + } + if m.modes[blk] < 2 { + add_residual_dpcm( + &mut pl.data, + bd, + stride, + origin, + 4, + 4, + &raster, + m.modes[blk] == 1, + true, + ); + } else { + add_residual_4x4(&mut pl.data, bd, stride, origin, &raster); + } + continue; + } + dequant_4x4(&mut raster, ls, qp, false); + inverse_transform_4x4(&raster, &mut resid); + for ry in 0..4 { + let row = origin + ry * stride; + for rx in 0..4 { + let v = p[ry * 4 + rx].to_i32() + resid[ry * 4 + rx]; + pl.data[row + rx] = S::clip(v, max); + } + } + } else { + if tc == 0 { + continue; // motion-compensated prediction already in place + } + if fld { + unfield(&scan, &mut raster); + } else { + unzigzag(&scan, &mut raster); + } + let pl = plane_mut(pic, comp); + if bypass { + add_residual_4x4(&mut pl.data, bd, stride, origin, &raster); + } else { + dequant_4x4(&mut raster, ls, qp, false); + inverse_transform_4x4(&raster, &mut resid); + add_residual_4x4(&mut pl.data, bd, stride, origin, &resid); + } + } + } + } + Ok(()) +} diff --git a/crates/ec-h264/src/sample.rs b/crates/ec-h264/src/sample.rs index 06ccf5f3..f9ad7a99 100644 --- a/crates/ec-h264/src/sample.rs +++ b/crates/ec-h264/src/sample.rs @@ -6,9 +6,11 @@ use crate::deblock::{ EdgeParams, filter_chroma_h_edge8, filter_chroma_line, filter_luma_h_edge16, filter_luma_line, }; -use crate::decoder::{SliceCtx, compensate8, compensate16}; +use crate::decoder::SliceCtx; +use crate::mc::{compensate8, compensate16}; use crate::dpb::Picture; use ec_core::error::Result; +use ec_core::frame::PixelFormat; /// A picture sample. pub(crate) trait Sample: @@ -16,6 +18,7 @@ pub(crate) trait Sample: { /// True for the 8-bit instantiation. const IS_8: bool; + const FORMATS: [PixelFormat; 3]; /// Bytes per sample in an output frame. const BYTES: usize; /// Append `src` to an output plane, little-endian, shifted left by `shift`. @@ -73,6 +76,7 @@ pub(crate) trait Sample: impl Sample for u8 { const IS_8: bool = true; + const FORMATS: [PixelFormat; 3] = [PixelFormat::I444, PixelFormat::I422, PixelFormat::I420]; const BYTES: usize = 1; #[inline] fn extend_bytes(out: &mut Vec, src: &[u8], _shift: u32) { @@ -130,6 +134,7 @@ impl Sample for u8 { impl Sample for u16 { const IS_8: bool = false; + const FORMATS: [PixelFormat; 3] = [PixelFormat::I410, PixelFormat::I210, PixelFormat::I010]; const BYTES: usize = 2; #[inline] fn extend_bytes(out: &mut Vec, src: &[u16], shift: u32) { diff --git a/crates/ec-h264/src/transform.rs b/crates/ec-h264/src/transform.rs index 07f611d3..ccf48f89 100644 --- a/crates/ec-h264/src/transform.rs +++ b/crates/ec-h264/src/transform.rs @@ -118,15 +118,18 @@ pub fn dequant_8x8(block: &mut [i32; 64], ls: &LevelScale8x8, qp: i32) { /// 8x8 zig-zag (Table 8-14). #[inline] pub fn unzigzag_8x8(scan: &[i32; 64], out: &mut [i32; 64]) { - for (s, &raster) in ZIGZAG_8X8.iter().enumerate() { - out[raster as usize] = scan[s]; - } + unscan(&ZIGZAG_8X8, scan, out); } /// The same with the 8x8 field scan (Table 8-14), for field macroblocks. #[inline] pub fn unfield_8x8(scan: &[i32; 64], out: &mut [i32; 64]) { - for (s, &raster) in FIELD_8X8.iter().enumerate() { + unscan(&FIELD_8X8, scan, out); +} + +#[inline] +pub fn unscan(order: &[u8], scan: &[i32; N], out: &mut [i32; N]) { + for (s, &raster) in order.iter().enumerate() { out[raster as usize] = scan[s]; } } @@ -197,17 +200,13 @@ pub fn inverse_transform_8x8(d: &[i32; 64], r: &mut [i32; 64]) { /// Place scan-order coefficients into raster order using the 4x4 zig-zag. #[inline] pub fn unzigzag(scan: &[i32; 16], out: &mut [i32; 16]) { - for (s, &raster) in ZIGZAG_4X4.iter().enumerate() { - out[raster as usize] = scan[s]; - } + unscan(&ZIGZAG_4X4, scan, out); } /// The same with the 4x4 field scan (Table 8-13), for field macroblocks. #[inline] pub fn unfield(scan: &[i32; 16], out: &mut [i32; 16]) { - for (s, &raster) in FIELD_4X4.iter().enumerate() { - out[raster as usize] = scan[s]; - } + unscan(&FIELD_4X4, scan, out); } /// Field-scan counterpart of [`unzigzag_ac15`].