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; +} +