forge
Explore
Log in

Don't you dare go Hollow

S8: split enc/mb.rs into mb/me, mb/intra, mb/inter and mb/residual (pure moves; items used across modules are pub(super))

Browse files at this commit

2a9d5ea1b8ba44d7571afaa783cb1b06c63efe7aAhmet Kaan GümüşParent: e69b563

5 changed files +3402 -3313

crates/ec-h264/src/enc/mb.rsmodified+17 -3313

Diff too large; view file

@@ -12,38 +12,33 @@
12 // the arrays instead would hide which geometry each loop names.12 // the arrays instead would hide which geometry each loop names.
13 #![allow(clippy::needless_range_loop)]13 #![allow(clippy::needless_range_loop)]
14 14
15+mod inter;
16+mod intra;
17+mod me;
18+mod residual;
19+
20+use self::inter::*;
21+use self::intra::*;
22+use self::me::*;
23+use self::residual::*;
24+
15 use ec_h264_syntax::SliceType;25 use ec_h264_syntax::SliceType;
16-use wide::{i16x8, i16x16};26+use wide::{i16x16};
17 27
18-use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line};
19 use crate::decoder::{28 use crate::decoder::{
20- MbNeighbors, chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors,29+ mb_neighbors,
21 };30 };
22-use crate::dpb::{BLK_SKIP, Picture, Plane8};31+use crate::dpb::{Picture, Plane8};
23 use crate::entropy::{32 use crate::entropy::{
24- BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8,33+ FLAG_SKIP, MbCtx, MbInfo,
25- MbCtx, MbInfo,
26 };34 };
27-use crate::inter::{Put, RefPlane, integer_origin, mc_chroma, mc_luma};35+use crate::tables::{CHROMA_QP};
28-use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd};
29-use crate::pred::{
30- PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16,
31- pred_chroma_8x8,
32-};
33-use crate::tables::{BLK4_POS, CHROMA_QP};
34 use crate::transform::{36 use crate::transform::{
35- LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8,37+ LevelScale4x4, LevelScale8x8, };
36- inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8,
37- unzigzag_ac15,
38-};
39 38
40-use super::quant::{
41- forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4,
42- quant_4x4_offset, quant_8x8, quant_8x8_offset, quant_chroma_dc, quant_luma_dc,
43-};
44 39
45 use super::{40 use super::{
46- entropy::{EncEntropy, sub_block_4x4},41+ entropy::{EncEntropy},
47 lambda_ssd,42 lambda_ssd,
48 };43 };
49 44
@@ -187,144 +182,6 @@ impl Default for Levels {
187 }182 }
188 }183 }
189 184
190-/// 4x4 Hadamard sum of absolute transformed differences between the source at
191-/// `(sx, sy)` and a 4x4 prediction.
192-// Tried (lane-h264perf r2): a transpose-based i32x4 vectorization of this
193-// butterfly, bit-identical, but cycles-flat-to-worse under perf stat
194-// (22.958B -> 23.042B cycles over 10 reps despite fewer instructions
195-// retired) -- reverted, dead end; see ledger.
196-fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 {
197- // Differences are at most 255 in magnitude and the 2-D Hadamard sums 16 of
198- // them, so every intermediate fits an i16.
199- let mut d = [[0i16; 4]; 4];
200- for (y, row) in d.iter_mut().enumerate() {
201- let s = &src[(sy + y) * sstride + sx..][..4];
202- let p = &pred[y * pstride..][..4];
203- for x in 0..4 {
204- row[x] = i16::from(s[x]) - i16::from(p[x]);
205- }
206- }
207- // Vertical butterflies, lane-wise over the four columns.
208- let mut v = [[0i16; 4]; 4];
209- for x in 0..4 {
210- let (a, b, c, e) = (d[0][x], d[1][x], d[2][x], d[3][x]);
211- let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e);
212- v[0][x] = s0 + s1;
213- v[1][x] = s0 - s1;
214- v[2][x] = s2 + s3;
215- v[3][x] = s2 - s3;
216- }
217- // Horizontal butterflies per row, then the absolute sum.
218- let mut sum = 0i32;
219- for row in &v {
220- let (a, b, c, e) = (row[0], row[1], row[2], row[3]);
221- let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e);
222- sum += i32::from((s0 + s1).abs())
223- + i32::from((s0 - s1).abs())
224- + i32::from((s2 + s3).abs())
225- + i32::from((s2 - s3).abs());
226- }
227- (sum + 2) >> 2
228-}
229-
230-/// SATD of a whole 16x16 luma macroblock against the prediction already in the
231-/// picture plane.
232-fn satd16(
233- src: &[u8],
234- sstride: usize,
235- sx: usize,
236- sy: usize,
237- plane: &[u8],
238- pstride: usize,
239- po: usize,
240-) -> i32 {
241- satd_block(src, sstride, sx, sy, plane, pstride, po, 16, 16)
242-}
243-
244-/// The same over a `w` x `h` partition.
245-#[allow(clippy::too_many_arguments)]
246-fn satd_block(
247- src: &[u8],
248- sstride: usize,
249- sx: usize,
250- sy: usize,
251- plane: &[u8],
252- pstride: usize,
253- po: usize,
254- w: usize,
255- h: usize,
256-) -> i32 {
257- let mut sum = 0;
258- for by in 0..h / 4 {
259- for bx in 0..w / 4 {
260- sum += satd4(
261- src,
262- sstride,
263- sx + bx * 4,
264- sy + by * 4,
265- &plane[po + by * 4 * pstride + bx * 4..],
266- pstride,
267- );
268- }
269- }
270- sum
271-}
272-
273-/// Sum of absolute differences of a `w` x `h` block against a prediction with
274-/// its own pitch. This is the motion search's inner loop and nothing else in
275-/// the encoder is called as often, so a full-width row goes through one vector.
276-#[allow(clippy::too_many_arguments)]
277-fn sad(
278- src: &[u8],
279- sstride: usize,
280- sx: usize,
281- sy: usize,
282- pred: &[u8],
283- pstride: usize,
284- w: usize,
285- h: usize,
286-) -> i32 {
287- if w == 16 {
288- let mut acc = i16x16::ZERO;
289- for y in 0..h {
290- let a = load16(src, (sy + y) * sstride + sx);
291- let b = load16(pred, y * pstride);
292- acc += (a - b).abs();
293- }
294- return acc.to_array().iter().map(|&v| i32::from(v)).sum();
295- }
296- let mut sum = 0;
297- for y in 0..h {
298- let s = &src[(sy + y) * sstride + sx..];
299- let p = &pred[y * pstride..];
300- for x in 0..w {
301- sum += (i32::from(s[x]) - i32::from(p[x])).abs();
302- }
303- }
304- sum
305-}
306-
307-/// Sum and maximum of the absolute differences between the 16x16 source block
308-/// at `(sx, sy)` and a 16-wide prediction.
309-fn sad_max16(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8]) -> (i32, i32) {
310- let mut acc = i16x16::ZERO;
311- let mut mx = i16x16::ZERO;
312- for y in 0..16 {
313- let a = load16(src, (sy + y) * sstride + sx);
314- let b = load16(pred, y * 16);
315- let d = (a - b).abs();
316- acc += d;
317- mx = mx.max(d);
318- }
319- let sum = acc.to_array().iter().map(|&v| i32::from(v)).sum();
320- let max = mx
321- .to_array()
322- .iter()
323- .map(|&v| i32::from(v))
324- .max()
325- .unwrap_or(0);
326- (sum, max)
327-}
328 185
329 /// Sixteen samples widened to 16-bit lanes; the tail past the slice is zero,186 /// Sixteen samples widened to 16-bit lanes; the tail past the slice is zero,
330 /// which only a caller reading past the plane could reach.187 /// 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] {
367 ]224 ]
368 }225 }
369 226
370-#[inline]
371-fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 {
372- (motion_lambda(e) * bits).round() as i32
373-}
374-
375-/// The multiplier `motion_rate` applies, for loops that price many vectors.
376-#[inline]
377-fn motion_lambda(e: &MbEnc<'_>) -> f64 {
378- if e.transform_8x8 {
379- e.lambda.sqrt()
380- } else {
381- e.lambda
382- }
383-}
384-
385 /// Everything one macroblock's coding writes into the picture, kept so that a227 /// Everything one macroblock's coding writes into the picture, kept so that a
386 /// branch can be coded, measured and undone.228 /// branch can be coded, measured and undone.
387 struct MbState {229 struct MbState {
@@ -643,3141 +485,3 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy
643 }485 }
644 }486 }
645 487
646-/// The Intra_16x16 mode this macroblock would use. Intra_16x16 against
647-/// Intra_4x4 is decided later, on real rate and real distortion (see
648-/// [`encode_intra_mb`]).
649-struct IntraCost {
650- i16_mode: u8,
651- /// SATD of the Intra_16x16 mode above: the cheap intra estimate that
652- /// `Preset::Fast` gates the full intra branch on.
653- satd: i32,
654- /// True when Intra_4x4 may be used at all for this picture and preset.
655- allow_i4: bool,
656-}
657-
658-/// Best Intra_16x16 mode by SATD, leaving nothing behind in the plane that a
659-/// later branch does not overwrite.
660-fn intra_pre_cost(
661- pic: &mut Picture,
662- e: &MbEnc<'_>,
663- nbr: &MbNeighbors,
664- mb_x: usize,
665- mb_y: usize,
666- modes: &[u8],
667-) -> IntraCost {
668- let (sx, sy) = (mb_x * 16, mb_y * 16);
669- let stride = pic.y.stride;
670- let origin = pic.y.at(sx, sy);
671- let mut best = (i32::MAX, 2u8);
672- for &mode in modes {
673- let ok = match mode {
674- 0 => nbr.b,
675- 1 => nbr.a,
676- 3 => nbr.a && nbr.b && nbr.d,
677- _ => true,
678- };
679- if !ok {
680- continue;
681- }
682- let mut win = PlaneWindow {
683- data: &mut pic.y.data,
684- stride,
685- origin,
686- };
687- pred_16x16(mode, 8, &mut win, nbr.b, nbr.a);
688- let cost = satd16(&e.src.y, e.src.stride, sx, sy, &pic.y.data, stride, origin);
689- if cost < best.0 {
690- best = (cost, mode);
691- }
692- }
693- IntraCost {
694- i16_mode: best.1,
695- satd: best.0,
696- // Intra_4x4 is tried in P pictures too, at every preset. Re-measured
697- // once the intra-versus-inter decision became a real one (BD-PSNR
698- // against x264, GOP 10, QP 22/26/30/34): restricting it to I pictures
699- // reads -1.613 dB on the film clip and -0.508 on the screen capture,
700- // where allowing it everywhere reads -0.728 and -0.500. It stays on
701- // everywhere. Under the old prediction-domain decision the screen
702- // capture preferred the restriction by a third of a dB; coding both
703- // branches for real removed that disagreement.
704- allow_i4: true,
705- }
706-}
707-
708-/// How much of a motion vector's signalling the search pays for. Half, which
709-/// is not the true rate: swept on consecutive pictures (BD-PSNR against x264,
710-/// GOP 10), 0.25/0.5/1.0/2.0 read -1.074/-1.043/-1.225/-1.618 on the film clip
711-/// and -0.676/-0.661/-0.795/-1.201 on the screen capture. Charging the whole
712-/// rate is worse than charging half on both contents, and the curve is flat
713-/// below a half and falls away above it.
714-const MV_BITS_WEIGHT: f64 = 0.5;
715-
716-/// Cap on whole-sample walk iterations per partition at `Preset::Fast`.
717-const FAST_ME_PASSES: usize = 3;
718-
719-/// The offsets the whole-sample search steps through, in units of the current
720-/// step size.
721-///
722-/// A square, not a cross. The cross this used to be could only walk along an
723-/// axis, so a diagonally moving macroblock had to be reached in two steps
724-/// through a point that was worse than both -- and a step search stops at the
725-/// first point it cannot improve on. Adding the four diagonals is worth 0.032
726-/// dB BD-PSNR-YUV on the film clip and 0.041 on the screen capture for twice
727-/// the candidates in the whole-sample stage, which is the cheap stage: it reads
728-/// the reference in place and never interpolates.
729-///
730-/// The step the walk starts from was swept with it, at 4, 8 and 16 whole
731-/// samples: -0.580/-0.580/-0.593 dB on the film clip and -0.474/-0.493/-0.529
732-/// on the screen capture. Four is screen capture's optimum and inside film's
733-/// flat part -- a wider opening step is not a wider search here, it just lands
734-/// the walk further from the seeds, which are already the answer most of the
735-/// time.
736-const ME_PATTERN: [(i16, i16); 8] = [
737- (1, 0),
738- (-1, 0),
739- (0, 1),
740- (0, -1),
741- (1, 1),
742- (-1, -1),
743- (1, -1),
744- (-1, 1),
745-];
746-
747-/// What the search charges P_8x8 for its own signalling, against the six bits
748-/// a 16x8 or 8x16 is charged: an mb_type that is one bin longer plus four
749-/// sub_mb_type bins, before the four predictors' own mvd.
750-///
751-/// Swept at `Preset::Balanced` -- the only preset that searches shapes at all
752-/// -- on consecutive pictures against x264. Off, 6, 12 and 20 bits read
753-/// -0.382/-0.379/-0.377/-0.378 dB BD-PSNR on the film clip and
754-/// -0.369/-0.364/-0.353/-0.356 on the screen capture: both contents put the
755-/// optimum at twelve, and quarters are worth 0.005 dB on camera content and
756-/// 0.016 on screen capture.
757-///
758-/// Re-swept once each partition was searched against its own predictor rather
759-/// than the macroblock's, because that changes what a split is worth: 6, 12
760-/// and 20 read -0.342/-0.343/-0.346 dB on the film clip and
761-/// -0.322/-0.314/-0.324 on the screen capture. Twelve survives the new path.
762-const QUAD_BITS: f64 = 12.0;
763-
764-/// The same charge for a 16x8 or 8x16: one extra mb_type bin over P_16x16,
765-/// with no sub_mb_type behind it.
766-///
767-/// Swept on the per-partition-predictor path at 3, 6 and 10 bits:
768-/// -0.329/-0.343/-0.358 dB on the film clip and -0.310/-0.314/-0.326 on the
769-/// screen capture. Both contents want the halves charged half of what the old
770-/// whole-macroblock predictor made them look worth -- with each half searched
771-/// against its own predictor its mvd is genuinely cheaper, so the search no
772-/// longer has to be talked out of splitting.
773-const HALF_BITS: f64 = 3.0;
774-
775-/// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.
776-#[derive(Clone, Copy, PartialEq, Eq, Debug)]
777-enum PShape {
778- /// P_L0_16x16.
779- Whole,
780- /// P_L0_L0_16x8: a top and a bottom half.
781- Horizontal,
782- /// P_L0_L0_8x16: a left and a right half.
783- Vertical,
784- /// P_8x8 with four P_L0_8x8 sub-partitions: a quarter each.
785- Quad,
786-}
787-
788-impl PShape {
789- /// mb_type of Table 7-13.
790- fn mb_type(self) -> u32 {
791- match self {
792- PShape::Whole => 0,
793- PShape::Horizontal => 1,
794- PShape::Vertical => 2,
795- PShape::Quad => 3,
796- }
797- }
798-
799- fn parts(self) -> usize {
800- match self {
801- PShape::Whole => 1,
802- PShape::Horizontal | PShape::Vertical => 2,
803- PShape::Quad => 4,
804- }
805- }
806-
807- /// Partition `part`'s origin in 4x4 blocks and its size in luma samples.
808- fn geometry(self, part: usize) -> ((usize, usize), (usize, usize)) {
809- match self {
810- PShape::Whole => ((0, 0), (16, 16)),
811- PShape::Horizontal => ((0, part * 2), (16, 8)),
812- PShape::Vertical => ((part * 2, 0), (8, 16)),
813- PShape::Quad => (((part % 2) * 2, (part / 2) * 2), (8, 8)),
814- }
815- }
816-
817- /// Which partition covers the 4x4 block at `(x, y)` in macroblock
818- /// coordinates, or `None` when the block is outside the macroblock.
819- fn part_of(self, x: i32, y: i32) -> Option<usize> {
820- if !(0..4).contains(&x) || !(0..4).contains(&y) {
821- return None;
822- }
823- let (x, y) = (x as usize, y as usize);
824- Some(match self {
825- PShape::Whole => 0,
826- PShape::Horizontal => y / 2,
827- PShape::Vertical => x / 2,
828- PShape::Quad => (y / 2) * 2 + x / 2,
829- })
830- }
831-
832- /// `MbPartWidth`/`MbPartHeight` in 4x4 blocks, which select the
833- /// directional shortcuts of 8.4.1.3.
834- fn part_blocks(self) -> (usize, usize) {
835- match self {
836- PShape::Whole => (4, 4),
837- PShape::Horizontal => (4, 2),
838- PShape::Vertical => (2, 4),
839- PShape::Quad => (2, 2),
840- }
841- }
842-}
843-
844-/// How much the two chroma planes weigh against luma in the inter decision.
845-///
846-/// Swept at 0, 0.25, 0.5, 1 and 2, read on BD-PSNR-YUV because a luma-only
847-/// metric cannot price a term whose whole purpose is chroma: the film clip
848-/// reads -0.653/-0.622/-0.612/-0.615/-0.626 dB and the screen capture
849-/// -0.517/-0.521/-0.515/-0.521/-0.546. A half is film's optimum and inside
850-/// screen capture's flat part; zero reproduces the chroma-blind decision
851-/// exactly, which is how the sweep proved the term was reaching the search.
852-///
853-/// It is worth 0.041 dB on the film clip and nothing on the screen capture --
854-/// small enough to name what it rules out. Our chroma trails x264 by 0.5-0.9 dB
855-/// per plane at every QP, and it is not because the vector was chosen without
856-/// looking: weighting chroma up lifts chroma PSNR monotonically, and past a
857-/// half the bits it spends cost more than the chroma it buys.
858-const CHROMA_ME_WEIGHT: f64 = 0.5;
859-
860-/// How many inter candidates the macroblock decision codes before choosing,
861-/// most promising first. One is the SATD winner alone, which is what this used
862-/// to do; five is every shape the search costed plus P_Skip. BD-PSNR-YUV
863-/// against x264 at GOP 10 over QP 22/26/30/34, at `Preset::Balanced`:
864-///
865-/// ```text
866-/// film 3840x1608 screen 2560x1440
867-/// 1 candidate -0.580 -0.474
868-/// 2 -0.521 -0.459
869-/// 3 -0.513 -0.447
870-/// 5 -0.504 -0.406
871-/// ```
872-///
873-/// monotone in the count with no turnover, so the decision is taken at the
874-/// full list. The SATD total that used to rank the shapes is a
875-/// prediction-domain estimate that never sees the residual it causes.
876-const SHAPE_RD_CANDIDATES: usize = 5;
877-
878-/// The inter decision for a P macroblock.
879-#[derive(Clone, Copy)]
880-struct InterChoice {
881- /// The candidate's SATD cost (luma plus chroma) as the shape search ranked it;
882- /// zero where the search did not rank it.
883- satd: i32,
884- shape: PShape,
885- /// One motion vector per partition.
886- mv: [[i16; 2]; 4],
887- /// The P_Skip motion vector of 8.4.1.1.
888- skip_mv: [i16; 2],
889- /// The skip candidate is at least as good as the searched one.
890- prefer_skip: bool,
891- /// The prediction is so close to the source that the macroblock is coded
892- /// as P_Skip without costing a residual (`Preset::Fast` only).
893- force_skip: bool,
894-}
895-
896-/// Motion search plus the skip candidate.
897-fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<InterChoice> {
898- let reference = e.reference.expect("a P slice has a reference");
899- let ctx = MvCtx {
900- mb_x,
901- mb_y,
902- slice_id: e.slice_id,
903- written: 0,
904- pos: Default::default(),
905- };
906- let n = ctx.neighbours(pic, 0, 0, 4, 0);
907- let mvp = predict_mv(&n, 0, 4, 4, 0);
908- // P_Skip (8.4.1.1): zero when either neighbour is missing or is itself a
909- // zero-motion reference-0 partition.
910- let a = ctx.at(pic, mb_x as i32 * 4 - 1, mb_y as i32 * 4, 0);
911- let b = ctx.at(pic, mb_x as i32 * 4, mb_y as i32 * 4 - 1, 0);
912- let zero = |nb: &crate::mv::Nb| nb.ref_idx == 0 && nb.mv == [0, 0];
913- let skip_mv = if !a.avail || !b.avail || zero(&a) || zero(&b) {
914- [0, 0]
915- } else {
916- mvp
917- };
918-
919- let plane = RefPlane {
920- data: &reference.y.data,
921- stride: reference.y.stride,
922- origin: reference.y.origin,
923- width: reference.y.width,
924- height: reference.y.height,
925- pad: reference.y.pad,
926- };
927- let (sx, sy) = (mb_x * 16, mb_y * 16);
928- let sw = e.src.stride;
929-
930- // What the two chroma planes cost under a candidate vector, in the same
931- // SATD domain the luma search ranks in. The search itself cannot afford
932- // this -- it runs on SAD over a whole neighbourhood -- but the handful of
933- // candidates that survive to the shape decision can, and until they did,
934- // no decision in this encoder had ever looked at chroma: the vector, the
935- // shape and the skip flag were all chosen on luma alone and chroma was
936- // coded against whatever came out. Measured per plane against x264 that
937- // showed up as a uniform 0.5-0.9 dB chroma deficit at every QP while we
938- // spent more bits, which is a prediction that was never asked about.
939- let cplanes = [&reference.cb, &reference.cr];
940- let chroma_satd = |px: usize, py: usize, w: usize, h: usize, mv: [i16; 2]| -> i32 {
941- if CHROMA_ME_WEIGHT == 0.0 {
942- return 0;
943- }
944- let mut buf = [0u8; 64];
945- let mut sum = 0;
946- for comp in 0..2 {
947- let src = cplanes[comp];
948- let rp = RefPlane {
949- data: &src.data,
950- stride: src.stride,
951- origin: src.origin,
952- width: src.width,
953- height: src.height,
954- pad: src.pad,
955- };
956- let (cw, ch) = (w / 2, h / 2);
957- mc_chroma(
958- &rp,
959- (sx + px) as i32 / 2,
960- (sy + py) as i32 / 2,
961- mv,
962- cw,
963- ch,
964- cw,
965- &mut buf,
966- crate::inter::Put::Set,
967- );
968- let plane = if comp == 0 { &e.src.u } else { &e.src.v };
969- sum += satd_block(
970- plane,
971- e.src.c_stride,
972- (sx + px) / 2,
973- (sy + py) / 2,
974- &buf,
975- cw,
976- 0,
977- cw,
978- ch,
979- );
980- }
981- (f64::from(sum) * CHROMA_ME_WEIGHT) as i32
982- };
983-
984- // Early skip: a prediction at the P_Skip vector that already sits inside
985- // the quantiser's dead zone codes nothing, so neither the search nor a
986- // residual is worth the time. Judged on luma SAD, the largest single
987- // difference and the chroma SATD, all against the quantiser step.
988- if e.preset == Preset::Fast && e.fast.early_skip > 0 {
989- let qstep = ((f64::from(e.qp) - 4.0) / 6.0).exp2();
990- let k = f64::from(e.fast.early_skip) / 100.0;
991- let mut buf = [0u8; 256];
992- mc_luma(
993- &plane,
994- sx as i32,
995- sy as i32,
996- skip_mv,
997- 16,
998- 16,
999- 16,
1000- &mut buf,
1001- Put::Set,
1002- );
1003- let (sad_luma, max_luma) = sad_max16(&e.src.y, sw, sx, sy, &buf);
1004- if f64::from(sad_luma) <= 256.0 * k * qstep && f64::from(max_luma) <= 4.0 * k * qstep + 2.0
1005- {
1006- let c = chroma_satd(0, 0, 16, 16, skip_mv);
1007- if f64::from(c) <= 64.0 * k * qstep * 4.0 {
1008- return vec![InterChoice {
1009- satd: 0,
1010- shape: PShape::Whole,
1011- mv: [skip_mv; 4],
1012- skip_mv,
1013- prefer_skip: true,
1014- force_skip: true,
1015- }];
1016- }
1017- }
1018- }
1019-
1020- let range = match e.preset {
1021- Preset::Fast => 16i16,
1022- Preset::Balanced => 48,
1023- };
1024-
1025- // One search over a `w` x `h` partition at `(px, py)` samples inside the
1026- // macroblock, seeded with the candidate vectors of its neighbourhood.
1027- let mlam = motion_lambda(e);
1028- let search = |px: usize, py: usize, w: usize, h: usize, mvp: [i16; 2], seeds: &[[i16; 2]]| {
1029- let (x0, y0) = (sx + px, sy + py);
1030- let mut buf = [0u8; 256];
1031- // Whole-sample candidates read the reference plane in place; only the
1032- // sub-sample refinement pays for interpolation. The search runs on SAD,
1033- // which is what a search can afford; the winner is re-costed on SATD
1034- // because the intra candidates are SATD and the two scales differ.
1035- let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 {
1036- let bits = (mlam
1037- * f64::from(
1038- se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1])),
1039- )
1040- * MV_BITS_WEIGHT)
1041- .round() as i32;
1042- if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 {
1043- let o = integer_origin(
1044- &plane,
1045- x0 as i32 + (mv[0] >> 2) as i32,
1046- y0 as i32 + (mv[1] >> 2) as i32,
1047- w,
1048- h,
1049- );
1050- return sad(&e.src.y, sw, x0, y0, &plane.data[o..], plane.stride, w, h) + bits;
1051- }
1052- mc_luma(
1053- &plane,
1054- x0 as i32,
1055- y0 as i32,
1056- mv,
1057- w,
1058- h,
1059- w,
1060- &mut buf,
1061- crate::inter::Put::Set,
1062- );
1063- let d = if satd {
1064- satd_block(&e.src.y, sw, x0, y0, &buf, w, 0, w, h)
1065- } else {
1066- sad(&e.src.y, sw, x0, y0, &buf, w, w, h)
1067- };
1068- d + bits
1069- };
1070-
1071- let fast = e.preset == Preset::Fast;
1072- let mut best = ([0i16; 2], i32::MAX);
1073- for (i, &cand) in seeds.iter().enumerate() {
1074- if seeds[..i].contains(&cand) {
1075- continue;
1076- }
1077- let c = cost_of(cand, false);
1078- if c < best.1 {
1079- best = (cand, c);
1080- }
1081- }
1082- // Every partition is searched. This used to stop at a seed whose cost
1083- // was already under half a level a sample, on the reasoning that the
1084- // prediction fit and the search is the encoder's hot loop. Swept on
1085- // consecutive pictures (BD-PSNR against x264, GOP 10) the threshold is
1086- // monotonically harmful: 0/0.25/0.5/1.0 levels a sample read
1087- // -0.586/-0.587/-0.593/-0.617 dB on the film clip and
1088- // -0.466/-0.470/-0.468/-0.476 on the screen capture. A seed that fits
1089- // is exactly where a little more refinement is cheap.
1090- {
1091- // Fast opens at two whole samples: the seeds already carry the
1092- // neighbours' motion, so the walk only has to settle around them.
1093- let mut step = if fast { 2i16 * 4 } else { 4i16 * 4 };
1094- let mut passes = 0;
1095- while step >= 4 {
1096- let mut improved = true;
1097- while improved {
1098- improved = false;
1099- passes += 1;
1100- if fast && passes > FAST_ME_PASSES {
1101- break;
1102- }
1103- for (dx, dy) in ME_PATTERN {
1104- let (dx, dy) = (dx * step, dy * step);
1105- let cand = [best.0[0] + dx, best.0[1] + dy];
1106- if (cand[0] - mvp[0]).abs() > range * 4
1107- || (cand[1] - mvp[1]).abs() > range * 4
1108- {
1109- continue;
1110- }
1111- let c = cost_of(cand, false);
1112- if c < best.1 {
1113- best = (cand, c);
1114- improved = true;
1115- }
1116- }
1117- }
1118- step /= 2;
1119- }
1120- // Sub-sample refinement runs on SATD, not SAD: interpolation
1121- // smooths, and a sum of absolute differences reads the smoothing
1122- // as a better match where a transform-domain cost does not. Worth
1123- // 0.06 dB BD-PSNR on the film clip and 0.04 dB on the screen
1124- // capture. The whole-sample winner is re-costed in the same domain
1125- // first so the two halves of the search compare.
1126- let sub_satd = !fast || e.fast.me_satd;
1127- best.1 = cost_of(best.0, sub_satd);
1128- // Balanced iterates both sub-sample steps to convergence. Fast
1129- // looks at each ring of eight once.
1130- let rings: &[i16] = if !fast {
1131- &[2, 1]
1132- } else {
1133- match e.fast.me_sub {
1134- 0 => &[],
1135- 1 => &[2],
1136- _ => &[2, 1],
1137- }
1138- };
1139- if fast && e.fast.me_sub == 1 {
1140- // The four half-sample neighbours on the axes, then only the
1141- // diagonal the two winning axes point at.
1142- let base = best;
1143- let mut axis = [(base.0, base.1); 2];
1144- for (k, dirs) in [[(2i16, 0i16), (-2, 0)], [(0, 2), (0, -2)]]
1145- .into_iter()
1146- .enumerate()
1147- {
1148- for (dx, dy) in dirs {
1149- let cand = [base.0[0] + dx, base.0[1] + dy];
1150- let c = cost_of(cand, sub_satd);
1151- if c < axis[k].1 {
1152- axis[k] = (cand, c);
1153- }
1154- }
1155- }
1156- let both = axis[0].1 < base.1 && axis[1].1 < base.1;
1157- if both {
1158- let cand = [axis[0].0[0], axis[1].0[1]];
1159- let c = cost_of(cand, sub_satd);
1160- if c < best.1 {
1161- best = (cand, c);
1162- }
1163- }
1164- for a in axis {
1165- if a.1 < best.1 {
1166- best = a;
1167- }
1168- }
1169- }
1170- let rings: &[i16] = if fast && e.fast.me_sub == 1 {
1171- &[]
1172- } else {
1173- rings
1174- };
1175- for &step in rings {
1176- let mut improved = true;
1177- while improved {
1178- improved = false;
1179- for (dx, dy) in [
1180- (step, 0),
1181- (-step, 0),
1182- (0, step),
1183- (0, -step),
1184- (step, step),
1185- (-step, -step),
1186- (step, -step),
1187- (-step, step),
1188- ] {
1189- let cand = [best.0[0] + dx, best.0[1] + dy];
1190- let c = cost_of(cand, sub_satd);
1191- if c < best.1 {
1192- best = (cand, c);
1193- improved = !fast;
1194- }
1195- }
1196- }
1197- }
1198- }
1199- (
1200- best.0,
1201- if !fast || e.fast.me_satd {
1202- best.1
1203- } else {
1204- cost_of(best.0, true)
1205- },
1206- )
1207- };
1208-
1209- let seeds = [mvp, skip_mv, [0, 0], n[0].mv, n[1].mv, n[2].mv];
1210- let (mv16, cost16) = search(0, 0, 16, 16, mvp, &seeds);
1211- let cost16 = cost16 + chroma_satd(0, 0, 16, 16, mv16);
1212- let skip_cost = {
1213- let mut buf = [0u8; 256];
1214- mc_luma(
1215- &plane,
1216- sx as i32,
1217- sy as i32,
1218- skip_mv,
1219- 16,
1220- 16,
1221- 16,
1222- &mut buf,
1223- Put::Set,
1224- );
1225- // P_Skip's rebate is the signalling it genuinely saves. Re-measured on
1226- // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip
1227- // and -0.741/-0.696 on the screen capture -- the two contents disagree
1228- // by less than the step between them, so this is the flat part. Six
1229- // costs 0.14 dB and twelve costs 0.42.
1230- //
1231- // The Intra_4x4 discount above was swept with it: 0.65/0.75/0.85/1.0
1232- // read -1.216/-1.154/-1.182/-1.373 on film and -0.970/-0.696/-0.591/
1233- // -0.562 on screen capture, so three quarters is film's optimum and
1234- // inside screen capture's flat part.
1235- satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) + chroma_satd(0, 0, 16, 16, skip_mv)
1236- - motion_rate(e, 2.0)
1237- };
1238-
1239- let mut best = (PShape::Whole, [mv16; 4], cost16);
1240- // Every shape the search costed, kept so the macroblock decision can rank
1241- // them on coded cost instead of on this SATD total (see `encode_mb`).
1242- let mut evaluated = vec![(PShape::Whole, [mv16; 4])];
1243- // Halves, seeded with the whole-macroblock winner. The predictor used here
1244- // is the whole-macroblock one rather than each half's own: the real
1245- // predictors are derived in coding order when the choice is made, and this
1246- // only has to rank the shapes. A macroblock the 16x16 search already fits
1247- // is left alone — splitting it could only spend bits.
1248- //
1249- // Measured: two more searches per macroblock buy 0.1-0.2 dB on screen
1250- // capture and nothing on camera content, for roughly twice the search
1251- // time. That is a Balanced trade, not a Fast one.
1252- // The threshold is a floor that real content clears everywhere: swept at
1253- // 0, 0.5, 1 and 2 levels a sample it moves neither clip's BD-PSNR by a
1254- // thousandth of a decibel, so on these sources the halves are always
1255- // searched. It stays as a guard for content flat enough to make the two
1256- // extra searches pure cost.
1257- if e.preset == Preset::Balanced && cost16 > 16 * 16 {
1258- for shape in [PShape::Horizontal, PShape::Vertical, PShape::Quad] {
1259- // What the shape itself costs to signal: its mb_type, plus one
1260- // sub_mb_type per quarter when it is P_8x8.
1261- let mut total = motion_rate(
1262- e,
1263- if shape == PShape::Quad {
1264- QUAD_BITS
1265- } else {
1266- HALF_BITS
1267- },
1268- );
1269- let mut mvs = [[0i16; 2]; 4];
1270- let (pw, ph) = shape.part_blocks();
1271- for part in 0..shape.parts() {
1272- let ((bx, by), (w, h)) = shape.geometry(part);
1273- // Each partition is searched against the predictor it will
1274- // actually be coded with (8.4.1.3), not against the whole
1275- // macroblock's: the partitions before it in this macroblock
1276- // are already chosen, so the neighbourhood the predictor reads
1277- // can be completed from `mvs`.
1278- let mut n = ctx.neighbours(pic, bx, by, pw, 0);
1279- let inside = |x: i32, y: i32, nb: &mut crate::mv::Nb| {
1280- if let Some(p) = shape.part_of(x, y).filter(|&p| p < part) {
1281- *nb = crate::mv::Nb {
1282- avail: true,
1283- mv: mvs[p],
1284- ref_idx: 0,
1285- };
1286- }
1287- };
1288- inside(bx as i32 - 1, by as i32, &mut n[0]);
1289- inside(bx as i32, by as i32 - 1, &mut n[1]);
1290- let cx = bx as i32 + pw as i32;
1291- if shape.part_of(cx, by as i32 - 1).is_some() {
1292- inside(cx, by as i32 - 1, &mut n[2]);
1293- } else if !n[2].avail {
1294- inside(bx as i32 - 1, by as i32 - 1, &mut n[2]);
1295- }
1296- let part_mvp = predict_mv(&n, 0, pw, ph, part);
1297- let seeds = [mv16, part_mvp, mvp, skip_mv, [0, 0]];
1298- let (mv, cost) = search(bx * 4, by * 4, w, h, part_mvp, &seeds);
1299- mvs[part] = mv;
1300- total += cost + chroma_satd(bx * 4, by * 4, w, h, mv);
1301- }
1302- evaluated.push((shape, mvs));
1303- if total < best.2 {
1304- best = (shape, mvs, total);
1305- }
1306- }
1307- }
1308-
1309- // How often each shape actually wins. Behind an environment switch because
1310- // it answers a question the rate gate cannot: a partition sweep that reads
1311- // flat is either a flat knob or a path nothing enters, and only a count
1312- // tells the two apart. It found the second -- at `Preset::Fast`, which is
1313- // what the x264 comparison runs by default, no macroblock is ever split.
1314- if std::env::var_os("EC_H264_SHAPE_STATS").is_some() {
1315- static N: [std::sync::atomic::AtomicUsize; 4] = [
1316- std::sync::atomic::AtomicUsize::new(0),
1317- std::sync::atomic::AtomicUsize::new(0),
1318- std::sync::atomic::AtomicUsize::new(0),
1319- std::sync::atomic::AtomicUsize::new(0),
1320- ];
1321- let i = match best.0 {
1322- PShape::Whole => 0,
1323- PShape::Horizontal => 1,
1324- PShape::Vertical => 2,
1325- PShape::Quad => 3,
1326- };
1327- let v = N[i].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
1328- let tot: usize = N
1329- .iter()
1330- .map(|n| n.load(std::sync::atomic::Ordering::Relaxed))
1331- .sum();
1332- if tot.is_multiple_of(20000) {
1333- eprintln!(
1334- "SHAPES whole={} horiz={} vert={} quad={} (last {i} -> {v})",
1335- N[0].load(std::sync::atomic::Ordering::Relaxed),
1336- N[1].load(std::sync::atomic::Ordering::Relaxed),
1337- N[2].load(std::sync::atomic::Ordering::Relaxed),
1338- N[3].load(std::sync::atomic::Ordering::Relaxed),
1339- );
1340- }
1341- }
1342- let winner = InterChoice {
1343- satd: best.2,
1344- shape: best.0,
1345- mv: best.1,
1346- skip_mv,
1347- prefer_skip: best.0 == PShape::Whole && skip_cost <= best.2,
1348- force_skip: false,
1349- };
1350- // The SATD winner first, then the shapes it beat, then the skip candidate
1351- // when the winner is not already it. The caller codes as many of these as
1352- // its preset allows and keeps the one with the smallest coded cost.
1353- let mut cands = vec![winner];
1354- for (shape, mv) in evaluated {
1355- if shape != winner.shape || winner.prefer_skip {
1356- cands.push(InterChoice {
1357- satd: 0,
1358- shape,
1359- mv,
1360- skip_mv,
1361- prefer_skip: false,
1362- force_skip: false,
1363- });
1364- }
1365- }
1366- if !winner.prefer_skip {
1367- cands.push(InterChoice {
1368- satd: skip_cost,
1369- shape: PShape::Whole,
1370- mv: [skip_mv; 4],
1371- skip_mv,
1372- prefer_skip: true,
1373- force_skip: false,
1374- });
1375- }
1376- cands
1377-}
1378-
1379-/// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock,
1380-/// prediction already in the plane.
1381-#[allow(clippy::too_many_arguments)]
1382-fn code_luma_4x4(
1383- pic: &mut Picture,
1384- e: &MbEnc<'_>,
1385- w: &EncEntropy,
1386- mb_x: usize,
1387- mb_y: usize,
1388- qp: i32,
1389- intra: bool,
1390- lv: &mut Levels,
1391-) {
1392- let stride = pic.y.stride;
1393- // An inter macroblock's blocks are reconstructed only after the whole
1394- // macroblock has been quantised, because [`decimate_score`] can still take
1395- // a block away. Intra blocks reconstruct as they go: the next block in the
1396- // macroblock predicts from them.
1397- let mut pending: [Option<[i32; 16]>; 16] = [None; 16];
1398- // Per 8x8 group, what coding its blocks buys and what it costs, for the
1399- // group-level test below. A block with no levels contributes nothing to
1400- // either side: its source energy stays in the reconstruction whatever the
1401- // group decides.
1402- let mut ssd_zero = [0i64; 4];
1403- let mut ssd_coded = [0i64; 4];
1404- let mut rate = [0f64; 4];
1405- for blk in 0..16 {
1406- let (dx, dy) = BLK4_POS[blk];
1407- let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1408- let origin = pic.y.at(x, y);
1409- let mut d = [0i32; 16];
1410- for ry in 0..4 {
1411- for rx in 0..4 {
1412- d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
1413- - i32::from(pic.y.data[origin + ry * stride + rx]);
1414- }
1415- }
1416- let source = d;
1417- forward_4x4(&mut d);
1418- let rdoq = !intra && w.is_cabac();
1419- let mut nz = if rdoq {
1420- quant_4x4_offset(&d, qp, RDOQ_DEAD_ZONE, false, &mut lv.luma[blk])
1421- } else {
1422- quant_4x4(&d, qp, intra, false, &mut lv.luma[blk])
1423- };
1424- if rdoq && nz != 0 {
1425- nz = rdoq_4x4(
1426- e,
1427- w,
1428- &source,
1429- &mut lv.luma[blk],
1430- qp,
1431- BlockCat::Luma4x4,
1432- false,
1433- );
1434- }
1435- lv.luma_nz[blk] = nz;
1436- if nz == 0 {
1437- continue;
1438- }
1439- let mut raster = [0i32; 16];
1440- unzigzag(&lv.luma[blk], &mut raster);
1441- dequant_4x4(&mut raster, &e.ls, qp, false);
1442- let mut resid = [0i32; 16];
1443- inverse_transform_4x4(&raster, &mut resid);
1444- // Is the block worth its bits? A block whose residual barely moves the
1445- // reconstruction is pure quantisation churn; dropping it is the cheap
1446- // half of rate-distortion optimised quantisation, and the half that
1447- // pays. Intra blocks are left alone: their reconstruction is what the
1448- // next block in the macroblock predicts from.
1449- if !rdoq
1450- && !intra
1451- && !worth_coding(
1452- &source,
1453- &resid,
1454- &lv.luma[blk],
1455- zero_block_lambda(e, qp, e.transform_8x8),
1456- )
1457- {
1458- lv.luma[blk] = [0; 16];
1459- lv.luma_nz[blk] = 0;
1460- continue;
1461- }
1462- if intra {
1463- lv.cbp_luma |= 1 << (blk >> 2);
1464- add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
1465- } else {
1466- for i in 0..16 {
1467- let z = i64::from(source[i]);
1468- let c = i64::from(source[i] - resid[i]);
1469- ssd_zero[blk >> 2] += z * z;
1470- ssd_coded[blk >> 2] += c * c;
1471- }
1472- rate[blk >> 2] +=
1473- match w.residual_block_cost(&lv.luma[blk], BlockCat::Luma4x4, Some(1), Some(1)) {
1474- // CABAC's own arithmetic cost for the levels, which is what
1475- // the group is really deciding about. It arrives in 256ths of
1476- // a bit.
1477- Some(bits) => f64::from(bits) / 256.0,
1478- None => block_bits(&lv.luma[blk]) as f64,
1479- };
1480- pending[blk] = Some(resid);
1481- }
1482- }
1483- if intra {
1484- return;
1485- }
1486- // A block that survives its own rate-distortion test can still be the last
1487- // coefficient standing in its 8x8 group, and then it is paying a
1488- // coded_block_pattern bit as well as its levels. x264 decides that with a
1489- // count of how tightly the levels cluster at the front of the scan
1490- // (`decimate`), thresholded at four per group; swept here, that count
1491- // wants opposite settings on the two contents -- monotonically off on
1492- // camera grain, monotonically harder on screen capture -- because it is a
1493- // heuristic standing in for a rate-distortion test the encoder can just
1494- // do. So do it: a group is coded only if its blocks buy more squared error
1495- // than their levels plus the pattern bit are worth, at the same lambda the
1496- // per-block test uses.
1497- // With an exact rate the lambda needs no correction factor: the group test
1498- // uses the mode decision's own lambda where the rate is CABAC's, and falls
1499- // back to the per-block test's discounted one where it is an estimate.
1500- let lambda = if w.is_cabac() {
1501- GROUP_LAMBDA * lambda_ssd(qp)
1502- } else {
1503- zero_block_lambda(e, qp, e.transform_8x8)
1504- };
1505- for g in 0..4 {
1506- if rate[g] == 0.0 {
1507- continue;
1508- }
1509- if ssd_coded[g] as f64 + lambda * (rate[g] + CBP_BIT) < ssd_zero[g] as f64 {
1510- continue;
1511- }
1512- for blk in g * 4..g * 4 + 4 {
1513- lv.luma[blk] = [0; 16];
1514- lv.luma_nz[blk] = 0;
1515- pending[blk] = None;
1516- }
1517- }
1518- for blk in 0..16 {
1519- let Some(resid) = pending[blk] else { continue };
1520- let (dx, dy) = BLK4_POS[blk];
1521- let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1522- let origin = pic.y.at(x, y);
1523- lv.cbp_luma |= 1 << (blk >> 2);
1524- add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
1525- }
1526-}
1527-
1528-/// What a group of four luma blocks pays in coded_block_pattern to be coded
1529-/// at all, in bits, on top of its own levels.
1530-///
1531-/// This charge and [`GROUP_LAMBDA`] move the group test along the same axis --
1532-/// both make dropping a group likelier -- so only one of them is worth tuning.
1533-/// Swept at 0, 6, 12 and 24 bits it reads -0.317/-0.335/-0.379/-0.472 dB on
1534-/// the film clip against -0.295/-0.212/-0.191/-0.185 on the screen capture:
1535-/// the same trade the lambda makes, at a worse exchange rate. It stays at a
1536-/// plausible six.
1537-const CBP_BIT: f64 = 6.0;
1538-
1539-/// What chroma pays to take its coded_block_pattern from one to two, in bits,
1540-/// on top of the levels: the pattern bins themselves plus a coded_block_flag
1541-/// for every AC block that then has to say it is empty.
1542-///
1543-/// Swept at 0, 4, 8, 16, 32 and 64 bits, read on the all-plane PSNR because a
1544-/// luma-only one cannot see what this decision spends: -0.688/-0.681/-0.659/
1545-/// -0.653/-0.670/-0.742 dB BD on the film clip and -0.537/-0.527/-0.530/
1546-/// -0.517/-0.524/-0.522 on the screen capture. Both turn over at sixteen. The
1547-/// same sweep read on luma alone climbs all the way to +0.079 dB at 64,
1548-/// because past the turn the test is buying luma bits by throwing chroma
1549-/// away -- which is exactly the trade an all-plane metric exists to catch.
1550-const CBP_CHROMA_BIT: f64 = 16.0;
1551-
1552-/// How much of the mode-decision lambda the group test uses.
1553-///
1554-/// The 8x8 transform path was swept the same way and does not want this test
1555-/// at all: at 0, 0.3 and 0.6 the `transform_8x8` gate reads +0.620/+0.624/
1556-/// +0.608 dB on the film clip and +0.007/+0.007/+0.009 on the screen capture,
1557-/// all inside its noise. One 8x8 block is a whole coded_block_pattern group,
1558-/// so its own zero test already decides what this one would, and `rdoq_8x8`
1559-/// drops it outright when the levels do not survive.
1560-///
1561-/// Swept at 0.25, 0.5, 0.6, 0.75, 0.9, 1.0 and 2.0 on both real clips:
1562-/// -0.315/-0.314/-0.321/-0.335/-0.354/-0.372/-0.575 dB on the 3840x1608 film
1563-/// clip and -0.297/-0.267/-0.252/-0.212/-0.202/-0.193/-0.277 on the 2560x1440
1564-/// screen capture. Screen capture has an interior optimum around one -- which
1565-/// the same test on an estimated rate did not, it only ever wanted more -- and
1566-/// camera grain wants less, because a grain block that scores as noise is
1567-/// carrying signal the eye is measuring. Six tenths is the most the film clip
1568-/// takes without losing ground, and it is worth 0.06 dB on screen capture.
1569-const GROUP_LAMBDA: f64 = 0.6;
1570-
1571-/// How much of the squared-error lambda the chroma DC zero test uses.
1572-///
1573-/// BD-PSNR-YUV against x264 at GOP 10 over QP 22/26/30/34, `Preset::Balanced`,
1574-/// with the test off against a ladder of multipliers:
1575-///
1576-/// ```text
1577-/// film screen phone handheld
1578-/// off -0.504 -0.227 -0.300 -0.886
1579-/// 0.25 -0.506 -0.227
1580-/// 0.5 -0.500 -0.220 -0.297 -0.884
1581-/// 0.75 -0.500 -0.223
1582-/// 1.0 -0.518 -0.246
1583-/// 2.0 -0.708 -0.566
1584-/// ```
1585-///
1586-/// Zeroing on squared error alone (a multiplier of 0) never fires, so the rate
1587-/// term is the whole test; above the peak it throws away chroma the picture
1588-/// needs.
1589-const CHROMA_DC_LAMBDA: f64 = 0.5;
1590-
1591-/// Squared error of coding `levels`, in the pixels the block reconstructs to.
1592-fn block_ssd(e: &MbEnc<'_>, source: &[i32; 16], levels: &[i32; 16], qp: i32, skip_dc: bool) -> i64 {
1593- let mut raster = [0i32; 16];
1594- if skip_dc {
1595- unzigzag_ac15(levels, &mut raster);
1596- } else {
1597- unzigzag(levels, &mut raster);
1598- }
1599- dequant_4x4(&mut raster, &e.ls, qp, skip_dc);
1600- let mut resid = [0i32; 16];
1601- inverse_transform_4x4(&raster, &mut resid);
1602- let mut ssd = 0i64;
1603- for i in 0..16 {
1604- let d = i64::from(source[i] - resid[i]);
1605- ssd += d * d;
1606- }
1607- ssd
1608-}
1609-
1610-/// How much of the mode-decision lambda rate-distortion quantisation uses.
1611-///
1612-/// The bits here are the coder's own, not an estimate, so there is no
1613-/// over-estimate to correct for and the scale starts at 1. Swept over 0.5,
1614-/// 1.0, 1.25, 1.5 and 2.0 against x264 on a 3840x1608 film clip and a
1615-/// 2560x1440 screen capture: the two disagree, film reading -0.607 dB at 0.5
1616-/// and -0.680 at 1.5 while screen capture reads -0.620 and -0.444, and 1.0 is
1617-/// the crossing point that costs neither (-0.628 and -0.471). Table in
1618-/// `lanes/h264x264-r2.report.md`.
1619-const RDOQ_LAMBDA: f64 = 1.0;
1620-
1621-/// The dead zone rate-distortion quantisation starts from, as a divisor of the
1622-/// quantiser step: 2 is round-to-nearest. The plain inter path uses 6, which
1623-/// has already thrown away the levels this search would weigh -- a search
1624-/// bounded by the heuristic it replaces measures the heuristic. This is the
1625-/// half of the change that pays: 1/6 -> 1/2 under the same search is worth
1626-/// 0.102 dB on the film clip and 0.301 on the synthetic gate. 1/3 and 1/4 read
1627-/// -0.647 and -0.677 dB where 1/2 reads -0.630.
1628-const RDOQ_DEAD_ZONE: i32 = 2;
1629-
1630-/// The largest level the search offers a smaller magnitude to. A big level is
1631-/// carrying real signal and never wins by shrinking; bounding the search is
1632-/// what keeps it free. Unbounded it tripled the synthetic clip's encode time
1633-/// (1.08 s -> 3.53 s) for the same BD-PSNR; at 2 the run is 1.09 s. Swept over
1634-/// 1, 2 and 3: -4.062/-0.623/-0.496, -4.073/-0.628/-0.471 and
1635-/// -4.065/-0.629/-0.477 dB on synthetic, film and screen capture.
1636-const RDOQ_MAX_LEVEL: i32 = 2;
1637-
1638-/// The rounding the chroma AC path keeps under the search: the inter dead zone
1639-/// it already had. Luma wanted the wider 1/2 rounding once a search could take
1640-/// levels back down (`RDOQ_DEAD_ZONE`); chroma does not. Measured on the two
1641-/// clips at the settled luma constants, BD-PSNR against x264: 1/2 rounding
1642-/// -0.653 film / -0.482 screen capture, 1/4 -0.623 / -0.472, 1/3 -0.644 /
1643-/// -0.481, and the 1/6 kept here -0.593 / -0.468 -- against -0.628 / -0.471
1644-/// with no chroma search at all. Chroma AC is sparse enough at these
1645-/// quantisers that offering more levels costs more bits than the search takes
1646-/// back; what pays is only the pruning.
1647-const RDOQ_CHROMA_DEAD_ZONE: i32 = 6;
1648-
1649-/// The rounding the 8x8 luma path keeps under the search. It answers the way
1650-/// 4x4 luma did, not the way chroma did: measured as BD-PSNR of the opt-in
1651-/// `transform_8x8` flag against flag-off, which isolates this path because the
1652-/// flag-off curve does not run through it. Film 3840x1608 / screen capture
1653-/// 2560x1440, no search +0.535 / +0.042, 1/6 +0.551 / --, 1/3 +0.605 / +0.075,
1654-/// and the 1/2 kept here +0.619 / +0.067. The 8x8 blocks carry enough
1655-/// coefficients for the extra levels to pay for themselves, as 4x4 luma's do.
1656-const RDOQ8_DEAD_ZONE: i32 = 2;
1657-
1658-/// Rate-distortion quantisation of one inter luma block: each level is offered
1659-/// the two cheaper magnitudes below it, and takes one when the squared error it
1660-/// gives up costs less than the bits it saves.
1661-///
1662-/// The rate is the CABAC coder's own price for the whole block against the
1663-/// context state as it stands, so dropping a level is priced with the
1664-/// significance map that follows from it — which is where most of the saving
1665-/// is. Intra blocks stay out: their reconstruction is what the next block in
1666-/// the macroblock predicts from, so a level changed here would move a
1667-/// prediction the decision cannot see.
1668-#[allow(clippy::too_many_arguments)]
1669-fn rdoq_4x4(
1670- e: &MbEnc<'_>,
1671- w: &EncEntropy,
1672- source: &[i32; 16],
1673- levels: &mut [i32; 16],
1674- qp: i32,
1675- cat: BlockCat,
1676- skip_dc: bool,
1677-) -> u8 {
1678- let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else {
1679- return levels.iter().filter(|&&l| l != 0).count() as u8;
1680- };
1681- let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
1682- let mut cost = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits);
1683- // Highest scanning position first: dropping the last significant level is
1684- // what shortens the significance map, so it is tried while the levels
1685- // above it are still gone.
1686- for pos in (0..cat.max_num_coeff()).rev() {
1687- let level = levels[pos];
1688- if level == 0 {
1689- continue;
1690- }
1691- let mag = level.abs();
1692- if mag > RDOQ_MAX_LEVEL {
1693- continue;
1694- }
1695- let mut tried = mag;
1696- for candidate in [mag - 1, 0] {
1697- if candidate == tried {
1698- continue;
1699- }
1700- tried = candidate;
1701- let keep = levels[pos];
1702- levels[pos] = candidate * level.signum();
1703- let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else {
1704- unreachable!("CAVLC returned early");
1705- };
1706- let trial = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits);
1707- if trial < cost {
1708- cost = trial;
1709- } else {
1710- levels[pos] = keep;
1711- }
1712- }
1713- }
1714- // And the block as a whole: zeroing it drops the coded_block_pattern bit as
1715- // well as every level, which no single-coefficient step can see. This is
1716- // the same decision `worth_coding` makes for the paths without an exact
1717- // rate, made here with one.
1718- let zero_bits = w
1719- .residual_block_cost(&[0; 16], cat, Some(1), Some(1))
1720- .expect("CABAC");
1721- let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
1722- if ssd_zero as f64 + lambda * f64::from(zero_bits) <= cost {
1723- *levels = [0; 16];
1724- return 0;
1725- }
1726- levels.iter().filter(|&&l| l != 0).count() as u8
1727-}
1728-
1729-/// How much of the mode-decision lambda the zero-block test uses.
1730-///
1731-/// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what
1732-/// CAVLC spends and an over-estimate of what CABAC spends; the multiplier
1733-/// brings the rate term back to the coder actually in force. Measured over
1734-/// 0.0, 0.4 and 1.0 on 1080p camera and screen-capture clips: 0.4 is the only
1735-/// one that gains on screen content (+0.13 to +0.39 dB at matched bitrate)
1736-/// without costing camera content.
1737-const ZERO_BLOCK_LAMBDA: f64 = 0.4;
1738-
1739-fn zero_block_lambda(e: &MbEnc<'_>, qp: i32, transform_8x8: bool) -> f64 {
1740- if transform_8x8 {
1741- e.lambda
1742- } else {
1743- ZERO_BLOCK_LAMBDA * lambda_ssd(qp)
1744- }
1745-}
1746-
1747-/// The rate-distortion test behind the per-block zero decision: coding the
1748-/// block has to buy more squared error than its bits are worth.
1749-fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], lambda: f64) -> bool {
1750- let mut ssd_zero = 0i64;
1751- let mut ssd_coded = 0i64;
1752- for i in 0..source.len() {
1753- let z = i64::from(source[i]);
1754- let c = i64::from(source[i] - resid[i]);
1755- ssd_zero += z * z;
1756- ssd_coded += c * c;
1757- }
1758- ssd_coded as f64 + lambda * (block_bits(levels) as f64) < ssd_zero as f64
1759-}
1760-
1761-/// Predict and code the luma of an Intra_16x16 macroblock.
1762-#[allow(clippy::too_many_arguments)]
1763-fn code_i16_luma(
1764- pic: &mut Picture,
1765- e: &MbEnc<'_>,
1766- mb_x: usize,
1767- mb_y: usize,
1768- qp: i32,
1769- mode: u8,
1770- nbr: &MbNeighbors,
1771- lv: &mut Levels,
1772-) {
1773- let w4 = pic.mb_w * 4;
1774- for dy in 0..4 {
1775- let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
1776- pic.i4_modes[base..base + 4].fill(2);
1777- }
1778- let stride = pic.y.stride;
1779- let origin = pic.y.at(mb_x * 16, mb_y * 16);
1780- let mut win = PlaneWindow {
1781- data: &mut pic.y.data,
1782- stride,
1783- origin,
1784- };
1785- pred_16x16(mode, 8, &mut win, nbr.b, nbr.a);
1786- code_luma_i16(pic, e, mb_x, mb_y, qp, lv);
1787-}
1788-
1789-/// The Intra_16x16 luma path (8.5.10 in reverse then forward again).
1790-fn code_luma_i16(
1791- pic: &mut Picture,
1792- e: &MbEnc<'_>,
1793- mb_x: usize,
1794- mb_y: usize,
1795- qp: i32,
1796- lv: &mut Levels,
1797-) {
1798- let stride = pic.y.stride;
1799- let mut dc = [0i32; 16];
1800- let mut ac = [[0i32; 16]; 16];
1801- for blk in 0..16 {
1802- let (dx, dy) = BLK4_POS[blk];
1803- let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1804- let origin = pic.y.at(x, y);
1805- let mut d = [0i32; 16];
1806- for ry in 0..4 {
1807- for rx in 0..4 {
1808- d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
1809- - i32::from(pic.y.data[origin + ry * stride + rx]);
1810- }
1811- }
1812- forward_4x4(&mut d);
1813- dc[dy as usize * 4 + dx as usize] = d[0];
1814- let nz = quant_4x4(&d, qp, true, true, &mut lv.luma[blk]);
1815- lv.luma_nz[blk] = nz;
1816- ac[blk] = lv.luma[blk];
1817- if nz > 0 {
1818- lv.cbp_luma = 15;
1819- }
1820- }
1821- if lv.cbp_luma == 0 {
1822- for blk in 0..16 {
1823- lv.luma[blk] = [0; 16];
1824- lv.luma_nz[blk] = 0;
1825- }
1826- }
1827- forward_hadamard_4x4(&mut dc);
1828- quant_luma_dc(&dc, qp, &mut lv.dc);
1829-
1830- // Reconstruct exactly as the decoder does: DC through 8.5.10, then each
1831- // block's AC with the DC substituted at raster position 0.
1832- let mut raster = [0i32; 16];
1833- unzigzag(&lv.dc, &mut raster);
1834- luma_dc_transform(&mut raster, &e.ls, qp);
1835- let dc_recon = raster;
1836- for blk in 0..16 {
1837- let (dx, dy) = BLK4_POS[blk];
1838- let dc_blk = dc_recon[dy as usize * 4 + dx as usize];
1839- let tc = lv.luma_nz[blk];
1840- if tc == 0 && dc_blk == 0 {
1841- continue;
1842- }
1843- let mut raster = [0i32; 16];
1844- if tc > 0 {
1845- unzigzag_ac15(&ac[blk], &mut raster);
1846- dequant_4x4(&mut raster, &e.ls, qp, true);
1847- }
1848- raster[0] = dc_blk;
1849- let mut resid = [0i32; 16];
1850- inverse_transform_4x4(&raster, &mut resid);
1851- let origin = pic
1852- .y
1853- .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1854- add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
1855- }
1856-}
1857-
1858-/// Chroma residual for both components (8.5.11 + the AC path).
1859-#[allow(clippy::too_many_arguments)]
1860-fn code_chroma(
1861- pic: &mut Picture,
1862- e: &MbEnc<'_>,
1863- w: &EncEntropy,
1864- mb_x: usize,
1865- mb_y: usize,
1866- qp_y: i32,
1867- intra: bool,
1868- lv: &mut Levels,
1869-) {
1870- let qp_c = chroma_qp(qp_y, e.cqo);
1871- let mut dc_lists = [[0i32; 4]; 2];
1872- let mut ac = [[[0i32; 16]; 4]; 2];
1873- let mut srcs = [[[0i32; 16]; 4]; 2];
1874- let mut any_ac = false;
1875- for comp in 0..2 {
1876- let (plane, src) = if comp == 0 {
1877- (&pic.cb, &e.src.u)
1878- } else {
1879- (&pic.cr, &e.src.v)
1880- };
1881- let stride = plane.stride;
1882- for blk in 0..4 {
1883- let (x, y) = (mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
1884- let origin = plane.at(x, y);
1885- let mut d = [0i32; 16];
1886- for ry in 0..4 {
1887- for rx in 0..4 {
1888- d[ry * 4 + rx] = i32::from(src[(y + ry) * e.src.c_stride + x + rx])
1889- - i32::from(plane.data[origin + ry * stride + rx]);
1890- }
1891- }
1892- let source = d;
1893- srcs[comp][blk] = d;
1894- forward_4x4(&mut d);
1895- dc_lists[comp][blk] = d[0];
1896- let rdoq = !intra && w.is_cabac();
1897- let mut nz = if rdoq {
1898- quant_4x4_offset(&d, qp_c, RDOQ_CHROMA_DEAD_ZONE, true, &mut ac[comp][blk])
1899- } else {
1900- quant_4x4(&d, qp_c, intra, true, &mut ac[comp][blk])
1901- };
1902- if rdoq && nz > 0 {
1903- nz = rdoq_4x4(
1904- e,
1905- w,
1906- &source,
1907- &mut ac[comp][blk],
1908- qp_c,
1909- BlockCat::ChromaAc,
1910- true,
1911- );
1912- } else if nz > 0 {
1913- // The same zero decision as luma, against the AC part alone:
1914- // the DC of this block travels through the 2x2 Hadamard and is
1915- // decided with the other three.
1916- let mut raster = [0i32; 16];
1917- unzigzag_ac15(&ac[comp][blk], &mut raster);
1918- dequant_4x4(&mut raster, &e.ls, qp_c, true);
1919- let mut resid = [0i32; 16];
1920- inverse_transform_4x4(&raster, &mut resid);
1921- if !worth_coding(
1922- &source,
1923- &resid,
1924- &ac[comp][blk],
1925- zero_block_lambda(e, qp_c, e.transform_8x8),
1926- ) {
1927- ac[comp][blk] = [0; 16];
1928- nz = 0;
1929- }
1930- }
1931- lv.chroma_nz[comp][blk] = nz;
1932- if nz > 0 {
1933- any_ac = true;
1934- }
1935- }
1936- }
1937- // The chroma pattern is one decision for all eight AC blocks: a single
1938- // surviving block takes coded_block_pattern from one to two, and every
1939- // other block then has to code a coded_block_flag to say it is empty. So
1940- // the same group test luma runs over four blocks runs here over all eight,
1941- // against the same lambda.
1942- if any_ac {
1943- let (mut ssd_zero, mut ssd_coded, mut rate) = (0i64, 0i64, 0f64);
1944- for comp in 0..2 {
1945- for blk in 0..4 {
1946- let source = &srcs[comp][blk];
1947- let mut resid = [0i32; 16];
1948- if lv.chroma_nz[comp][blk] > 0 {
1949- let mut raster = [0i32; 16];
1950- unzigzag_ac15(&ac[comp][blk], &mut raster);
1951- dequant_4x4(&mut raster, &e.ls, qp_c, true);
1952- inverse_transform_4x4(&raster, &mut resid);
1953- rate += match w.residual_block_cost(
1954- &ac[comp][blk],
1955- BlockCat::ChromaAc,
1956- Some(1),
1957- Some(1),
1958- ) {
1959- Some(bits) => f64::from(bits) / 256.0,
1960- None => block_bits(&ac[comp][blk]) as f64,
1961- };
1962- }
1963- for i in 0..16 {
1964- let z = i64::from(source[i]);
1965- let c = i64::from(source[i] - resid[i]);
1966- ssd_zero += z * z;
1967- ssd_coded += c * c;
1968- }
1969- }
1970- }
1971- let lambda = if w.is_cabac() {
1972- GROUP_LAMBDA * lambda_ssd(qp_c)
1973- } else {
1974- zero_block_lambda(e, qp_c, false)
1975- };
1976- if ssd_coded as f64 + lambda * (rate + CBP_CHROMA_BIT) >= ssd_zero as f64 {
1977- ac = [[[0; 16]; 4]; 2];
1978- lv.chroma_nz = [[0; 4]; 2];
1979- any_ac = false;
1980- }
1981- }
1982- // The chroma DC block had no zero test at all: whatever the quantiser
1983- // produced was coded. Its four coefficients spread over all 64 samples of
1984- // the component, and with only DC in the block the inverse transform gives
1985- // every sample the same (dc + 32) >> 6, so the squared error zeroing costs
1986- // is exact in one pass over the AC residual that is already reconstructed
1987- // here.
1988- let mut any_dc = false;
1989- for comp in 0..2 {
1990- forward_hadamard_2x2(&mut dc_lists[comp]);
1991- let mut nz = quant_chroma_dc(&dc_lists[comp], qp_c, intra, &mut lv.chroma_dc[comp]);
1992- if nz > 0 {
1993- let mut dc = [
1994- lv.chroma_dc[comp][0],
1995- lv.chroma_dc[comp][1],
1996- lv.chroma_dc[comp][2],
1997- lv.chroma_dc[comp][3],
1998- ];
1999- chroma_dc_transform_420(&mut dc, &e.ls, qp_c);
2000- let mut delta = 0i64;
2001- for blk in 0..4 {
2002- let mut resid = [0i32; 16];
2003- if any_ac && lv.chroma_nz[comp][blk] > 0 {
2004- let mut raster = [0i32; 16];
2005- unzigzag_ac15(&ac[comp][blk], &mut raster);
2006- dequant_4x4(&mut raster, &e.ls, qp_c, true);
2007- inverse_transform_4x4(&raster, &mut resid);
2008- }
2009- let c = i64::from((dc[blk] + 32) >> 6);
2010- let err: i64 = (0..16)
2011- .map(|i| i64::from(srcs[comp][blk][i] - resid[i]))
2012- .sum();
2013- delta += 16 * c * c - 2 * c * err;
2014- }
2015- let rate = match w.residual_block_cost(
2016- &lv.chroma_dc[comp],
2017- BlockCat::ChromaDc(comp as u8),
2018- Some(1),
2019- Some(1),
2020- ) {
2021- Some(bits) => f64::from(bits) / 256.0,
2022- None => block_bits(&lv.chroma_dc[comp]) as f64,
2023- };
2024- if delta as f64 + CHROMA_DC_LAMBDA * lambda_ssd(qp_c) * rate >= 0.0 {
2025- lv.chroma_dc[comp] = [0; 16];
2026- nz = 0;
2027- }
2028- }
2029- if nz > 0 {
2030- any_dc = true;
2031- }
2032- }
2033- lv.cbp_chroma = if any_ac {
2034- 2
2035- } else if any_dc {
2036- 1
2037- } else {
2038- 0
2039- };
2040- if lv.cbp_chroma < 2 {
2041- lv.chroma_nz = [[0; 4]; 2];
2042- } else {
2043- lv.chroma = ac;
2044- }
2045- if lv.cbp_chroma == 0 {
2046- return;
2047- }
2048- for comp in 0..2 {
2049- let mut dc = [
2050- lv.chroma_dc[comp][0],
2051- lv.chroma_dc[comp][1],
2052- lv.chroma_dc[comp][2],
2053- lv.chroma_dc[comp][3],
2054- ];
2055- chroma_dc_transform_420(&mut dc, &e.ls, qp_c);
2056- let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
2057- let stride = plane.stride;
2058- for blk in 0..4 {
2059- let tc = lv.chroma_nz[comp][blk];
2060- if tc == 0 && dc[blk] == 0 {
2061- continue;
2062- }
2063- let mut raster = [0i32; 16];
2064- if tc > 0 {
2065- unzigzag_ac15(&lv.chroma[comp][blk], &mut raster);
2066- dequant_4x4(&mut raster, &e.ls, qp_c, true);
2067- }
2068- raster[0] = dc[blk];
2069- let mut resid = [0i32; 16];
2070- inverse_transform_4x4(&raster, &mut resid);
2071- let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
2072- add_residual_4x4(&mut plane.data, 8, stride, origin, &resid);
2073- }
2074- }
2075-}
2076-
2077-/// Code the luma of an Intra_4x4 macroblock: per block, choose the prediction
2078-/// mode against the *reconstructed* neighbours and reconstruct it immediately,
2079-/// because the next block predicts from it. Returns the chosen modes and the
2080-/// modes they were predicted to be.
2081-/// How many SATD survivors the Intra_4x4 mode decision re-costs with real
2082-/// quantisation before choosing.
2083-const I4_RD_CANDIDATES: usize = 3;
2084-
2085-fn code_intra_4x4(
2086- pic: &mut Picture,
2087- e: &MbEnc<'_>,
2088- mb_x: usize,
2089- mb_y: usize,
2090- qp: i32,
2091- nbr: &MbNeighbors,
2092- lv: &mut Levels,
2093-) -> ([u8; 16], [u8; 16]) {
2094- let w4 = pic.mb_w * 4;
2095- let (bx0, by0) = (mb_x * 4, mb_y * 4);
2096- let mut modes = [2u8; 16];
2097- let mut pred_modes = [2u8; 16];
2098- for blk in 0..16 {
2099- let (dx, dy) = BLK4_POS[blk];
2100- let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
2101- let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
2102- let left_avail = if dx == 0 { nbr.a } else { true };
2103- let top_avail = if dy == 0 { nbr.b } else { true };
2104- let predicted = if left_avail && top_avail {
2105- pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx])
2106- } else {
2107- 2
2108- };
2109- pred_modes[blk] = predicted;
2110- let n = gather_nbr4(pic, nbr, blk, x, y);
2111- let have_tl = match (dx, dy) {
2112- (0, 0) => nbr.d,
2113- (0, _) => nbr.a,
2114- (_, 0) => nbr.b,
2115- _ => true,
2116- };
2117- let allowed = modes_allowed(n.have_top, n.have_left, have_tl);
2118- let mut best = (i32::MAX, predicted.min(2));
2119- let mut p = [0u8; 16];
2120- let mut ranked = [(i32::MAX, 2u8); 9];
2121- for mode in 0..9u8 {
2122- if !allowed[mode as usize] {
2123- continue;
2124- }
2125- pred_4x4(mode, 8, &n, &mut p);
2126- let bits = if mode == predicted { 1 } else { 4 };
2127- let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + motion_rate(e, f64::from(bits));
2128- ranked[mode as usize] = (c, mode);
2129- if c < best.0 {
2130- best = (c, mode);
2131- }
2132- }
2133- let mut mode = best.1;
2134- // SATD ranks the modes; the survivors are re-costed with the
2135- // quantisation actually in force, because a mode that predicts a
2136- // little worse can quantise to far fewer levels. Measured against
2137- // x264 with `bd_psnr_vs_x264` on a 3840x1608 film clip and a 2560x1440
2138- // screen capture: +0.129 and +0.088 dB all-intra, +0.062 and +0.043 dB
2139- // at GOP 10, for 3-4% encode time. Three survivors is where it
2140- // saturates -- all nine landed within 0.002 dB of three, for 7% more
2141- // encode time.
2142- {
2143- ranked.sort_unstable();
2144- let keep = I4_RD_CANDIDATES;
2145- // The same over-count [`ZERO_BLOCK_LAMBDA`] corrects for: with the
2146- // full rate term this search loses 0.065 dB instead of gaining,
2147- // and it loses more the more candidates it sees.
2148- let lambda = ZERO_BLOCK_LAMBDA
2149- * if e.transform_8x8 {
2150- e.lambda
2151- } else {
2152- lambda_ssd(qp)
2153- };
2154- let mut best_rd = f64::MAX;
2155- for &(c, cand) in ranked.iter().take(keep) {
2156- if c == i32::MAX {
2157- break;
2158- }
2159- pred_4x4(cand, 8, &n, &mut p);
2160- let mut d = [0i32; 16];
2161- for ry in 0..4 {
2162- for rx in 0..4 {
2163- d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
2164- - i32::from(p[ry * 4 + rx]);
2165- }
2166- }
2167- let src = d;
2168- forward_4x4(&mut d);
2169- let mut levels = [0i32; 16];
2170- let nz = quant_4x4(&d, qp, true, false, &mut levels);
2171- let mut resid = [0i32; 16];
2172- if nz > 0 {
2173- let mut raster = [0i32; 16];
2174- unzigzag(&levels, &mut raster);
2175- dequant_4x4(&mut raster, &e.ls, qp, false);
2176- inverse_transform_4x4(&raster, &mut resid);
2177- }
2178- let mut ssd = 0i64;
2179- for i in 0..16 {
2180- let err = i64::from(src[i] - resid[i]);
2181- ssd += err * err;
2182- }
2183- let mode_bits = if cand == predicted { 1 } else { 4 };
2184- let bits = block_bits(&levels) + mode_bits;
2185- let cost = ssd as f64 + lambda * bits as f64;
2186- if cost < best_rd {
2187- best_rd = cost;
2188- mode = cand;
2189- }
2190- }
2191- }
2192- modes[blk] = mode;
2193- pic.i4_modes[by * w4 + bx] = mode;
2194- // Prediction into the plane, then residual and reconstruction.
2195- pred_4x4(mode, 8, &n, &mut p);
2196- let stride = pic.y.stride;
2197- let origin = pic.y.at(x, y);
2198- for ry in 0..4 {
2199- let row = origin + ry * stride;
2200- pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
2201- }
2202- let mut d = [0i32; 16];
2203- for ry in 0..4 {
2204- for rx in 0..4 {
2205- d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
2206- - i32::from(p[ry * 4 + rx]);
2207- }
2208- }
2209- forward_4x4(&mut d);
2210- let nz = quant_4x4(&d, qp, true, false, &mut lv.luma[blk]);
2211- lv.luma_nz[blk] = nz;
2212- if nz > 0 {
2213- lv.cbp_luma |= 1 << (blk >> 2);
2214- let mut raster = [0i32; 16];
2215- unzigzag(&lv.luma[blk], &mut raster);
2216- dequant_4x4(&mut raster, &e.ls, qp, false);
2217- let mut resid = [0i32; 16];
2218- inverse_transform_4x4(&raster, &mut resid);
2219- add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
2220- }
2221- }
2222- (modes, pred_modes)
2223-}
2224-
2225-/// Predicted Intra_8x8 mode of `blk8` (8.3.2.1): the decoder's rule, read
2226-/// from the 4x4 slots every size writes its mode into.
2227-fn predicted_mode8(pic: &Picture, nbr: &MbNeighbors, bx: usize, by: usize, blk8: usize) -> u8 {
2228- let w4 = pic.mb_w * 4;
2229- let left_avail = if blk8.is_multiple_of(2) { nbr.a } else { true };
2230- let top_avail = if blk8 < 2 { nbr.b } else { true };
2231- if left_avail && top_avail {
2232- pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx])
2233- } else {
2234- 2
2235- }
2236-}
2237-
2238-/// Residual of one 8x8 luma block against the prediction already in the
2239-/// plane: forward transform, quantise, and — when anything survives —
2240-/// reconstruct with the decoder's own inverse. Returns the non-zero count.
2241-#[allow(clippy::too_many_arguments)]
2242-fn code_block_8x8(
2243- pic: &mut Picture,
2244- e: &MbEnc<'_>,
2245- w: &EncEntropy,
2246- x: usize,
2247- y: usize,
2248- qp: i32,
2249- intra: bool,
2250- out: &mut [i32; 64],
2251-) -> u8 {
2252- let stride = pic.y.stride;
2253- let origin = pic.y.at(x, y);
2254- let mut d = [0i32; 64];
2255- for ry in 0..8 {
2256- for rx in 0..8 {
2257- d[ry * 8 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
2258- - i32::from(pic.y.data[origin + ry * stride + rx]);
2259- }
2260- }
2261- let rdoq = !intra && w.is_cabac();
2262- let fwd = forward_8x8(&d);
2263- let mut nz = if rdoq {
2264- quant_8x8_offset(&fwd, &e.ls8, qp, RDOQ8_DEAD_ZONE, out)
2265- } else {
2266- quant_8x8(&fwd, &e.ls8, qp, intra, out)
2267- };
2268- if nz == 0 {
2269- return 0;
2270- }
2271- if rdoq {
2272- nz = rdoq_8x8(e, w, &d, out, qp);
2273- if nz == 0 {
2274- return 0;
2275- }
2276- }
2277- let mut raster = [0i32; 64];
2278- unzigzag_8x8(out, &mut raster);
2279- dequant_8x8(&mut raster, &e.ls8, qp);
2280- let mut resid = [0i32; 64];
2281- inverse_transform_8x8(&raster, &mut resid);
2282- if !rdoq && !intra && !worth_coding(&d, &resid, out, zero_block_lambda(e, qp, e.transform_8x8))
2283- {
2284- *out = [0; 64];
2285- return 0;
2286- }
2287- add_residual_8x8(&mut pic.y.data, 8, stride, origin, &resid);
2288- nz
2289-}
2290-
2291-/// Code the luma of an Intra_8x8 macroblock, the 8x8 sibling of
2292-/// [`code_intra_4x4`]: neighbours are the decoder's filtered reference
2293-/// samples, and every 4x4 mode slot of a block carries its mode.
2294-#[allow(clippy::too_many_arguments)]
2295-fn code_intra_8x8(
2296- pic: &mut Picture,
2297- e: &MbEnc<'_>,
2298- w: &EncEntropy,
2299- mb_x: usize,
2300- mb_y: usize,
2301- qp: i32,
2302- nbr: &MbNeighbors,
2303- lv: &mut Levels,
2304-) -> ([u8; 4], [u8; 4]) {
2305- let w4 = pic.mb_w * 4;
2306- let mut modes = [2u8; 4];
2307- let mut pred_modes = [2u8; 4];
2308- lv.trans8 = true;
2309- for blk8 in 0..4 {
2310- let (bx, by) = (mb_x * 4 + (blk8 % 2) * 2, mb_y * 4 + (blk8 / 2) * 2);
2311- let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
2312- let predicted = predicted_mode8(pic, nbr, bx, by, blk8);
2313- pred_modes[blk8] = predicted;
2314- let n = filter_nbr8(&gather_nbr8(pic, nbr, blk8, x, y));
2315- let allowed = modes_allowed(n.have_top, n.have_left, n.have_tl);
2316- let mut p = [0u8; 64];
2317- {
2318- let (mode, coded, recon) =
2319- i8_mode_by_rd(pic, e, w, x, y, qp, &n, &allowed, predicted, &mut p);
2320- let stride = pic.y.stride;
2321- let origin = pic.y.at(x, y);
2322- for ry in 0..8 {
2323- let row = origin + ry * stride;
2324- pic.y.data[row..row + 8].copy_from_slice(&recon[ry * 8..ry * 8 + 8]);
2325- }
2326- lv.luma8[blk8] = coded.0;
2327- if coded.1 {
2328- lv.cbp_luma |= 1 << blk8;
2329- }
2330- modes[blk8] = mode;
2331- for dy in 0..2 {
2332- let base = (by + dy) * w4 + bx;
2333- pic.i4_modes[base..base + 2].fill(mode);
2334- }
2335- }
2336- }
2337- (modes, pred_modes)
2338-}
2339-
2340-/// The inter residual under the 8x8 transform, prediction already in the
2341-/// plane: the sibling of [`code_luma_4x4`].
2342-fn code_luma_8x8(
2343- pic: &mut Picture,
2344- e: &MbEnc<'_>,
2345- w: &EncEntropy,
2346- mb_x: usize,
2347- mb_y: usize,
2348- qp: i32,
2349- lv: &mut Levels,
2350-) {
2351- lv.trans8 = true;
2352- for blk8 in 0..4 {
2353- let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
2354- if code_block_8x8(pic, e, w, x, y, qp, false, &mut lv.luma8[blk8]) > 0 {
2355- lv.cbp_luma |= 1 << blk8;
2356- }
2357- }
2358-}
2359-
2360-/// Squared error of coding `levels` as an 8x8 block, in its pixels.
2361-fn block_ssd_8x8(e: &MbEnc<'_>, source: &[i32; 64], levels: &[i32; 64], qp: i32) -> i64 {
2362- let mut raster = [0i32; 64];
2363- unzigzag_8x8(levels, &mut raster);
2364- dequant_8x8(&mut raster, &e.ls8, qp);
2365- let mut resid = [0i32; 64];
2366- inverse_transform_8x8(&raster, &mut resid);
2367- let mut ssd = 0i64;
2368- for k in 0..64 {
2369- let d = i64::from(source[k]) - i64::from(resid[k]);
2370- ssd += d * d;
2371- }
2372- ssd
2373-}
2374-
2375-/// [`rdoq_4x4`] for the 8x8 transform: the same walk down the scan against the
2376-/// CABAC coder's own price, with the 8x8 block's own contexts.
2377-fn rdoq_8x8(
2378- e: &MbEnc<'_>,
2379- w: &EncEntropy,
2380- source: &[i32; 64],
2381- levels: &mut [i32; 64],
2382- qp: i32,
2383-) -> u8 {
2384- let Some(bits) = w.residual_block_8x8_cost(levels) else {
2385- return levels.iter().filter(|&&l| l != 0).count() as u8;
2386- };
2387- let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
2388- let mut cost = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
2389- for pos in (0..64).rev() {
2390- let level = levels[pos];
2391- if level == 0 {
2392- continue;
2393- }
2394- let mag = level.abs();
2395- if mag > RDOQ_MAX_LEVEL {
2396- continue;
2397- }
2398- let mut tried = mag;
2399- for candidate in [mag - 1, 0] {
2400- if candidate == tried {
2401- continue;
2402- }
2403- tried = candidate;
2404- let keep = levels[pos];
2405- levels[pos] = candidate * level.signum();
2406- let bits = w
2407- .residual_block_8x8_cost(levels)
2408- .expect("CAVLC returned early");
2409- let trial = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
2410- if trial < cost {
2411- cost = trial;
2412- } else {
2413- levels[pos] = keep;
2414- break;
2415- }
2416- }
2417- }
2418- // The whole block against nothing, on the same exact price.
2419- let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
2420- if ssd_zero as f64 <= cost {
2421- *levels = [0; 64];
2422- return 0;
crates/ec-h264/src/enc/mb/inter.rsadded+346 -0
@@ -0,0 +1,346 @@
1+#![allow(clippy::needless_range_loop)]
2+
3+
4+use crate::decoder::{
5+ MbNeighbors, };
6+use crate::dpb::{BLK_SKIP, Picture};
7+use crate::entropy::{
8+ FLAG_DECODED, FLAG_INTER, FLAG_SKIP, };
9+use crate::inter::{Put, RefPlane, mc_chroma, mc_luma};
10+use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_mvd};
11+
12+
13+use crate::enc::{
14+ entropy::{EncEntropy},
15+ lambda_ssd,
16+};
17+use super::*;
18+
19+#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly
20+pub(super) fn inter_mb_bits(
21+ pic: &Picture,
22+ e: &MbEnc<'_>,
23+ w: &EncEntropy,
24+ mb_addr: usize,
25+ nbr: &MbNeighbors,
26+ shape: PShape,
27+ mvd: &[[i16; 2]; 4],
28+ inc: &[[usize; 2]; 4],
29+ lv: &Levels,
30+) -> i64 {
31+ entropy_bits(w, |cw| {
32+ cw.begin_mb(&e.mb_ctx);
33+ cw.coded_mb(true, e.skip_inc);
34+ cw.set_intra(false);
35+ cw.mb_type(true, shape.mb_type());
36+ if shape == PShape::Quad {
37+ for _ in 0..4 {
38+ cw.sub_mb_type_p(0); // P_L0_8x8
39+ }
40+ }
41+ for part in 0..shape.parts() {
42+ for comp in 0..2 {
43+ cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp]));
44+ }
45+ }
46+ cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false);
47+ if lv.cbp_luma != 0 && e.transform_8x8 {
48+ cw.transform_size_8x8_flag(lv.trans8);
49+ }
50+ if lv.cbp_luma != 0 || lv.cbp_chroma != 0 {
51+ cw.mb_qp_delta(e.target_qp - e.qp);
52+ let mb_x = mb_addr % pic.mb_w;
53+ let mb_y = mb_addr / pic.mb_w;
54+ write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, false);
55+ write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv);
56+ }
57+ })
58+}
59+
60+/// Motion-compensate one partition into the picture planes.
61+pub(super) fn compensate_part(
62+ pic: &mut Picture,
63+ reference: &Picture,
64+ mb_x: usize,
65+ mb_y: usize,
66+ (bx, by): (usize, usize),
67+ (w, h): (usize, usize),
68+ mv: [i16; 2],
69+) {
70+ let (x0, y0) = ((mb_x * 16 + bx * 4) as i32, (mb_y * 16 + by * 4) as i32);
71+ let plane = RefPlane {
72+ data: &reference.y.data,
73+ stride: reference.y.stride,
74+ origin: reference.y.origin,
75+ width: reference.y.width,
76+ height: reference.y.height,
77+ pad: reference.y.pad,
78+ };
79+ let stride = pic.y.stride;
80+ let origin = pic.y.at(mb_x * 16 + bx * 4, mb_y * 16 + by * 4);
81+ mc_luma(
82+ &plane,
83+ x0,
84+ y0,
85+ mv,
86+ w,
87+ h,
88+ stride,
89+ &mut pic.y.data[origin..],
90+ Put::Set,
91+ );
92+ for comp in 0..2 {
93+ let src = if comp == 0 {
94+ &reference.cb
95+ } else {
96+ &reference.cr
97+ };
98+ let plane = RefPlane {
99+ data: &src.data,
100+ stride: src.stride,
101+ origin: src.origin,
102+ width: src.width,
103+ height: src.height,
104+ pad: src.pad,
105+ };
106+ let dst = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
107+ let stride = dst.stride;
108+ let origin = dst.at(mb_x * 8 + bx * 2, mb_y * 8 + by * 2);
109+ mc_chroma(
110+ &plane,
111+ x0 / 2,
112+ y0 / 2,
113+ mv,
114+ w / 2,
115+ h / 2,
116+ stride,
117+ &mut dst.data[origin..],
118+ Put::Set,
119+ );
120+ }
121+}
122+
123+/// Code a P macroblock: skip, one 16x16 partition, two halves or four
124+/// quarters.
125+pub(super) fn encode_inter_mb(
126+ pic: &mut Picture,
127+ e: &mut MbEnc<'_>,
128+ w: &mut EncEntropy,
129+ mb_addr: usize,
130+ nbr: MbNeighbors,
131+ choice: InterChoice,
132+) {
133+ let mb_x = mb_addr % pic.mb_w;
134+ let mb_y = mb_addr / pic.mb_w;
135+ let reference = e.reference.expect("a P macroblock has a reference");
136+ let ref_id = reference.id;
137+ let qp = e.target_qp;
138+ let shape = if choice.prefer_skip {
139+ PShape::Whole
140+ } else {
141+ choice.shape
142+ };
143+
144+ // Motion vectors, their predictors and the reconstruction, partition by
145+ // partition and in coding order: a partition's predictor reads the motion
146+ // of the partitions before it (8.4.1.3), so the order is not free.
147+ let mut ctx = MvCtx {
148+ mb_x,
149+ mb_y,
150+ slice_id: e.slice_id,
151+ written: 0,
152+ pos: Default::default(),
153+ };
154+ let (part_w, part_h) = shape.part_blocks();
155+ let mut mvd = [[0i16; 2]; 4];
156+ let mut inc = [[0usize; 2]; 4];
157+ for part in 0..shape.parts() {
158+ let ((bx, by), (pw, ph)) = shape.geometry(part);
159+ let mv = if choice.prefer_skip {
160+ choice.skip_mv
161+ } else {
162+ choice.mv[part]
163+ };
164+ let n = ctx.neighbours(pic, bx, by, part_w, 0);
165+ let mvp = predict_mv(&n, 0, part_w, part_h, part);
166+ // ctxIdxInc from the neighbouring partitions' absolute mvd
167+ // (9.3.3.1.1.7), read before this partition writes its own.
168+ let (gx, gy) = ((mb_x * 4 + bx) as i32, (mb_y * 4 + by) as i32);
169+ for comp in 0..2 {
170+ let sum = neighbour_mvd(pic, &ctx, gx - 1, gy, 0)[comp]
171+ + neighbour_mvd(pic, &ctx, gx, gy - 1, 0)[comp];
172+ inc[part][comp] = if sum > 32 {
173+ 2
174+ } else if sum > 2 {
175+ 1
176+ } else {
177+ 0
178+ };
179+ }
180+ mvd[part] = [mv[0] - mvp[0], mv[1] - mvp[1]];
181+ compensate_part(pic, reference, mb_x, mb_y, (bx, by), (pw, ph), mv);
182+ for py in by..by + ph / 4 {
183+ for px in bx..bx + pw / 4 {
184+ write_block(
185+ pic,
186+ &mut ctx,
187+ px,
188+ py,
189+ [mv, [0, 0]],
190+ [0, -1],
191+ [ref_id, -1],
192+ 0,
193+ );
194+ write_mvd(pic, mb_x, mb_y, px, py, 0, mvd[part]);
195+ }
196+ }
197+ }
198+
199+ // Skipping is only *available* on the P_Skip vector of a whole macroblock,
200+ // and only worth taking when the residual it drops is worth less than the
201+ // bits it saves: on static content a macroblock whose residual is pure
202+ // quantisation churn costs bits every picture and improves nothing.
203+ let may_skip = choice.prefer_skip;
204+ let (lv, skip) = if choice.force_skip {
205+ (Levels::default(), true)
206+ } else {
207+ let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y));
208+ let mut chroma_lv = Levels::default();
209+ code_chroma(pic, e, w, mb_x, mb_y, qp, false, &mut chroma_lv);
210+ let mut lv = chroma_lv.clone();
211+ let tx_mode = if e.preset == Preset::Fast {
212+ e.fast.inter_tx
213+ } else {
214+ 0
215+ };
216+ if e.transform_8x8 && tx_mode == 1 {
217+ code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv);
218+ } else if e.transform_8x8 && tx_mode != 2 {
219+ // Both transform sizes on the same prediction; the cheaper
220+ // rate-distortion cost is coded.
221+ let mut pred = [0u8; 256];
222+ save_luma(pic, mb_x, mb_y, &mut pred);
223+ let mut lv4 = chroma_lv.clone();
224+ code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv4);
225+ // At Fast the 8x8 trial is only worth its time when the 4x4 coding
226+ // left a few levels in a smooth residual: an empty one cannot be
227+ // beaten and a dense one rarely is.
228+ let nz4: u32 = lv4.luma_nz.iter().map(|&n| u32::from(n)).sum();
229+ if tx_mode == 3 && (lv4.cbp_luma == 0 || nz4 > e.fast.tx8_nz_limit) {
230+ lv = lv4;
231+ } else {
232+ let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4);
233+ let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 as f64;
234+ let mut recon4 = [0u8; 256];
235+ save_luma(pic, mb_x, mb_y, &mut recon4);
236+ restore_luma(pic, mb_x, mb_y, &pred);
237+ let mut lv8 = chroma_lv;
238+ code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv8);
239+ let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8);
240+ let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64;
241+ if cost8 < cost4 {
242+ lv = lv8;
243+ } else {
244+ lv = lv4;
245+ restore_luma(pic, mb_x, mb_y, &recon4);
246+ }
247+ }
248+ } else {
249+ code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv);
250+ }
251+ let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0;
252+ let skip = match ssd_skip {
253+ None => false,
254+ Some(_) if empty => true,
255+ Some(ssd_skip) => {
256+ let coded = if e.transform_8x8 {
257+ let bits = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv);
258+ ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64
259+ } else {
260+ ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64
261+ };
262+ if ssd_skip as f64 <= coded {
263+ // Put the prediction back: the residual has been added to it.
264+ compensate_part(pic, reference, mb_x, mb_y, (0, 0), (16, 16), choice.skip_mv);
265+ true
266+ } else {
267+ false
268+ }
269+ }
270+ };
271+ (lv, skip)
272+ };
273+
274+ let w4 = pic.mb_w * 4;
275+ if skip {
276+ for py in 0..4 {
277+ for px in 0..4 {
278+ let idx = (mb_y * 4 + py) * w4 + mb_x * 4 + px;
279+ pic.blk[idx] = BLK_SKIP;
280+ pic.mvd_abs[idx] = [0; 4];
281+ }
282+ }
283+ for dy in 0..4 {
284+ let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
285+ pic.nz_y[base..base + 4].fill(0);
286+ pic.i4_modes[base..base + 4].fill(2);
287+ }
288+ for comp in 0..2 {
289+ for dy in 0..2 {
290+ let base = (mb_y * 2 + dy) * pic.mb_w * 2 + mb_x * 2;
291+ pic.nz_c[comp][base..base + 2].fill(0);
292+ }
293+ }
294+ pic.mb_qp[mb_addr] = e.qp as i8;
295+ pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_INTER | FLAG_SKIP;
296+ pic.mb_cbp[mb_addr] = 0;
297+ pic.mb_dc_cbf[mb_addr] = 0;
298+ pic.mb_slice[mb_addr] = e.slice_id;
299+ pic.decoded_mbs += 1;
300+ e.qp_delta_inc = 0;
301+ w.skipped_mb(e.skip_inc);
302+ return;
303+ }
304+ for dy in 0..4 {
305+ let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
306+ pic.i4_modes[base..base + 4].fill(2);
307+ }
308+
309+ // ---- syntax ----
310+ w.begin_mb(&e.mb_ctx);
311+ w.coded_mb(true, e.skip_inc);
312+ w.set_intra(false);
313+ w.mb_type(true, shape.mb_type());
314+ if shape == PShape::Quad {
315+ for _ in 0..4 {
316+ w.sub_mb_type_p(0); // P_L0_8x8
317+ }
318+ }
319+ // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded.
320+ for part in 0..shape.parts() {
321+ for comp in 0..2 {
322+ w.mvd(comp, inc[part][comp], i32::from(mvd[part][comp]));
323+ }
324+ }
325+ w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false);
326+ // Every shape this encoder emits is 8x8-aligned, so the decoder reads the
327+ // flag whenever luma is coded.
328+ if lv.cbp_luma != 0 && e.transform_8x8 {
329+ w.transform_size_8x8_flag(lv.trans8);
330+ }
331+ finish_mb(
332+ pic,
333+ e,
334+ w,
335+ mb_addr,
336+ &nbr,
337+ &lv,
338+ MbRecord {
339+ intra: false,
340+ is_i16: false,
341+ chroma_mode: 0,
342+ qp,
343+ },
344+ );
345+}
346+
crates/ec-h264/src/enc/mb/intra.rsadded+800 -0
@@ -0,0 +1,800 @@
1+#![allow(clippy::needless_range_loop)]
2+
3+use ec_h264_syntax::SliceType;
4+
5+use crate::decoder::{
6+ MbNeighbors, gather_nbr4, gather_nbr8, };
7+use crate::dpb::{Picture};
8+use crate::entropy::{
9+ BlockCat, };
10+use crate::mv::{write_intra_mb};
11+use crate::pred::{
12+ PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16,
13+ pred_chroma_8x8,
14+};
15+use crate::tables::{BLK4_POS};
16+use crate::transform::{
17+ dequant_4x4, dequant_8x8,
18+ inverse_transform_4x4, inverse_transform_8x8, unzigzag, unzigzag_8x8,
19+ };
20+
21+use crate::enc::quant::{
22+ forward_4x4, forward_8x8, quant_4x4,
23+ quant_8x8, quant_8x8_offset, };
24+
25+use crate::enc::{
26+ entropy::{EncEntropy},
27+ lambda_ssd,
28+};
29+use super::*;
30+
31+/// The Intra_16x16 mode this macroblock would use. Intra_16x16 against
32+/// Intra_4x4 is decided later, on real rate and real distortion (see
33+/// [`encode_intra_mb`]).
34+pub(super) struct IntraCost {
35+ pub(super) i16_mode: u8,
36+ /// SATD of the Intra_16x16 mode above: the cheap intra estimate that
37+ /// `Preset::Fast` gates the full intra branch on.
38+ pub(super) satd: i32,
39+ /// True when Intra_4x4 may be used at all for this picture and preset.
40+ pub(super) allow_i4: bool,
41+}
42+
43+/// Best Intra_16x16 mode by SATD, leaving nothing behind in the plane that a
44+/// later branch does not overwrite.
45+pub(super) fn intra_pre_cost(
46+ pic: &mut Picture,
47+ e: &MbEnc<'_>,
48+ nbr: &MbNeighbors,
49+ mb_x: usize,
50+ mb_y: usize,
51+ modes: &[u8],
52+) -> IntraCost {
53+ let (sx, sy) = (mb_x * 16, mb_y * 16);
54+ let stride = pic.y.stride;
55+ let origin = pic.y.at(sx, sy);
56+ let mut best = (i32::MAX, 2u8);
57+ for &mode in modes {
58+ let ok = match mode {
59+ 0 => nbr.b,
60+ 1 => nbr.a,
61+ 3 => nbr.a && nbr.b && nbr.d,
62+ _ => true,
63+ };
64+ if !ok {
65+ continue;
66+ }
67+ let mut win = PlaneWindow {
68+ data: &mut pic.y.data,
69+ stride,
70+ origin,
71+ };
72+ pred_16x16(mode, 8, &mut win, nbr.b, nbr.a);
73+ let cost = satd16(&e.src.y, e.src.stride, sx, sy, &pic.y.data, stride, origin);
74+ if cost < best.0 {
75+ best = (cost, mode);
76+ }
77+ }
78+ IntraCost {
79+ i16_mode: best.1,
80+ satd: best.0,
81+ // Intra_4x4 is tried in P pictures too, at every preset. Re-measured
82+ // once the intra-versus-inter decision became a real one (BD-PSNR
83+ // against x264, GOP 10, QP 22/26/30/34): restricting it to I pictures
84+ // reads -1.613 dB on the film clip and -0.508 on the screen capture,
85+ // where allowing it everywhere reads -0.728 and -0.500. It stays on
86+ // everywhere. Under the old prediction-domain decision the screen
87+ // capture preferred the restriction by a third of a dB; coding both
88+ // branches for real removed that disagreement.
89+ allow_i4: true,
90+ }
91+}
92+
93+/// Code the luma of an Intra_4x4 macroblock: per block, choose the prediction
94+/// mode against the *reconstructed* neighbours and reconstruct it immediately,
95+/// because the next block predicts from it. Returns the chosen modes and the
96+/// modes they were predicted to be.
97+/// How many SATD survivors the Intra_4x4 mode decision re-costs with real
98+/// quantisation before choosing.
99+pub(super) const I4_RD_CANDIDATES: usize = 3;
100+
101+pub(super) fn code_intra_4x4(
102+ pic: &mut Picture,
103+ e: &MbEnc<'_>,
104+ mb_x: usize,
105+ mb_y: usize,
106+ qp: i32,
107+ nbr: &MbNeighbors,
108+ lv: &mut Levels,
109+) -> ([u8; 16], [u8; 16]) {
110+ let w4 = pic.mb_w * 4;
111+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
112+ let mut modes = [2u8; 16];
113+ let mut pred_modes = [2u8; 16];
114+ for blk in 0..16 {
115+ let (dx, dy) = BLK4_POS[blk];
116+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
117+ let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
118+ let left_avail = if dx == 0 { nbr.a } else { true };
119+ let top_avail = if dy == 0 { nbr.b } else { true };
120+ let predicted = if left_avail && top_avail {
121+ pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx])
122+ } else {
123+ 2
124+ };
125+ pred_modes[blk] = predicted;
126+ let n = gather_nbr4(pic, nbr, blk, x, y);
127+ let have_tl = match (dx, dy) {
128+ (0, 0) => nbr.d,
129+ (0, _) => nbr.a,
130+ (_, 0) => nbr.b,
131+ _ => true,
132+ };
133+ let allowed = modes_allowed(n.have_top, n.have_left, have_tl);
134+ let mut best = (i32::MAX, predicted.min(2));
135+ let mut p = [0u8; 16];
136+ let mut ranked = [(i32::MAX, 2u8); 9];
137+ for mode in 0..9u8 {
138+ if !allowed[mode as usize] {
139+ continue;
140+ }
141+ pred_4x4(mode, 8, &n, &mut p);
142+ let bits = if mode == predicted { 1 } else { 4 };
143+ let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + motion_rate(e, f64::from(bits));
144+ ranked[mode as usize] = (c, mode);
145+ if c < best.0 {
146+ best = (c, mode);
147+ }
148+ }
149+ let mut mode = best.1;
150+ // SATD ranks the modes; the survivors are re-costed with the
151+ // quantisation actually in force, because a mode that predicts a
152+ // little worse can quantise to far fewer levels. Measured against
153+ // x264 with `bd_psnr_vs_x264` on a 3840x1608 film clip and a 2560x1440
154+ // screen capture: +0.129 and +0.088 dB all-intra, +0.062 and +0.043 dB
155+ // at GOP 10, for 3-4% encode time. Three survivors is where it
156+ // saturates -- all nine landed within 0.002 dB of three, for 7% more
157+ // encode time.
158+ {
159+ ranked.sort_unstable();
160+ let keep = I4_RD_CANDIDATES;
161+ // The same over-count [`ZERO_BLOCK_LAMBDA`] corrects for: with the
162+ // full rate term this search loses 0.065 dB instead of gaining,
163+ // and it loses more the more candidates it sees.
164+ let lambda = ZERO_BLOCK_LAMBDA
165+ * if e.transform_8x8 {
166+ e.lambda
167+ } else {
168+ lambda_ssd(qp)
169+ };
170+ let mut best_rd = f64::MAX;
171+ for &(c, cand) in ranked.iter().take(keep) {
172+ if c == i32::MAX {
173+ break;
174+ }
175+ pred_4x4(cand, 8, &n, &mut p);
176+ let mut d = [0i32; 16];
177+ for ry in 0..4 {
178+ for rx in 0..4 {
179+ d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
180+ - i32::from(p[ry * 4 + rx]);
181+ }
182+ }
183+ let src = d;
184+ forward_4x4(&mut d);
185+ let mut levels = [0i32; 16];
186+ let nz = quant_4x4(&d, qp, true, false, &mut levels);
187+ let mut resid = [0i32; 16];
188+ if nz > 0 {
189+ let mut raster = [0i32; 16];
190+ unzigzag(&levels, &mut raster);
191+ dequant_4x4(&mut raster, &e.ls, qp, false);
192+ inverse_transform_4x4(&raster, &mut resid);
193+ }
194+ let mut ssd = 0i64;
195+ for i in 0..16 {
196+ let err = i64::from(src[i] - resid[i]);
197+ ssd += err * err;
198+ }
199+ let mode_bits = if cand == predicted { 1 } else { 4 };
200+ let bits = block_bits(&levels) + mode_bits;
201+ let cost = ssd as f64 + lambda * bits as f64;
202+ if cost < best_rd {
203+ best_rd = cost;
204+ mode = cand;
205+ }
206+ }
207+ }
208+ modes[blk] = mode;
209+ pic.i4_modes[by * w4 + bx] = mode;
210+ // Prediction into the plane, then residual and reconstruction.
211+ pred_4x4(mode, 8, &n, &mut p);
212+ let stride = pic.y.stride;
213+ let origin = pic.y.at(x, y);
214+ for ry in 0..4 {
215+ let row = origin + ry * stride;
216+ pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
217+ }
218+ let mut d = [0i32; 16];
219+ for ry in 0..4 {
220+ for rx in 0..4 {
221+ d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
222+ - i32::from(p[ry * 4 + rx]);
223+ }
224+ }
225+ forward_4x4(&mut d);
226+ let nz = quant_4x4(&d, qp, true, false, &mut lv.luma[blk]);
227+ lv.luma_nz[blk] = nz;
228+ if nz > 0 {
229+ lv.cbp_luma |= 1 << (blk >> 2);
230+ let mut raster = [0i32; 16];
231+ unzigzag(&lv.luma[blk], &mut raster);
232+ dequant_4x4(&mut raster, &e.ls, qp, false);
233+ let mut resid = [0i32; 16];
234+ inverse_transform_4x4(&raster, &mut resid);
235+ add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
236+ }
237+ }
238+ (modes, pred_modes)
239+}
240+
241+/// Predicted Intra_8x8 mode of `blk8` (8.3.2.1): the decoder's rule, read
242+/// from the 4x4 slots every size writes its mode into.
243+pub(super) fn predicted_mode8(pic: &Picture, nbr: &MbNeighbors, bx: usize, by: usize, blk8: usize) -> u8 {
244+ let w4 = pic.mb_w * 4;
245+ let left_avail = if blk8.is_multiple_of(2) { nbr.a } else { true };
246+ let top_avail = if blk8 < 2 { nbr.b } else { true };
247+ if left_avail && top_avail {
248+ pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx])
249+ } else {
250+ 2
251+ }
252+}
253+
254+/// Residual of one 8x8 luma block against the prediction already in the
255+/// plane: forward transform, quantise, and — when anything survives —
256+/// reconstruct with the decoder's own inverse. Returns the non-zero count.
257+#[allow(clippy::too_many_arguments)]
258+pub(super) fn code_block_8x8(
259+ pic: &mut Picture,
260+ e: &MbEnc<'_>,
261+ w: &EncEntropy,
262+ x: usize,
263+ y: usize,
264+ qp: i32,
265+ intra: bool,
266+ out: &mut [i32; 64],
267+) -> u8 {
268+ let stride = pic.y.stride;
269+ let origin = pic.y.at(x, y);
270+ let mut d = [0i32; 64];
271+ for ry in 0..8 {
272+ for rx in 0..8 {
273+ d[ry * 8 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
274+ - i32::from(pic.y.data[origin + ry * stride + rx]);
275+ }
276+ }
277+ let rdoq = !intra && w.is_cabac();
278+ let fwd = forward_8x8(&d);
279+ let mut nz = if rdoq {
280+ quant_8x8_offset(&fwd, &e.ls8, qp, RDOQ8_DEAD_ZONE, out)
281+ } else {
282+ quant_8x8(&fwd, &e.ls8, qp, intra, out)
283+ };
284+ if nz == 0 {
285+ return 0;
286+ }
287+ if rdoq {
288+ nz = rdoq_8x8(e, w, &d, out, qp);
289+ if nz == 0 {
290+ return 0;
291+ }
292+ }
293+ let mut raster = [0i32; 64];
294+ unzigzag_8x8(out, &mut raster);
295+ dequant_8x8(&mut raster, &e.ls8, qp);
296+ let mut resid = [0i32; 64];
297+ inverse_transform_8x8(&raster, &mut resid);
298+ if !rdoq && !intra && !worth_coding(&d, &resid, out, zero_block_lambda(e, qp, e.transform_8x8))
299+ {
300+ *out = [0; 64];
301+ return 0;
302+ }
303+ add_residual_8x8(&mut pic.y.data, 8, stride, origin, &resid);
304+ nz
305+}
306+
307+/// Code the luma of an Intra_8x8 macroblock, the 8x8 sibling of
308+/// [`code_intra_4x4`]: neighbours are the decoder's filtered reference
309+/// samples, and every 4x4 mode slot of a block carries its mode.
310+#[allow(clippy::too_many_arguments)]
311+pub(super) fn code_intra_8x8(
312+ pic: &mut Picture,
313+ e: &MbEnc<'_>,
314+ w: &EncEntropy,
315+ mb_x: usize,
316+ mb_y: usize,
317+ qp: i32,
318+ nbr: &MbNeighbors,
319+ lv: &mut Levels,
320+) -> ([u8; 4], [u8; 4]) {
321+ let w4 = pic.mb_w * 4;
322+ let mut modes = [2u8; 4];
323+ let mut pred_modes = [2u8; 4];
324+ lv.trans8 = true;
325+ for blk8 in 0..4 {
326+ let (bx, by) = (mb_x * 4 + (blk8 % 2) * 2, mb_y * 4 + (blk8 / 2) * 2);
327+ let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
328+ let predicted = predicted_mode8(pic, nbr, bx, by, blk8);
329+ pred_modes[blk8] = predicted;
330+ let n = filter_nbr8(&gather_nbr8(pic, nbr, blk8, x, y));
331+ let allowed = modes_allowed(n.have_top, n.have_left, n.have_tl);
332+ let mut p = [0u8; 64];
333+ {
334+ let (mode, coded, recon) =
335+ i8_mode_by_rd(pic, e, w, x, y, qp, &n, &allowed, predicted, &mut p);
336+ let stride = pic.y.stride;
337+ let origin = pic.y.at(x, y);
338+ for ry in 0..8 {
339+ let row = origin + ry * stride;
340+ pic.y.data[row..row + 8].copy_from_slice(&recon[ry * 8..ry * 8 + 8]);
341+ }
342+ lv.luma8[blk8] = coded.0;
343+ if coded.1 {
344+ lv.cbp_luma |= 1 << blk8;
345+ }
346+ modes[blk8] = mode;
347+ for dy in 0..2 {
348+ let base = (by + dy) * w4 + bx;
349+ pic.i4_modes[base..base + 2].fill(mode);
350+ }
351+ }
352+ }
353+ (modes, pred_modes)
354+}
355+
356+#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly
357+pub(super) fn intra_mb_bits(
358+ pic: &Picture,
359+ e: &MbEnc<'_>,
360+ w: &EncEntropy,
361+ mb_addr: usize,
362+ nbr: &MbNeighbors,
363+ lv: &Levels,
364+ i4: Option<(&[u8], &[u8])>,
365+ i16_mode: u8,
366+ chroma_mode: u8,
367+) -> i64 {
368+ let use_i4 = i4.is_some();
369+ let p_slice = e.slice_type == SliceType::P;
370+ let offset = if p_slice { 5 } else { 0 };
371+ let intra_type = if use_i4 {
372+ 0
373+ } else {
374+ 1 + u32::from(i16_mode)
375+ + 4 * u32::from(lv.cbp_chroma)
376+ + if lv.cbp_luma != 0 { 12 } else { 0 }
377+ };
378+ entropy_bits(w, |cw| {
379+ cw.begin_mb(&e.mb_ctx);
380+ cw.coded_mb(p_slice, e.skip_inc);
381+ cw.set_intra(true);
382+ cw.mb_type(p_slice, intra_type + offset);
383+ if let Some((modes, pred)) = i4 {
384+ if e.transform_8x8 {
385+ cw.transform_size_8x8_flag(lv.trans8);
386+ }
387+ for blk in 0..modes.len() {
388+ let rem = if modes[blk] == pred[blk] {
389+ None
390+ } else if modes[blk] > pred[blk] {
391+ Some(modes[blk] - 1)
392+ } else {
393+ Some(modes[blk])
394+ };
395+ cw.intra4x4_pred_mode(rem);
396+ }
397+ }
398+ cw.intra_chroma_pred_mode(chroma_mode);
399+ if use_i4 {
400+ cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true);
401+ }
402+ let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || !use_i4;
403+ if coded {
404+ cw.mb_qp_delta(e.target_qp - e.qp);
405+ }
406+ let mb_x = mb_addr % pic.mb_w;
407+ let mb_y = mb_addr / pic.mb_w;
408+ write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, !use_i4);
409+ write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv);
410+ })
411+}
412+
413+/// Code an intra macroblock, choosing Intra_16x16 against Intra_4x4 on real
414+/// rate and real distortion.
415+///
416+/// A SATD estimate of the 4x4 form has to predict from the source samples
417+/// inside the macroblock — the reconstruction it would predict from does not
418+/// exist until the mode is chosen — and on flat or text-heavy pictures that
419+/// estimate misjudges which form wins. Coding both and measuring is worth
420+/// more than it costs: it is 1.1 dB on screen capture at matched bitrate.
421+pub(super) fn encode_intra_mb(
422+ pic: &mut Picture,
423+ e: &mut MbEnc<'_>,
424+ w: &mut EncEntropy,
425+ mb_addr: usize,
426+ nbr: MbNeighbors,
427+ cost: IntraCost,
428+) {
429+ let mb_x = mb_addr % pic.mb_w;
430+ let mb_y = mb_addr / pic.mb_w;
431+ let w4 = pic.mb_w * 4;
432+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
433+ let qp = e.target_qp;
434+ write_intra_mb(pic, mb_x, mb_y);
435+ let mut lv: Levels;
436+ let mut modes = [2u8; 16];
437+ let mut pred_modes = [2u8; 16];
438+ let mut modes8 = [2u8; 4];
439+ let mut pred_modes8 = [2u8; 4];
440+ let mut use_i4 = false;
441+ let mut chroma_lv = Levels::default();
442+ let chroma_mode = choose_chroma_mode_rd(pic, e, w, &nbr, mb_x, mb_y, qp, &mut chroma_lv);
443+ let mut use_i8 = false;
444+
445+ if cost.allow_i4 {
446+ let mut lv4 = chroma_lv.clone();
447+ let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4);
448+ let cost4 = if e.transform_8x8 {
449+ let bits = intra_mb_bits(
450+ pic,
451+ e,
452+ w,
453+ mb_addr,
454+ &nbr,
455+ &lv4,
456+ Some((&m4, &p4)),
457+ cost.i16_mode,
458+ chroma_mode,
459+ );
460+ ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64
461+ + e.lambda * bits as f64
462+ } else {
463+ ssd_luma(pic, e, mb_x, mb_y) as f64
464+ + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f64
465+ };
466+ let mut recon4 = [0u8; 256];
467+ save_luma(pic, mb_x, mb_y, &mut recon4);
468+ let mut modes4 = [2u8; 16];
469+ for blk in 0..16 {
470+ let (dx, dy) = BLK4_POS[blk];
471+ modes4[blk] = pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize];
472+ }
473+
474+ // Intra_8x8 on the same terms, when the PPS allows it.
475+ let mut lv8 = chroma_lv.clone();
476+ let mut recon8 = [0u8; 256];
477+ let skip8 = e.preset == Preset::Fast
478+ && (e.fast.skip_i8 || (e.fast.p_skip_i8 && e.slice_type == SliceType::P));
479+ let cost8 = if e.transform_8x8 && !skip8 {
480+ let (m8, p8) = code_intra_8x8(pic, e, w, mb_x, mb_y, qp, &nbr, &mut lv8);
481+ modes8 = m8;
482+ pred_modes8 = p8;
483+ save_luma(pic, mb_x, mb_y, &mut recon8);
484+ let bits = intra_mb_bits(
485+ pic,
486+ e,
487+ w,
488+ mb_addr,
489+ &nbr,
490+ &lv8,
491+ Some((&m8, &p8)),
492+ cost.i16_mode,
493+ chroma_mode,
494+ );
495+ ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, true, intra_bs) as f64
496+ + e.lambda * bits as f64
497+ } else {
498+ f64::INFINITY
499+ };
500+
501+ let mut lv16 = chroma_lv;
502+ code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16);
503+ let cost16 = if e.transform_8x8 {
504+ let bits = intra_mb_bits(
505+ pic,
506+ e,
507+ w,
508+ mb_addr,
509+ &nbr,
510+ &lv16,
511+ None,
512+ cost.i16_mode,
513+ chroma_mode,
514+ );
515+ ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64
516+ + e.lambda * bits as f64
517+ } else {
518+ ssd_luma(pic, e, mb_x, mb_y) as f64
519+ + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64
520+ };
521+
522+ if cost8 <= cost4 && cost8 <= cost16 {
523+ use_i4 = true;
524+ use_i8 = true;
525+ restore_luma(pic, mb_x, mb_y, &recon8);
526+ for blk8 in 0..4 {
527+ for dy in 0..2 {
528+ let base = (by0 + (blk8 / 2) * 2 + dy) * w4 + bx0 + (blk8 % 2) * 2;
529+ pic.i4_modes[base..base + 2].fill(modes8[blk8]);
530+ }
531+ }
532+ lv = lv8;
533+ } else if cost4 <= cost16 {
534+ use_i4 = true;
535+ restore_luma(pic, mb_x, mb_y, &recon4);
536+ for blk in 0..16 {
537+ let (dx, dy) = BLK4_POS[blk];
538+ pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize] = modes4[blk];
539+ }
540+ lv = lv4;
541+ modes = m4;
542+ pred_modes = p4;
543+ } else {
544+ lv = lv16;
545+ }
546+ } else {
547+ lv = chroma_lv;
548+ code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv);
549+ }
550+
551+ // ---- syntax ----
552+ w.begin_mb(&e.mb_ctx);
553+ w.coded_mb(e.slice_type == SliceType::P, e.skip_inc);
554+ w.set_intra(true);
555+ let intra_type = if use_i4 {
556+ 0
557+ } else {
558+ 1 + u32::from(cost.i16_mode)
559+ + 4 * u32::from(lv.cbp_chroma)
560+ + if lv.cbp_luma != 0 { 12 } else { 0 }
561+ };
562+ let p_slice = e.slice_type == SliceType::P;
563+ let offset = if p_slice { 5 } else { 0 };
564+ w.mb_type(p_slice, intra_type + offset);
565+ if use_i4 {
566+ if e.transform_8x8 {
567+ w.transform_size_8x8_flag(use_i8);
568+ }
569+ // prev_intra8x8_pred_mode_flag / rem_intra8x8_pred_mode share the 4x4
570+ // elements' binarisation and contexts (9.3.2.2, Table 9-34).
571+ let (modes, pred_modes): (&[u8], &[u8]) = if use_i8 {
572+ (&modes8, &pred_modes8)
573+ } else {
574+ (&modes, &pred_modes)
575+ };
576+ for blk in 0..modes.len() {
577+ let rem = if modes[blk] == pred_modes[blk] {
578+ None
579+ } else if modes[blk] > pred_modes[blk] {
580+ Some(modes[blk] - 1)
581+ } else {
582+ Some(modes[blk])
583+ };
584+ w.intra4x4_pred_mode(rem);
585+ }
586+ }
587+ w.intra_chroma_pred_mode(chroma_mode);
588+ if use_i4 {
589+ w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true);
590+ }
591+ finish_mb(
592+ pic,
593+ e,
594+ w,
595+ mb_addr,
596+ &nbr,
597+ &lv,
598+ MbRecord {
599+ intra: true,
600+ is_i16: !use_i4,
601+ chroma_mode,
602+ qp,
603+ },
604+ );
605+}
606+
607+/// Chroma prediction mode by rate-distortion: every available mode is coded
608+/// through the real chroma path and scored on reconstructed SSD plus the bits
609+/// its levels and its own name actually cost. The SATD-plus-mode-bits chooser
610+/// this replaced picked the mode before the quantiser had a say, which reads
611+/// as a chroma deficit at matched luma: measured with `bd_psnr_vs_x264`
612+/// against x264 `-preset medium`, BD-PSNR-YUV, GOP 10, 24 pictures:
613+///
614+/// | clip | SATD | RD |
615+/// |---|---|---|
616+/// | 3840x1608 film | -0.500 dB | -0.443 dB |
617+/// | 2560x1440 screen capture | -0.220 dB | -0.146 dB |
618+/// | 2560x1440 screen capture, second scene | -0.571 dB | -0.538 dB |
619+/// | 1080p phone clip | -1.122 dB | -1.084 dB |
620+/// | 720p web clip | -0.606 dB | -0.572 dB |
621+///
622+/// Luma is unmoved (film -0.065 -> -0.070 dB) and the encode time does not
623+/// change measurably: only intra macroblocks pay, and only four trials of the
624+/// chroma path each.
625+#[allow(clippy::too_many_arguments)]
626+pub(super) fn choose_chroma_mode_rd(
627+ pic: &mut Picture,
628+ e: &MbEnc<'_>,
629+ w: &EncEntropy,
630+ nbr: &MbNeighbors,
631+ mb_x: usize,
632+ mb_y: usize,
633+ qp: i32,
634+ out: &mut Levels,
635+) -> u8 {
636+ let qp_c = chroma_qp(qp, e.cqo);
637+ let lambda = lambda_ssd(qp_c);
638+ let mut best: Option<(f64, u8, Levels, [[u8; 64]; 2])> = None;
639+ for mode in [0u8, 1, 2, 3] {
640+ let ok = match mode {
641+ 1 => nbr.a,
642+ 2 => nbr.b,
643+ 3 => nbr.a && nbr.b && nbr.d,
644+ _ => true,
645+ };
646+ if !ok {
647+ continue;
648+ }
649+ for comp in 0..2 {
650+ let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
651+ let stride = plane.stride;
652+ let origin = plane.at(mb_x * 8, mb_y * 8);
653+ let mut win = PlaneWindow {
654+ data: &mut plane.data,
655+ stride,
656+ origin,
657+ };
658+ pred_chroma_8x8(mode, 8, &mut win, nbr.b, nbr.a);
659+ }
660+ let mut lv = Levels::default();
661+ code_chroma(pic, e, w, mb_x, mb_y, qp, true, &mut lv);
662+ let mut ssd = 0i64;
663+ let mut recon = [[0u8; 64]; 2];
664+ for comp in 0..2 {
665+ let (plane, src) = if comp == 0 {
666+ (&pic.cb, &e.src.u)
667+ } else {
668+ (&pic.cr, &e.src.v)
669+ };
670+ let origin = plane.at(mb_x * 8, mb_y * 8);
671+ for ry in 0..8 {
672+ for rx in 0..8 {
673+ let r = plane.data[origin + ry * plane.stride + rx];
674+ recon[comp][ry * 8 + rx] = r;
675+ let d = i64::from(src[(mb_y * 8 + ry) * e.src.c_stride + mb_x * 8 + rx])
676+ - i64::from(r);
677+ ssd += d * d;
678+ }
679+ }
680+ }
681+ let mut bits = match mode {
682+ 0 => 1.0,
683+ 3 => 5.0,
684+ _ => 3.0,
685+ };
686+ for comp in 0..2 {
687+ bits += match w.residual_block_cost(
688+ &lv.chroma_dc[comp],
689+ BlockCat::ChromaDc(comp as u8),
690+ Some(1),
691+ Some(1),
692+ ) {
693+ Some(b) => f64::from(b) / 256.0,
694+ None => block_bits(&lv.chroma_dc[comp]) as f64,
695+ };
696+ for blk in 0..4 {
697+ bits += match w.residual_block_cost(
698+ &lv.chroma[comp][blk],
699+ BlockCat::ChromaAc,
700+ Some(1),
701+ Some(1),
702+ ) {
703+ Some(b) => f64::from(b) / 256.0,
704+ None => block_bits(&lv.chroma[comp][blk]) as f64,
705+ };
706+ }
707+ }
708+ let cost = ssd as f64 + lambda * bits;
709+ if best.as_ref().is_none_or(|b| cost < b.0) {
710+ best = Some((cost, mode, lv, recon));
711+ }
712+ }
713+ let (_, mode, lv, recon) = best.expect("chroma DC prediction is always available");
714+ for comp in 0..2 {
715+ let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
716+ let stride = plane.stride;
717+ let origin = plane.at(mb_x * 8, mb_y * 8);
718+ for ry in 0..8 {
719+ for rx in 0..8 {
720+ plane.data[origin + ry * stride + rx] = recon[comp][ry * 8 + rx];
721+ }
722+ }
723+ }
724+ *out = lv;
725+ mode
726+}
727+
728+/// The mode decision of [`code_intra_8x8`]: for every allowed mode, predict,
729+/// code the 8x8 residual at the real QP and score `SSD + lambda * bits`, then
730+/// keep the cheapest. The SATD chooser this replaced scored the prediction
731+/// residual before the quantiser had a say, so it optimised a proxy.
732+///
733+/// Returns the winning mode, its coded levels with whether the block has any,
734+/// and the reconstructed 8x8 to write back. Measured on BD-PSNR against x264
735+/// with the 8x8 transform on, GOP 10, 24 consecutive pictures, luma / YUV:
736+/// • 3840x1608 film: +0.475 / -0.068 -> +0.512 / -0.035
737+/// • 1138x640 web: +0.040 / -0.031 -> +0.076 / +0.003
738+/// • 854x480 web: +0.070 / +0.047 -> +0.132 / +0.108
739+/// • 2560x1440 screen: -0.206 / -0.199 -> -0.215 / -0.207
740+/// Three clips of four gain; the screen capture loses 0.008 dB. Encode time
741+/// moves from 12 s to 13 s on the 854x480 clip.
742+#[allow(clippy::too_many_arguments)]
743+pub(super) fn i8_mode_by_rd(
744+ pic: &mut Picture,
745+ e: &MbEnc<'_>,
746+ w: &EncEntropy,
747+ x: usize,
748+ y: usize,
749+ qp: i32,
750+ n: &crate::pred::Nbr8,
751+ allowed: &[bool; 9],
752+ predicted: u8,
753+ p: &mut [u8; 64],
754+) -> (u8, ([i32; 64], bool), [u8; 64]) {
755+ let lambda = lambda_ssd(qp);
756+ let stride = pic.y.stride;
757+ let origin = pic.y.at(x, y);
758+ type Best = Option<(f64, u8, [i32; 64], bool, [u8; 64])>;
759+ let mut best: Best = None;
760+ for mode in 0..9u8 {
761+ if !allowed[mode as usize] {
762+ continue;
763+ }
764+ pred_8x8(mode, 8, n, p);
765+ for ry in 0..8 {
766+ let row = origin + ry * stride;
767+ pic.y.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]);
768+ }
769+ let mut levels = [0i32; 64];
770+ let nz = code_block_8x8(pic, e, w, x, y, qp, true, &mut levels);
771+ let mut ssd = 0i64;
772+ let mut recon = [0u8; 64];
773+ for ry in 0..8 {
774+ let row = origin + ry * stride;
775+ for rx in 0..8 {
776+ let r = pic.y.data[row + rx];
777+ recon[ry * 8 + rx] = r;
778+ let d = i64::from(e.src.y[(y + ry) * e.src.stride + x + rx]) - i64::from(r);
779+ ssd += d * d;
780+ }
781+ }
782+ let mut bits = if mode == predicted { 1.0 } else { 4.0 };
783+ if nz > 0 {
784+ // `Luma8x8` has no coded_block_flag of its own — the CBP carries it
785+ // — so it needs the 8x8 cost path, not the cbf-indexed one.
786+ bits += match w.residual_block_8x8_cost(&levels) {
787+ Some(b) => f64::from(b) / 256.0,
788+ None => block_bits(&levels) as f64,
789+ };
790+ }
791+ let cost = ssd as f64 + lambda * bits;
792+ if best.as_ref().is_none_or(|b| cost < b.0) {
793+ best = Some((cost, mode, levels, nz > 0, recon));
794+ }
795+ }
796+ let (_, mode, levels, coded, recon) =
797+ best.expect("Intra_8x8 always has at least the DC mode available");
798+ (mode, (levels, coded), recon)
799+}
800+
crates/ec-h264/src/enc/mb/me.rsadded+836 -0
@@ -0,0 +1,836 @@
1+#![allow(clippy::needless_range_loop)]
2+
3+use wide::{i16x16};
4+
5+use crate::dpb::{Picture};
6+use crate::inter::{Put, RefPlane, integer_origin, mc_chroma, mc_luma};
7+use crate::mv::{MvCtx, predict_mv};
8+
9+
10+use super::*;
11+
12+/// 4x4 Hadamard sum of absolute transformed differences between the source at
13+/// `(sx, sy)` and a 4x4 prediction.
14+// Tried (lane-h264perf r2): a transpose-based i32x4 vectorization of this
15+// butterfly, bit-identical, but cycles-flat-to-worse under perf stat
16+// (22.958B -> 23.042B cycles over 10 reps despite fewer instructions
17+// retired) -- reverted, dead end; see ledger.
18+pub(super) fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 {
19+ // Differences are at most 255 in magnitude and the 2-D Hadamard sums 16 of
20+ // them, so every intermediate fits an i16.
21+ let mut d = [[0i16; 4]; 4];
22+ for (y, row) in d.iter_mut().enumerate() {
23+ let s = &src[(sy + y) * sstride + sx..][..4];
24+ let p = &pred[y * pstride..][..4];
25+ for x in 0..4 {
26+ row[x] = i16::from(s[x]) - i16::from(p[x]);
27+ }
28+ }
29+ // Vertical butterflies, lane-wise over the four columns.
30+ let mut v = [[0i16; 4]; 4];
31+ for x in 0..4 {
32+ let (a, b, c, e) = (d[0][x], d[1][x], d[2][x], d[3][x]);
33+ let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e);
34+ v[0][x] = s0 + s1;
35+ v[1][x] = s0 - s1;
36+ v[2][x] = s2 + s3;
37+ v[3][x] = s2 - s3;
38+ }
39+ // Horizontal butterflies per row, then the absolute sum.
40+ let mut sum = 0i32;
41+ for row in &v {
42+ let (a, b, c, e) = (row[0], row[1], row[2], row[3]);
43+ let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e);
44+ sum += i32::from((s0 + s1).abs())
45+ + i32::from((s0 - s1).abs())
46+ + i32::from((s2 + s3).abs())
47+ + i32::from((s2 - s3).abs());
48+ }
49+ (sum + 2) >> 2
50+}
51+
52+/// SATD of a whole 16x16 luma macroblock against the prediction already in the
53+/// picture plane.
54+pub(super) fn satd16(
55+ src: &[u8],
56+ sstride: usize,
57+ sx: usize,
58+ sy: usize,
59+ plane: &[u8],
60+ pstride: usize,
61+ po: usize,
62+) -> i32 {
63+ satd_block(src, sstride, sx, sy, plane, pstride, po, 16, 16)
64+}
65+
66+/// The same over a `w` x `h` partition.
67+#[allow(clippy::too_many_arguments)]
68+pub(super) fn satd_block(
69+ src: &[u8],
70+ sstride: usize,
71+ sx: usize,
72+ sy: usize,
73+ plane: &[u8],
74+ pstride: usize,
75+ po: usize,
76+ w: usize,
77+ h: usize,
78+) -> i32 {
79+ let mut sum = 0;
80+ for by in 0..h / 4 {
81+ for bx in 0..w / 4 {
82+ sum += satd4(
83+ src,
84+ sstride,
85+ sx + bx * 4,
86+ sy + by * 4,
87+ &plane[po + by * 4 * pstride + bx * 4..],
88+ pstride,
89+ );
90+ }
91+ }
92+ sum
93+}
94+
95+/// Sum of absolute differences of a `w` x `h` block against a prediction with
96+/// its own pitch. This is the motion search's inner loop and nothing else in
97+/// the encoder is called as often, so a full-width row goes through one vector.
98+#[allow(clippy::too_many_arguments)]
99+pub(super) fn sad(
100+ src: &[u8],
101+ sstride: usize,
102+ sx: usize,
103+ sy: usize,
104+ pred: &[u8],
105+ pstride: usize,
106+ w: usize,
107+ h: usize,
108+) -> i32 {
109+ if w == 16 {
110+ let mut acc = i16x16::ZERO;
111+ for y in 0..h {
112+ let a = load16(src, (sy + y) * sstride + sx);
113+ let b = load16(pred, y * pstride);
114+ acc += (a - b).abs();
115+ }
116+ return acc.to_array().iter().map(|&v| i32::from(v)).sum();
117+ }
118+ let mut sum = 0;
119+ for y in 0..h {
120+ let s = &src[(sy + y) * sstride + sx..];
121+ let p = &pred[y * pstride..];
122+ for x in 0..w {
123+ sum += (i32::from(s[x]) - i32::from(p[x])).abs();
124+ }
125+ }
126+ sum
127+}
128+
129+/// Sum and maximum of the absolute differences between the 16x16 source block
130+/// at `(sx, sy)` and a 16-wide prediction.
131+pub(super) fn sad_max16(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8]) -> (i32, i32) {
132+ let mut acc = i16x16::ZERO;
133+ let mut mx = i16x16::ZERO;
134+ for y in 0..16 {
135+ let a = load16(src, (sy + y) * sstride + sx);
136+ let b = load16(pred, y * 16);
137+ let d = (a - b).abs();
138+ acc += d;
139+ mx = mx.max(d);
140+ }
141+ let sum = acc.to_array().iter().map(|&v| i32::from(v)).sum();
142+ let max = mx
143+ .to_array()
144+ .iter()
145+ .map(|&v| i32::from(v))
146+ .max()
147+ .unwrap_or(0);
148+ (sum, max)
149+}
150+
151+#[inline]
152+pub(super) fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 {
153+ (motion_lambda(e) * bits).round() as i32
154+}
155+
156+/// The multiplier `motion_rate` applies, for loops that price many vectors.
157+#[inline]
158+pub(super) fn motion_lambda(e: &MbEnc<'_>) -> f64 {
159+ if e.transform_8x8 {
160+ e.lambda.sqrt()
161+ } else {
162+ e.lambda
163+ }
164+}
165+
166+/// How much of a motion vector's signalling the search pays for. Half, which
167+/// is not the true rate: swept on consecutive pictures (BD-PSNR against x264,
168+/// GOP 10), 0.25/0.5/1.0/2.0 read -1.074/-1.043/-1.225/-1.618 on the film clip
169+/// and -0.676/-0.661/-0.795/-1.201 on the screen capture. Charging the whole
170+/// rate is worse than charging half on both contents, and the curve is flat
171+/// below a half and falls away above it.
172+pub(super) const MV_BITS_WEIGHT: f64 = 0.5;
173+
174+/// Cap on whole-sample walk iterations per partition at `Preset::Fast`.
175+pub(super) const FAST_ME_PASSES: usize = 3;
176+
177+/// The offsets the whole-sample search steps through, in units of the current
178+/// step size.
179+///
180+/// A square, not a cross. The cross this used to be could only walk along an
181+/// axis, so a diagonally moving macroblock had to be reached in two steps
182+/// through a point that was worse than both -- and a step search stops at the
183+/// first point it cannot improve on. Adding the four diagonals is worth 0.032
184+/// dB BD-PSNR-YUV on the film clip and 0.041 on the screen capture for twice
185+/// the candidates in the whole-sample stage, which is the cheap stage: it reads
186+/// the reference in place and never interpolates.
187+///
188+/// The step the walk starts from was swept with it, at 4, 8 and 16 whole
189+/// samples: -0.580/-0.580/-0.593 dB on the film clip and -0.474/-0.493/-0.529
190+/// on the screen capture. Four is screen capture's optimum and inside film's
191+/// flat part -- a wider opening step is not a wider search here, it just lands
192+/// the walk further from the seeds, which are already the answer most of the
193+/// time.
194+pub(super) const ME_PATTERN: [(i16, i16); 8] = [
195+ (1, 0),
196+ (-1, 0),
197+ (0, 1),
198+ (0, -1),
199+ (1, 1),
200+ (-1, -1),
201+ (1, -1),
202+ (-1, 1),
203+];
204+
205+/// What the search charges P_8x8 for its own signalling, against the six bits
206+/// a 16x8 or 8x16 is charged: an mb_type that is one bin longer plus four
207+/// sub_mb_type bins, before the four predictors' own mvd.
208+///
209+/// Swept at `Preset::Balanced` -- the only preset that searches shapes at all
210+/// -- on consecutive pictures against x264. Off, 6, 12 and 20 bits read
211+/// -0.382/-0.379/-0.377/-0.378 dB BD-PSNR on the film clip and
212+/// -0.369/-0.364/-0.353/-0.356 on the screen capture: both contents put the
213+/// optimum at twelve, and quarters are worth 0.005 dB on camera content and
214+/// 0.016 on screen capture.
215+///
216+/// Re-swept once each partition was searched against its own predictor rather
217+/// than the macroblock's, because that changes what a split is worth: 6, 12
218+/// and 20 read -0.342/-0.343/-0.346 dB on the film clip and
219+/// -0.322/-0.314/-0.324 on the screen capture. Twelve survives the new path.
220+pub(super) const QUAD_BITS: f64 = 12.0;
221+
222+/// The same charge for a 16x8 or 8x16: one extra mb_type bin over P_16x16,
223+/// with no sub_mb_type behind it.
224+///
225+/// Swept on the per-partition-predictor path at 3, 6 and 10 bits:
226+/// -0.329/-0.343/-0.358 dB on the film clip and -0.310/-0.314/-0.326 on the
227+/// screen capture. Both contents want the halves charged half of what the old
228+/// whole-macroblock predictor made them look worth -- with each half searched
229+/// against its own predictor its mvd is genuinely cheaper, so the search no
230+/// longer has to be talked out of splitting.
231+pub(super) const HALF_BITS: f64 = 3.0;
232+
233+/// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.
234+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
235+pub(super) enum PShape {
236+ /// P_L0_16x16.
237+ Whole,
238+ /// P_L0_L0_16x8: a top and a bottom half.
239+ Horizontal,
240+ /// P_L0_L0_8x16: a left and a right half.
241+ Vertical,
242+ /// P_8x8 with four P_L0_8x8 sub-partitions: a quarter each.
243+ Quad,
244+}
245+
246+impl PShape {
247+ /// mb_type of Table 7-13.
248+ pub(super) fn mb_type(self) -> u32 {
249+ match self {
250+ PShape::Whole => 0,
251+ PShape::Horizontal => 1,
252+ PShape::Vertical => 2,
253+ PShape::Quad => 3,
254+ }
255+ }
256+
257+ pub(super) fn parts(self) -> usize {
258+ match self {
259+ PShape::Whole => 1,
260+ PShape::Horizontal | PShape::Vertical => 2,
261+ PShape::Quad => 4,
262+ }
263+ }
264+
265+ /// Partition `part`'s origin in 4x4 blocks and its size in luma samples.
266+ pub(super) fn geometry(self, part: usize) -> ((usize, usize), (usize, usize)) {
267+ match self {
268+ PShape::Whole => ((0, 0), (16, 16)),
269+ PShape::Horizontal => ((0, part * 2), (16, 8)),
270+ PShape::Vertical => ((part * 2, 0), (8, 16)),
271+ PShape::Quad => (((part % 2) * 2, (part / 2) * 2), (8, 8)),
272+ }
273+ }
274+
275+ /// Which partition covers the 4x4 block at `(x, y)` in macroblock
276+ /// coordinates, or `None` when the block is outside the macroblock.
277+ pub(super) fn part_of(self, x: i32, y: i32) -> Option<usize> {
278+ if !(0..4).contains(&x) || !(0..4).contains(&y) {
279+ return None;
280+ }
281+ let (x, y) = (x as usize, y as usize);
282+ Some(match self {
283+ PShape::Whole => 0,
284+ PShape::Horizontal => y / 2,
285+ PShape::Vertical => x / 2,
286+ PShape::Quad => (y / 2) * 2 + x / 2,
287+ })
288+ }
289+
290+ /// `MbPartWidth`/`MbPartHeight` in 4x4 blocks, which select the
291+ /// directional shortcuts of 8.4.1.3.
292+ pub(super) fn part_blocks(self) -> (usize, usize) {
293+ match self {
294+ PShape::Whole => (4, 4),
295+ PShape::Horizontal => (4, 2),
296+ PShape::Vertical => (2, 4),
297+ PShape::Quad => (2, 2),
298+ }
299+ }
300+}
301+
302+/// How much the two chroma planes weigh against luma in the inter decision.
303+///
304+/// Swept at 0, 0.25, 0.5, 1 and 2, read on BD-PSNR-YUV because a luma-only
305+/// metric cannot price a term whose whole purpose is chroma: the film clip
306+/// reads -0.653/-0.622/-0.612/-0.615/-0.626 dB and the screen capture
307+/// -0.517/-0.521/-0.515/-0.521/-0.546. A half is film's optimum and inside
308+/// screen capture's flat part; zero reproduces the chroma-blind decision
309+/// exactly, which is how the sweep proved the term was reaching the search.
310+///
311+/// It is worth 0.041 dB on the film clip and nothing on the screen capture --
312+/// small enough to name what it rules out. Our chroma trails x264 by 0.5-0.9 dB
313+/// per plane at every QP, and it is not because the vector was chosen without
314+/// looking: weighting chroma up lifts chroma PSNR monotonically, and past a
315+/// half the bits it spends cost more than the chroma it buys.
316+pub(super) const CHROMA_ME_WEIGHT: f64 = 0.5;
317+
318+/// How many inter candidates the macroblock decision codes before choosing,
319+/// most promising first. One is the SATD winner alone, which is what this used
320+/// to do; five is every shape the search costed plus P_Skip. BD-PSNR-YUV
321+/// against x264 at GOP 10 over QP 22/26/30/34, at `Preset::Balanced`:
322+///
323+/// ```text
324+/// film 3840x1608 screen 2560x1440
325+/// 1 candidate -0.580 -0.474
326+/// 2 -0.521 -0.459
327+/// 3 -0.513 -0.447
328+/// 5 -0.504 -0.406
329+/// ```
330+///
331+/// monotone in the count with no turnover, so the decision is taken at the
332+/// full list. The SATD total that used to rank the shapes is a
333+/// prediction-domain estimate that never sees the residual it causes.
334+pub(super) const SHAPE_RD_CANDIDATES: usize = 5;
335+
336+/// The inter decision for a P macroblock.
337+#[derive(Clone, Copy)]
338+pub(super) struct InterChoice {
339+ /// The candidate's SATD cost (luma plus chroma) as the shape search ranked it;
340+ /// zero where the search did not rank it.
341+ pub(super) satd: i32,
342+ pub(super) shape: PShape,
343+ /// One motion vector per partition.
344+ pub(super) mv: [[i16; 2]; 4],
345+ /// The P_Skip motion vector of 8.4.1.1.
346+ pub(super) skip_mv: [i16; 2],
347+ /// The skip candidate is at least as good as the searched one.
348+ pub(super) prefer_skip: bool,
349+ /// The prediction is so close to the source that the macroblock is coded
350+ /// as P_Skip without costing a residual (`Preset::Fast` only).
351+ pub(super) force_skip: bool,
352+}
353+
354+/// Motion search plus the skip candidate.
355+pub(super) fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<InterChoice> {
356+ let reference = e.reference.expect("a P slice has a reference");
357+ let ctx = MvCtx {
358+ mb_x,
359+ mb_y,
360+ slice_id: e.slice_id,
361+ written: 0,
362+ pos: Default::default(),
363+ };
364+ let n = ctx.neighbours(pic, 0, 0, 4, 0);
365+ let mvp = predict_mv(&n, 0, 4, 4, 0);
366+ // P_Skip (8.4.1.1): zero when either neighbour is missing or is itself a
367+ // zero-motion reference-0 partition.
368+ let a = ctx.at(pic, mb_x as i32 * 4 - 1, mb_y as i32 * 4, 0);
369+ let b = ctx.at(pic, mb_x as i32 * 4, mb_y as i32 * 4 - 1, 0);
370+ let zero = |nb: &crate::mv::Nb| nb.ref_idx == 0 && nb.mv == [0, 0];
371+ let skip_mv = if !a.avail || !b.avail || zero(&a) || zero(&b) {
372+ [0, 0]
373+ } else {
374+ mvp
375+ };
376+
377+ let plane = RefPlane {
378+ data: &reference.y.data,
379+ stride: reference.y.stride,
380+ origin: reference.y.origin,
381+ width: reference.y.width,
382+ height: reference.y.height,
383+ pad: reference.y.pad,
384+ };
385+ let (sx, sy) = (mb_x * 16, mb_y * 16);
386+ let sw = e.src.stride;
387+
388+ // What the two chroma planes cost under a candidate vector, in the same
389+ // SATD domain the luma search ranks in. The search itself cannot afford
390+ // this -- it runs on SAD over a whole neighbourhood -- but the handful of
391+ // candidates that survive to the shape decision can, and until they did,
392+ // no decision in this encoder had ever looked at chroma: the vector, the
393+ // shape and the skip flag were all chosen on luma alone and chroma was
394+ // coded against whatever came out. Measured per plane against x264 that
395+ // showed up as a uniform 0.5-0.9 dB chroma deficit at every QP while we
396+ // spent more bits, which is a prediction that was never asked about.
397+ let cplanes = [&reference.cb, &reference.cr];
398+ let chroma_satd = |px: usize, py: usize, w: usize, h: usize, mv: [i16; 2]| -> i32 {
399+ if CHROMA_ME_WEIGHT == 0.0 {
400+ return 0;
401+ }
402+ let mut buf = [0u8; 64];
403+ let mut sum = 0;
404+ for comp in 0..2 {
405+ let src = cplanes[comp];
406+ let rp = RefPlane {
407+ data: &src.data,
408+ stride: src.stride,
409+ origin: src.origin,
410+ width: src.width,
411+ height: src.height,
412+ pad: src.pad,
413+ };
414+ let (cw, ch) = (w / 2, h / 2);
415+ mc_chroma(
416+ &rp,
417+ (sx + px) as i32 / 2,
418+ (sy + py) as i32 / 2,
419+ mv,
420+ cw,
421+ ch,
422+ cw,
423+ &mut buf,
424+ crate::inter::Put::Set,
425+ );
426+ let plane = if comp == 0 { &e.src.u } else { &e.src.v };
427+ sum += satd_block(
428+ plane,
429+ e.src.c_stride,
430+ (sx + px) / 2,
431+ (sy + py) / 2,
432+ &buf,
433+ cw,
434+ 0,
435+ cw,
436+ ch,
437+ );
438+ }
439+ (f64::from(sum) * CHROMA_ME_WEIGHT) as i32
440+ };
441+
442+ // Early skip: a prediction at the P_Skip vector that already sits inside
443+ // the quantiser's dead zone codes nothing, so neither the search nor a
444+ // residual is worth the time. Judged on luma SAD, the largest single
445+ // difference and the chroma SATD, all against the quantiser step.
446+ if e.preset == Preset::Fast && e.fast.early_skip > 0 {
447+ let qstep = ((f64::from(e.qp) - 4.0) / 6.0).exp2();
448+ let k = f64::from(e.fast.early_skip) / 100.0;
449+ let mut buf = [0u8; 256];
450+ mc_luma(
451+ &plane,
452+ sx as i32,
453+ sy as i32,
454+ skip_mv,
455+ 16,
456+ 16,
457+ 16,
458+ &mut buf,
459+ Put::Set,
460+ );
461+ let (sad_luma, max_luma) = sad_max16(&e.src.y, sw, sx, sy, &buf);
462+ if f64::from(sad_luma) <= 256.0 * k * qstep && f64::from(max_luma) <= 4.0 * k * qstep + 2.0
463+ {
464+ let c = chroma_satd(0, 0, 16, 16, skip_mv);
465+ if f64::from(c) <= 64.0 * k * qstep * 4.0 {
466+ return vec![InterChoice {
467+ satd: 0,
468+ shape: PShape::Whole,
469+ mv: [skip_mv; 4],
470+ skip_mv,
471+ prefer_skip: true,
472+ force_skip: true,
473+ }];
474+ }
475+ }
476+ }
477+
478+ let range = match e.preset {
479+ Preset::Fast => 16i16,
480+ Preset::Balanced => 48,
481+ };
482+
483+ // One search over a `w` x `h` partition at `(px, py)` samples inside the
484+ // macroblock, seeded with the candidate vectors of its neighbourhood.
485+ let mlam = motion_lambda(e);
486+ let search = |px: usize, py: usize, w: usize, h: usize, mvp: [i16; 2], seeds: &[[i16; 2]]| {
487+ let (x0, y0) = (sx + px, sy + py);
488+ let mut buf = [0u8; 256];
489+ // Whole-sample candidates read the reference plane in place; only the
490+ // sub-sample refinement pays for interpolation. The search runs on SAD,
491+ // which is what a search can afford; the winner is re-costed on SATD
492+ // because the intra candidates are SATD and the two scales differ.
493+ let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 {
494+ let bits = (mlam
495+ * f64::from(
496+ se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1])),
497+ )
498+ * MV_BITS_WEIGHT)
499+ .round() as i32;
500+ if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 {
501+ let o = integer_origin(
502+ &plane,
503+ x0 as i32 + (mv[0] >> 2) as i32,
504+ y0 as i32 + (mv[1] >> 2) as i32,
505+ w,
506+ h,
507+ );
508+ return sad(&e.src.y, sw, x0, y0, &plane.data[o..], plane.stride, w, h) + bits;
509+ }
510+ mc_luma(
511+ &plane,
512+ x0 as i32,
513+ y0 as i32,
514+ mv,
515+ w,
516+ h,
517+ w,
518+ &mut buf,
519+ crate::inter::Put::Set,
520+ );
521+ let d = if satd {
522+ satd_block(&e.src.y, sw, x0, y0, &buf, w, 0, w, h)
523+ } else {
524+ sad(&e.src.y, sw, x0, y0, &buf, w, w, h)
525+ };
526+ d + bits
527+ };
528+
529+ let fast = e.preset == Preset::Fast;
530+ let mut best = ([0i16; 2], i32::MAX);
531+ for (i, &cand) in seeds.iter().enumerate() {
532+ if seeds[..i].contains(&cand) {
533+ continue;
534+ }
535+ let c = cost_of(cand, false);
536+ if c < best.1 {
537+ best = (cand, c);
538+ }
539+ }
540+ // Every partition is searched. This used to stop at a seed whose cost
541+ // was already under half a level a sample, on the reasoning that the
542+ // prediction fit and the search is the encoder's hot loop. Swept on
543+ // consecutive pictures (BD-PSNR against x264, GOP 10) the threshold is
544+ // monotonically harmful: 0/0.25/0.5/1.0 levels a sample read
545+ // -0.586/-0.587/-0.593/-0.617 dB on the film clip and
546+ // -0.466/-0.470/-0.468/-0.476 on the screen capture. A seed that fits
547+ // is exactly where a little more refinement is cheap.
548+ {
549+ // Fast opens at two whole samples: the seeds already carry the
550+ // neighbours' motion, so the walk only has to settle around them.
551+ let mut step = if fast { 2i16 * 4 } else { 4i16 * 4 };
552+ let mut passes = 0;
553+ while step >= 4 {
554+ let mut improved = true;
555+ while improved {
556+ improved = false;
557+ passes += 1;
558+ if fast && passes > FAST_ME_PASSES {
559+ break;
560+ }
561+ for (dx, dy) in ME_PATTERN {
562+ let (dx, dy) = (dx * step, dy * step);
563+ let cand = [best.0[0] + dx, best.0[1] + dy];
564+ if (cand[0] - mvp[0]).abs() > range * 4
565+ || (cand[1] - mvp[1]).abs() > range * 4
566+ {
567+ continue;
568+ }
569+ let c = cost_of(cand, false);
570+ if c < best.1 {
571+ best = (cand, c);
572+ improved = true;
573+ }
574+ }
575+ }
576+ step /= 2;
577+ }
578+ // Sub-sample refinement runs on SATD, not SAD: interpolation
579+ // smooths, and a sum of absolute differences reads the smoothing
580+ // as a better match where a transform-domain cost does not. Worth
581+ // 0.06 dB BD-PSNR on the film clip and 0.04 dB on the screen
582+ // capture. The whole-sample winner is re-costed in the same domain
583+ // first so the two halves of the search compare.
584+ let sub_satd = !fast || e.fast.me_satd;
585+ best.1 = cost_of(best.0, sub_satd);
586+ // Balanced iterates both sub-sample steps to convergence. Fast
587+ // looks at each ring of eight once.
588+ let rings: &[i16] = if !fast {
589+ &[2, 1]
590+ } else {
591+ match e.fast.me_sub {
592+ 0 => &[],
593+ 1 => &[2],
594+ _ => &[2, 1],
595+ }
596+ };
597+ if fast && e.fast.me_sub == 1 {
598+ // The four half-sample neighbours on the axes, then only the
599+ // diagonal the two winning axes point at.
600+ let base = best;
601+ let mut axis = [(base.0, base.1); 2];
602+ for (k, dirs) in [[(2i16, 0i16), (-2, 0)], [(0, 2), (0, -2)]]
603+ .into_iter()
604+ .enumerate()
605+ {
606+ for (dx, dy) in dirs {
607+ let cand = [base.0[0] + dx, base.0[1] + dy];
608+ let c = cost_of(cand, sub_satd);
609+ if c < axis[k].1 {
610+ axis[k] = (cand, c);
611+ }
612+ }
613+ }
614+ let both = axis[0].1 < base.1 && axis[1].1 < base.1;
615+ if both {
616+ let cand = [axis[0].0[0], axis[1].0[1]];
617+ let c = cost_of(cand, sub_satd);
618+ if c < best.1 {
619+ best = (cand, c);
620+ }
621+ }
622+ for a in axis {
623+ if a.1 < best.1 {
624+ best = a;
625+ }
626+ }
627+ }
628+ let rings: &[i16] = if fast && e.fast.me_sub == 1 {
629+ &[]
630+ } else {
631+ rings
632+ };
633+ for &step in rings {
634+ let mut improved = true;
635+ while improved {
636+ improved = false;
637+ for (dx, dy) in [
638+ (step, 0),
639+ (-step, 0),
640+ (0, step),
641+ (0, -step),
642+ (step, step),
643+ (-step, -step),
644+ (step, -step),
645+ (-step, step),
646+ ] {
647+ let cand = [best.0[0] + dx, best.0[1] + dy];
648+ let c = cost_of(cand, sub_satd);
649+ if c < best.1 {
650+ best = (cand, c);
651+ improved = !fast;
652+ }
653+ }
654+ }
655+ }
656+ }
657+ (
658+ best.0,
659+ if !fast || e.fast.me_satd {
660+ best.1
661+ } else {
662+ cost_of(best.0, true)
663+ },
664+ )
665+ };
666+
667+ let seeds = [mvp, skip_mv, [0, 0], n[0].mv, n[1].mv, n[2].mv];
668+ let (mv16, cost16) = search(0, 0, 16, 16, mvp, &seeds);
669+ let cost16 = cost16 + chroma_satd(0, 0, 16, 16, mv16);
670+ let skip_cost = {
671+ let mut buf = [0u8; 256];
672+ mc_luma(
673+ &plane,
674+ sx as i32,
675+ sy as i32,
676+ skip_mv,
677+ 16,
678+ 16,
679+ 16,
680+ &mut buf,
681+ Put::Set,
682+ );
683+ // P_Skip's rebate is the signalling it genuinely saves. Re-measured on
684+ // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip
685+ // and -0.741/-0.696 on the screen capture -- the two contents disagree
686+ // by less than the step between them, so this is the flat part. Six
687+ // costs 0.14 dB and twelve costs 0.42.
688+ //
689+ // The Intra_4x4 discount above was swept with it: 0.65/0.75/0.85/1.0
690+ // read -1.216/-1.154/-1.182/-1.373 on film and -0.970/-0.696/-0.591/
691+ // -0.562 on screen capture, so three quarters is film's optimum and
692+ // inside screen capture's flat part.
693+ satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) + chroma_satd(0, 0, 16, 16, skip_mv)
694+ - motion_rate(e, 2.0)
695+ };
696+
697+ let mut best = (PShape::Whole, [mv16; 4], cost16);
698+ // Every shape the search costed, kept so the macroblock decision can rank
699+ // them on coded cost instead of on this SATD total (see `encode_mb`).
700+ let mut evaluated = vec![(PShape::Whole, [mv16; 4])];
701+ // Halves, seeded with the whole-macroblock winner. The predictor used here
702+ // is the whole-macroblock one rather than each half's own: the real
703+ // predictors are derived in coding order when the choice is made, and this
704+ // only has to rank the shapes. A macroblock the 16x16 search already fits
705+ // is left alone — splitting it could only spend bits.
706+ //
707+ // Measured: two more searches per macroblock buy 0.1-0.2 dB on screen
708+ // capture and nothing on camera content, for roughly twice the search
709+ // time. That is a Balanced trade, not a Fast one.
710+ // The threshold is a floor that real content clears everywhere: swept at
711+ // 0, 0.5, 1 and 2 levels a sample it moves neither clip's BD-PSNR by a
712+ // thousandth of a decibel, so on these sources the halves are always
713+ // searched. It stays as a guard for content flat enough to make the two
714+ // extra searches pure cost.
715+ if e.preset == Preset::Balanced && cost16 > 16 * 16 {
716+ for shape in [PShape::Horizontal, PShape::Vertical, PShape::Quad] {
717+ // What the shape itself costs to signal: its mb_type, plus one
718+ // sub_mb_type per quarter when it is P_8x8.
719+ let mut total = motion_rate(
720+ e,
721+ if shape == PShape::Quad {
722+ QUAD_BITS
723+ } else {
724+ HALF_BITS
725+ },
726+ );
727+ let mut mvs = [[0i16; 2]; 4];
728+ let (pw, ph) = shape.part_blocks();
729+ for part in 0..shape.parts() {
730+ let ((bx, by), (w, h)) = shape.geometry(part);
731+ // Each partition is searched against the predictor it will
732+ // actually be coded with (8.4.1.3), not against the whole
733+ // macroblock's: the partitions before it in this macroblock
734+ // are already chosen, so the neighbourhood the predictor reads
735+ // can be completed from `mvs`.
736+ let mut n = ctx.neighbours(pic, bx, by, pw, 0);
737+ let inside = |x: i32, y: i32, nb: &mut crate::mv::Nb| {
738+ if let Some(p) = shape.part_of(x, y).filter(|&p| p < part) {
739+ *nb = crate::mv::Nb {
740+ avail: true,
741+ mv: mvs[p],
742+ ref_idx: 0,
743+ };
744+ }
745+ };
746+ inside(bx as i32 - 1, by as i32, &mut n[0]);
747+ inside(bx as i32, by as i32 - 1, &mut n[1]);
748+ let cx = bx as i32 + pw as i32;
749+ if shape.part_of(cx, by as i32 - 1).is_some() {
750+ inside(cx, by as i32 - 1, &mut n[2]);
751+ } else if !n[2].avail {
752+ inside(bx as i32 - 1, by as i32 - 1, &mut n[2]);
753+ }
754+ let part_mvp = predict_mv(&n, 0, pw, ph, part);
755+ let seeds = [mv16, part_mvp, mvp, skip_mv, [0, 0]];
756+ let (mv, cost) = search(bx * 4, by * 4, w, h, part_mvp, &seeds);
757+ mvs[part] = mv;
758+ total += cost + chroma_satd(bx * 4, by * 4, w, h, mv);
759+ }
760+ evaluated.push((shape, mvs));
761+ if total < best.2 {
762+ best = (shape, mvs, total);
763+ }
764+ }
765+ }
766+
767+ // How often each shape actually wins. Behind an environment switch because
768+ // it answers a question the rate gate cannot: a partition sweep that reads
769+ // flat is either a flat knob or a path nothing enters, and only a count
770+ // tells the two apart. It found the second -- at `Preset::Fast`, which is
771+ // what the x264 comparison runs by default, no macroblock is ever split.
772+ if std::env::var_os("EC_H264_SHAPE_STATS").is_some() {
773+ static N: [std::sync::atomic::AtomicUsize; 4] = [
774+ std::sync::atomic::AtomicUsize::new(0),
775+ std::sync::atomic::AtomicUsize::new(0),
776+ std::sync::atomic::AtomicUsize::new(0),
777+ std::sync::atomic::AtomicUsize::new(0),
778+ ];
779+ let i = match best.0 {
780+ PShape::Whole => 0,
781+ PShape::Horizontal => 1,
782+ PShape::Vertical => 2,
783+ PShape::Quad => 3,
784+ };
785+ let v = N[i].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
786+ let tot: usize = N
787+ .iter()
788+ .map(|n| n.load(std::sync::atomic::Ordering::Relaxed))
789+ .sum();
790+ if tot.is_multiple_of(20000) {
791+ eprintln!(
792+ "SHAPES whole={} horiz={} vert={} quad={} (last {i} -> {v})",
793+ N[0].load(std::sync::atomic::Ordering::Relaxed),
794+ N[1].load(std::sync::atomic::Ordering::Relaxed),
795+ N[2].load(std::sync::atomic::Ordering::Relaxed),
796+ N[3].load(std::sync::atomic::Ordering::Relaxed),
797+ );
798+ }
799+ }
800+ let winner = InterChoice {
801+ satd: best.2,
802+ shape: best.0,
803+ mv: best.1,
804+ skip_mv,
805+ prefer_skip: best.0 == PShape::Whole && skip_cost <= best.2,
806+ force_skip: false,
807+ };
808+ // The SATD winner first, then the shapes it beat, then the skip candidate
809+ // when the winner is not already it. The caller codes as many of these as
810+ // its preset allows and keeps the one with the smallest coded cost.
811+ let mut cands = vec![winner];
812+ for (shape, mv) in evaluated {
813+ if shape != winner.shape || winner.prefer_skip {
814+ cands.push(InterChoice {
815+ satd: 0,
816+ shape,
817+ mv,
818+ skip_mv,
819+ prefer_skip: false,
820+ force_skip: false,
821+ });
822+ }
823+ }
824+ if !winner.prefer_skip {
825+ cands.push(InterChoice {
826+ satd: skip_cost,
827+ shape: PShape::Whole,
828+ mv: [skip_mv; 4],
829+ skip_mv,
830+ prefer_skip: true,
831+ force_skip: false,
832+ });
833+ }
834+ cands
835+}
836+
crates/ec-h264/src/enc/mb/residual.rsadded+1403 -0
@@ -0,0 +1,1403 @@
1+#![allow(clippy::needless_range_loop)]
2+
3+use wide::{i16x8};
4+
5+use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line};
6+use crate::decoder::{
7+ MbNeighbors, chroma_nz_pair, luma_nz_pair, };
8+use crate::dpb::{Picture};
9+use crate::entropy::{
10+ BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_TRANS8X8,
11+ };
12+use crate::pred::{
13+ PlaneWindow, add_residual_4x4, pred_16x16,
14+ };
15+use crate::tables::{BLK4_POS};
16+use crate::transform::{
17+ chroma_dc_transform_420, dequant_4x4, dequant_8x8,
18+ inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8,
19+ unzigzag_ac15,
20+};
21+
22+use crate::enc::quant::{
23+ forward_4x4, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4,
24+ quant_4x4_offset, quant_chroma_dc, quant_luma_dc,
25+};
26+
27+use crate::enc::{
28+ entropy::{EncEntropy, sub_block_4x4},
29+ lambda_ssd,
30+};
31+use super::*;
32+
33+/// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock,
34+/// prediction already in the plane.
35+#[allow(clippy::too_many_arguments)]
36+pub(super) fn code_luma_4x4(
37+ pic: &mut Picture,
38+ e: &MbEnc<'_>,
39+ w: &EncEntropy,
40+ mb_x: usize,
41+ mb_y: usize,
42+ qp: i32,
43+ intra: bool,
44+ lv: &mut Levels,
45+) {
46+ let stride = pic.y.stride;
47+ // An inter macroblock's blocks are reconstructed only after the whole
48+ // macroblock has been quantised, because [`decimate_score`] can still take
49+ // a block away. Intra blocks reconstruct as they go: the next block in the
50+ // macroblock predicts from them.
51+ let mut pending: [Option<[i32; 16]>; 16] = [None; 16];
52+ // Per 8x8 group, what coding its blocks buys and what it costs, for the
53+ // group-level test below. A block with no levels contributes nothing to
54+ // either side: its source energy stays in the reconstruction whatever the
55+ // group decides.
56+ let mut ssd_zero = [0i64; 4];
57+ let mut ssd_coded = [0i64; 4];
58+ let mut rate = [0f64; 4];
59+ for blk in 0..16 {
60+ let (dx, dy) = BLK4_POS[blk];
61+ let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
62+ let origin = pic.y.at(x, y);
63+ let mut d = [0i32; 16];
64+ for ry in 0..4 {
65+ for rx in 0..4 {
66+ d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
67+ - i32::from(pic.y.data[origin + ry * stride + rx]);
68+ }
69+ }
70+ let source = d;
71+ forward_4x4(&mut d);
72+ let rdoq = !intra && w.is_cabac();
73+ let mut nz = if rdoq {
74+ quant_4x4_offset(&d, qp, RDOQ_DEAD_ZONE, false, &mut lv.luma[blk])
75+ } else {
76+ quant_4x4(&d, qp, intra, false, &mut lv.luma[blk])
77+ };
78+ if rdoq && nz != 0 {
79+ nz = rdoq_4x4(
80+ e,
81+ w,
82+ &source,
83+ &mut lv.luma[blk],
84+ qp,
85+ BlockCat::Luma4x4,
86+ false,
87+ );
88+ }
89+ lv.luma_nz[blk] = nz;
90+ if nz == 0 {
91+ continue;
92+ }
93+ let mut raster = [0i32; 16];
94+ unzigzag(&lv.luma[blk], &mut raster);
95+ dequant_4x4(&mut raster, &e.ls, qp, false);
96+ let mut resid = [0i32; 16];
97+ inverse_transform_4x4(&raster, &mut resid);
98+ // Is the block worth its bits? A block whose residual barely moves the
99+ // reconstruction is pure quantisation churn; dropping it is the cheap
100+ // half of rate-distortion optimised quantisation, and the half that
101+ // pays. Intra blocks are left alone: their reconstruction is what the
102+ // next block in the macroblock predicts from.
103+ if !rdoq
104+ && !intra
105+ && !worth_coding(
106+ &source,
107+ &resid,
108+ &lv.luma[blk],
109+ zero_block_lambda(e, qp, e.transform_8x8),
110+ )
111+ {
112+ lv.luma[blk] = [0; 16];
113+ lv.luma_nz[blk] = 0;
114+ continue;
115+ }
116+ if intra {
117+ lv.cbp_luma |= 1 << (blk >> 2);
118+ add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
119+ } else {
120+ for i in 0..16 {
121+ let z = i64::from(source[i]);
122+ let c = i64::from(source[i] - resid[i]);
123+ ssd_zero[blk >> 2] += z * z;
124+ ssd_coded[blk >> 2] += c * c;
125+ }
126+ rate[blk >> 2] +=
127+ match w.residual_block_cost(&lv.luma[blk], BlockCat::Luma4x4, Some(1), Some(1)) {
128+ // CABAC's own arithmetic cost for the levels, which is what
129+ // the group is really deciding about. It arrives in 256ths of
130+ // a bit.
131+ Some(bits) => f64::from(bits) / 256.0,
132+ None => block_bits(&lv.luma[blk]) as f64,
133+ };
134+ pending[blk] = Some(resid);
135+ }
136+ }
137+ if intra {
138+ return;
139+ }
140+ // A block that survives its own rate-distortion test can still be the last
141+ // coefficient standing in its 8x8 group, and then it is paying a
142+ // coded_block_pattern bit as well as its levels. x264 decides that with a
143+ // count of how tightly the levels cluster at the front of the scan
144+ // (`decimate`), thresholded at four per group; swept here, that count
145+ // wants opposite settings on the two contents -- monotonically off on
146+ // camera grain, monotonically harder on screen capture -- because it is a
147+ // heuristic standing in for a rate-distortion test the encoder can just
148+ // do. So do it: a group is coded only if its blocks buy more squared error
149+ // than their levels plus the pattern bit are worth, at the same lambda the
150+ // per-block test uses.
151+ // With an exact rate the lambda needs no correction factor: the group test
152+ // uses the mode decision's own lambda where the rate is CABAC's, and falls
153+ // back to the per-block test's discounted one where it is an estimate.
154+ let lambda = if w.is_cabac() {
155+ GROUP_LAMBDA * lambda_ssd(qp)
156+ } else {
157+ zero_block_lambda(e, qp, e.transform_8x8)
158+ };
159+ for g in 0..4 {
160+ if rate[g] == 0.0 {
161+ continue;
162+ }
163+ if ssd_coded[g] as f64 + lambda * (rate[g] + CBP_BIT) < ssd_zero[g] as f64 {
164+ continue;
165+ }
166+ for blk in g * 4..g * 4 + 4 {
167+ lv.luma[blk] = [0; 16];
168+ lv.luma_nz[blk] = 0;
169+ pending[blk] = None;
170+ }
171+ }
172+ for blk in 0..16 {
173+ let Some(resid) = pending[blk] else { continue };
174+ let (dx, dy) = BLK4_POS[blk];
175+ let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
176+ let origin = pic.y.at(x, y);
177+ lv.cbp_luma |= 1 << (blk >> 2);
178+ add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
179+ }
180+}
181+
182+/// What a group of four luma blocks pays in coded_block_pattern to be coded
183+/// at all, in bits, on top of its own levels.
184+///
185+/// This charge and [`GROUP_LAMBDA`] move the group test along the same axis --
186+/// both make dropping a group likelier -- so only one of them is worth tuning.
187+/// Swept at 0, 6, 12 and 24 bits it reads -0.317/-0.335/-0.379/-0.472 dB on
188+/// the film clip against -0.295/-0.212/-0.191/-0.185 on the screen capture:
189+/// the same trade the lambda makes, at a worse exchange rate. It stays at a
190+/// plausible six.
191+pub(super) const CBP_BIT: f64 = 6.0;
192+
193+/// What chroma pays to take its coded_block_pattern from one to two, in bits,
194+/// on top of the levels: the pattern bins themselves plus a coded_block_flag
195+/// for every AC block that then has to say it is empty.
196+///
197+/// Swept at 0, 4, 8, 16, 32 and 64 bits, read on the all-plane PSNR because a
198+/// luma-only one cannot see what this decision spends: -0.688/-0.681/-0.659/
199+/// -0.653/-0.670/-0.742 dB BD on the film clip and -0.537/-0.527/-0.530/
200+/// -0.517/-0.524/-0.522 on the screen capture. Both turn over at sixteen. The
201+/// same sweep read on luma alone climbs all the way to +0.079 dB at 64,
202+/// because past the turn the test is buying luma bits by throwing chroma
203+/// away -- which is exactly the trade an all-plane metric exists to catch.
204+pub(super) const CBP_CHROMA_BIT: f64 = 16.0;
205+
206+/// How much of the mode-decision lambda the group test uses.
207+///
208+/// The 8x8 transform path was swept the same way and does not want this test
209+/// at all: at 0, 0.3 and 0.6 the `transform_8x8` gate reads +0.620/+0.624/
210+/// +0.608 dB on the film clip and +0.007/+0.007/+0.009 on the screen capture,
211+/// all inside its noise. One 8x8 block is a whole coded_block_pattern group,
212+/// so its own zero test already decides what this one would, and `rdoq_8x8`
213+/// drops it outright when the levels do not survive.
214+///
215+/// Swept at 0.25, 0.5, 0.6, 0.75, 0.9, 1.0 and 2.0 on both real clips:
216+/// -0.315/-0.314/-0.321/-0.335/-0.354/-0.372/-0.575 dB on the 3840x1608 film
217+/// clip and -0.297/-0.267/-0.252/-0.212/-0.202/-0.193/-0.277 on the 2560x1440
218+/// screen capture. Screen capture has an interior optimum around one -- which
219+/// the same test on an estimated rate did not, it only ever wanted more -- and
220+/// camera grain wants less, because a grain block that scores as noise is
221+/// carrying signal the eye is measuring. Six tenths is the most the film clip
222+/// takes without losing ground, and it is worth 0.06 dB on screen capture.
223+pub(super) const GROUP_LAMBDA: f64 = 0.6;
224+
225+/// How much of the squared-error lambda the chroma DC zero test uses.
226+///
227+/// BD-PSNR-YUV against x264 at GOP 10 over QP 22/26/30/34, `Preset::Balanced`,
228+/// with the test off against a ladder of multipliers:
229+///
230+/// ```text
231+/// film screen phone handheld
232+/// off -0.504 -0.227 -0.300 -0.886
233+/// 0.25 -0.506 -0.227
234+/// 0.5 -0.500 -0.220 -0.297 -0.884
235+/// 0.75 -0.500 -0.223
236+/// 1.0 -0.518 -0.246
237+/// 2.0 -0.708 -0.566
238+/// ```
239+///
240+/// Zeroing on squared error alone (a multiplier of 0) never fires, so the rate
241+/// term is the whole test; above the peak it throws away chroma the picture
242+/// needs.
243+pub(super) const CHROMA_DC_LAMBDA: f64 = 0.5;
244+
245+/// Squared error of coding `levels`, in the pixels the block reconstructs to.
246+pub(super) fn block_ssd(e: &MbEnc<'_>, source: &[i32; 16], levels: &[i32; 16], qp: i32, skip_dc: bool) -> i64 {
247+ let mut raster = [0i32; 16];
248+ if skip_dc {
249+ unzigzag_ac15(levels, &mut raster);
250+ } else {
251+ unzigzag(levels, &mut raster);
252+ }
253+ dequant_4x4(&mut raster, &e.ls, qp, skip_dc);
254+ let mut resid = [0i32; 16];
255+ inverse_transform_4x4(&raster, &mut resid);
256+ let mut ssd = 0i64;
257+ for i in 0..16 {
258+ let d = i64::from(source[i] - resid[i]);
259+ ssd += d * d;
260+ }
261+ ssd
262+}
263+
264+/// How much of the mode-decision lambda rate-distortion quantisation uses.
265+///
266+/// The bits here are the coder's own, not an estimate, so there is no
267+/// over-estimate to correct for and the scale starts at 1. Swept over 0.5,
268+/// 1.0, 1.25, 1.5 and 2.0 against x264 on a 3840x1608 film clip and a
269+/// 2560x1440 screen capture: the two disagree, film reading -0.607 dB at 0.5
270+/// and -0.680 at 1.5 while screen capture reads -0.620 and -0.444, and 1.0 is
271+/// the crossing point that costs neither (-0.628 and -0.471). Table in
272+/// `lanes/h264x264-r2.report.md`.
273+pub(super) const RDOQ_LAMBDA: f64 = 1.0;
274+
275+/// The dead zone rate-distortion quantisation starts from, as a divisor of the
276+/// quantiser step: 2 is round-to-nearest. The plain inter path uses 6, which
277+/// has already thrown away the levels this search would weigh -- a search
278+/// bounded by the heuristic it replaces measures the heuristic. This is the
279+/// half of the change that pays: 1/6 -> 1/2 under the same search is worth
280+/// 0.102 dB on the film clip and 0.301 on the synthetic gate. 1/3 and 1/4 read
281+/// -0.647 and -0.677 dB where 1/2 reads -0.630.
282+pub(super) const RDOQ_DEAD_ZONE: i32 = 2;
283+
284+/// The largest level the search offers a smaller magnitude to. A big level is
285+/// carrying real signal and never wins by shrinking; bounding the search is
286+/// what keeps it free. Unbounded it tripled the synthetic clip's encode time
287+/// (1.08 s -> 3.53 s) for the same BD-PSNR; at 2 the run is 1.09 s. Swept over
288+/// 1, 2 and 3: -4.062/-0.623/-0.496, -4.073/-0.628/-0.471 and
289+/// -4.065/-0.629/-0.477 dB on synthetic, film and screen capture.
290+pub(super) const RDOQ_MAX_LEVEL: i32 = 2;
291+
292+/// The rounding the chroma AC path keeps under the search: the inter dead zone
293+/// it already had. Luma wanted the wider 1/2 rounding once a search could take
294+/// levels back down (`RDOQ_DEAD_ZONE`); chroma does not. Measured on the two
295+/// clips at the settled luma constants, BD-PSNR against x264: 1/2 rounding
296+/// -0.653 film / -0.482 screen capture, 1/4 -0.623 / -0.472, 1/3 -0.644 /
297+/// -0.481, and the 1/6 kept here -0.593 / -0.468 -- against -0.628 / -0.471
298+/// with no chroma search at all. Chroma AC is sparse enough at these
299+/// quantisers that offering more levels costs more bits than the search takes
300+/// back; what pays is only the pruning.
301+pub(super) const RDOQ_CHROMA_DEAD_ZONE: i32 = 6;
302+
303+/// The rounding the 8x8 luma path keeps under the search. It answers the way
304+/// 4x4 luma did, not the way chroma did: measured as BD-PSNR of the opt-in
305+/// `transform_8x8` flag against flag-off, which isolates this path because the
306+/// flag-off curve does not run through it. Film 3840x1608 / screen capture
307+/// 2560x1440, no search +0.535 / +0.042, 1/6 +0.551 / --, 1/3 +0.605 / +0.075,
308+/// and the 1/2 kept here +0.619 / +0.067. The 8x8 blocks carry enough
309+/// coefficients for the extra levels to pay for themselves, as 4x4 luma's do.
310+pub(super) const RDOQ8_DEAD_ZONE: i32 = 2;
311+
312+/// Rate-distortion quantisation of one inter luma block: each level is offered
313+/// the two cheaper magnitudes below it, and takes one when the squared error it
314+/// gives up costs less than the bits it saves.
315+///
316+/// The rate is the CABAC coder's own price for the whole block against the
317+/// context state as it stands, so dropping a level is priced with the
318+/// significance map that follows from it — which is where most of the saving
319+/// is. Intra blocks stay out: their reconstruction is what the next block in
320+/// the macroblock predicts from, so a level changed here would move a
321+/// prediction the decision cannot see.
322+#[allow(clippy::too_many_arguments)]
323+pub(super) fn rdoq_4x4(
324+ e: &MbEnc<'_>,
325+ w: &EncEntropy,
326+ source: &[i32; 16],
327+ levels: &mut [i32; 16],
328+ qp: i32,
329+ cat: BlockCat,
330+ skip_dc: bool,
331+) -> u8 {
332+ let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else {
333+ return levels.iter().filter(|&&l| l != 0).count() as u8;
334+ };
335+ let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
336+ let mut cost = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits);
337+ // Highest scanning position first: dropping the last significant level is
338+ // what shortens the significance map, so it is tried while the levels
339+ // above it are still gone.
340+ for pos in (0..cat.max_num_coeff()).rev() {
341+ let level = levels[pos];
342+ if level == 0 {
343+ continue;
344+ }
345+ let mag = level.abs();
346+ if mag > RDOQ_MAX_LEVEL {
347+ continue;
348+ }
349+ let mut tried = mag;
350+ for candidate in [mag - 1, 0] {
351+ if candidate == tried {
352+ continue;
353+ }
354+ tried = candidate;
355+ let keep = levels[pos];
356+ levels[pos] = candidate * level.signum();
357+ let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else {
358+ unreachable!("CAVLC returned early");
359+ };
360+ let trial = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits);
361+ if trial < cost {
362+ cost = trial;
363+ } else {
364+ levels[pos] = keep;
365+ }
366+ }
367+ }
368+ // And the block as a whole: zeroing it drops the coded_block_pattern bit as
369+ // well as every level, which no single-coefficient step can see. This is
370+ // the same decision `worth_coding` makes for the paths without an exact
371+ // rate, made here with one.
372+ let zero_bits = w
373+ .residual_block_cost(&[0; 16], cat, Some(1), Some(1))
374+ .expect("CABAC");
375+ let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
376+ if ssd_zero as f64 + lambda * f64::from(zero_bits) <= cost {
377+ *levels = [0; 16];
378+ return 0;
379+ }
380+ levels.iter().filter(|&&l| l != 0).count() as u8
381+}
382+
383+/// How much of the mode-decision lambda the zero-block test uses.
384+///
385+/// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what
386+/// CAVLC spends and an over-estimate of what CABAC spends; the multiplier
387+/// brings the rate term back to the coder actually in force. Measured over
388+/// 0.0, 0.4 and 1.0 on 1080p camera and screen-capture clips: 0.4 is the only
389+/// one that gains on screen content (+0.13 to +0.39 dB at matched bitrate)
390+/// without costing camera content.
391+pub(super) const ZERO_BLOCK_LAMBDA: f64 = 0.4;
392+
393+pub(super) fn zero_block_lambda(e: &MbEnc<'_>, qp: i32, transform_8x8: bool) -> f64 {
394+ if transform_8x8 {
395+ e.lambda
396+ } else {
397+ ZERO_BLOCK_LAMBDA * lambda_ssd(qp)
398+ }
399+}
400+
401+/// The rate-distortion test behind the per-block zero decision: coding the
402+/// block has to buy more squared error than its bits are worth.
403+pub(super) fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], lambda: f64) -> bool {
404+ let mut ssd_zero = 0i64;
405+ let mut ssd_coded = 0i64;
406+ for i in 0..source.len() {
407+ let z = i64::from(source[i]);
408+ let c = i64::from(source[i] - resid[i]);
409+ ssd_zero += z * z;
410+ ssd_coded += c * c;
411+ }
412+ ssd_coded as f64 + lambda * (block_bits(levels) as f64) < ssd_zero as f64
413+}
414+
415+/// Predict and code the luma of an Intra_16x16 macroblock.
416+#[allow(clippy::too_many_arguments)]
417+pub(super) fn code_i16_luma(
418+ pic: &mut Picture,
419+ e: &MbEnc<'_>,
420+ mb_x: usize,
421+ mb_y: usize,
422+ qp: i32,
423+ mode: u8,
424+ nbr: &MbNeighbors,
425+ lv: &mut Levels,
426+) {
427+ let w4 = pic.mb_w * 4;
428+ for dy in 0..4 {
429+ let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
430+ pic.i4_modes[base..base + 4].fill(2);
431+ }
432+ let stride = pic.y.stride;
433+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
434+ let mut win = PlaneWindow {
435+ data: &mut pic.y.data,
436+ stride,
437+ origin,
438+ };
439+ pred_16x16(mode, 8, &mut win, nbr.b, nbr.a);
440+ code_luma_i16(pic, e, mb_x, mb_y, qp, lv);
441+}
442+
443+/// The Intra_16x16 luma path (8.5.10 in reverse then forward again).
444+pub(super) fn code_luma_i16(
445+ pic: &mut Picture,
446+ e: &MbEnc<'_>,
447+ mb_x: usize,
448+ mb_y: usize,
449+ qp: i32,
450+ lv: &mut Levels,
451+) {
452+ let stride = pic.y.stride;
453+ let mut dc = [0i32; 16];
454+ let mut ac = [[0i32; 16]; 16];
455+ for blk in 0..16 {
456+ let (dx, dy) = BLK4_POS[blk];
457+ let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
458+ let origin = pic.y.at(x, y);
459+ let mut d = [0i32; 16];
460+ for ry in 0..4 {
461+ for rx in 0..4 {
462+ d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
463+ - i32::from(pic.y.data[origin + ry * stride + rx]);
464+ }
465+ }
466+ forward_4x4(&mut d);
467+ dc[dy as usize * 4 + dx as usize] = d[0];
468+ let nz = quant_4x4(&d, qp, true, true, &mut lv.luma[blk]);
469+ lv.luma_nz[blk] = nz;
470+ ac[blk] = lv.luma[blk];
471+ if nz > 0 {
472+ lv.cbp_luma = 15;
473+ }
474+ }
475+ if lv.cbp_luma == 0 {
476+ for blk in 0..16 {
477+ lv.luma[blk] = [0; 16];
478+ lv.luma_nz[blk] = 0;
479+ }
480+ }
481+ forward_hadamard_4x4(&mut dc);
482+ quant_luma_dc(&dc, qp, &mut lv.dc);
483+
484+ // Reconstruct exactly as the decoder does: DC through 8.5.10, then each
485+ // block's AC with the DC substituted at raster position 0.
486+ let mut raster = [0i32; 16];
487+ unzigzag(&lv.dc, &mut raster);
488+ luma_dc_transform(&mut raster, &e.ls, qp);
489+ let dc_recon = raster;
490+ for blk in 0..16 {
491+ let (dx, dy) = BLK4_POS[blk];
492+ let dc_blk = dc_recon[dy as usize * 4 + dx as usize];
493+ let tc = lv.luma_nz[blk];
494+ if tc == 0 && dc_blk == 0 {
495+ continue;
496+ }
497+ let mut raster = [0i32; 16];
498+ if tc > 0 {
499+ unzigzag_ac15(&ac[blk], &mut raster);
500+ dequant_4x4(&mut raster, &e.ls, qp, true);
501+ }
502+ raster[0] = dc_blk;
503+ let mut resid = [0i32; 16];
504+ inverse_transform_4x4(&raster, &mut resid);
505+ let origin = pic
506+ .y
507+ .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
508+ add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
509+ }
510+}
511+
512+/// Chroma residual for both components (8.5.11 + the AC path).
513+#[allow(clippy::too_many_arguments)]
514+pub(super) fn code_chroma(
515+ pic: &mut Picture,
516+ e: &MbEnc<'_>,
517+ w: &EncEntropy,
518+ mb_x: usize,
519+ mb_y: usize,
520+ qp_y: i32,
521+ intra: bool,
522+ lv: &mut Levels,
523+) {
524+ let qp_c = chroma_qp(qp_y, e.cqo);
525+ let mut dc_lists = [[0i32; 4]; 2];
526+ let mut ac = [[[0i32; 16]; 4]; 2];
527+ let mut srcs = [[[0i32; 16]; 4]; 2];
528+ let mut any_ac = false;
529+ for comp in 0..2 {
530+ let (plane, src) = if comp == 0 {
531+ (&pic.cb, &e.src.u)
532+ } else {
533+ (&pic.cr, &e.src.v)
534+ };
535+ let stride = plane.stride;
536+ for blk in 0..4 {
537+ let (x, y) = (mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
538+ let origin = plane.at(x, y);
539+ let mut d = [0i32; 16];
540+ for ry in 0..4 {
541+ for rx in 0..4 {
542+ d[ry * 4 + rx] = i32::from(src[(y + ry) * e.src.c_stride + x + rx])
543+ - i32::from(plane.data[origin + ry * stride + rx]);
544+ }
545+ }
546+ let source = d;
547+ srcs[comp][blk] = d;
548+ forward_4x4(&mut d);
549+ dc_lists[comp][blk] = d[0];
550+ let rdoq = !intra && w.is_cabac();
551+ let mut nz = if rdoq {
552+ quant_4x4_offset(&d, qp_c, RDOQ_CHROMA_DEAD_ZONE, true, &mut ac[comp][blk])
553+ } else {
554+ quant_4x4(&d, qp_c, intra, true, &mut ac[comp][blk])
555+ };
556+ if rdoq && nz > 0 {
557+ nz = rdoq_4x4(
558+ e,
559+ w,
560+ &source,
561+ &mut ac[comp][blk],
562+ qp_c,
563+ BlockCat::ChromaAc,
564+ true,
565+ );
566+ } else if nz > 0 {
567+ // The same zero decision as luma, against the AC part alone:
568+ // the DC of this block travels through the 2x2 Hadamard and is
569+ // decided with the other three.
570+ let mut raster = [0i32; 16];
571+ unzigzag_ac15(&ac[comp][blk], &mut raster);
572+ dequant_4x4(&mut raster, &e.ls, qp_c, true);
573+ let mut resid = [0i32; 16];
574+ inverse_transform_4x4(&raster, &mut resid);
575+ if !worth_coding(
576+ &source,
577+ &resid,
578+ &ac[comp][blk],
579+ zero_block_lambda(e, qp_c, e.transform_8x8),
580+ ) {
581+ ac[comp][blk] = [0; 16];
582+ nz = 0;
583+ }
584+ }
585+ lv.chroma_nz[comp][blk] = nz;
586+ if nz > 0 {
587+ any_ac = true;
588+ }
589+ }
590+ }
591+ // The chroma pattern is one decision for all eight AC blocks: a single
592+ // surviving block takes coded_block_pattern from one to two, and every
593+ // other block then has to code a coded_block_flag to say it is empty. So
594+ // the same group test luma runs over four blocks runs here over all eight,
595+ // against the same lambda.
596+ if any_ac {
597+ let (mut ssd_zero, mut ssd_coded, mut rate) = (0i64, 0i64, 0f64);
598+ for comp in 0..2 {
599+ for blk in 0..4 {
600+ let source = &srcs[comp][blk];
601+ let mut resid = [0i32; 16];
602+ if lv.chroma_nz[comp][blk] > 0 {
603+ let mut raster = [0i32; 16];
604+ unzigzag_ac15(&ac[comp][blk], &mut raster);
605+ dequant_4x4(&mut raster, &e.ls, qp_c, true);
606+ inverse_transform_4x4(&raster, &mut resid);
607+ rate += match w.residual_block_cost(
608+ &ac[comp][blk],
609+ BlockCat::ChromaAc,
610+ Some(1),
611+ Some(1),
612+ ) {
613+ Some(bits) => f64::from(bits) / 256.0,
614+ None => block_bits(&ac[comp][blk]) as f64,
615+ };
616+ }
617+ for i in 0..16 {
618+ let z = i64::from(source[i]);
619+ let c = i64::from(source[i] - resid[i]);
620+ ssd_zero += z * z;
621+ ssd_coded += c * c;
622+ }
623+ }
624+ }
625+ let lambda = if w.is_cabac() {
626+ GROUP_LAMBDA * lambda_ssd(qp_c)
627+ } else {
628+ zero_block_lambda(e, qp_c, false)
629+ };
630+ if ssd_coded as f64 + lambda * (rate + CBP_CHROMA_BIT) >= ssd_zero as f64 {
631+ ac = [[[0; 16]; 4]; 2];
632+ lv.chroma_nz = [[0; 4]; 2];
633+ any_ac = false;
634+ }
635+ }
636+ // The chroma DC block had no zero test at all: whatever the quantiser
637+ // produced was coded. Its four coefficients spread over all 64 samples of
638+ // the component, and with only DC in the block the inverse transform gives
639+ // every sample the same (dc + 32) >> 6, so the squared error zeroing costs
640+ // is exact in one pass over the AC residual that is already reconstructed
641+ // here.
642+ let mut any_dc = false;
643+ for comp in 0..2 {
644+ forward_hadamard_2x2(&mut dc_lists[comp]);
645+ let mut nz = quant_chroma_dc(&dc_lists[comp], qp_c, intra, &mut lv.chroma_dc[comp]);
646+ if nz > 0 {
647+ let mut dc = [
648+ lv.chroma_dc[comp][0],
649+ lv.chroma_dc[comp][1],
650+ lv.chroma_dc[comp][2],
651+ lv.chroma_dc[comp][3],
652+ ];
653+ chroma_dc_transform_420(&mut dc, &e.ls, qp_c);
654+ let mut delta = 0i64;
655+ for blk in 0..4 {
656+ let mut resid = [0i32; 16];
657+ if any_ac && lv.chroma_nz[comp][blk] > 0 {
658+ let mut raster = [0i32; 16];
659+ unzigzag_ac15(&ac[comp][blk], &mut raster);
660+ dequant_4x4(&mut raster, &e.ls, qp_c, true);
661+ inverse_transform_4x4(&raster, &mut resid);
662+ }
663+ let c = i64::from((dc[blk] + 32) >> 6);
664+ let err: i64 = (0..16)
665+ .map(|i| i64::from(srcs[comp][blk][i] - resid[i]))
666+ .sum();
667+ delta += 16 * c * c - 2 * c * err;
668+ }
669+ let rate = match w.residual_block_cost(
670+ &lv.chroma_dc[comp],
671+ BlockCat::ChromaDc(comp as u8),
672+ Some(1),
673+ Some(1),
674+ ) {
675+ Some(bits) => f64::from(bits) / 256.0,
676+ None => block_bits(&lv.chroma_dc[comp]) as f64,
677+ };
678+ if delta as f64 + CHROMA_DC_LAMBDA * lambda_ssd(qp_c) * rate >= 0.0 {
679+ lv.chroma_dc[comp] = [0; 16];
680+ nz = 0;
681+ }
682+ }
683+ if nz > 0 {
684+ any_dc = true;
685+ }
686+ }
687+ lv.cbp_chroma = if any_ac {
688+ 2
689+ } else if any_dc {
690+ 1
691+ } else {
692+ 0
693+ };
694+ if lv.cbp_chroma < 2 {
695+ lv.chroma_nz = [[0; 4]; 2];
696+ } else {
697+ lv.chroma = ac;
698+ }
699+ if lv.cbp_chroma == 0 {
700+ return;
701+ }
702+ for comp in 0..2 {
703+ let mut dc = [
704+ lv.chroma_dc[comp][0],
705+ lv.chroma_dc[comp][1],
706+ lv.chroma_dc[comp][2],
707+ lv.chroma_dc[comp][3],
708+ ];
709+ chroma_dc_transform_420(&mut dc, &e.ls, qp_c);
710+ let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
711+ let stride = plane.stride;
712+ for blk in 0..4 {
713+ let tc = lv.chroma_nz[comp][blk];
714+ if tc == 0 && dc[blk] == 0 {
715+ continue;
716+ }
717+ let mut raster = [0i32; 16];
718+ if tc > 0 {
719+ unzigzag_ac15(&lv.chroma[comp][blk], &mut raster);
720+ dequant_4x4(&mut raster, &e.ls, qp_c, true);
721+ }
722+ raster[0] = dc[blk];
723+ let mut resid = [0i32; 16];
724+ inverse_transform_4x4(&raster, &mut resid);
725+ let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
726+ add_residual_4x4(&mut plane.data, 8, stride, origin, &resid);
727+ }
728+ }
729+}
730+
731+/// The inter residual under the 8x8 transform, prediction already in the
732+/// plane: the sibling of [`code_luma_4x4`].
733+pub(super) fn code_luma_8x8(
734+ pic: &mut Picture,
735+ e: &MbEnc<'_>,
736+ w: &EncEntropy,
737+ mb_x: usize,
738+ mb_y: usize,
739+ qp: i32,
740+ lv: &mut Levels,
741+) {
742+ lv.trans8 = true;
743+ for blk8 in 0..4 {
744+ let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
745+ if code_block_8x8(pic, e, w, x, y, qp, false, &mut lv.luma8[blk8]) > 0 {
746+ lv.cbp_luma |= 1 << blk8;
747+ }
748+ }
749+}
750+
751+/// Squared error of coding `levels` as an 8x8 block, in its pixels.
752+pub(super) fn block_ssd_8x8(e: &MbEnc<'_>, source: &[i32; 64], levels: &[i32; 64], qp: i32) -> i64 {
753+ let mut raster = [0i32; 64];
754+ unzigzag_8x8(levels, &mut raster);
755+ dequant_8x8(&mut raster, &e.ls8, qp);
756+ let mut resid = [0i32; 64];
757+ inverse_transform_8x8(&raster, &mut resid);
758+ let mut ssd = 0i64;
759+ for k in 0..64 {
760+ let d = i64::from(source[k]) - i64::from(resid[k]);
761+ ssd += d * d;
762+ }
763+ ssd
764+}
765+
766+/// [`rdoq_4x4`] for the 8x8 transform: the same walk down the scan against the
767+/// CABAC coder's own price, with the 8x8 block's own contexts.
768+pub(super) fn rdoq_8x8(
769+ e: &MbEnc<'_>,
770+ w: &EncEntropy,
771+ source: &[i32; 64],
772+ levels: &mut [i32; 64],
773+ qp: i32,
774+) -> u8 {
775+ let Some(bits) = w.residual_block_8x8_cost(levels) else {
776+ return levels.iter().filter(|&&l| l != 0).count() as u8;
777+ };
778+ let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
779+ let mut cost = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
780+ for pos in (0..64).rev() {
781+ let level = levels[pos];
782+ if level == 0 {
783+ continue;
784+ }
785+ let mag = level.abs();
786+ if mag > RDOQ_MAX_LEVEL {
787+ continue;
788+ }
789+ let mut tried = mag;
790+ for candidate in [mag - 1, 0] {
791+ if candidate == tried {
792+ continue;
793+ }
794+ tried = candidate;
795+ let keep = levels[pos];
796+ levels[pos] = candidate * level.signum();
797+ let bits = w
798+ .residual_block_8x8_cost(levels)
799+ .expect("CAVLC returned early");
800+ let trial = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
801+ if trial < cost {
802+ cost = trial;
803+ } else {
804+ levels[pos] = keep;
805+ break;
806+ }
807+ }
808+ }
809+ // The whole block against nothing, on the same exact price.
810+ let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
811+ if ssd_zero as f64 <= cost {
812+ *levels = [0; 64];
813+ return 0;
814+ }
815+ levels.iter().filter(|&&l| l != 0).count() as u8
816+}
817+
818+/// Squared error of the luma macroblock against the source.
819+pub(super) fn ssd_luma(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 {
820+ let stride = pic.y.stride;
821+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
822+ let mut sum = 0i64;
823+ for row in 0..16 {
824+ let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
825+ for x in 0..16 {
826+ let d = i64::from(e.src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]);
827+ sum += d * d;
828+ }
829+ }
830+ sum
831+}
832+
833+/// Copy the luma macroblock out of the plane, and back in.
834+pub(super) fn save_luma(pic: &Picture, mb_x: usize, mb_y: usize, out: &mut [u8; 256]) {
835+ let stride = pic.y.stride;
836+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
837+ for row in 0..16 {
838+ out[row * 16..row * 16 + 16].copy_from_slice(&pic.y.data[origin + row * stride..][..16]);
839+ }
840+}
841+
842+pub(super) fn restore_luma(pic: &mut Picture, mb_x: usize, mb_y: usize, src: &[u8; 256]) {
843+ let stride = pic.y.stride;
844+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
845+ for row in 0..16 {
846+ pic.y.data[origin + row * stride..][..16].copy_from_slice(&src[row * 16..row * 16 + 16]);
847+ }
848+}
849+
850+pub(super) fn rough_intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 {
851+ let mut bits = estimate_luma_bits(lv);
852+ match i4 {
853+ Some((modes, pred)) => {
854+ bits += 6;
855+ for blk in 0..modes.len() {
856+ bits += if modes[blk] == pred[blk] { 1 } else { 4 };
857+ }
858+ }
859+ None => bits += 8,
860+ }
861+ bits
862+}
863+
864+pub(super) fn entropy_bits(w: &EncEntropy, write: impl FnOnce(&mut EncEntropy)) -> i64 {
865+ let mut probe = w.probe_copy();
866+ let before = probe.bit_len();
867+ write(&mut probe);
868+ (probe.bit_len() - before) as i64
869+}
870+
871+pub(super) fn cost_luma_nz_pair(
872+ pic: &Picture,
873+ nbr: &MbNeighbors,
874+ local: &[u8; 16],
875+ bx0: usize,
876+ by0: usize,
877+ bx: usize,
878+ by: usize,
879+) -> (Option<u8>, Option<u8>) {
880+ let w4 = pic.mb_w * 4;
881+ let left_avail = if bx.is_multiple_of(4) { nbr.a } else { true };
882+ let top_avail = if by.is_multiple_of(4) { nbr.b } else { true };
883+ let left = (left_avail && bx > 0).then(|| {
884+ if bx > bx0 {
885+ local[(by - by0) * 4 + (bx - bx0 - 1)]
886+ } else {
887+ pic.nz_y[by * w4 + bx - 1]
888+ }
889+ });
890+ let top = (top_avail && by > 0).then(|| {
891+ if by > by0 {
892+ local[(by - by0 - 1) * 4 + (bx - bx0)]
893+ } else {
894+ pic.nz_y[(by - 1) * w4 + bx]
895+ }
896+ });
897+ (left, top)
898+}
899+
900+pub(super) fn write_luma_for_cost(
901+ pic: &Picture,
902+ nbr: &MbNeighbors,
903+ w: &mut EncEntropy,
904+ mb_x: usize,
905+ mb_y: usize,
906+ lv: &Levels,
907+ is_i16: bool,
908+) {
909+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
910+ let mut nz = [0u8; 16];
911+ if is_i16 {
912+ let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx0, by0);
913+ nz[0] = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb);
914+ }
915+ if lv.trans8 {
916+ for blk8 in 0..4 {
917+ let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
918+ if lv.cbp_luma & (1 << blk8) == 0 {
919+ continue;
920+ }
921+ if w.is_cabac() {
922+ let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None);
923+ for dy in 0..2 {
924+ let base = (by - by0 + dy) * 4 + bx - bx0;
925+ nz[base..base + 2].fill(tc.min(16));
926+ }
927+ } else {
928+ for i4 in 0..4 {
929+ let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
930+ let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
931+ let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, sx, sy);
932+ let sub = sub_block_4x4(&lv.luma8[blk8], i4);
933+ nz[(sy - by0) * 4 + (sx - bx0)] =
934+ w.residual_block(&sub, BlockCat::Luma4x4, na, nb);
935+ }
936+ }
937+ }
938+ return;
939+ }
940+ for blk in 0..16 {
941+ let (dx, dy) = BLK4_POS[blk];
942+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
943+ let group = 1 << (blk >> 2);
944+ let coded_block = if is_i16 {
945+ lv.cbp_luma != 0
946+ } else {
947+ lv.cbp_luma & group != 0
948+ };
949+ if coded_block {
950+ let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx, by);
951+ let (levels, cat) = if is_i16 {
952+ (&lv.luma[blk][..15], BlockCat::LumaAc)
953+ } else {
954+ (&lv.luma[blk][..16], BlockCat::Luma4x4)
955+ };
956+ nz[(by - by0) * 4 + (bx - bx0)] = w.residual_block(levels, cat, na, nb);
957+ }
958+ }
959+}
960+
961+#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly
962+pub(super) fn cost_chroma_nz_pair(
963+ pic: &Picture,
964+ nbr: &MbNeighbors,
965+ local: &[[u8; 4]; 2],
966+ comp: usize,
967+ cx0: usize,
968+ cy0: usize,
969+ cx: usize,
970+ cy: usize,
971+) -> (Option<u8>, Option<u8>) {
972+ let w2 = pic.mb_w * 2;
973+ let left_avail = if cx.is_multiple_of(2) { nbr.a } else { true };
974+ let top_avail = if cy.is_multiple_of(2) { nbr.b } else { true };
975+ let left = (left_avail && cx > 0).then(|| {
976+ if cx > cx0 {
977+ local[comp][(cy - cy0) * 2 + (cx - cx0 - 1)]
978+ } else {
979+ pic.nz_c[comp][cy * w2 + cx - 1]
980+ }
981+ });
982+ let top = (top_avail && cy > 0).then(|| {
983+ if cy > cy0 {
984+ local[comp][(cy - cy0 - 1) * 2 + (cx - cx0)]
985+ } else {
986+ pic.nz_c[comp][(cy - 1) * w2 + cx]
987+ }
988+ });
989+ (left, top)
990+}
991+
992+pub(super) fn write_chroma_for_cost(
993+ pic: &Picture,
994+ nbr: &MbNeighbors,
995+ w: &mut EncEntropy,
996+ mb_x: usize,
997+ mb_y: usize,
998+ lv: &Levels,
999+) {
1000+ if lv.cbp_chroma != 0 {
1001+ for comp in 0..2 {
1002+ w.residual_block(
1003+ &lv.chroma_dc[comp][..4],
1004+ BlockCat::ChromaDc(comp as u8),
1005+ None,
1006+ None,
1007+ );
1008+ }
1009+ }
1010+ if lv.cbp_chroma != 2 {
1011+ return;
1012+ }
1013+ let (cx0, cy0) = (mb_x * 2, mb_y * 2);
1014+ let mut nz = [[0u8; 4]; 2];
1015+ for comp in 0..2 {
1016+ for blk in 0..4 {
1017+ let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
1018+ let (na, nb) = cost_chroma_nz_pair(pic, nbr, &nz, comp, cx0, cy0, cx, cy);
1019+ nz[comp][blk] =
1020+ w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb);
1021+ }
1022+ }
1023+}
1024+
1025+/// Eight samples widened to 16-bit lanes; the tail past the slice is zero,
1026+/// which only a caller reading past the plane could reach.
1027+#[inline]
1028+pub(super) fn load8(data: &[u8], at: usize) -> i16x8 {
1029+ let mut a = [0i16; 8];
1030+ if let Some(row) = data.get(at..at + 8) {
1031+ for (o, &b) in a.iter_mut().zip(row) {
1032+ *o = i16::from(b);
1033+ }
1034+ }
1035+ i16x8::from(a)
1036+}
1037+
1038+/// Squared error of the whole macroblock against the source, luma and chroma:
1039+/// the distortion term of the skip decision.
1040+///
1041+/// Each row's 16 (luma) or 8 (chroma) per-pixel differences fit in `i16`
1042+/// (range `-255..=255`), and `dot` widens the pairwise products to `i32`
1043+/// before summing, so this is the exact same integer value as scalar
1044+/// `i64::from(d) * i64::from(d)` per pixel, just batched a row at a time and
1045+/// summed into the `i64` accumulator in a different (still overflow-free,
1046+/// so exact) order.
1047+pub(super) fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 {
1048+ let mut sum = 0i64;
1049+ let stride = pic.y.stride;
1050+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
1051+ for row in 0..16 {
1052+ let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
1053+ let d = load16(&e.src.y, s) - load16(&pic.y.data, origin + row * stride);
1054+ sum += d
1055+ .dot(d)
1056+ .to_array()
1057+ .iter()
1058+ .map(|&v| i64::from(v))
1059+ .sum::<i64>();
1060+ }
1061+ for comp in 0..2 {
1062+ let (plane, src) = if comp == 0 {
1063+ (&pic.cb, &e.src.u)
1064+ } else {
1065+ (&pic.cr, &e.src.v)
1066+ };
1067+ let stride = plane.stride;
1068+ let origin = plane.at(mb_x * 8, mb_y * 8);
1069+ for row in 0..8 {
1070+ let s = (mb_y * 8 + row) * e.src.c_stride + mb_x * 8;
1071+ let d = load8(src, s) - load8(&plane.data, origin + row * stride);
1072+ sum += d
1073+ .dot(d)
1074+ .to_array()
1075+ .iter()
1076+ .map(|&v| i64::from(v))
1077+ .sum::<i64>();
1078+ }
1079+ }
1080+ sum
1081+}
1082+
1083+/// [`ssd_mb`] with the luma half measured after the loop filter this
1084+/// macroblock's reconstruction will get. `bs(edge, seg, vertical)` is the
1085+/// boundary strength of one 4-sample edge segment — edge 0 the macroblock
1086+/// edge, edges 1..3 the internal edges at offsets 4/8/12 — as the decoder
1087+/// will derive it, so an intra candidate passes its forced 4/3 and an inter
1088+/// candidate its own coded/motion strengths. A transform-8x8 macroblock has
1089+/// no transform edge at luma offsets 4 and 12, so those stay unfiltered,
1090+/// exactly as the decoder's `internal` gate decides it. Neighbours share
1091+/// this slice's qp with the zero offsets the encoder writes, so every edge
1092+/// is parameterised by the trial qp alone. The right and bottom edges
1093+/// belong to macroblocks coded later and cannot be known here; the aprons
1094+/// are the pre-filter neighbour samples, which is everything that exists at
1095+/// decision time. The chroma half is left pre-filter: chroma never takes
1096+/// the 8x8 transform, so it cannot separate the candidates.
1097+///
1098+/// The 8x8-vs-4x4 trials are judged by this and not by [`ssd_mb`] because the
1099+/// two candidates meet different edge sets under the same loop filter: a
1100+/// pre-filter SSD prices the 4x4 candidate as if its extra filtered edges
1101+/// cost nothing.
1102+pub(super) fn ssd_mb_deblocked(
1103+ pic: &Picture,
1104+ e: &MbEnc<'_>,
1105+ mb_x: usize,
1106+ mb_y: usize,
1107+ nbr: &MbNeighbors,
1108+ trans8: bool,
1109+ bs: impl Fn(usize, usize, bool) -> u8,
1110+) -> i64 {
1111+ // The macroblock at (A, A) plus 4-sample left and top aprons: a bS-4
1112+ // edge reads p3 and rewrites p2 on its far side.
1113+ const A: usize = 4;
1114+ const S: usize = A + 16;
1115+ let mut scratch = [0u8; S * S];
1116+ let stride = pic.y.stride;
1117+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
1118+ for row in 0..16 {
1119+ let src = origin + row * stride;
1120+ let dst = (A + row) * S + A;
1121+ scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]);
1122+ }
1123+ if nbr.a {
1124+ for row in 0..16 {
1125+ let src = origin + row * stride - A;
1126+ let dst = (A + row) * S;
1127+ scratch[dst..dst + A].copy_from_slice(&pic.y.data[src..src + A]);
1128+ }
1129+ }
1130+ if nbr.b {
1131+ for row in 0..A {
1132+ let src = origin - (A - row) * stride;
1133+ let dst = row * S + A;
1134+ scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]);
1135+ }
1136+ }
1137+ // Vertical edges left to right, then horizontal top to bottom, the order
1138+ // of 8.7.1: each edge filters what the earlier edges left behind. Each
1139+ // 4-sample segment carries its own strength, as in the decoder.
1140+ let qp = e.target_qp;
1141+ for edge in 0..4 {
1142+ let x = edge * 4;
1143+ if (edge == 0 && !nbr.a) || (trans8 && x != 0 && x != 8) {
1144+ continue;
1145+ }
1146+ for seg in 0..4 {
1147+ let s = bs(edge, seg, true);
1148+ if s == 0 {
1149+ continue;
1150+ }
1151+ let ep = edge_params(qp, 0, 0, s, 8);
1152+ for row in seg * 4..seg * 4 + 4 {
1153+ filter_luma_line(&mut scratch, 255, (A + row) * S + A + x, 1, &ep);
1154+ }
1155+ }
1156+ }
1157+ for edge in 0..4 {
1158+ let y = edge * 4;
1159+ if (edge == 0 && !nbr.b) || (trans8 && y != 0 && y != 8) {
1160+ continue;
1161+ }
1162+ let seg_bs = [
1163+ bs(edge, 0, false),
1164+ bs(edge, 1, false),
1165+ bs(edge, 2, false),
1166+ bs(edge, 3, false),
1167+ ];
1168+ if seg_bs[0] == seg_bs[1] && seg_bs[1] == seg_bs[2] && seg_bs[2] == seg_bs[3] {
1169+ if seg_bs[0] != 0 {
1170+ let ep = edge_params(qp, 0, 0, seg_bs[0], 8);
1171+ filter_luma_h_edge16(&mut scratch, (A + y) * S + A, S, &ep);
1172+ }
1173+ continue;
1174+ }
1175+ for seg in 0..4 {
1176+ if seg_bs[seg] == 0 {
1177+ continue;
1178+ }
1179+ let ep = edge_params(qp, 0, 0, seg_bs[seg], 8);
1180+ for col in seg * 4..seg * 4 + 4 {
1181+ filter_luma_line(&mut scratch, 255, (A + y) * S + A + col, S, &ep);
1182+ }
1183+ }
1184+ }
1185+ let mut sum = ssd_mb(pic, e, mb_x, mb_y) - ssd_luma(pic, e, mb_x, mb_y);
1186+ for row in 0..16 {
1187+ let src = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
1188+ for x in 0..16 {
1189+ let d = i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]);
1190+ sum += d * d;
1191+ }
1192+ }
1193+ sum
1194+}
1195+
1196+/// Boundary strengths an intra candidate forces (8.7.2.1): 4 on its
1197+/// macroblock edges, 3 on the internal luma edges.
1198+pub(super) fn intra_bs(edge: usize, _seg: usize, _vertical: bool) -> u8 {
1199+ if edge == 0 { 4 } else { 3 }
1200+}
1201+
1202+/// Rough bit cost of a macroblock's luma residual.
1203+pub(super) fn estimate_luma_bits(lv: &Levels) -> i64 {
1204+ let mut bits = 0;
1205+ if lv.trans8 {
1206+ for blk8 in 0..4 {
1207+ if lv.cbp_luma & (1 << blk8) != 0 {
1208+ // A level's position costs two more bits in a 64-coefficient
1209+ // significance map than in a 16-coefficient one; measured
1210+ // against the coded size on the text clip, without this the
1211+ // estimate undercharges Intra_8x8 by ~44 bits a macroblock.
1212+ let b = &lv.luma8[blk8];
1213+ bits += block_bits(b) + 2 * b.iter().filter(|&&l| l != 0).count() as i64;
1214+ }
1215+ }
1216+ return bits;
1217+ }
1218+ for blk in 0..16 {
1219+ if lv.cbp_luma & (1 << (blk >> 2)) != 0 {
1220+ bits += block_bits(&lv.luma[blk]);
1221+ }
1222+ }
1223+ if lv.cbp_luma == 15 {
1224+ // Intra_16x16 also carries the DC block.
1225+ bits += block_bits(&lv.dc);
1226+ }
1227+ bits
1228+}
1229+
1230+/// Bits one residual block costs, to the accuracy a mode decision needs.
1231+pub(super) fn block_bits(b: &[i32]) -> i64 {
1232+ let mut n = 0i64;
1233+ for &l in b {
1234+ if l != 0 {
1235+ n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1;
1236+ }
1237+ }
1238+ if n > 0 { n + 6 } else { 2 }
1239+}
1240+
1241+/// Rough bit cost of a macroblock's residual, for the skip decision: a level
1242+/// costs its magnitude's exp-Golomb-ish width, a coded block its token.
1243+pub(super) fn estimate_bits(lv: &Levels) -> i64 {
1244+ let mut bits = 10 + estimate_luma_bits(lv);
1245+ if lv.cbp_chroma != 0 {
1246+ for comp in 0..2 {
1247+ bits += block_bits(&lv.chroma_dc[comp][..4]);
1248+ if lv.cbp_chroma == 2 {
1249+ for blk in 0..4 {
1250+ bits += block_bits(&lv.chroma[comp][blk][..15]);
1251+ }
1252+ }
1253+ }
1254+ }
1255+ bits
1256+}
1257+
1258+/// What the residual writer needs to know about the macroblock it closes.
1259+pub(super) struct MbRecord {
1260+ pub(super) intra: bool,
1261+ pub(super) is_i16: bool,
1262+ pub(super) chroma_mode: u8,
1263+ /// The QP the residual was quantised at.
1264+ pub(super) qp: i32,
1265+}
1266+
1267+/// mb_qp_delta, the residual blocks and the per-macroblock metadata: the
1268+/// writing half of [`crate::decoder::finish_macroblock`].
1269+pub(super) fn finish_mb(
1270+ pic: &mut Picture,
1271+ e: &mut MbEnc<'_>,
1272+ w: &mut EncEntropy,
1273+ mb_addr: usize,
1274+ nbr: &MbNeighbors,
1275+ lv: &Levels,
1276+ m: MbRecord,
1277+) {
1278+ let mb_x = mb_addr % pic.mb_w;
1279+ let mb_y = mb_addr / pic.mb_w;
1280+ let w4 = pic.mb_w * 4;
1281+ let w2 = pic.mb_w * 2;
1282+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
1283+ let (cx0, cy0) = (mb_x * 2, mb_y * 2);
1284+
1285+ let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || m.is_i16;
1286+ let qp_y = if coded {
1287+ let delta = m.qp - e.qp;
1288+ w.mb_qp_delta(delta);
1289+ e.qp_delta_inc = u8::from(delta != 0);
1290+ e.qp = m.qp;
1291+ m.qp
1292+ } else {
1293+ // No residual: the QP prediction chain is untouched (7.4.5), and the
1294+ // deblocking filter uses the chain value.
1295+ e.qp_delta_inc = 0;
1296+ e.qp
1297+ };
1298+ pic.mb_qp[mb_addr] = qp_y as i8;
1299+ pic.mb_flags[mb_addr] = FLAG_DECODED
1300+ | if m.is_i16 { FLAG_I16 } else { 0 }
1301+ | if m.intra { 0 } else { FLAG_INTER }
1302+ // The flag only reaches the stream when the decoder reads it (7.3.5).
1303+ | if lv.trans8 && (m.intra || lv.cbp_luma != 0) {
1304+ FLAG_TRANS8X8
1305+ } else {
1306+ 0
1307+ }
1308+ | if m.intra && m.chroma_mode != 0 {
1309+ FLAG_CHROMA_PRED
1310+ } else {
1311+ 0
1312+ };
1313+ pic.mb_cbp[mb_addr] = lv.cbp_luma | (lv.cbp_chroma << 4);
1314+ pic.mb_slice[mb_addr] = e.slice_id;
1315+ pic.decoded_mbs += 1;
1316+
1317+ let mut dc_cbf = 0u8;
1318+ // Luma DC (Intra_16x16 only), then the luma blocks in Z-order.
1319+ if m.is_i16 {
1320+ let (na, nb) = luma_nz_pair(pic, nbr, bx0, by0);
1321+ let tc = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb);
1322+ dc_cbf |= u8::from(tc != 0);
1323+ }
1324+ if lv.trans8 {
1325+ // The decoder's 8x8 branch: CABAC codes one cat-5 block and reports
1326+ // its count in every 4x4 slot; CAVLC codes four interleaved 4x4
1327+ // blocks, each with its own nC and count.
1328+ for blk8 in 0..4 {
1329+ let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
1330+ if lv.cbp_luma & (1 << blk8) == 0 {
1331+ for dy in 0..2 {
1332+ let base = (by + dy) * w4 + bx;
1333+ pic.nz_y[base..base + 2].fill(0);
1334+ }
1335+ } else if w.is_cabac() {
1336+ let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None);
1337+ for dy in 0..2 {
1338+ let base = (by + dy) * w4 + bx;
1339+ pic.nz_y[base..base + 2].fill(tc.min(16));
1340+ }
1341+ } else {
1342+ for i4 in 0..4 {
1343+ let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
1344+ let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
1345+ let (na, nb) = luma_nz_pair(pic, nbr, sx, sy);
1346+ let sub = sub_block_4x4(&lv.luma8[blk8], i4);
1347+ pic.nz_y[sy * w4 + sx] = w.residual_block(&sub, BlockCat::Luma4x4, na, nb);
1348+ }
1349+ }
1350+ }
1351+ }
1352+ for blk in 0..16 {
1353+ if lv.trans8 {
1354+ break;
1355+ }
1356+ let (dx, dy) = BLK4_POS[blk];
1357+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
1358+ let group = 1 << (blk >> 2);
1359+ let coded_block = if m.is_i16 {
1360+ lv.cbp_luma != 0
1361+ } else {
1362+ lv.cbp_luma & group != 0
1363+ };
1364+ let tc = if coded_block {
1365+ let (na, nb) = luma_nz_pair(pic, nbr, bx, by);
1366+ let (levels, cat) = if m.is_i16 {
1367+ (&lv.luma[blk][..15], BlockCat::LumaAc)
1368+ } else {
1369+ (&lv.luma[blk][..16], BlockCat::Luma4x4)
1370+ };
1371+ w.residual_block(levels, cat, na, nb)
1372+ } else {
1373+ 0
1374+ };
1375+ pic.nz_y[by * w4 + bx] = tc;
1376+ }
1377+ // Chroma DC then chroma AC, in bitstream order.
1378+ if lv.cbp_chroma != 0 {
1379+ for comp in 0..2 {
1380+ let tc = w.residual_block(
1381+ &lv.chroma_dc[comp][..4],
1382+ BlockCat::ChromaDc(comp as u8),
1383+ None,
1384+ None,
1385+ );
1386+ dc_cbf |= u8::from(tc != 0) << (1 + comp);
1387+ }
1388+ }
1389+ for comp in 0..2 {
1390+ for blk in 0..4 {
1391+ let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
1392+ let tc = if lv.cbp_chroma == 2 {
1393+ let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy);
1394+ w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb)
1395+ } else {
1396+ 0
1397+ };
1398+ pic.nz_c[comp][cy * w2 + cx] = tc;
1399+ }
1400+ }
1401+ pic.mb_dc_cbf[mb_addr] = dc_cbf;
1402+}
1403+