forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mb.rs3844 lines, 137.9 KiBHistoryRawDownload
1//! Macroblock coding: mode decision, quantisation, reconstruction and syntax.
2//!
3//! Reconstruction here is the decoder's own: prediction comes from
4//! [`crate::pred`] and [`crate::inter`], dequantisation and the inverse
5//! transforms from [`crate::transform`], and the metadata every block writes
6//! into [`crate::dpb::Picture`] is what the decoder writes at the same point.
7//! The encoder therefore cannot drift from the decoder by construction — the
8//! only thing it adds is the *choice* of mode and the forward quantiser.
9
10// A block index is simultaneously a bitstream position, a geometry key
11// (BLK4_POS) and a grid coordinate here, exactly as in the decoder; iterating
12// the arrays instead would hide which geometry each loop names.
13#![allow(clippy::needless_range_loop)]
14
15use ec_h264_syntax::SliceType;
16use wide::{i16x8, i16x16};
17
18use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line};
19use crate::decoder::{
20 MbNeighbors, chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors,
21};
22use crate::dpb::{BLK_SKIP, Picture, Plane8};
23use crate::entropy::{
24 BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8,
25 MbCtx, MbInfo,
26};
27use crate::inter::{Put, RefPlane, integer_origin, mc_chroma, mc_luma};
28use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd};
29use crate::pred::{
30 PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16,
31 pred_chroma_8x8,
32};
33use crate::tables::{BLK4_POS, CHROMA_QP};
34use crate::transform::{
35 LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8,
36 inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8,
37 unzigzag_ac15,
38};
39
40use 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};
44use super::timing::mb_timed;
45use super::{
46 entropy::{EncEntropy, sub_block_4x4},
47 lambda_ssd,
48};
49
50/// Speed/quality ladder. Two rungs, because the two the incumbent exposed are
51/// the two edith actually picks between.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
53pub enum Preset {
54 /// Diamond motion search, 16x16 partitions.
55 #[default]
56 Fast,
57 /// Wider search with a hexagon refinement and half-macroblock partitions.
58 Balanced,
59}
60
61/// Speed settings of `Preset::Fast`. The defaults are what the encoder ships;
62/// `EC_H264_INTRA_GATE` and `EC_H264_SKIP_I8` override them for sweeps (see
63/// `fast_knobs` in `mod.rs`). Balanced ignores all of them.
64#[derive(Debug, Clone, Copy)]
65pub(crate) struct FastKnobs {
66 /// A P macroblock skips its intra branch when the best inter SATD is at
67 /// most this fraction of the Intra_16x16 SATD. Zero keeps the branch.
68 pub intra_gate: f64,
69 /// Intra_8x8 is not tried; Intra_4x4 and Intra_16x16 are still coded.
70 pub skip_i8: bool,
71 /// Sub-sample refinement: 0 none, 1 half-sample ring only, 2 half and quarter.
72 pub me_sub: u8,
73 /// Sub-sample candidates are ranked on SATD (true) or SAD (false).
74 pub me_satd: bool,
75 /// Intra_8x8 is skipped inside P pictures only.
76 pub p_skip_i8: bool,
77 /// Inter transform size: 0 codes both and keeps the cheaper, 1 only 8x8, 2 only 4x4.
78 pub inter_tx: u8,
79 /// In P pictures the gate is tried against the DC mode's SATD before the
80 /// other Intra_16x16 modes are costed.
81 pub lazy_i16: bool,
82 /// Early P_Skip threshold in percent of the quantiser step; zero is off.
83 pub early_skip: u32,
84 /// With `inter_tx` 3: the 8x8 transform is tried only when the 4x4 coding
85 /// left at most this many levels in the macroblock.
86 pub tx8_nz_limit: u32,
87}
88
89impl Default for FastKnobs {
90 fn default() -> FastKnobs {
91 FastKnobs {
92 intra_gate: 2.0,
93 skip_i8: false,
94 me_sub: 1,
95 me_satd: false,
96 p_skip_i8: true,
97 inter_tx: 3,
98 lazy_i16: true,
99 early_skip: 8,
100 tx8_nz_limit: 16,
101 }
102 }
103}
104
105/// Source planes of one picture, edge-padded out to whole macroblocks.
106#[derive(Default)]
107pub(crate) struct Source {
108 pub y: Vec<u8>,
109 pub u: Vec<u8>,
110 pub v: Vec<u8>,
111 /// Luma row pitch, equal to the coded width.
112 pub stride: usize,
113 /// Chroma row pitch.
114 pub c_stride: usize,
115}
116
117/// Everything one macroblock's coding reads and updates.
118pub(crate) struct MbEnc<'a> {
119 pub src: &'a Source,
120 /// The single list-0 reference, absent in an I slice.
121 pub reference: Option<&'a Picture>,
122 pub slice_type: SliceType,
123 pub slice_id: u16,
124 /// QPY of the previous macroblock: the prediction chain of 7.4.5.
125 pub qp: i32,
126 /// What rate control wants this macroblock coded at.
127 pub target_qp: i32,
128 /// Lagrangian multiplier; it is in the squared-error domain when 8x8
129 /// transform decisions are enabled.
130 pub lambda: f64,
131 /// Whether `lambda` is the standard squared-error multiplier.
132 pub lambda_standard: bool,
133 /// Extra rate saving an 8x8 trial must buy before it may replace 4x4.
134 pub t8x8_margin_bits: f64,
135 pub preset: Preset,
136 /// Fast-preset speed knobs (see [`FastKnobs`]).
137 pub fast: FastKnobs,
138 /// The PPS carries transform_8x8_mode_flag: transform_size_8x8_flag must
139 /// be written for every eligible macroblock (7.3.5).
140 pub transform_8x8: bool,
141 /// Whether intra macroblocks may select 8x8. The PPS can remain enabled
142 /// while an ablation measures the classes independently.
143 pub transform_8x8_intra: bool,
144 /// Whether inter macroblocks may select 8x8.
145 pub transform_8x8_inter: bool,
146 /// Whether the ablation restricts 8x8 eligibility to even macroblock
147 /// rows; odd rows then code exactly as they would with 8x8 disabled.
148 pub transform_8x8_roweven: bool,
149 pub ls: LevelScale4x4,
150 pub ls8: LevelScale8x8,
151 /// Neighbourhood of the macroblock being written (CABAC).
152 pub mb_ctx: MbCtx,
153 /// The picture's `chroma_qp_index_offset`, chosen from the source in
154 /// `Encoder::chroma_qp_offset_for_source`.
155 pub cqo: i32,
156 /// ctxIdxInc for this macroblock's mb_skip_flag.
157 pub skip_inc: usize,
158 /// `qp_delta_inc` of 9.3.3.1.1.5: whether the previous macroblock in this
159 /// slice carried a non-zero mb_qp_delta.
160 pub qp_delta_inc: u8,
161}
162
163impl MbEnc<'_> {
164 /// Intra 8x8 eligibility of macroblock row `mb_y`.
165 fn t8x8_intra(&self, mb_y: usize) -> bool {
166 self.transform_8x8_intra && (mb_y.is_multiple_of(2) || !self.transform_8x8_roweven)
167 }
168
169 /// Inter 8x8 eligibility of macroblock row `mb_y`.
170 fn t8x8_inter(&self, mb_y: usize) -> bool {
171 self.transform_8x8_inter && (mb_y.is_multiple_of(2) || !self.transform_8x8_roweven)
172 }
173}
174
175/// Quantised levels of one macroblock, scan order per block.
176#[derive(Clone)]
177struct Levels {
178 /// Luma AC/4x4 blocks in Z-order; only `[..15]` is used under Intra_16x16.
179 luma: [[i32; 16]; 16],
180 /// Non-zero count per luma block, Z-order.
181 luma_nz: [u8; 16],
182 /// transform_size_8x8_flag: the luma residual is `luma8`, not `luma`.
183 trans8: bool,
184 /// Luma 8x8 blocks in 8x8 zig-zag order.
185 luma8: [[i32; 64]; 4],
186 /// Intra_16x16 luma DC, scan order.
187 dc: [i32; 16],
188 /// Chroma DC per component.
189 chroma_dc: [[i32; 16]; 2],
190 /// Chroma AC per component and block.
191 chroma: [[[i32; 16]; 4]; 2],
192 chroma_nz: [[u8; 4]; 2],
193 cbp_luma: u8,
194 cbp_chroma: u8,
195}
196
197impl Default for Levels {
198 fn default() -> Levels {
199 Levels {
200 luma: [[0; 16]; 16],
201 luma_nz: [0; 16],
202 trans8: false,
203 luma8: [[0; 64]; 4],
204 dc: [0; 16],
205 chroma_dc: [[0; 16]; 2],
206 chroma: [[[0; 16]; 4]; 2],
207 chroma_nz: [[0; 4]; 2],
208 cbp_luma: 0,
209 cbp_chroma: 0,
210 }
211 }
212}
213
214/// 4x4 Hadamard sum of absolute transformed differences between the source at
215/// `(sx, sy)` and a 4x4 prediction.
216// Tried (lane-h264perf r2): a transpose-based i32x4 vectorization of this
217// butterfly, bit-identical, but cycles-flat-to-worse under perf stat
218// (22.958B -> 23.042B cycles over 10 reps despite fewer instructions
219// retired) -- reverted, dead end; see ledger.
220fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 {
221 // Differences are at most 255 in magnitude and the 2-D Hadamard sums 16 of
222 // them, so every intermediate fits an i16.
223 let mut d = [[0i16; 4]; 4];
224 for (y, row) in d.iter_mut().enumerate() {
225 let s = &src[(sy + y) * sstride + sx..][..4];
226 let p = &pred[y * pstride..][..4];
227 for x in 0..4 {
228 row[x] = i16::from(s[x]) - i16::from(p[x]);
229 }
230 }
231 // Vertical butterflies, lane-wise over the four columns.
232 let mut v = [[0i16; 4]; 4];
233 for x in 0..4 {
234 let (a, b, c, e) = (d[0][x], d[1][x], d[2][x], d[3][x]);
235 let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e);
236 v[0][x] = s0 + s1;
237 v[1][x] = s0 - s1;
238 v[2][x] = s2 + s3;
239 v[3][x] = s2 - s3;
240 }
241 // Horizontal butterflies per row, then the absolute sum.
242 let mut sum = 0i32;
243 for row in &v {
244 let (a, b, c, e) = (row[0], row[1], row[2], row[3]);
245 let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e);
246 sum += i32::from((s0 + s1).abs())
247 + i32::from((s0 - s1).abs())
248 + i32::from((s2 + s3).abs())
249 + i32::from((s2 - s3).abs());
250 }
251 (sum + 2) >> 2
252}
253
254/// SATD of a whole 16x16 luma macroblock against the prediction already in the
255/// picture plane.
256fn satd16(
257 src: &[u8],
258 sstride: usize,
259 sx: usize,
260 sy: usize,
261 plane: &[u8],
262 pstride: usize,
263 po: usize,
264) -> i32 {
265 satd_block(src, sstride, sx, sy, plane, pstride, po, 16, 16)
266}
267
268/// The same over a `w` x `h` partition.
269#[allow(clippy::too_many_arguments)]
270fn satd_block(
271 src: &[u8],
272 sstride: usize,
273 sx: usize,
274 sy: usize,
275 plane: &[u8],
276 pstride: usize,
277 po: usize,
278 w: usize,
279 h: usize,
280) -> i32 {
281 let mut sum = 0;
282 for by in 0..h / 4 {
283 for bx in 0..w / 4 {
284 sum += satd4(
285 src,
286 sstride,
287 sx + bx * 4,
288 sy + by * 4,
289 &plane[po + by * 4 * pstride + bx * 4..],
290 pstride,
291 );
292 }
293 }
294 sum
295}
296
297/// Sum of absolute differences of a `w` x `h` block against a prediction with
298/// its own pitch. This is the motion search's inner loop and nothing else in
299/// the encoder is called as often, so a full-width row goes through one vector.
300#[allow(clippy::too_many_arguments)]
301fn sad(
302 src: &[u8],
303 sstride: usize,
304 sx: usize,
305 sy: usize,
306 pred: &[u8],
307 pstride: usize,
308 w: usize,
309 h: usize,
310) -> i32 {
311 if w == 16 {
312 let mut acc = i16x16::ZERO;
313 for y in 0..h {
314 let a = load16(src, (sy + y) * sstride + sx);
315 let b = load16(pred, y * pstride);
316 acc += (a - b).abs();
317 }
318 return acc.to_array().iter().map(|&v| i32::from(v)).sum();
319 }
320 let mut sum = 0;
321 for y in 0..h {
322 let s = &src[(sy + y) * sstride + sx..];
323 let p = &pred[y * pstride..];
324 for x in 0..w {
325 sum += (i32::from(s[x]) - i32::from(p[x])).abs();
326 }
327 }
328 sum
329}
330
331/// Sum and maximum of the absolute differences between the 16x16 source block
332/// at `(sx, sy)` and a 16-wide prediction.
333fn sad_max16(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8]) -> (i32, i32) {
334 let mut acc = i16x16::ZERO;
335 let mut mx = i16x16::ZERO;
336 for y in 0..16 {
337 let a = load16(src, (sy + y) * sstride + sx);
338 let b = load16(pred, y * 16);
339 let d = (a - b).abs();
340 acc += d;
341 mx = mx.max(d);
342 }
343 let sum = acc.to_array().iter().map(|&v| i32::from(v)).sum();
344 let max = mx
345 .to_array()
346 .iter()
347 .map(|&v| i32::from(v))
348 .max()
349 .unwrap_or(0);
350 (sum, max)
351}
352
353/// Sixteen samples widened to 16-bit lanes; the tail past the slice is zero,
354/// which only a caller reading past the plane could reach.
355#[inline]
356fn load16(data: &[u8], at: usize) -> i16x16 {
357 let mut a = [0i16; 16];
358 if let Some(row) = data.get(at..at + 16) {
359 for (o, &b) in a.iter_mut().zip(row) {
360 *o = i16::from(b);
361 }
362 }
363 i16x16::from(a)
364}
365
366/// Bits an exp-Golomb `se(v)` costs, for the motion-vector cost term.
367#[inline]
368pub(crate) fn se_bits(v: i32) -> i32 {
369 let k = if v > 0 { 2 * v - 1 } else { -2 * v } as u32;
370 (32 - (k + 1).leading_zeros()) as i32 * 2 - 1
371}
372
373/// Chroma QP of a luma QP under the picture's `chroma_qp_index_offset`.
374#[inline]
375fn chroma_qp(qp: i32, cqo: i32) -> i32 {
376 i32::from(CHROMA_QP[(qp + cqo).clamp(0, 51) as usize])
377}
378
379/// Which intra 4x4 modes the available neighbours allow (8.3.1.2).
380fn modes_allowed(have_top: bool, have_left: bool, have_tl: bool) -> [bool; 9] {
381 [
382 have_top,
383 have_left,
384 true,
385 have_top,
386 have_top && have_left && have_tl,
387 have_top && have_left && have_tl,
388 have_top && have_left && have_tl,
389 have_top,
390 have_left,
391 ]
392}
393
394#[inline]
395fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 {
396 (motion_lambda(e) * bits).round() as i32
397}
398
399/// The multiplier `motion_rate` applies, for loops that price many vectors.
400#[inline]
401fn motion_lambda(e: &MbEnc<'_>) -> f64 {
402 if e.lambda_standard {
403 e.lambda.sqrt()
404 } else {
405 e.lambda
406 }
407}
408
409/// Everything one macroblock's coding writes into the picture, kept so that a
410/// branch can be coded, measured and undone.
411struct MbState {
412 y: [u8; 256],
413 c: [[u8; 64]; 2],
414 nz_y: [u8; 16],
415 nz_c: [[u8; 4]; 2],
416 i4_modes: [u8; 16],
417 mv: [[[i16; 2]; 2]; 16],
418 ref_idx: [[i8; 2]; 16],
419 ref_id: [[i32; 2]; 16],
420 mvd_abs: [[u8; 4]; 16],
421 blk: [u8; 16],
422 mb_qp: i8,
423 mb_flags: u8,
424 mb_cbp: u8,
425 mb_dc_cbf: u8,
426 mb_slice: u16,
427 decoded_mbs: usize,
428 qp: i32,
429 qp_delta_inc: u8,
430}
431
432/// Copy `mb`'s samples out of `plane`, `n` by `n`.
433fn save_plane(plane: &Plane8, x0: usize, y0: usize, out: &mut [u8], n: usize) {
434 for row in 0..n {
435 let o = plane.at(x0, y0 + row);
436 out[row * n..(row + 1) * n].copy_from_slice(&plane.data[o..o + n]);
437 }
438}
439
440fn load_plane(plane: &mut Plane8, x0: usize, y0: usize, src: &[u8], n: usize) {
441 for row in 0..n {
442 let o = plane.at(x0, y0 + row);
443 plane.data[o..o + n].copy_from_slice(&src[row * n..(row + 1) * n]);
444 }
445}
446
447fn save_mb_state(pic: &Picture, e: &MbEnc<'_>, mb_addr: usize) -> MbState {
448 let (mb_x, mb_y) = (mb_addr % pic.mb_w, mb_addr / pic.mb_w);
449 let (w4, w2) = (pic.mb_w * 4, pic.mb_w * 2);
450 let mut st = MbState {
451 y: [0; 256],
452 c: [[0; 64]; 2],
453 nz_y: [0; 16],
454 nz_c: [[0; 4]; 2],
455 i4_modes: [0; 16],
456 mv: [[[0; 2]; 2]; 16],
457 ref_idx: [[0; 2]; 16],
458 ref_id: [[0; 2]; 16],
459 mvd_abs: [[0; 4]; 16],
460 blk: [0; 16],
461 mb_qp: pic.mb_qp[mb_addr],
462 mb_flags: pic.mb_flags[mb_addr],
463 mb_cbp: pic.mb_cbp[mb_addr],
464 mb_dc_cbf: pic.mb_dc_cbf[mb_addr],
465 mb_slice: pic.mb_slice[mb_addr],
466 decoded_mbs: pic.decoded_mbs,
467 qp: e.qp,
468 qp_delta_inc: e.qp_delta_inc,
469 };
470 save_plane(&pic.y, mb_x * 16, mb_y * 16, &mut st.y, 16);
471 save_plane(&pic.cb, mb_x * 8, mb_y * 8, &mut st.c[0], 8);
472 save_plane(&pic.cr, mb_x * 8, mb_y * 8, &mut st.c[1], 8);
473 for row in 0..4 {
474 let b = (mb_y * 4 + row) * w4 + mb_x * 4;
475 for col in 0..4 {
476 let (i, j) = (row * 4 + col, b + col);
477 st.nz_y[i] = pic.nz_y[j];
478 st.i4_modes[i] = pic.i4_modes[j];
479 st.mv[i] = pic.mv[j];
480 st.ref_idx[i] = pic.ref_idx[j];
481 st.ref_id[i] = pic.ref_id[j];
482 st.mvd_abs[i] = pic.mvd_abs[j];
483 st.blk[i] = pic.blk[j];
484 }
485 }
486 for comp in 0..2 {
487 for row in 0..2 {
488 let b = (mb_y * 2 + row) * w2 + mb_x * 2;
489 st.nz_c[comp][row * 2..row * 2 + 2].copy_from_slice(&pic.nz_c[comp][b..b + 2]);
490 }
491 }
492 st
493}
494
495fn load_mb_state(pic: &mut Picture, e: &mut MbEnc<'_>, mb_addr: usize, st: &MbState) {
496 let (mb_x, mb_y) = (mb_addr % pic.mb_w, mb_addr / pic.mb_w);
497 let (w4, w2) = (pic.mb_w * 4, pic.mb_w * 2);
498 load_plane(&mut pic.y, mb_x * 16, mb_y * 16, &st.y, 16);
499 load_plane(&mut pic.cb, mb_x * 8, mb_y * 8, &st.c[0], 8);
500 load_plane(&mut pic.cr, mb_x * 8, mb_y * 8, &st.c[1], 8);
501 for row in 0..4 {
502 let b = (mb_y * 4 + row) * w4 + mb_x * 4;
503 for col in 0..4 {
504 let (i, j) = (row * 4 + col, b + col);
505 pic.nz_y[j] = st.nz_y[i];
506 pic.i4_modes[j] = st.i4_modes[i];
507 pic.mv[j] = st.mv[i];
508 pic.ref_idx[j] = st.ref_idx[i];
509 pic.ref_id[j] = st.ref_id[i];
510 pic.mvd_abs[j] = st.mvd_abs[i];
511 pic.blk[j] = st.blk[i];
512 }
513 }
514 for comp in 0..2 {
515 for row in 0..2 {
516 let b = (mb_y * 2 + row) * w2 + mb_x * 2;
517 pic.nz_c[comp][b..b + 2].copy_from_slice(&st.nz_c[comp][row * 2..row * 2 + 2]);
518 }
519 }
520 pic.mb_qp[mb_addr] = st.mb_qp;
521 pic.mb_flags[mb_addr] = st.mb_flags;
522 pic.mb_cbp[mb_addr] = st.mb_cbp;
523 pic.mb_dc_cbf[mb_addr] = st.mb_dc_cbf;
524 pic.mb_slice[mb_addr] = st.mb_slice;
525 pic.decoded_mbs = st.decoded_mbs;
526 e.qp = st.qp;
527 e.qp_delta_inc = st.qp_delta_inc;
528}
529
530/// Code one macroblock: decide its mode, reconstruct it into `pic` and write
531/// its syntax into `w`.
532pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy, mb_addr: usize) {
533 let mb_x = mb_addr % pic.mb_w;
534 let mb_y = mb_addr / pic.mb_w;
535 let nbr = mb_neighbors(pic, mb_x, mb_y, e.slice_id);
536 // The neighbourhood CABAC reads, captured before anything is written.
537 let info = |addr: usize| MbInfo {
538 flags: pic.mb_flags[addr],
539 cbp: pic.mb_cbp[addr],
540 dc_cbf: pic.mb_dc_cbf[addr],
541 };
542 e.mb_ctx = MbCtx {
543 a: nbr.a.then(|| info(mb_addr - 1)),
544 b: nbr.b.then(|| info(mb_addr - pic.mb_w)),
545 qp_delta_inc: e.qp_delta_inc,
546 field: false,
547 mbaff_a: None,
548 };
549 // ctxIdxInc for mb_skip_flag (9.3.3.1.1.1).
550 e.skip_inc = usize::from(nbr.a && pic.mb_flags[mb_addr - 1] & FLAG_SKIP == 0)
551 + usize::from(nbr.b && pic.mb_flags[mb_addr - pic.mb_w] & FLAG_SKIP == 0);
552
553 // Clear this macroblock's motion state, as the decoder does before parsing.
554 let w4 = pic.mb_w * 4;
555 for py in 0..4 {
556 let base = (mb_y * 4 + py) * w4 + mb_x * 4;
557 for idx in base..base + 4 {
558 pic.mv[idx] = [[0; 2]; 2];
559 pic.ref_idx[idx] = [-1; 2];
560 pic.ref_id[idx] = [-1; 2];
561 pic.mvd_abs[idx] = [0; 4];
562 pic.blk[idx] = 0;
563 }
564 }
565
566 let mut inter: Option<Vec<InterChoice>> = None;
567 if e.slice_type == SliceType::P {
568 inter = Some(mb_timed!(0, choose_inter(pic, e, mb_x, mb_y)));
569 }
570
571 // Intra against inter is decided on real coded cost: both branches are
572 // coded, and the one with the smaller squared error plus lambda times its
573 // actual bits is kept. The prediction-domain comparison this replaced
574 // compared an intra SATD, discounted by a constant, against a coded inter
575 // cost, and paid for the intra side's signalling with a guessed twelve
576 // bits -- three approximations where the encoder can simply measure. On
577 // the library, BD-PSNR against x264 at GOP 10 over QP 22/26/30/34:
578 //
579 // film 3840x1608 screen 2560x1440 synthetic
580 // SATD and guess -1.043 -1.064 -4.449
581 // coded cost -0.728 -0.500 -4.523
582 //
583 // and the bit premium over x264 falls with it: on the screen capture from
584 // +34.4% to +17.2% at QP 22. The synthetic clip loses 0.074 dB; it is
585 // 352x288 of moving synthetic shapes and it prefers a heavier rate term
586 // (scaling lambda by 1.4 reads -4.310 there and -0.744/-0.477 on the two
587 // real clips), which is not a reason to put an unmeasured constant in
588 // front of the standard multiplier.
589 //
590 // The second encode costs about two seconds on a run that took 28.8: each
591 // P macroblock is coded twice, and the loser's reconstruction and entropy
592 // writer are thrown away.
593 // In a P picture at Fast the gate only needs a cheap intra estimate. The
594 // DC mode's SATD is an upper bound on the best mode's, so when the inter
595 // candidate already beats the gate against it the other three modes are
596 // never costed.
597 let gate = e.preset == Preset::Fast && e.fast.intra_gate > 0.0;
598 let intra_cost = match inter.as_ref() {
599 Some(c) if gate && e.fast.lazy_i16 => {
600 let dc = mb_timed!(1, intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2]));
601 if f64::from(c[0].satd) <= e.fast.intra_gate * f64::from(dc.satd) {
602 dc
603 } else {
604 mb_timed!(1, intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2, 0, 1, 3]))
605 }
606 }
607 _ => mb_timed!(1, intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2, 0, 1, 3])),
608 };
609 let Some(choices) = inter else {
610 mb_timed!(3, encode_intra_mb(pic, e, w, mb_addr, nbr, intra_cost));
611 return;
612 };
613
614 let lambda = if e.lambda_standard {
615 e.lambda
616 } else {
617 lambda_ssd(e.qp)
618 };
619 let gated = e.preset == Preset::Fast
620 && e.fast.intra_gate > 0.0
621 && f64::from(choices[0].satd) <= e.fast.intra_gate * f64::from(intra_cost.satd);
622 if gated {
623 // Inter only and one candidate at Fast: nothing is compared, so the
624 // macroblock is coded straight into the picture and the writer.
625 mb_timed!(2, encode_inter_mb(pic, e, w, mb_addr, nbr, choices[0]));
626 return;
627 }
628 let before = mb_timed!(4, save_mb_state(pic, e, mb_addr));
629 // The shape and the skip flag are ranked the same way intra and inter are:
630 // by coding each candidate and measuring it. The SATD total that ordered
631 // them inside the search is a prediction-domain estimate that never sees
632 // the residual it causes, which is exactly the step x264 takes between
633 // subme 4 and subme 6 -- the 0.29 dB the feature ladder localised there.
634 let rd_cands = if e.preset == Preset::Balanced {
635 choices.len().min(SHAPE_RD_CANDIDATES)
636 } else {
637 1
638 };
639 let mut best_inter: Option<(f64, MbState, EncEntropy)> = None;
640 for &choice in &choices[..rd_cands.max(1)] {
641 mb_timed!(4, load_mb_state(pic, e, mb_addr, &before));
642 let mut w_c = mb_timed!(5, w.probe_copy());
643 let start = w_c.bit_len();
644 mb_timed!(2, encode_inter_mb(pic, e, &mut w_c, mb_addr, nbr, choice));
645 let bits = (w_c.bit_len() - start) as f64;
646 let rd = ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda * bits;
647 if best_inter.as_ref().is_none_or(|b| rd < b.0) {
648 best_inter = Some((rd, mb_timed!(4, save_mb_state(pic, e, mb_addr)), w_c));
649 }
650 }
651 let (inter_rd, after_inter, w_inter) = best_inter.expect("at least one inter candidate");
652 mb_timed!(4, load_mb_state(pic, e, mb_addr, &before));
653
654 let mut w_intra = mb_timed!(5, w.probe_copy());
655 let intra_bits = {
656 let start = w_intra.bit_len();
657 mb_timed!(
658 3,
659 encode_intra_mb(pic, e, &mut w_intra, mb_addr, nbr, intra_cost)
660 );
661 (w_intra.bit_len() - start) as f64
662 };
663 let intra_rd = ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda * intra_bits;
664
665 if intra_rd < inter_rd {
666 w.adopt(w_intra);
667 } else {
668 mb_timed!(4, load_mb_state(pic, e, mb_addr, &after_inter));
669 w.adopt(w_inter);
670 }
671}
672
673/// The Intra_16x16 mode this macroblock would use. Intra_16x16 against
674/// Intra_4x4 is decided later, on real rate and real distortion (see
675/// [`encode_intra_mb`]).
676struct IntraCost {
677 i16_mode: u8,
678 /// SATD of the Intra_16x16 mode above: the cheap intra estimate that
679 /// `Preset::Fast` gates the full intra branch on.
680 satd: i32,
681 /// True when Intra_4x4 may be used at all for this picture and preset.
682 allow_i4: bool,
683}
684
685/// Best Intra_16x16 mode by SATD, leaving nothing behind in the plane that a
686/// later branch does not overwrite.
687fn intra_pre_cost(
688 pic: &mut Picture,
689 e: &MbEnc<'_>,
690 nbr: &MbNeighbors,
691 mb_x: usize,
692 mb_y: usize,
693 modes: &[u8],
694) -> IntraCost {
695 let (sx, sy) = (mb_x * 16, mb_y * 16);
696 let stride = pic.y.stride;
697 let origin = pic.y.at(sx, sy);
698 let mut best = (i32::MAX, 2u8);
699 for &mode in modes {
700 let ok = match mode {
701 0 => nbr.b,
702 1 => nbr.a,
703 3 => nbr.a && nbr.b && nbr.d,
704 _ => true,
705 };
706 if !ok {
707 continue;
708 }
709 let mut win = PlaneWindow {
710 data: &mut pic.y.data,
711 stride,
712 origin,
713 };
714 pred_16x16(mode, 8, &mut win, nbr.b, nbr.a);
715 let cost = satd16(&e.src.y, e.src.stride, sx, sy, &pic.y.data, stride, origin);
716 if cost < best.0 {
717 best = (cost, mode);
718 }
719 }
720 IntraCost {
721 i16_mode: best.1,
722 satd: best.0,
723 // Intra_4x4 is tried in P pictures too, at every preset. Re-measured
724 // once the intra-versus-inter decision became a real one (BD-PSNR
725 // against x264, GOP 10, QP 22/26/30/34): restricting it to I pictures
726 // reads -1.613 dB on the film clip and -0.508 on the screen capture,
727 // where allowing it everywhere reads -0.728 and -0.500. It stays on
728 // everywhere. Under the old prediction-domain decision the screen
729 // capture preferred the restriction by a third of a dB; coding both
730 // branches for real removed that disagreement.
731 allow_i4: true,
732 }
733}
734
735/// How much of a motion vector's signalling the search pays for. Half, which
736/// is not the true rate: swept on consecutive pictures (BD-PSNR against x264,
737/// GOP 10), 0.25/0.5/1.0/2.0 read -1.074/-1.043/-1.225/-1.618 on the film clip
738/// and -0.676/-0.661/-0.795/-1.201 on the screen capture. Charging the whole
739/// rate is worse than charging half on both contents, and the curve is flat
740/// below a half and falls away above it.
741const MV_BITS_WEIGHT: f64 = 0.5;
742
743/// Cap on whole-sample walk iterations per partition at `Preset::Fast`.
744const FAST_ME_PASSES: usize = 3;
745
746/// The offsets the whole-sample search steps through, in units of the current
747/// step size.
748///
749/// A square, not a cross. The cross this used to be could only walk along an
750/// axis, so a diagonally moving macroblock had to be reached in two steps
751/// through a point that was worse than both -- and a step search stops at the
752/// first point it cannot improve on. Adding the four diagonals is worth 0.032
753/// dB BD-PSNR-YUV on the film clip and 0.041 on the screen capture for twice
754/// the candidates in the whole-sample stage, which is the cheap stage: it reads
755/// the reference in place and never interpolates.
756///
757/// The step the walk starts from was swept with it, at 4, 8 and 16 whole
758/// samples: -0.580/-0.580/-0.593 dB on the film clip and -0.474/-0.493/-0.529
759/// on the screen capture. Four is screen capture's optimum and inside film's
760/// flat part -- a wider opening step is not a wider search here, it just lands
761/// the walk further from the seeds, which are already the answer most of the
762/// time.
763const ME_PATTERN: [(i16, i16); 8] = [
764 (1, 0),
765 (-1, 0),
766 (0, 1),
767 (0, -1),
768 (1, 1),
769 (-1, -1),
770 (1, -1),
771 (-1, 1),
772];
773
774/// What the search charges P_8x8 for its own signalling, against the six bits
775/// a 16x8 or 8x16 is charged: an mb_type that is one bin longer plus four
776/// sub_mb_type bins, before the four predictors' own mvd.
777///
778/// Swept at `Preset::Balanced` -- the only preset that searches shapes at all
779/// -- on consecutive pictures against x264. Off, 6, 12 and 20 bits read
780/// -0.382/-0.379/-0.377/-0.378 dB BD-PSNR on the film clip and
781/// -0.369/-0.364/-0.353/-0.356 on the screen capture: both contents put the
782/// optimum at twelve, and quarters are worth 0.005 dB on camera content and
783/// 0.016 on screen capture.
784///
785/// Re-swept once each partition was searched against its own predictor rather
786/// than the macroblock's, because that changes what a split is worth: 6, 12
787/// and 20 read -0.342/-0.343/-0.346 dB on the film clip and
788/// -0.322/-0.314/-0.324 on the screen capture. Twelve survives the new path.
789const QUAD_BITS: f64 = 12.0;
790
791/// The same charge for a 16x8 or 8x16: one extra mb_type bin over P_16x16,
792/// with no sub_mb_type behind it.
793///
794/// Swept on the per-partition-predictor path at 3, 6 and 10 bits:
795/// -0.329/-0.343/-0.358 dB on the film clip and -0.310/-0.314/-0.326 on the
796/// screen capture. Both contents want the halves charged half of what the old
797/// whole-macroblock predictor made them look worth -- with each half searched
798/// against its own predictor its mvd is genuinely cheaper, so the search no
799/// longer has to be talked out of splitting.
800const HALF_BITS: f64 = 3.0;
801
802/// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.
803#[derive(Clone, Copy, PartialEq, Eq, Debug)]
804enum PShape {
805 /// P_L0_16x16.
806 Whole,
807 /// P_L0_L0_16x8: a top and a bottom half.
808 Horizontal,
809 /// P_L0_L0_8x16: a left and a right half.
810 Vertical,
811 /// P_8x8 with four P_L0_8x8 sub-partitions: a quarter each.
812 Quad,
813}
814
815impl PShape {
816 /// mb_type of Table 7-13.
817 fn mb_type(self) -> u32 {
818 match self {
819 PShape::Whole => 0,
820 PShape::Horizontal => 1,
821 PShape::Vertical => 2,
822 PShape::Quad => 3,
823 }
824 }
825
826 fn parts(self) -> usize {
827 match self {
828 PShape::Whole => 1,
829 PShape::Horizontal | PShape::Vertical => 2,
830 PShape::Quad => 4,
831 }
832 }
833
834 /// Partition `part`'s origin in 4x4 blocks and its size in luma samples.
835 fn geometry(self, part: usize) -> ((usize, usize), (usize, usize)) {
836 match self {
837 PShape::Whole => ((0, 0), (16, 16)),
838 PShape::Horizontal => ((0, part * 2), (16, 8)),
839 PShape::Vertical => ((part * 2, 0), (8, 16)),
840 PShape::Quad => (((part % 2) * 2, (part / 2) * 2), (8, 8)),
841 }
842 }
843
844 /// Which partition covers the 4x4 block at `(x, y)` in macroblock
845 /// coordinates, or `None` when the block is outside the macroblock.
846 fn part_of(self, x: i32, y: i32) -> Option<usize> {
847 if !(0..4).contains(&x) || !(0..4).contains(&y) {
848 return None;
849 }
850 let (x, y) = (x as usize, y as usize);
851 Some(match self {
852 PShape::Whole => 0,
853 PShape::Horizontal => y / 2,
854 PShape::Vertical => x / 2,
855 PShape::Quad => (y / 2) * 2 + x / 2,
856 })
857 }
858
859 /// `MbPartWidth`/`MbPartHeight` in 4x4 blocks, which select the
860 /// directional shortcuts of 8.4.1.3.
861 fn part_blocks(self) -> (usize, usize) {
862 match self {
863 PShape::Whole => (4, 4),
864 PShape::Horizontal => (4, 2),
865 PShape::Vertical => (2, 4),
866 PShape::Quad => (2, 2),
867 }
868 }
869}
870
871/// How much the two chroma planes weigh against luma in the inter decision.
872///
873/// Swept at 0, 0.25, 0.5, 1 and 2, read on BD-PSNR-YUV because a luma-only
874/// metric cannot price a term whose whole purpose is chroma: the film clip
875/// reads -0.653/-0.622/-0.612/-0.615/-0.626 dB and the screen capture
876/// -0.517/-0.521/-0.515/-0.521/-0.546. A half is film's optimum and inside
877/// screen capture's flat part; zero reproduces the chroma-blind decision
878/// exactly, which is how the sweep proved the term was reaching the search.
879///
880/// It is worth 0.041 dB on the film clip and nothing on the screen capture --
881/// small enough to name what it rules out. Our chroma trails x264 by 0.5-0.9 dB
882/// per plane at every QP, and it is not because the vector was chosen without
883/// looking: weighting chroma up lifts chroma PSNR monotonically, and past a
884/// half the bits it spends cost more than the chroma it buys.
885const CHROMA_ME_WEIGHT: f64 = 0.5;
886
887/// How many inter candidates the macroblock decision codes before choosing,
888/// most promising first. One is the SATD winner alone, which is what this used
889/// to do; five is every shape the search costed plus P_Skip. BD-PSNR-YUV
890/// against x264 at GOP 10 over QP 22/26/30/34, at `Preset::Balanced`:
891///
892/// ```text
893/// film 3840x1608 screen 2560x1440
894/// 1 candidate -0.580 -0.474
895/// 2 -0.521 -0.459
896/// 3 -0.513 -0.447
897/// 5 -0.504 -0.406
898/// ```
899///
900/// monotone in the count with no turnover, so the decision is taken at the
901/// full list. The SATD total that used to rank the shapes is a
902/// prediction-domain estimate that never sees the residual it causes.
903const SHAPE_RD_CANDIDATES: usize = 5;
904
905/// The inter decision for a P macroblock.
906#[derive(Clone, Copy)]
907struct InterChoice {
908 /// The candidate's SATD cost (luma plus chroma) as the shape search ranked it;
909 /// zero where the search did not rank it.
910 satd: i32,
911 shape: PShape,
912 /// One motion vector per partition.
913 mv: [[i16; 2]; 4],
914 /// The P_Skip motion vector of 8.4.1.1.
915 skip_mv: [i16; 2],
916 /// The skip candidate is at least as good as the searched one.
917 prefer_skip: bool,
918 /// The prediction is so close to the source that the macroblock is coded
919 /// as P_Skip without costing a residual (`Preset::Fast` only).
920 force_skip: bool,
921}
922
923/// Motion search plus the skip candidate.
924fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<InterChoice> {
925 let reference = e.reference.expect("a P slice has a reference");
926 let ctx = MvCtx {
927 mb_x,
928 mb_y,
929 slice_id: e.slice_id,
930 written: 0,
931 pos: Default::default(),
932 };
933 let n = ctx.neighbours(pic, 0, 0, 4, 0);
934 let mvp = predict_mv(&n, 0, 4, 4, 0);
935 // P_Skip (8.4.1.1): zero when either neighbour is missing or is itself a
936 // zero-motion reference-0 partition.
937 let a = ctx.at(pic, mb_x as i32 * 4 - 1, mb_y as i32 * 4, 0);
938 let b = ctx.at(pic, mb_x as i32 * 4, mb_y as i32 * 4 - 1, 0);
939 let zero = |nb: &crate::mv::Nb| nb.ref_idx == 0 && nb.mv == [0, 0];
940 let skip_mv = if !a.avail || !b.avail || zero(&a) || zero(&b) {
941 [0, 0]
942 } else {
943 mvp
944 };
945
946 let plane = RefPlane {
947 data: &reference.y.data,
948 stride: reference.y.stride,
949 origin: reference.y.origin,
950 width: reference.y.width,
951 height: reference.y.height,
952 pad: reference.y.pad,
953 };
954 let (sx, sy) = (mb_x * 16, mb_y * 16);
955 let sw = e.src.stride;
956
957 // What the two chroma planes cost under a candidate vector, in the same
958 // SATD domain the luma search ranks in. The search itself cannot afford
959 // this -- it runs on SAD over a whole neighbourhood -- but the handful of
960 // candidates that survive to the shape decision can, and until they did,
961 // no decision in this encoder had ever looked at chroma: the vector, the
962 // shape and the skip flag were all chosen on luma alone and chroma was
963 // coded against whatever came out. Measured per plane against x264 that
964 // showed up as a uniform 0.5-0.9 dB chroma deficit at every QP while we
965 // spent more bits, which is a prediction that was never asked about.
966 let cplanes = [&reference.cb, &reference.cr];
967 let chroma_satd = |px: usize, py: usize, w: usize, h: usize, mv: [i16; 2]| -> i32 {
968 if CHROMA_ME_WEIGHT == 0.0 {
969 return 0;
970 }
971 let mut buf = [0u8; 64];
972 let mut sum = 0;
973 for comp in 0..2 {
974 let src = cplanes[comp];
975 let rp = RefPlane {
976 data: &src.data,
977 stride: src.stride,
978 origin: src.origin,
979 width: src.width,
980 height: src.height,
981 pad: src.pad,
982 };
983 let (cw, ch) = (w / 2, h / 2);
984 mc_chroma(
985 &rp,
986 (sx + px) as i32 / 2,
987 (sy + py) as i32 / 2,
988 mv,
989 cw,
990 ch,
991 cw,
992 &mut buf,
993 crate::inter::Put::Set,
994 );
995 let plane = if comp == 0 { &e.src.u } else { &e.src.v };
996 sum += satd_block(
997 plane,
998 e.src.c_stride,
999 (sx + px) / 2,
1000 (sy + py) / 2,
1001 &buf,
1002 cw,
1003 0,
1004 cw,
1005 ch,
1006 );
1007 }
1008 (f64::from(sum) * CHROMA_ME_WEIGHT) as i32
1009 };
1010
1011 // Early skip: a prediction at the P_Skip vector that already sits inside
1012 // the quantiser's dead zone codes nothing, so neither the search nor a
1013 // residual is worth the time. Judged on luma SAD, the largest single
1014 // difference and the chroma SATD, all against the quantiser step.
1015 if e.preset == Preset::Fast && e.fast.early_skip > 0 {
1016 let qstep = ((f64::from(e.qp) - 4.0) / 6.0).exp2();
1017 let k = f64::from(e.fast.early_skip) / 100.0;
1018 let mut buf = [0u8; 256];
1019 mc_luma(
1020 &plane,
1021 sx as i32,
1022 sy as i32,
1023 skip_mv,
1024 16,
1025 16,
1026 16,
1027 &mut buf,
1028 Put::Set,
1029 );
1030 let (sad_luma, max_luma) = sad_max16(&e.src.y, sw, sx, sy, &buf);
1031 if f64::from(sad_luma) <= 256.0 * k * qstep && f64::from(max_luma) <= 4.0 * k * qstep + 2.0
1032 {
1033 let c = chroma_satd(0, 0, 16, 16, skip_mv);
1034 if f64::from(c) <= 64.0 * k * qstep * 4.0 {
1035 return vec![InterChoice {
1036 satd: 0,
1037 shape: PShape::Whole,
1038 mv: [skip_mv; 4],
1039 skip_mv,
1040 prefer_skip: true,
1041 force_skip: true,
1042 }];
1043 }
1044 }
1045 }
1046
1047 let range = match e.preset {
1048 Preset::Fast => 16i16,
1049 Preset::Balanced => 48,
1050 };
1051
1052 // One search over a `w` x `h` partition at `(px, py)` samples inside the
1053 // macroblock, seeded with the candidate vectors of its neighbourhood.
1054 let mlam = motion_lambda(e);
1055 let search = |px: usize, py: usize, w: usize, h: usize, mvp: [i16; 2], seeds: &[[i16; 2]]| {
1056 let (x0, y0) = (sx + px, sy + py);
1057 let mut buf = [0u8; 256];
1058 // Whole-sample candidates read the reference plane in place; only the
1059 // sub-sample refinement pays for interpolation. The search runs on SAD,
1060 // which is what a search can afford; the winner is re-costed on SATD
1061 // because the intra candidates are SATD and the two scales differ.
1062 let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 {
1063 let bits = (mlam
1064 * f64::from(
1065 se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1])),
1066 )
1067 * MV_BITS_WEIGHT)
1068 .round() as i32;
1069 if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 {
1070 let o = integer_origin(
1071 &plane,
1072 x0 as i32 + (mv[0] >> 2) as i32,
1073 y0 as i32 + (mv[1] >> 2) as i32,
1074 w,
1075 h,
1076 );
1077 return sad(&e.src.y, sw, x0, y0, &plane.data[o..], plane.stride, w, h) + bits;
1078 }
1079 mc_luma(
1080 &plane,
1081 x0 as i32,
1082 y0 as i32,
1083 mv,
1084 w,
1085 h,
1086 w,
1087 &mut buf,
1088 crate::inter::Put::Set,
1089 );
1090 let d = if satd {
1091 satd_block(&e.src.y, sw, x0, y0, &buf, w, 0, w, h)
1092 } else {
1093 sad(&e.src.y, sw, x0, y0, &buf, w, w, h)
1094 };
1095 d + bits
1096 };
1097
1098 let fast = e.preset == Preset::Fast;
1099 let mut best = ([0i16; 2], i32::MAX);
1100 mb_timed!(
1101 12,
1102 for (i, &cand) in seeds.iter().enumerate() {
1103 if seeds[..i].contains(&cand) {
1104 continue;
1105 }
1106 let c = cost_of(cand, false);
1107 if c < best.1 {
1108 best = (cand, c);
1109 }
1110 }
1111 );
1112 // Every partition is searched. This used to stop at a seed whose cost
1113 // was already under half a level a sample, on the reasoning that the
1114 // prediction fit and the search is the encoder's hot loop. Swept on
1115 // consecutive pictures (BD-PSNR against x264, GOP 10) the threshold is
1116 // monotonically harmful: 0/0.25/0.5/1.0 levels a sample read
1117 // -0.586/-0.587/-0.593/-0.617 dB on the film clip and
1118 // -0.466/-0.470/-0.468/-0.476 on the screen capture. A seed that fits
1119 // is exactly where a little more refinement is cheap.
1120 {
1121 // Fast opens at two whole samples: the seeds already carry the
1122 // neighbours' motion, so the walk only has to settle around them.
1123 let mut step = if fast { 2i16 * 4 } else { 4i16 * 4 };
1124 let mut passes = 0;
1125 mb_timed!(
1126 13,
1127 while step >= 4 {
1128 let mut improved = true;
1129 while improved {
1130 improved = false;
1131 passes += 1;
1132 if fast && passes > FAST_ME_PASSES {
1133 break;
1134 }
1135 for (dx, dy) in ME_PATTERN {
1136 let (dx, dy) = (dx * step, dy * step);
1137 let cand = [best.0[0] + dx, best.0[1] + dy];
1138 if (cand[0] - mvp[0]).abs() > range * 4
1139 || (cand[1] - mvp[1]).abs() > range * 4
1140 {
1141 continue;
1142 }
1143 let c = cost_of(cand, false);
1144 if c < best.1 {
1145 best = (cand, c);
1146 improved = true;
1147 }
1148 }
1149 }
1150 step /= 2;
1151 }
1152 );
1153 // Sub-sample refinement runs on SATD, not SAD: interpolation
1154 // smooths, and a sum of absolute differences reads the smoothing
1155 // as a better match where a transform-domain cost does not. Worth
1156 // 0.06 dB BD-PSNR on the film clip and 0.04 dB on the screen
1157 // capture. The whole-sample winner is re-costed in the same domain
1158 // first so the two halves of the search compare.
1159 let sub_satd = !fast || e.fast.me_satd;
1160 mb_timed!(14, {
1161 best.1 = cost_of(best.0, sub_satd);
1162 // Balanced iterates both sub-sample steps to convergence. Fast
1163 // looks at each ring of eight once.
1164 let rings: &[i16] = if !fast {
1165 &[2, 1]
1166 } else {
1167 match e.fast.me_sub {
1168 0 => &[],
1169 1 => &[2],
1170 _ => &[2, 1],
1171 }
1172 };
1173 if fast && e.fast.me_sub == 1 {
1174 // The four half-sample neighbours on the axes, then only the
1175 // diagonal the two winning axes point at.
1176 let base = best;
1177 let mut axis = [(base.0, base.1); 2];
1178 for (k, dirs) in [[(2i16, 0i16), (-2, 0)], [(0, 2), (0, -2)]]
1179 .into_iter()
1180 .enumerate()
1181 {
1182 for (dx, dy) in dirs {
1183 let cand = [base.0[0] + dx, base.0[1] + dy];
1184 let c = cost_of(cand, sub_satd);
1185 if c < axis[k].1 {
1186 axis[k] = (cand, c);
1187 }
1188 }
1189 }
1190 let both = axis[0].1 < base.1 && axis[1].1 < base.1;
1191 if both {
1192 let cand = [axis[0].0[0], axis[1].0[1]];
1193 let c = cost_of(cand, sub_satd);
1194 if c < best.1 {
1195 best = (cand, c);
1196 }
1197 }
1198 for a in axis {
1199 if a.1 < best.1 {
1200 best = a;
1201 }
1202 }
1203 }
1204 let rings: &[i16] = if fast && e.fast.me_sub == 1 {
1205 &[]
1206 } else {
1207 rings
1208 };
1209 for &step in rings {
1210 let mut improved = true;
1211 while improved {
1212 improved = false;
1213 for (dx, dy) in [
1214 (step, 0),
1215 (-step, 0),
1216 (0, step),
1217 (0, -step),
1218 (step, step),
1219 (-step, -step),
1220 (step, -step),
1221 (-step, step),
1222 ] {
1223 let cand = [best.0[0] + dx, best.0[1] + dy];
1224 let c = cost_of(cand, sub_satd);
1225 if c < best.1 {
1226 best = (cand, c);
1227 improved = !fast;
1228 }
1229 }
1230 }
1231 }
1232 });
1233 }
1234 (
1235 best.0,
1236 if !fast || e.fast.me_satd {
1237 best.1
1238 } else {
1239 cost_of(best.0, true)
1240 },
1241 )
1242 };
1243
1244 let seeds = [mvp, skip_mv, [0, 0], n[0].mv, n[1].mv, n[2].mv];
1245 let (mv16, cost16) = search(0, 0, 16, 16, mvp, &seeds);
1246 let cost16 = cost16 + chroma_satd(0, 0, 16, 16, mv16);
1247 let skip_cost = {
1248 let mut buf = [0u8; 256];
1249 mc_luma(
1250 &plane,
1251 sx as i32,
1252 sy as i32,
1253 skip_mv,
1254 16,
1255 16,
1256 16,
1257 &mut buf,
1258 Put::Set,
1259 );
1260 // P_Skip's rebate is the signalling it genuinely saves. Re-measured on
1261 // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip
1262 // and -0.741/-0.696 on the screen capture -- the two contents disagree
1263 // by less than the step between them, so this is the flat part. Six
1264 // costs 0.14 dB and twelve costs 0.42.
1265 //
1266 // The Intra_4x4 discount above was swept with it: 0.65/0.75/0.85/1.0
1267 // read -1.216/-1.154/-1.182/-1.373 on film and -0.970/-0.696/-0.591/
1268 // -0.562 on screen capture, so three quarters is film's optimum and
1269 // inside screen capture's flat part.
1270 satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) + chroma_satd(0, 0, 16, 16, skip_mv)
1271 - motion_rate(e, 2.0)
1272 };
1273
1274 let mut best = (PShape::Whole, [mv16; 4], cost16);
1275 // Every shape the search costed, kept so the macroblock decision can rank
1276 // them on coded cost instead of on this SATD total (see `encode_mb`).
1277 let mut evaluated = vec![(PShape::Whole, [mv16; 4])];
1278 // Halves, seeded with the whole-macroblock winner. The predictor used here
1279 // is the whole-macroblock one rather than each half's own: the real
1280 // predictors are derived in coding order when the choice is made, and this
1281 // only has to rank the shapes. A macroblock the 16x16 search already fits
1282 // is left alone — splitting it could only spend bits.
1283 //
1284 // Measured: two more searches per macroblock buy 0.1-0.2 dB on screen
1285 // capture and nothing on camera content, for roughly twice the search
1286 // time. That is a Balanced trade, not a Fast one.
1287 // The threshold is a floor that real content clears everywhere: swept at
1288 // 0, 0.5, 1 and 2 levels a sample it moves neither clip's BD-PSNR by a
1289 // thousandth of a decibel, so on these sources the halves are always
1290 // searched. It stays as a guard for content flat enough to make the two
1291 // extra searches pure cost.
1292 if e.preset == Preset::Balanced && cost16 > 16 * 16 {
1293 for shape in [PShape::Horizontal, PShape::Vertical, PShape::Quad] {
1294 // What the shape itself costs to signal: its mb_type, plus one
1295 // sub_mb_type per quarter when it is P_8x8.
1296 let mut total = motion_rate(
1297 e,
1298 if shape == PShape::Quad {
1299 QUAD_BITS
1300 } else {
1301 HALF_BITS
1302 },
1303 );
1304 let mut mvs = [[0i16; 2]; 4];
1305 let (pw, ph) = shape.part_blocks();
1306 for part in 0..shape.parts() {
1307 let ((bx, by), (w, h)) = shape.geometry(part);
1308 // Each partition is searched against the predictor it will
1309 // actually be coded with (8.4.1.3), not against the whole
1310 // macroblock's: the partitions before it in this macroblock
1311 // are already chosen, so the neighbourhood the predictor reads
1312 // can be completed from `mvs`.
1313 let mut n = ctx.neighbours(pic, bx, by, pw, 0);
1314 let inside = |x: i32, y: i32, nb: &mut crate::mv::Nb| {
1315 if let Some(p) = shape.part_of(x, y).filter(|&p| p < part) {
1316 *nb = crate::mv::Nb {
1317 avail: true,
1318 mv: mvs[p],
1319 ref_idx: 0,
1320 };
1321 }
1322 };
1323 inside(bx as i32 - 1, by as i32, &mut n[0]);
1324 inside(bx as i32, by as i32 - 1, &mut n[1]);
1325 let cx = bx as i32 + pw as i32;
1326 if shape.part_of(cx, by as i32 - 1).is_some() {
1327 inside(cx, by as i32 - 1, &mut n[2]);
1328 } else if !n[2].avail {
1329 inside(bx as i32 - 1, by as i32 - 1, &mut n[2]);
1330 }
1331 let part_mvp = predict_mv(&n, 0, pw, ph, part);
1332 let seeds = [mv16, part_mvp, mvp, skip_mv, [0, 0]];
1333 let (mv, cost) = search(bx * 4, by * 4, w, h, part_mvp, &seeds);
1334 mvs[part] = mv;
1335 total += cost + chroma_satd(bx * 4, by * 4, w, h, mv);
1336 }
1337 evaluated.push((shape, mvs));
1338 if total < best.2 {
1339 best = (shape, mvs, total);
1340 }
1341 }
1342 }
1343
1344 // How often each shape actually wins. Behind an environment switch because
1345 // it answers a question the rate gate cannot: a partition sweep that reads
1346 // flat is either a flat knob or a path nothing enters, and only a count
1347 // tells the two apart. It found the second -- at `Preset::Fast`, which is
1348 // what the x264 comparison runs by default, no macroblock is ever split.
1349 if std::env::var_os("EC_H264_SHAPE_STATS").is_some() {
1350 static N: [std::sync::atomic::AtomicUsize; 4] = [
1351 std::sync::atomic::AtomicUsize::new(0),
1352 std::sync::atomic::AtomicUsize::new(0),
1353 std::sync::atomic::AtomicUsize::new(0),
1354 std::sync::atomic::AtomicUsize::new(0),
1355 ];
1356 let i = match best.0 {
1357 PShape::Whole => 0,
1358 PShape::Horizontal => 1,
1359 PShape::Vertical => 2,
1360 PShape::Quad => 3,
1361 };
1362 let v = N[i].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
1363 let tot: usize = N
1364 .iter()
1365 .map(|n| n.load(std::sync::atomic::Ordering::Relaxed))
1366 .sum();
1367 if tot.is_multiple_of(20000) {
1368 eprintln!(
1369 "SHAPES whole={} horiz={} vert={} quad={} (last {i} -> {v})",
1370 N[0].load(std::sync::atomic::Ordering::Relaxed),
1371 N[1].load(std::sync::atomic::Ordering::Relaxed),
1372 N[2].load(std::sync::atomic::Ordering::Relaxed),
1373 N[3].load(std::sync::atomic::Ordering::Relaxed),
1374 );
1375 }
1376 }
1377 let winner = InterChoice {
1378 satd: best.2,
1379 shape: best.0,
1380 mv: best.1,
1381 skip_mv,
1382 prefer_skip: best.0 == PShape::Whole && skip_cost <= best.2,
1383 force_skip: false,
1384 };
1385 // The SATD winner first, then the shapes it beat, then the skip candidate
1386 // when the winner is not already it. The caller codes as many of these as
1387 // its preset allows and keeps the one with the smallest coded cost.
1388 let mut cands = vec![winner];
1389 for (shape, mv) in evaluated {
1390 if shape != winner.shape || winner.prefer_skip {
1391 cands.push(InterChoice {
1392 satd: 0,
1393 shape,
1394 mv,
1395 skip_mv,
1396 prefer_skip: false,
1397 force_skip: false,
1398 });
1399 }
1400 }
1401 if !winner.prefer_skip {
1402 cands.push(InterChoice {
1403 satd: skip_cost,
1404 shape: PShape::Whole,
1405 mv: [skip_mv; 4],
1406 skip_mv,
1407 prefer_skip: true,
1408 force_skip: false,
1409 });
1410 }
1411 cands
1412}
1413
1414/// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock,
1415/// prediction already in the plane.
1416#[allow(clippy::too_many_arguments)]
1417fn code_luma_4x4(
1418 pic: &mut Picture,
1419 e: &MbEnc<'_>,
1420 w: &EncEntropy,
1421 mb_x: usize,
1422 mb_y: usize,
1423 qp: i32,
1424 intra: bool,
1425 lv: &mut Levels,
1426) {
1427 let stride = pic.y.stride;
1428 // An inter macroblock's blocks are reconstructed only after the whole
1429 // macroblock has been quantised, because [`decimate_score`] can still take
1430 // a block away. Intra blocks reconstruct as they go: the next block in the
1431 // macroblock predicts from them.
1432 let mut pending: [Option<[i32; 16]>; 16] = [None; 16];
1433 // Per 8x8 group, what coding its blocks buys and what it costs, for the
1434 // group-level test below. A block with no levels contributes nothing to
1435 // either side: its source energy stays in the reconstruction whatever the
1436 // group decides.
1437 let mut ssd_zero = [0i64; 4];
1438 let mut ssd_coded = [0i64; 4];
1439 let mut rate = [0f64; 4];
1440 for blk in 0..16 {
1441 let (dx, dy) = BLK4_POS[blk];
1442 let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1443 let origin = pic.y.at(x, y);
1444 let mut d = [0i32; 16];
1445 for ry in 0..4 {
1446 for rx in 0..4 {
1447 d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
1448 - i32::from(pic.y.data[origin + ry * stride + rx]);
1449 }
1450 }
1451 let source = d;
1452 forward_4x4(&mut d);
1453 let rdoq = !intra && w.is_cabac();
1454 let mut nz = if rdoq {
1455 quant_4x4_offset(&d, qp, RDOQ_DEAD_ZONE, false, &mut lv.luma[blk])
1456 } else {
1457 quant_4x4(&d, qp, intra, false, &mut lv.luma[blk])
1458 };
1459 if rdoq && nz != 0 {
1460 nz = rdoq_4x4(
1461 e,
1462 w,
1463 &source,
1464 &mut lv.luma[blk],
1465 qp,
1466 BlockCat::Luma4x4,
1467 false,
1468 );
1469 }
1470 lv.luma_nz[blk] = nz;
1471 if nz == 0 {
1472 continue;
1473 }
1474 let mut raster = [0i32; 16];
1475 unzigzag(&lv.luma[blk], &mut raster);
1476 dequant_4x4(&mut raster, &e.ls, qp, false);
1477 let mut resid = [0i32; 16];
1478 inverse_transform_4x4(&raster, &mut resid);
1479 // Is the block worth its bits? A block whose residual barely moves the
1480 // reconstruction is pure quantisation churn; dropping it is the cheap
1481 // half of rate-distortion optimised quantisation, and the half that
1482 // pays. Intra blocks are left alone: their reconstruction is what the
1483 // next block in the macroblock predicts from.
1484 if !rdoq
1485 && !intra
1486 && !worth_coding(
1487 &source,
1488 &resid,
1489 &lv.luma[blk],
1490 zero_block_lambda(e, qp, e.t8x8_inter(mb_y)),
1491 )
1492 {
1493 lv.luma[blk] = [0; 16];
1494 lv.luma_nz[blk] = 0;
1495 continue;
1496 }
1497 if intra {
1498 lv.cbp_luma |= 1 << (blk >> 2);
1499 add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
1500 } else {
1501 for i in 0..16 {
1502 let z = i64::from(source[i]);
1503 let c = i64::from(source[i] - resid[i]);
1504 ssd_zero[blk >> 2] += z * z;
1505 ssd_coded[blk >> 2] += c * c;
1506 }
1507 rate[blk >> 2] +=
1508 match w.residual_block_cost(&lv.luma[blk], BlockCat::Luma4x4, Some(1), Some(1)) {
1509 // CABAC's own arithmetic cost for the levels, which is what
1510 // the group is really deciding about. It arrives in 256ths of
1511 // a bit.
1512 Some(bits) => f64::from(bits) / 256.0,
1513 None => block_bits(&lv.luma[blk]) as f64,
1514 };
1515 pending[blk] = Some(resid);
1516 }
1517 }
1518 if intra {
1519 return;
1520 }
1521 // A block that survives its own rate-distortion test can still be the last
1522 // coefficient standing in its 8x8 group, and then it is paying a
1523 // coded_block_pattern bit as well as its levels. x264 decides that with a
1524 // count of how tightly the levels cluster at the front of the scan
1525 // (`decimate`), thresholded at four per group; swept here, that count
1526 // wants opposite settings on the two contents -- monotonically off on
1527 // camera grain, monotonically harder on screen capture -- because it is a
1528 // heuristic standing in for a rate-distortion test the encoder can just
1529 // do. So do it: a group is coded only if its blocks buy more squared error
1530 // than their levels plus the pattern bit are worth, at the same lambda the
1531 // per-block test uses.
1532 // With an exact rate the lambda needs no correction factor: the group test
1533 // uses the mode decision's own lambda where the rate is CABAC's, and falls
1534 // back to the per-block test's discounted one where it is an estimate.
1535 let lambda = if w.is_cabac() {
1536 GROUP_LAMBDA * lambda_ssd(qp)
1537 } else {
1538 zero_block_lambda(e, qp, e.t8x8_inter(mb_y))
1539 };
1540 for g in 0..4 {
1541 if rate[g] == 0.0 {
1542 continue;
1543 }
1544 if ssd_coded[g] as f64 + lambda * (rate[g] + CBP_BIT) < ssd_zero[g] as f64 {
1545 continue;
1546 }
1547 for blk in g * 4..g * 4 + 4 {
1548 lv.luma[blk] = [0; 16];
1549 lv.luma_nz[blk] = 0;
1550 pending[blk] = None;
1551 }
1552 }
1553 for blk in 0..16 {
1554 let Some(resid) = pending[blk] else { continue };
1555 let (dx, dy) = BLK4_POS[blk];
1556 let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1557 let origin = pic.y.at(x, y);
1558 lv.cbp_luma |= 1 << (blk >> 2);
1559 add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
1560 }
1561}
1562
1563/// What a group of four luma blocks pays in coded_block_pattern to be coded
1564/// at all, in bits, on top of its own levels.
1565///
1566/// This charge and [`GROUP_LAMBDA`] move the group test along the same axis --
1567/// both make dropping a group likelier -- so only one of them is worth tuning.
1568/// Swept at 0, 6, 12 and 24 bits it reads -0.317/-0.335/-0.379/-0.472 dB on
1569/// the film clip against -0.295/-0.212/-0.191/-0.185 on the screen capture:
1570/// the same trade the lambda makes, at a worse exchange rate. It stays at a
1571/// plausible six.
1572const CBP_BIT: f64 = 6.0;
1573
1574/// What chroma pays to take its coded_block_pattern from one to two, in bits,
1575/// on top of the levels: the pattern bins themselves plus a coded_block_flag
1576/// for every AC block that then has to say it is empty.
1577///
1578/// Swept at 0, 4, 8, 16, 32 and 64 bits, read on the all-plane PSNR because a
1579/// luma-only one cannot see what this decision spends: -0.688/-0.681/-0.659/
1580/// -0.653/-0.670/-0.742 dB BD on the film clip and -0.537/-0.527/-0.530/
1581/// -0.517/-0.524/-0.522 on the screen capture. Both turn over at sixteen. The
1582/// same sweep read on luma alone climbs all the way to +0.079 dB at 64,
1583/// because past the turn the test is buying luma bits by throwing chroma
1584/// away -- which is exactly the trade an all-plane metric exists to catch.
1585const CBP_CHROMA_BIT: f64 = 16.0;
1586
1587/// How much of the mode-decision lambda the group test uses.
1588///
1589/// The 8x8 transform path was swept the same way and does not want this test
1590/// at all: at 0, 0.3 and 0.6 the `transform_8x8` gate reads +0.620/+0.624/
1591/// +0.608 dB on the film clip and +0.007/+0.007/+0.009 on the screen capture,
1592/// all inside its noise. One 8x8 block is a whole coded_block_pattern group,
1593/// so its own zero test already decides what this one would, and `rdoq_8x8`
1594/// drops it outright when the levels do not survive.
1595///
1596/// Swept at 0.25, 0.5, 0.6, 0.75, 0.9, 1.0 and 2.0 on both real clips:
1597/// -0.315/-0.314/-0.321/-0.335/-0.354/-0.372/-0.575 dB on the 3840x1608 film
1598/// clip and -0.297/-0.267/-0.252/-0.212/-0.202/-0.193/-0.277 on the 2560x1440
1599/// screen capture. Screen capture has an interior optimum around one -- which
1600/// the same test on an estimated rate did not, it only ever wanted more -- and
1601/// camera grain wants less, because a grain block that scores as noise is
1602/// carrying signal the eye is measuring. Six tenths is the most the film clip
1603/// takes without losing ground, and it is worth 0.06 dB on screen capture.
1604const GROUP_LAMBDA: f64 = 0.6;
1605
1606/// How much of the squared-error lambda the chroma DC zero test uses.
1607///
1608/// BD-PSNR-YUV against x264 at GOP 10 over QP 22/26/30/34, `Preset::Balanced`,
1609/// with the test off against a ladder of multipliers:
1610///
1611/// ```text
1612/// film screen phone handheld
1613/// off -0.504 -0.227 -0.300 -0.886
1614/// 0.25 -0.506 -0.227
1615/// 0.5 -0.500 -0.220 -0.297 -0.884
1616/// 0.75 -0.500 -0.223
1617/// 1.0 -0.518 -0.246
1618/// 2.0 -0.708 -0.566
1619/// ```
1620///
1621/// Zeroing on squared error alone (a multiplier of 0) never fires, so the rate
1622/// term is the whole test; above the peak it throws away chroma the picture
1623/// needs.
1624const CHROMA_DC_LAMBDA: f64 = 0.5;
1625
1626/// Squared error of coding `levels`, in the pixels the block reconstructs to.
1627fn block_ssd(e: &MbEnc<'_>, source: &[i32; 16], levels: &[i32; 16], qp: i32, skip_dc: bool) -> i64 {
1628 let mut raster = [0i32; 16];
1629 if skip_dc {
1630 unzigzag_ac15(levels, &mut raster);
1631 } else {
1632 unzigzag(levels, &mut raster);
1633 }
1634 dequant_4x4(&mut raster, &e.ls, qp, skip_dc);
1635 let mut resid = [0i32; 16];
1636 inverse_transform_4x4(&raster, &mut resid);
1637 let mut ssd = 0i64;
1638 for i in 0..16 {
1639 let d = i64::from(source[i] - resid[i]);
1640 ssd += d * d;
1641 }
1642 ssd
1643}
1644
1645/// How much of the mode-decision lambda rate-distortion quantisation uses.
1646///
1647/// The bits here are the coder's own, not an estimate, so there is no
1648/// over-estimate to correct for and the scale starts at 1. Swept over 0.5,
1649/// 1.0, 1.25, 1.5 and 2.0 against x264 on a 3840x1608 film clip and a
1650/// 2560x1440 screen capture: the two disagree, film reading -0.607 dB at 0.5
1651/// and -0.680 at 1.5 while screen capture reads -0.620 and -0.444, and 1.0 is
1652/// the crossing point that costs neither (-0.628 and -0.471). Table in
1653/// `lanes/h264x264-r2.report.md`.
1654const RDOQ_LAMBDA: f64 = 1.0;
1655
1656/// The dead zone rate-distortion quantisation starts from, as a divisor of the
1657/// quantiser step: 2 is round-to-nearest. The plain inter path uses 6, which
1658/// has already thrown away the levels this search would weigh -- a search
1659/// bounded by the heuristic it replaces measures the heuristic. This is the
1660/// half of the change that pays: 1/6 -> 1/2 under the same search is worth
1661/// 0.102 dB on the film clip and 0.301 on the synthetic gate. 1/3 and 1/4 read
1662/// -0.647 and -0.677 dB where 1/2 reads -0.630.
1663const RDOQ_DEAD_ZONE: i32 = 2;
1664
1665/// The largest level the search offers a smaller magnitude to. A big level is
1666/// carrying real signal and never wins by shrinking; bounding the search is
1667/// what keeps it free. Unbounded it tripled the synthetic clip's encode time
1668/// (1.08 s -> 3.53 s) for the same BD-PSNR; at 2 the run is 1.09 s. Swept over
1669/// 1, 2 and 3: -4.062/-0.623/-0.496, -4.073/-0.628/-0.471 and
1670/// -4.065/-0.629/-0.477 dB on synthetic, film and screen capture.
1671const RDOQ_MAX_LEVEL: i32 = 2;
1672
1673/// The rounding the chroma AC path keeps under the search: the inter dead zone
1674/// it already had. Luma wanted the wider 1/2 rounding once a search could take
1675/// levels back down (`RDOQ_DEAD_ZONE`); chroma does not. Measured on the two
1676/// clips at the settled luma constants, BD-PSNR against x264: 1/2 rounding
1677/// -0.653 film / -0.482 screen capture, 1/4 -0.623 / -0.472, 1/3 -0.644 /
1678/// -0.481, and the 1/6 kept here -0.593 / -0.468 -- against -0.628 / -0.471
1679/// with no chroma search at all. Chroma AC is sparse enough at these
1680/// quantisers that offering more levels costs more bits than the search takes
1681/// back; what pays is only the pruning.
1682const RDOQ_CHROMA_DEAD_ZONE: i32 = 6;
1683
1684/// The rounding the 8x8 luma path keeps under the search. It answers the way
1685/// 4x4 luma did, not the way chroma did: measured as BD-PSNR of the opt-in
1686/// `transform_8x8` flag against flag-off, which isolates this path because the
1687/// flag-off curve does not run through it. Film 3840x1608 / screen capture
1688/// 2560x1440, no search +0.535 / +0.042, 1/6 +0.551 / --, 1/3 +0.605 / +0.075,
1689/// and the 1/2 kept here +0.619 / +0.067. The 8x8 blocks carry enough
1690/// coefficients for the extra levels to pay for themselves, as 4x4 luma's do.
1691const RDOQ8_DEAD_ZONE: i32 = 2;
1692
1693/// Rate-distortion quantisation of one inter luma block: each level is offered
1694/// the two cheaper magnitudes below it, and takes one when the squared error it
1695/// gives up costs less than the bits it saves.
1696///
1697/// The rate is the CABAC coder's own price for the whole block against the
1698/// context state as it stands, so dropping a level is priced with the
1699/// significance map that follows from it — which is where most of the saving
1700/// is. Intra blocks stay out: their reconstruction is what the next block in
1701/// the macroblock predicts from, so a level changed here would move a
1702/// prediction the decision cannot see.
1703#[allow(clippy::too_many_arguments)]
1704fn rdoq_4x4(
1705 e: &MbEnc<'_>,
1706 w: &EncEntropy,
1707 source: &[i32; 16],
1708 levels: &mut [i32; 16],
1709 qp: i32,
1710 cat: BlockCat,
1711 skip_dc: bool,
1712) -> u8 {
1713 let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else {
1714 return levels.iter().filter(|&&l| l != 0).count() as u8;
1715 };
1716 let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
1717 let mut cost = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits);
1718 // Highest scanning position first: dropping the last significant level is
1719 // what shortens the significance map, so it is tried while the levels
1720 // above it are still gone.
1721 for pos in (0..cat.max_num_coeff()).rev() {
1722 let level = levels[pos];
1723 if level == 0 {
1724 continue;
1725 }
1726 let mag = level.abs();
1727 if mag > RDOQ_MAX_LEVEL {
1728 continue;
1729 }
1730 let mut tried = mag;
1731 for candidate in [mag - 1, 0] {
1732 if candidate == tried {
1733 continue;
1734 }
1735 tried = candidate;
1736 let keep = levels[pos];
1737 levels[pos] = candidate * level.signum();
1738 let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else {
1739 unreachable!("CAVLC returned early");
1740 };
1741 let trial = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits);
1742 if trial < cost {
1743 cost = trial;
1744 } else {
1745 levels[pos] = keep;
1746 }
1747 }
1748 }
1749 // And the block as a whole: zeroing it drops the coded_block_pattern bit as
1750 // well as every level, which no single-coefficient step can see. This is
1751 // the same decision `worth_coding` makes for the paths without an exact
1752 // rate, made here with one.
1753 let zero_bits = w
1754 .residual_block_cost(&[0; 16], cat, Some(1), Some(1))
1755 .expect("CABAC");
1756 let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
1757 if ssd_zero as f64 + lambda * f64::from(zero_bits) <= cost {
1758 *levels = [0; 16];
1759 return 0;
1760 }
1761 levels.iter().filter(|&&l| l != 0).count() as u8
1762}
1763
1764/// How much of the mode-decision lambda the zero-block test uses.
1765///
1766/// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what
1767/// CAVLC spends and an over-estimate of what CABAC spends; the multiplier
1768/// brings the rate term back to the coder actually in force. Measured over
1769/// 0.0, 0.4 and 1.0 on 1080p camera and screen-capture clips: 0.4 is the only
1770/// one that gains on screen content (+0.13 to +0.39 dB at matched bitrate)
1771/// without costing camera content.
1772const ZERO_BLOCK_LAMBDA: f64 = 0.4;
1773
1774fn zero_block_lambda(e: &MbEnc<'_>, qp: i32, transform_8x8: bool) -> f64 {
1775 if transform_8x8 {
1776 e.lambda
1777 } else {
1778 ZERO_BLOCK_LAMBDA * lambda_ssd(qp)
1779 }
1780}
1781
1782/// The rate-distortion test behind the per-block zero decision: coding the
1783/// block has to buy more squared error than its bits are worth.
1784fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], lambda: f64) -> bool {
1785 let mut ssd_zero = 0i64;
1786 let mut ssd_coded = 0i64;
1787 for i in 0..source.len() {
1788 let z = i64::from(source[i]);
1789 let c = i64::from(source[i] - resid[i]);
1790 ssd_zero += z * z;
1791 ssd_coded += c * c;
1792 }
1793 ssd_coded as f64 + lambda * (block_bits(levels) as f64) < ssd_zero as f64
1794}
1795
1796/// Predict and code the luma of an Intra_16x16 macroblock.
1797#[allow(clippy::too_many_arguments)]
1798fn code_i16_luma(
1799 pic: &mut Picture,
1800 e: &MbEnc<'_>,
1801 mb_x: usize,
1802 mb_y: usize,
1803 qp: i32,
1804 mode: u8,
1805 nbr: &MbNeighbors,
1806 lv: &mut Levels,
1807) {
1808 let w4 = pic.mb_w * 4;
1809 for dy in 0..4 {
1810 let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
1811 pic.i4_modes[base..base + 4].fill(2);
1812 }
1813 let stride = pic.y.stride;
1814 let origin = pic.y.at(mb_x * 16, mb_y * 16);
1815 let mut win = PlaneWindow {
1816 data: &mut pic.y.data,
1817 stride,
1818 origin,
1819 };
1820 pred_16x16(mode, 8, &mut win, nbr.b, nbr.a);
1821 code_luma_i16(pic, e, mb_x, mb_y, qp, lv);
1822}
1823
1824/// The Intra_16x16 luma path (8.5.10 in reverse then forward again).
1825fn code_luma_i16(
1826 pic: &mut Picture,
1827 e: &MbEnc<'_>,
1828 mb_x: usize,
1829 mb_y: usize,
1830 qp: i32,
1831 lv: &mut Levels,
1832) {
1833 let stride = pic.y.stride;
1834 let mut dc = [0i32; 16];
1835 let mut ac = [[0i32; 16]; 16];
1836 for blk in 0..16 {
1837 let (dx, dy) = BLK4_POS[blk];
1838 let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1839 let origin = pic.y.at(x, y);
1840 let mut d = [0i32; 16];
1841 for ry in 0..4 {
1842 for rx in 0..4 {
1843 d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
1844 - i32::from(pic.y.data[origin + ry * stride + rx]);
1845 }
1846 }
1847 forward_4x4(&mut d);
1848 dc[dy as usize * 4 + dx as usize] = d[0];
1849 let nz = quant_4x4(&d, qp, true, true, &mut lv.luma[blk]);
1850 lv.luma_nz[blk] = nz;
1851 ac[blk] = lv.luma[blk];
1852 if nz > 0 {
1853 lv.cbp_luma = 15;
1854 }
1855 }
1856 if lv.cbp_luma == 0 {
1857 for blk in 0..16 {
1858 lv.luma[blk] = [0; 16];
1859 lv.luma_nz[blk] = 0;
1860 }
1861 }
1862 forward_hadamard_4x4(&mut dc);
1863 quant_luma_dc(&dc, qp, &mut lv.dc);
1864
1865 // Reconstruct exactly as the decoder does: DC through 8.5.10, then each
1866 // block's AC with the DC substituted at raster position 0.
1867 let mut raster = [0i32; 16];
1868 unzigzag(&lv.dc, &mut raster);
1869 luma_dc_transform(&mut raster, &e.ls, qp);
1870 let dc_recon = raster;
1871 for blk in 0..16 {
1872 let (dx, dy) = BLK4_POS[blk];
1873 let dc_blk = dc_recon[dy as usize * 4 + dx as usize];
1874 let tc = lv.luma_nz[blk];
1875 if tc == 0 && dc_blk == 0 {
1876 continue;
1877 }
1878 let mut raster = [0i32; 16];
1879 if tc > 0 {
1880 unzigzag_ac15(&ac[blk], &mut raster);
1881 dequant_4x4(&mut raster, &e.ls, qp, true);
1882 }
1883 raster[0] = dc_blk;
1884 let mut resid = [0i32; 16];
1885 inverse_transform_4x4(&raster, &mut resid);
1886 let origin = pic
1887 .y
1888 .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1889 add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
1890 }
1891}
1892
1893/// Chroma residual for both components (8.5.11 + the AC path).
1894#[allow(clippy::too_many_arguments)]
1895fn code_chroma(
1896 pic: &mut Picture,
1897 e: &MbEnc<'_>,
1898 w: &EncEntropy,
1899 mb_x: usize,
1900 mb_y: usize,
1901 qp_y: i32,
1902 intra: bool,
1903 lv: &mut Levels,
1904) {
1905 let qp_c = chroma_qp(qp_y, e.cqo);
1906 let mut dc_lists = [[0i32; 4]; 2];
1907 let mut ac = [[[0i32; 16]; 4]; 2];
1908 let mut srcs = [[[0i32; 16]; 4]; 2];
1909 let mut any_ac = false;
1910 for comp in 0..2 {
1911 let (plane, src) = if comp == 0 {
1912 (&pic.cb, &e.src.u)
1913 } else {
1914 (&pic.cr, &e.src.v)
1915 };
1916 let stride = plane.stride;
1917 for blk in 0..4 {
1918 let (x, y) = (mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
1919 let origin = plane.at(x, y);
1920 let mut d = [0i32; 16];
1921 for ry in 0..4 {
1922 for rx in 0..4 {
1923 d[ry * 4 + rx] = i32::from(src[(y + ry) * e.src.c_stride + x + rx])
1924 - i32::from(plane.data[origin + ry * stride + rx]);
1925 }
1926 }
1927 let source = d;
1928 srcs[comp][blk] = d;
1929 forward_4x4(&mut d);
1930 dc_lists[comp][blk] = d[0];
1931 let rdoq = !intra && w.is_cabac();
1932 let mut nz = if rdoq {
1933 quant_4x4_offset(&d, qp_c, RDOQ_CHROMA_DEAD_ZONE, true, &mut ac[comp][blk])
1934 } else {
1935 quant_4x4(&d, qp_c, intra, true, &mut ac[comp][blk])
1936 };
1937 if rdoq && nz > 0 {
1938 nz = rdoq_4x4(
1939 e,
1940 w,
1941 &source,
1942 &mut ac[comp][blk],
1943 qp_c,
1944 BlockCat::ChromaAc,
1945 true,
1946 );
1947 } else if nz > 0 {
1948 // The same zero decision as luma, against the AC part alone:
1949 // the DC of this block travels through the 2x2 Hadamard and is
1950 // decided with the other three.
1951 let mut raster = [0i32; 16];
1952 unzigzag_ac15(&ac[comp][blk], &mut raster);
1953 dequant_4x4(&mut raster, &e.ls, qp_c, true);
1954 let mut resid = [0i32; 16];
1955 inverse_transform_4x4(&raster, &mut resid);
1956 if !worth_coding(
1957 &source,
1958 &resid,
1959 &ac[comp][blk],
1960 zero_block_lambda(
1961 e,
1962 qp_c,
1963 if intra {
1964 e.t8x8_intra(mb_y)
1965 } else {
1966 e.t8x8_inter(mb_y)
1967 },
1968 ),
1969 ) {
1970 ac[comp][blk] = [0; 16];
1971 nz = 0;
1972 }
1973 }
1974 lv.chroma_nz[comp][blk] = nz;
1975 if nz > 0 {
1976 any_ac = true;
1977 }
1978 }
1979 }
1980 // The chroma pattern is one decision for all eight AC blocks: a single
1981 // surviving block takes coded_block_pattern from one to two, and every
1982 // other block then has to code a coded_block_flag to say it is empty. So
1983 // the same group test luma runs over four blocks runs here over all eight,
1984 // against the same lambda.
1985 if any_ac {
1986 let (mut ssd_zero, mut ssd_coded, mut rate) = (0i64, 0i64, 0f64);
1987 for comp in 0..2 {
1988 for blk in 0..4 {
1989 let source = &srcs[comp][blk];
1990 let mut resid = [0i32; 16];
1991 if lv.chroma_nz[comp][blk] > 0 {
1992 let mut raster = [0i32; 16];
1993 unzigzag_ac15(&ac[comp][blk], &mut raster);
1994 dequant_4x4(&mut raster, &e.ls, qp_c, true);
1995 inverse_transform_4x4(&raster, &mut resid);
1996 rate += match w.residual_block_cost(
1997 &ac[comp][blk],
1998 BlockCat::ChromaAc,
1999 Some(1),
2000 Some(1),
2001 ) {
2002 Some(bits) => f64::from(bits) / 256.0,
2003 None => block_bits(&ac[comp][blk]) as f64,
2004 };
2005 }
2006 for i in 0..16 {
2007 let z = i64::from(source[i]);
2008 let c = i64::from(source[i] - resid[i]);
2009 ssd_zero += z * z;
2010 ssd_coded += c * c;
2011 }
2012 }
2013 }
2014 let lambda = if w.is_cabac() {
2015 GROUP_LAMBDA * lambda_ssd(qp_c)
2016 } else {
2017 zero_block_lambda(e, qp_c, false)
2018 };
2019 if ssd_coded as f64 + lambda * (rate + CBP_CHROMA_BIT) >= ssd_zero as f64 {
2020 ac = [[[0; 16]; 4]; 2];
2021 lv.chroma_nz = [[0; 4]; 2];
2022 any_ac = false;
2023 }
2024 }
2025 // The chroma DC block had no zero test at all: whatever the quantiser
2026 // produced was coded. Its four coefficients spread over all 64 samples of
2027 // the component, and with only DC in the block the inverse transform gives
2028 // every sample the same (dc + 32) >> 6, so the squared error zeroing costs
2029 // is exact in one pass over the AC residual that is already reconstructed
2030 // here.
2031 let mut any_dc = false;
2032 for comp in 0..2 {
2033 forward_hadamard_2x2(&mut dc_lists[comp]);
2034 let mut nz = quant_chroma_dc(&dc_lists[comp], qp_c, intra, &mut lv.chroma_dc[comp]);
2035 if nz > 0 {
2036 let mut dc = [
2037 lv.chroma_dc[comp][0],
2038 lv.chroma_dc[comp][1],
2039 lv.chroma_dc[comp][2],
2040 lv.chroma_dc[comp][3],
2041 ];
2042 chroma_dc_transform_420(&mut dc, &e.ls, qp_c);
2043 let mut delta = 0i64;
2044 for blk in 0..4 {
2045 let mut resid = [0i32; 16];
2046 if any_ac && lv.chroma_nz[comp][blk] > 0 {
2047 let mut raster = [0i32; 16];
2048 unzigzag_ac15(&ac[comp][blk], &mut raster);
2049 dequant_4x4(&mut raster, &e.ls, qp_c, true);
2050 inverse_transform_4x4(&raster, &mut resid);
2051 }
2052 let c = i64::from((dc[blk] + 32) >> 6);
2053 let err: i64 = (0..16)
2054 .map(|i| i64::from(srcs[comp][blk][i] - resid[i]))
2055 .sum();
2056 delta += 16 * c * c - 2 * c * err;
2057 }
2058 let rate = match w.residual_block_cost(
2059 &lv.chroma_dc[comp],
2060 BlockCat::ChromaDc(comp as u8),
2061 Some(1),
2062 Some(1),
2063 ) {
2064 Some(bits) => f64::from(bits) / 256.0,
2065 None => block_bits(&lv.chroma_dc[comp]) as f64,
2066 };
2067 if delta as f64 + CHROMA_DC_LAMBDA * lambda_ssd(qp_c) * rate >= 0.0 {
2068 lv.chroma_dc[comp] = [0; 16];
2069 nz = 0;
2070 }
2071 }
2072 if nz > 0 {
2073 any_dc = true;
2074 }
2075 }
2076 lv.cbp_chroma = if any_ac {
2077 2
2078 } else if any_dc {
2079 1
2080 } else {
2081 0
2082 };
2083 if lv.cbp_chroma < 2 {
2084 lv.chroma_nz = [[0; 4]; 2];
2085 } else {
2086 lv.chroma = ac;
2087 }
2088 if lv.cbp_chroma == 0 {
2089 return;
2090 }
2091 for comp in 0..2 {
2092 let mut dc = [
2093 lv.chroma_dc[comp][0],
2094 lv.chroma_dc[comp][1],
2095 lv.chroma_dc[comp][2],
2096 lv.chroma_dc[comp][3],
2097 ];
2098 chroma_dc_transform_420(&mut dc, &e.ls, qp_c);
2099 let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
2100 let stride = plane.stride;
2101 for blk in 0..4 {
2102 let tc = lv.chroma_nz[comp][blk];
2103 if tc == 0 && dc[blk] == 0 {
2104 continue;
2105 }
2106 let mut raster = [0i32; 16];
2107 if tc > 0 {
2108 unzigzag_ac15(&lv.chroma[comp][blk], &mut raster);
2109 dequant_4x4(&mut raster, &e.ls, qp_c, true);
2110 }
2111 raster[0] = dc[blk];
2112 let mut resid = [0i32; 16];
2113 inverse_transform_4x4(&raster, &mut resid);
2114 let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
2115 add_residual_4x4(&mut plane.data, 8, stride, origin, &resid);
2116 }
2117 }
2118}
2119
2120/// Code the luma of an Intra_4x4 macroblock: per block, choose the prediction
2121/// mode against the *reconstructed* neighbours and reconstruct it immediately,
2122/// because the next block predicts from it. Returns the chosen modes and the
2123/// modes they were predicted to be.
2124/// How many SATD survivors the Intra_4x4 mode decision re-costs with real
2125/// quantisation before choosing.
2126const I4_RD_CANDIDATES: usize = 3;
2127
2128fn code_intra_4x4(
2129 pic: &mut Picture,
2130 e: &MbEnc<'_>,
2131 mb_x: usize,
2132 mb_y: usize,
2133 qp: i32,
2134 nbr: &MbNeighbors,
2135 lv: &mut Levels,
2136) -> ([u8; 16], [u8; 16]) {
2137 let w4 = pic.mb_w * 4;
2138 let (bx0, by0) = (mb_x * 4, mb_y * 4);
2139 let mut modes = [2u8; 16];
2140 let mut pred_modes = [2u8; 16];
2141 for blk in 0..16 {
2142 let (dx, dy) = BLK4_POS[blk];
2143 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
2144 let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
2145 let left_avail = if dx == 0 { nbr.a } else { true };
2146 let top_avail = if dy == 0 { nbr.b } else { true };
2147 let predicted = if left_avail && top_avail {
2148 pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx])
2149 } else {
2150 2
2151 };
2152 pred_modes[blk] = predicted;
2153 let n = gather_nbr4(pic, nbr, blk, x, y);
2154 let have_tl = match (dx, dy) {
2155 (0, 0) => nbr.d,
2156 (0, _) => nbr.a,
2157 (_, 0) => nbr.b,
2158 _ => true,
2159 };
2160 let allowed = modes_allowed(n.have_top, n.have_left, have_tl);
2161 let mut best = (i32::MAX, predicted.min(2));
2162 let mut p = [0u8; 16];
2163 let mut ranked = [(i32::MAX, 2u8); 9];
2164 for mode in 0..9u8 {
2165 if !allowed[mode as usize] {
2166 continue;
2167 }
2168 pred_4x4(mode, 8, &n, &mut p);
2169 let bits = if mode == predicted { 1 } else { 4 };
2170 let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + motion_rate(e, f64::from(bits));
2171 ranked[mode as usize] = (c, mode);
2172 if c < best.0 {
2173 best = (c, mode);
2174 }
2175 }
2176 let mut mode = best.1;
2177 // SATD ranks the modes; the survivors are re-costed with the
2178 // quantisation actually in force, because a mode that predicts a
2179 // little worse can quantise to far fewer levels. Measured against
2180 // x264 with `bd_psnr_vs_x264` on a 3840x1608 film clip and a 2560x1440
2181 // screen capture: +0.129 and +0.088 dB all-intra, +0.062 and +0.043 dB
2182 // at GOP 10, for 3-4% encode time. Three survivors is where it
2183 // saturates -- all nine landed within 0.002 dB of three, for 7% more
2184 // encode time.
2185 {
2186 ranked.sort_unstable();
2187 let keep = I4_RD_CANDIDATES;
2188 // The same over-count [`ZERO_BLOCK_LAMBDA`] corrects for: with the
2189 // full rate term this search loses 0.065 dB instead of gaining,
2190 // and it loses more the more candidates it sees.
2191 let lambda = ZERO_BLOCK_LAMBDA
2192 * if e.lambda_standard {
2193 e.lambda
2194 } else {
2195 lambda_ssd(qp)
2196 };
2197 let mut best_rd = f64::MAX;
2198 for &(c, cand) in ranked.iter().take(keep) {
2199 if c == i32::MAX {
2200 break;
2201 }
2202 pred_4x4(cand, 8, &n, &mut p);
2203 let mut d = [0i32; 16];
2204 for ry in 0..4 {
2205 for rx in 0..4 {
2206 d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
2207 - i32::from(p[ry * 4 + rx]);
2208 }
2209 }
2210 let src = d;
2211 forward_4x4(&mut d);
2212 let mut levels = [0i32; 16];
2213 let nz = quant_4x4(&d, qp, true, false, &mut levels);
2214 let mut resid = [0i32; 16];
2215 if nz > 0 {
2216 let mut raster = [0i32; 16];
2217 unzigzag(&levels, &mut raster);
2218 dequant_4x4(&mut raster, &e.ls, qp, false);
2219 inverse_transform_4x4(&raster, &mut resid);
2220 }
2221 let mut ssd = 0i64;
2222 for i in 0..16 {
2223 let err = i64::from(src[i] - resid[i]);
2224 ssd += err * err;
2225 }
2226 let mode_bits = if cand == predicted { 1 } else { 4 };
2227 let bits = block_bits(&levels) + mode_bits;
2228 let cost = ssd as f64 + lambda * bits as f64;
2229 if cost < best_rd {
2230 best_rd = cost;
2231 mode = cand;
2232 }
2233 }
2234 }
2235 modes[blk] = mode;
2236 pic.i4_modes[by * w4 + bx] = mode;
2237 // Prediction into the plane, then residual and reconstruction.
2238 pred_4x4(mode, 8, &n, &mut p);
2239 let stride = pic.y.stride;
2240 let origin = pic.y.at(x, y);
2241 for ry in 0..4 {
2242 let row = origin + ry * stride;
2243 pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
2244 }
2245 let mut d = [0i32; 16];
2246 for ry in 0..4 {
2247 for rx in 0..4 {
2248 d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
2249 - i32::from(p[ry * 4 + rx]);
2250 }
2251 }
2252 forward_4x4(&mut d);
2253 let nz = quant_4x4(&d, qp, true, false, &mut lv.luma[blk]);
2254 lv.luma_nz[blk] = nz;
2255 if nz > 0 {
2256 lv.cbp_luma |= 1 << (blk >> 2);
2257 let mut raster = [0i32; 16];
2258 unzigzag(&lv.luma[blk], &mut raster);
2259 dequant_4x4(&mut raster, &e.ls, qp, false);
2260 let mut resid = [0i32; 16];
2261 inverse_transform_4x4(&raster, &mut resid);
2262 add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
2263 }
2264 }
2265 (modes, pred_modes)
2266}
2267
2268/// Predicted Intra_8x8 mode of `blk8` (8.3.2.1): the decoder's rule, read
2269/// from the 4x4 slots every size writes its mode into.
2270fn predicted_mode8(pic: &Picture, nbr: &MbNeighbors, bx: usize, by: usize, blk8: usize) -> u8 {
2271 let w4 = pic.mb_w * 4;
2272 let left_avail = if blk8.is_multiple_of(2) { nbr.a } else { true };
2273 let top_avail = if blk8 < 2 { nbr.b } else { true };
2274 if left_avail && top_avail {
2275 pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx])
2276 } else {
2277 2
2278 }
2279}
2280
2281/// Residual of one 8x8 luma block against the prediction already in the
2282/// plane: forward transform, quantise, and — when anything survives —
2283/// reconstruct with the decoder's own inverse. Returns the non-zero count.
2284#[allow(clippy::too_many_arguments)]
2285fn code_block_8x8(
2286 pic: &mut Picture,
2287 e: &MbEnc<'_>,
2288 w: &EncEntropy,
2289 x: usize,
2290 y: usize,
2291 qp: i32,
2292 intra: bool,
2293 out: &mut [i32; 64],
2294) -> u8 {
2295 let stride = pic.y.stride;
2296 let origin = pic.y.at(x, y);
2297 let mut d = [0i32; 64];
2298 for ry in 0..8 {
2299 for rx in 0..8 {
2300 d[ry * 8 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
2301 - i32::from(pic.y.data[origin + ry * stride + rx]);
2302 }
2303 }
2304 let rdoq = !intra && w.is_cabac();
2305 let fwd = forward_8x8(&d);
2306 let mut nz = if rdoq {
2307 quant_8x8_offset(&fwd, &e.ls8, qp, RDOQ8_DEAD_ZONE, out)
2308 } else {
2309 quant_8x8(&fwd, &e.ls8, qp, intra, out)
2310 };
2311 if nz == 0 {
2312 return 0;
2313 }
2314 if rdoq {
2315 nz = rdoq_8x8(e, w, &d, out, qp);
2316 if nz == 0 {
2317 return 0;
2318 }
2319 }
2320 let mut raster = [0i32; 64];
2321 unzigzag_8x8(out, &mut raster);
2322 dequant_8x8(&mut raster, &e.ls8, qp);
2323 let mut resid = [0i32; 64];
2324 inverse_transform_8x8(&raster, &mut resid);
2325 if !rdoq
2326 && !intra
2327 && !worth_coding(
2328 &d,
2329 &resid,
2330 out,
2331 zero_block_lambda(e, qp, e.transform_8x8_inter),
2332 )
2333 {
2334 *out = [0; 64];
2335 return 0;
2336 }
2337 add_residual_8x8(&mut pic.y.data, 8, stride, origin, &resid);
2338 nz
2339}
2340
2341/// Code the luma of an Intra_8x8 macroblock, the 8x8 sibling of
2342/// [`code_intra_4x4`]: neighbours are the decoder's filtered reference
2343/// samples, and every 4x4 mode slot of a block carries its mode.
2344#[allow(clippy::too_many_arguments)]
2345fn code_intra_8x8(
2346 pic: &mut Picture,
2347 e: &MbEnc<'_>,
2348 w: &EncEntropy,
2349 mb_x: usize,
2350 mb_y: usize,
2351 qp: i32,
2352 nbr: &MbNeighbors,
2353 lv: &mut Levels,
2354) -> ([u8; 4], [u8; 4]) {
2355 let w4 = pic.mb_w * 4;
2356 let mut modes = [2u8; 4];
2357 let mut pred_modes = [2u8; 4];
2358 lv.trans8 = true;
2359 for blk8 in 0..4 {
2360 let (bx, by) = (mb_x * 4 + (blk8 % 2) * 2, mb_y * 4 + (blk8 / 2) * 2);
2361 let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
2362 let predicted = predicted_mode8(pic, nbr, bx, by, blk8);
2363 pred_modes[blk8] = predicted;
2364 let n = filter_nbr8(&gather_nbr8(pic, nbr, blk8, x, y));
2365 let allowed = modes_allowed(n.have_top, n.have_left, n.have_tl);
2366 let mut p = [0u8; 64];
2367 {
2368 let (mode, coded, recon) =
2369 i8_mode_by_rd(pic, e, w, x, y, qp, &n, &allowed, predicted, &mut p);
2370 let stride = pic.y.stride;
2371 let origin = pic.y.at(x, y);
2372 for ry in 0..8 {
2373 let row = origin + ry * stride;
2374 pic.y.data[row..row + 8].copy_from_slice(&recon[ry * 8..ry * 8 + 8]);
2375 }
2376 lv.luma8[blk8] = coded.0;
2377 if coded.1 {
2378 lv.cbp_luma |= 1 << blk8;
2379 }
2380 modes[blk8] = mode;
2381 for dy in 0..2 {
2382 let base = (by + dy) * w4 + bx;
2383 pic.i4_modes[base..base + 2].fill(mode);
2384 }
2385 }
2386 }
2387 (modes, pred_modes)
2388}
2389
2390/// The inter residual under the 8x8 transform, prediction already in the
2391/// plane: the sibling of [`code_luma_4x4`].
2392fn code_luma_8x8(
2393 pic: &mut Picture,
2394 e: &MbEnc<'_>,
2395 w: &EncEntropy,
2396 mb_x: usize,
2397 mb_y: usize,
2398 qp: i32,
2399 lv: &mut Levels,
2400) {
2401 lv.trans8 = true;
2402 for blk8 in 0..4 {
2403 let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
2404 if code_block_8x8(pic, e, w, x, y, qp, false, &mut lv.luma8[blk8]) > 0 {
2405 lv.cbp_luma |= 1 << blk8;
2406 }
2407 }
2408}
2409
2410/// Squared error of coding `levels` as an 8x8 block, in its pixels.
2411fn block_ssd_8x8(e: &MbEnc<'_>, source: &[i32; 64], levels: &[i32; 64], qp: i32) -> i64 {
2412 let mut raster = [0i32; 64];
2413 unzigzag_8x8(levels, &mut raster);
2414 dequant_8x8(&mut raster, &e.ls8, qp);
2415 let mut resid = [0i32; 64];
2416 inverse_transform_8x8(&raster, &mut resid);
2417 let mut ssd = 0i64;
2418 for k in 0..64 {
2419 let d = i64::from(source[k]) - i64::from(resid[k]);
2420 ssd += d * d;
2421 }
2422 ssd
2423}
2424
2425/// [`rdoq_4x4`] for the 8x8 transform: the same walk down the scan against the
2426/// CABAC coder's own price, with the 8x8 block's own contexts.
2427fn rdoq_8x8(
2428 e: &MbEnc<'_>,
2429 w: &EncEntropy,
2430 source: &[i32; 64],
2431 levels: &mut [i32; 64],
2432 qp: i32,
2433) -> u8 {
2434 let Some(bits) = w.residual_block_8x8_cost(levels) else {
2435 return levels.iter().filter(|&&l| l != 0).count() as u8;
2436 };
2437 let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
2438 let mut cost = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
2439 for pos in (0..64).rev() {
2440 let level = levels[pos];
2441 if level == 0 {
2442 continue;
2443 }
2444 let mag = level.abs();
2445 if mag > RDOQ_MAX_LEVEL {
2446 continue;
2447 }
2448 let mut tried = mag;
2449 for candidate in [mag - 1, 0] {
2450 if candidate == tried {
2451 continue;
2452 }
2453 tried = candidate;
2454 let keep = levels[pos];
2455 levels[pos] = candidate * level.signum();
2456 let bits = w
2457 .residual_block_8x8_cost(levels)
2458 .expect("CAVLC returned early");
2459 let trial = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
2460 if trial < cost {
2461 cost = trial;
2462 } else {
2463 levels[pos] = keep;
2464 break;
2465 }
2466 }
2467 }
2468 // The whole block against nothing, on the same exact price.
2469 let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
2470 if ssd_zero as f64 <= cost {
2471 *levels = [0; 64];
2472 return 0;
2473 }
2474 levels.iter().filter(|&&l| l != 0).count() as u8
2475}
2476
2477/// Squared error of the luma macroblock against the source.
2478fn ssd_luma(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 {
2479 let stride = pic.y.stride;
2480 let origin = pic.y.at(mb_x * 16, mb_y * 16);
2481 let mut sum = 0i64;
2482 for row in 0..16 {
2483 let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
2484 for x in 0..16 {
2485 let d = i64::from(e.src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]);
2486 sum += d * d;
2487 }
2488 }
2489 sum
2490}
2491
2492/// Copy the luma macroblock out of the plane, and back in.
2493fn save_luma(pic: &Picture, mb_x: usize, mb_y: usize, out: &mut [u8; 256]) {
2494 let stride = pic.y.stride;
2495 let origin = pic.y.at(mb_x * 16, mb_y * 16);
2496 for row in 0..16 {
2497 out[row * 16..row * 16 + 16].copy_from_slice(&pic.y.data[origin + row * stride..][..16]);
2498 }
2499}
2500
2501fn restore_luma(pic: &mut Picture, mb_x: usize, mb_y: usize, src: &[u8; 256]) {
2502 let stride = pic.y.stride;
2503 let origin = pic.y.at(mb_x * 16, mb_y * 16);
2504 for row in 0..16 {
2505 pic.y.data[origin + row * stride..][..16].copy_from_slice(&src[row * 16..row * 16 + 16]);
2506 }
2507}
2508
2509fn rough_intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 {
2510 let mut bits = estimate_luma_bits(lv);
2511 match i4 {
2512 Some((modes, pred)) => {
2513 bits += 6;
2514 for blk in 0..modes.len() {
2515 bits += if modes[blk] == pred[blk] { 1 } else { 4 };
2516 }
2517 }
2518 None => bits += 8,
2519 }
2520 bits
2521}
2522
2523fn entropy_bits(w: &EncEntropy, write: impl FnOnce(&mut EncEntropy)) -> i64 {
2524 let mut probe = w.probe_copy();
2525 let before = probe.bit_len();
2526 write(&mut probe);
2527 (probe.bit_len() - before) as i64
2528}
2529
2530fn cost_luma_nz_pair(
2531 pic: &Picture,
2532 nbr: &MbNeighbors,
2533 local: &[u8; 16],
2534 bx0: usize,
2535 by0: usize,
2536 bx: usize,
2537 by: usize,
2538) -> (Option<u8>, Option<u8>) {
2539 let w4 = pic.mb_w * 4;
2540 let left_avail = if bx.is_multiple_of(4) { nbr.a } else { true };
2541 let top_avail = if by.is_multiple_of(4) { nbr.b } else { true };
2542 let left = (left_avail && bx > 0).then(|| {
2543 if bx > bx0 {
2544 local[(by - by0) * 4 + (bx - bx0 - 1)]
2545 } else {
2546 pic.nz_y[by * w4 + bx - 1]
2547 }
2548 });
2549 let top = (top_avail && by > 0).then(|| {
2550 if by > by0 {
2551 local[(by - by0 - 1) * 4 + (bx - bx0)]
2552 } else {
2553 pic.nz_y[(by - 1) * w4 + bx]
2554 }
2555 });
2556 (left, top)
2557}
2558
2559fn write_luma_for_cost(
2560 pic: &Picture,
2561 nbr: &MbNeighbors,
2562 w: &mut EncEntropy,
2563 mb_x: usize,
2564 mb_y: usize,
2565 lv: &Levels,
2566 is_i16: bool,
2567) {
2568 let (bx0, by0) = (mb_x * 4, mb_y * 4);
2569 let mut nz = [0u8; 16];
2570 if is_i16 {
2571 let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx0, by0);
2572 nz[0] = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb);
2573 }
2574 if lv.trans8 {
2575 for blk8 in 0..4 {
2576 let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
2577 if lv.cbp_luma & (1 << blk8) == 0 {
2578 continue;
2579 }
2580 if w.is_cabac() {
2581 let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None);
2582 for dy in 0..2 {
2583 let base = (by - by0 + dy) * 4 + bx - bx0;
2584 nz[base..base + 2].fill(tc.min(16));
2585 }
2586 } else {
2587 for i4 in 0..4 {
2588 let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
2589 let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
2590 let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, sx, sy);
2591 let sub = sub_block_4x4(&lv.luma8[blk8], i4);
2592 nz[(sy - by0) * 4 + (sx - bx0)] =
2593 w.residual_block(&sub, BlockCat::Luma4x4, na, nb);
2594 }
2595 }
2596 }
2597 return;
2598 }
2599 for blk in 0..16 {
2600 let (dx, dy) = BLK4_POS[blk];
2601 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
2602 let group = 1 << (blk >> 2);
2603 let coded_block = if is_i16 {
2604 lv.cbp_luma != 0
2605 } else {
2606 lv.cbp_luma & group != 0
2607 };
2608 if coded_block {
2609 let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx, by);
2610 let (levels, cat) = if is_i16 {
2611 (&lv.luma[blk][..15], BlockCat::LumaAc)
2612 } else {
2613 (&lv.luma[blk][..16], BlockCat::Luma4x4)
2614 };
2615 nz[(by - by0) * 4 + (bx - bx0)] = w.residual_block(levels, cat, na, nb);
2616 }
2617 }
2618}
2619#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly
2620fn cost_chroma_nz_pair(
2621 pic: &Picture,
2622 nbr: &MbNeighbors,
2623 local: &[[u8; 4]; 2],
2624 comp: usize,
2625 cx0: usize,
2626 cy0: usize,
2627 cx: usize,
2628 cy: usize,
2629) -> (Option<u8>, Option<u8>) {
2630 let w2 = pic.mb_w * 2;
2631 let left_avail = if cx.is_multiple_of(2) { nbr.a } else { true };
2632 let top_avail = if cy.is_multiple_of(2) { nbr.b } else { true };
2633 let left = (left_avail && cx > 0).then(|| {
2634 if cx > cx0 {
2635 local[comp][(cy - cy0) * 2 + (cx - cx0 - 1)]
2636 } else {
2637 pic.nz_c[comp][cy * w2 + cx - 1]
2638 }
2639 });
2640 let top = (top_avail && cy > 0).then(|| {
2641 if cy > cy0 {
2642 local[comp][(cy - cy0 - 1) * 2 + (cx - cx0)]
2643 } else {
2644 pic.nz_c[comp][(cy - 1) * w2 + cx]
2645 }
2646 });
2647 (left, top)
2648}
2649
2650fn write_chroma_for_cost(
2651 pic: &Picture,
2652 nbr: &MbNeighbors,
2653 w: &mut EncEntropy,
2654 mb_x: usize,
2655 mb_y: usize,
2656 lv: &Levels,
2657) {
2658 if lv.cbp_chroma != 0 {
2659 for comp in 0..2 {
2660 w.residual_block(
2661 &lv.chroma_dc[comp][..4],
2662 BlockCat::ChromaDc(comp as u8),
2663 None,
2664 None,
2665 );
2666 }
2667 }
2668 if lv.cbp_chroma != 2 {
2669 return;
2670 }
2671 let (cx0, cy0) = (mb_x * 2, mb_y * 2);
2672 let mut nz = [[0u8; 4]; 2];
2673 for comp in 0..2 {
2674 for blk in 0..4 {
2675 let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
2676 let (na, nb) = cost_chroma_nz_pair(pic, nbr, &nz, comp, cx0, cy0, cx, cy);
2677 nz[comp][blk] =
2678 w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb);
2679 }
2680 }
2681}
2682
2683#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly
2684fn intra_mb_bits(
2685 pic: &Picture,
2686 e: &MbEnc<'_>,
2687 w: &EncEntropy,
2688 mb_addr: usize,
2689 nbr: &MbNeighbors,
2690 lv: &Levels,
2691 i4: Option<(&[u8], &[u8])>,
2692 i16_mode: u8,
2693 chroma_mode: u8,
2694) -> i64 {
2695 let use_i4 = i4.is_some();
2696 let p_slice = e.slice_type == SliceType::P;
2697 let offset = if p_slice { 5 } else { 0 };
2698 let intra_type = if use_i4 {
2699 0
2700 } else {
2701 1 + u32::from(i16_mode)
2702 + 4 * u32::from(lv.cbp_chroma)
2703 + if lv.cbp_luma != 0 { 12 } else { 0 }
2704 };
2705 entropy_bits(w, |cw| {
2706 cw.begin_mb(&e.mb_ctx);
2707 cw.coded_mb(p_slice, e.skip_inc);
2708 cw.set_intra(true);
2709 cw.mb_type(p_slice, intra_type + offset);
2710 if let Some((modes, pred)) = i4 {
2711 if e.transform_8x8 {
2712 cw.transform_size_8x8_flag(lv.trans8);
2713 }
2714 for blk in 0..modes.len() {
2715 let rem = if modes[blk] == pred[blk] {
2716 None
2717 } else if modes[blk] > pred[blk] {
2718 Some(modes[blk] - 1)
2719 } else {
2720 Some(modes[blk])
2721 };
2722 cw.intra4x4_pred_mode(rem);
2723 }
2724 }
2725 cw.intra_chroma_pred_mode(chroma_mode);
2726 if use_i4 {
2727 cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true);
2728 }
2729 let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || !use_i4;
2730 if coded {
2731 cw.mb_qp_delta(e.target_qp - e.qp);
2732 }
2733 let mb_x = mb_addr % pic.mb_w;
2734 let mb_y = mb_addr / pic.mb_w;
2735 write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, !use_i4);
2736 write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv);
2737 })
2738}
2739
2740#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly
2741fn inter_mb_bits(
2742 pic: &Picture,
2743 e: &MbEnc<'_>,
2744 w: &EncEntropy,
2745 mb_addr: usize,
2746 nbr: &MbNeighbors,
2747 shape: PShape,
2748 mvd: &[[i16; 2]; 4],
2749 inc: &[[usize; 2]; 4],
2750 lv: &Levels,
2751) -> i64 {
2752 entropy_bits(w, |cw| {
2753 cw.begin_mb(&e.mb_ctx);
2754 cw.coded_mb(true, e.skip_inc);
2755 cw.set_intra(false);
2756 cw.mb_type(true, shape.mb_type());
2757 if shape == PShape::Quad {
2758 for _ in 0..4 {
2759 cw.sub_mb_type_p(0); // P_L0_8x8
2760 }
2761 }
2762 for part in 0..shape.parts() {
2763 for comp in 0..2 {
2764 cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp]));
2765 }
2766 }
2767 cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false);
2768 if lv.cbp_luma != 0 && e.transform_8x8 {
2769 cw.transform_size_8x8_flag(lv.trans8);
2770 }
2771 if lv.cbp_luma != 0 || lv.cbp_chroma != 0 {
2772 cw.mb_qp_delta(e.target_qp - e.qp);
2773 let mb_x = mb_addr % pic.mb_w;
2774 let mb_y = mb_addr / pic.mb_w;
2775 write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, false);
2776 write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv);
2777 }
2778 })
2779}
2780
2781/// Code an intra macroblock, choosing Intra_16x16 against Intra_4x4 on real
2782/// rate and real distortion.
2783///
2784/// A SATD estimate of the 4x4 form has to predict from the source samples
2785/// inside the macroblock — the reconstruction it would predict from does not
2786/// exist until the mode is chosen — and on flat or text-heavy pictures that
2787/// estimate misjudges which form wins. Coding both and measuring is worth
2788/// more than it costs: it is 1.1 dB on screen capture at matched bitrate.
2789fn encode_intra_mb(
2790 pic: &mut Picture,
2791 e: &mut MbEnc<'_>,
2792 w: &mut EncEntropy,
2793 mb_addr: usize,
2794 nbr: MbNeighbors,
2795 cost: IntraCost,
2796) {
2797 let mb_x = mb_addr % pic.mb_w;
2798 let mb_y = mb_addr / pic.mb_w;
2799 let w4 = pic.mb_w * 4;
2800 let (bx0, by0) = (mb_x * 4, mb_y * 4);
2801 let qp = e.target_qp;
2802 write_intra_mb(pic, mb_x, mb_y);
2803 let mut lv: Levels;
2804 let mut modes = [2u8; 16];
2805 let mut pred_modes = [2u8; 16];
2806 let mut modes8 = [2u8; 4];
2807 let mut pred_modes8 = [2u8; 4];
2808 let mut use_i4 = false;
2809 let mut chroma_lv = Levels::default();
2810 let chroma_mode = mb_timed!(
2811 10,
2812 choose_chroma_mode_rd(pic, e, w, &nbr, mb_x, mb_y, qp, &mut chroma_lv)
2813 );
2814 let mut use_i8 = false;
2815
2816 if cost.allow_i4 {
2817 let mut lv4 = chroma_lv.clone();
2818 let (m4, p4) = mb_timed!(6, code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4));
2819 let cost4 = if e.t8x8_intra(mb_y) {
2820 let bits = intra_mb_bits(
2821 pic,
2822 e,
2823 w,
2824 mb_addr,
2825 &nbr,
2826 &lv4,
2827 Some((&m4, &p4)),
2828 cost.i16_mode,
2829 chroma_mode,
2830 );
2831 ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64
2832 + e.lambda * bits as f64
2833 } else {
2834 ssd_luma(pic, e, mb_x, mb_y) as f64
2835 + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f64
2836 };
2837 let mut recon4 = [0u8; 256];
2838 save_luma(pic, mb_x, mb_y, &mut recon4);
2839 let mut modes4 = [2u8; 16];
2840 for blk in 0..16 {
2841 let (dx, dy) = BLK4_POS[blk];
2842 modes4[blk] = pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize];
2843 }
2844
2845 // Intra_8x8 on the same terms, when the PPS allows it.
2846 let mut lv8 = chroma_lv.clone();
2847 let mut recon8 = [0u8; 256];
2848 let skip8 = e.preset == Preset::Fast
2849 && (e.fast.skip_i8 || (e.fast.p_skip_i8 && e.slice_type == SliceType::P));
2850 let cost8 = if e.t8x8_intra(mb_y) && !skip8 {
2851 let (m8, p8) = mb_timed!(7, code_intra_8x8(pic, e, w, mb_x, mb_y, qp, &nbr, &mut lv8));
2852 modes8 = m8;
2853 pred_modes8 = p8;
2854 save_luma(pic, mb_x, mb_y, &mut recon8);
2855 let bits = intra_mb_bits(
2856 pic,
2857 e,
2858 w,
2859 mb_addr,
2860 &nbr,
2861 &lv8,
2862 Some((&m8, &p8)),
2863 cost.i16_mode,
2864 chroma_mode,
2865 );
2866 ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, true, intra_bs) as f64
2867 + e.lambda * bits as f64
2868 } else {
2869 f64::INFINITY
2870 };
2871
2872 let mut lv16 = chroma_lv;
2873 mb_timed!(
2874 11,
2875 code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16)
2876 );
2877 let cost16 = if e.t8x8_intra(mb_y) {
2878 let bits = intra_mb_bits(
2879 pic,
2880 e,
2881 w,
2882 mb_addr,
2883 &nbr,
2884 &lv16,
2885 None,
2886 cost.i16_mode,
2887 chroma_mode,
2888 );
2889 ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64
2890 + e.lambda * bits as f64
2891 } else {
2892 ssd_luma(pic, e, mb_x, mb_y) as f64
2893 + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64
2894 };
2895
2896 if cost8 + e.lambda * e.t8x8_margin_bits <= cost4
2897 && cost8 + e.lambda * e.t8x8_margin_bits <= cost16
2898 {
2899 use_i4 = true;
2900 use_i8 = true;
2901 restore_luma(pic, mb_x, mb_y, &recon8);
2902 for blk8 in 0..4 {
2903 for dy in 0..2 {
2904 let base = (by0 + (blk8 / 2) * 2 + dy) * w4 + bx0 + (blk8 % 2) * 2;
2905 pic.i4_modes[base..base + 2].fill(modes8[blk8]);
2906 }
2907 }
2908 lv = lv8;
2909 } else if cost4 <= cost16 {
2910 use_i4 = true;
2911 restore_luma(pic, mb_x, mb_y, &recon4);
2912 for blk in 0..16 {
2913 let (dx, dy) = BLK4_POS[blk];
2914 pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize] = modes4[blk];
2915 }
2916 lv = lv4;
2917 modes = m4;
2918 pred_modes = p4;
2919 } else {
2920 lv = lv16;
2921 }
2922 } else {
2923 lv = chroma_lv;
2924 mb_timed!(
2925 11,
2926 code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv)
2927 );
2928 }
2929
2930 // ---- syntax ----
2931 w.begin_mb(&e.mb_ctx);
2932 w.coded_mb(e.slice_type == SliceType::P, e.skip_inc);
2933 w.set_intra(true);
2934 let intra_type = if use_i4 {
2935 0
2936 } else {
2937 1 + u32::from(cost.i16_mode)
2938 + 4 * u32::from(lv.cbp_chroma)
2939 + if lv.cbp_luma != 0 { 12 } else { 0 }
2940 };
2941 let p_slice = e.slice_type == SliceType::P;
2942 let offset = if p_slice { 5 } else { 0 };
2943 w.mb_type(p_slice, intra_type + offset);
2944 if use_i4 {
2945 if e.transform_8x8 {
2946 w.transform_size_8x8_flag(use_i8);
2947 }
2948 // prev_intra8x8_pred_mode_flag / rem_intra8x8_pred_mode share the 4x4
2949 // elements' binarisation and contexts (9.3.2.2, Table 9-34).
2950 let (modes, pred_modes): (&[u8], &[u8]) = if use_i8 {
2951 (&modes8, &pred_modes8)
2952 } else {
2953 (&modes, &pred_modes)
2954 };
2955 for blk in 0..modes.len() {
2956 let rem = if modes[blk] == pred_modes[blk] {
2957 None
2958 } else if modes[blk] > pred_modes[blk] {
2959 Some(modes[blk] - 1)
2960 } else {
2961 Some(modes[blk])
2962 };
2963 w.intra4x4_pred_mode(rem);
2964 }
2965 }
2966 w.intra_chroma_pred_mode(chroma_mode);
2967 if use_i4 {
2968 w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true);
2969 }
2970 finish_mb(
2971 pic,
2972 e,
2973 w,
2974 mb_addr,
2975 &nbr,
2976 &lv,
2977 MbRecord {
2978 intra: true,
2979 is_i16: !use_i4,
2980 chroma_mode,
2981 qp,
2982 },
2983 );
2984}
2985
2986/// Eight samples widened to 16-bit lanes; the tail past the slice is zero,
2987/// which only a caller reading past the plane could reach.
2988#[inline]
2989fn load8(data: &[u8], at: usize) -> i16x8 {
2990 let mut a = [0i16; 8];
2991 if let Some(row) = data.get(at..at + 8) {
2992 for (o, &b) in a.iter_mut().zip(row) {
2993 *o = i16::from(b);
2994 }
2995 }
2996 i16x8::from(a)
2997}
2998
2999/// Squared error of the whole macroblock against the source, luma and chroma:
3000/// the distortion term of the skip decision.
3001///
3002/// Each row's 16 (luma) or 8 (chroma) per-pixel differences fit in `i16`
3003/// (range `-255..=255`), and `dot` widens the pairwise products to `i32`
3004/// before summing, so this is the exact same integer value as scalar
3005/// `i64::from(d) * i64::from(d)` per pixel, just batched a row at a time and
3006/// summed into the `i64` accumulator in a different (still overflow-free,
3007/// so exact) order.
3008fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 {
3009 let mut sum = 0i64;
3010 let stride = pic.y.stride;
3011 let origin = pic.y.at(mb_x * 16, mb_y * 16);
3012 for row in 0..16 {
3013 let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
3014 let d = load16(&e.src.y, s) - load16(&pic.y.data, origin + row * stride);
3015 sum += d
3016 .dot(d)
3017 .to_array()
3018 .iter()
3019 .map(|&v| i64::from(v))
3020 .sum::<i64>();
3021 }
3022 for comp in 0..2 {
3023 let (plane, src) = if comp == 0 {
3024 (&pic.cb, &e.src.u)
3025 } else {
3026 (&pic.cr, &e.src.v)
3027 };
3028 let stride = plane.stride;
3029 let origin = plane.at(mb_x * 8, mb_y * 8);
3030 for row in 0..8 {
3031 let s = (mb_y * 8 + row) * e.src.c_stride + mb_x * 8;
3032 let d = load8(src, s) - load8(&plane.data, origin + row * stride);
3033 sum += d
3034 .dot(d)
3035 .to_array()
3036 .iter()
3037 .map(|&v| i64::from(v))
3038 .sum::<i64>();
3039 }
3040 }
3041 sum
3042}
3043
3044/// [`ssd_mb`] with the luma half measured after the loop filter this
3045/// macroblock's reconstruction will get. `bs(edge, seg, vertical)` is the
3046/// boundary strength of one 4-sample edge segment — edge 0 the macroblock
3047/// edge, edges 1..3 the internal edges at offsets 4/8/12 — as the decoder
3048/// will derive it, so an intra candidate passes its forced 4/3 and an inter
3049/// candidate its own coded/motion strengths. A transform-8x8 macroblock has
3050/// no transform edge at luma offsets 4 and 12, so those stay unfiltered,
3051/// exactly as the decoder's `internal` gate decides it. Neighbours share
3052/// this slice's qp with the zero offsets the encoder writes, so every edge
3053/// is parameterised by the trial qp alone. The right and bottom edges
3054/// belong to macroblocks coded later and cannot be known here; the aprons
3055/// are the pre-filter neighbour samples, which is everything that exists at
3056/// decision time. The chroma half is left pre-filter: chroma never takes
3057/// the 8x8 transform, so it cannot separate the candidates.
3058///
3059/// The 8x8-vs-4x4 trials are judged by this and not by [`ssd_mb`] because the
3060/// two candidates meet different edge sets under the same loop filter: a
3061/// pre-filter SSD prices the 4x4 candidate as if its extra filtered edges
3062/// cost nothing.
3063fn ssd_mb_deblocked(
3064 pic: &Picture,
3065 e: &MbEnc<'_>,
3066 mb_x: usize,
3067 mb_y: usize,
3068 nbr: &MbNeighbors,
3069 trans8: bool,
3070 bs: impl Fn(usize, usize, bool) -> u8,
3071) -> i64 {
3072 // The macroblock at (A, A) plus 4-sample left and top aprons: a bS-4
3073 // edge reads p3 and rewrites p2 on its far side.
3074 const A: usize = 4;
3075 const S: usize = A + 16;
3076 let mut scratch = [0u8; S * S];
3077 let stride = pic.y.stride;
3078 let origin = pic.y.at(mb_x * 16, mb_y * 16);
3079 for row in 0..16 {
3080 let src = origin + row * stride;
3081 let dst = (A + row) * S + A;
3082 scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]);
3083 }
3084 if nbr.a {
3085 for row in 0..16 {
3086 let src = origin + row * stride - A;
3087 let dst = (A + row) * S;
3088 scratch[dst..dst + A].copy_from_slice(&pic.y.data[src..src + A]);
3089 }
3090 }
3091 if nbr.b {
3092 for row in 0..A {
3093 let src = origin - (A - row) * stride;
3094 let dst = row * S + A;
3095 scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]);
3096 }
3097 }
3098 // Vertical edges left to right, then horizontal top to bottom, the order
3099 // of 8.7.1: each edge filters what the earlier edges left behind. Each
3100 // 4-sample segment carries its own strength, as in the decoder.
3101 let qp = e.target_qp;
3102 for edge in 0..4 {
3103 let x = edge * 4;
3104 if (edge == 0 && !nbr.a) || (trans8 && x != 0 && x != 8) {
3105 continue;
3106 }
3107 for seg in 0..4 {
3108 let s = bs(edge, seg, true);
3109 if s == 0 {
3110 continue;
3111 }
3112 let ep = edge_params(qp, 0, 0, s, 8);
3113 for row in seg * 4..seg * 4 + 4 {
3114 filter_luma_line(&mut scratch, 255, (A + row) * S + A + x, 1, &ep);
3115 }
3116 }
3117 }
3118 for edge in 0..4 {
3119 let y = edge * 4;
3120 if (edge == 0 && !nbr.b) || (trans8 && y != 0 && y != 8) {
3121 continue;
3122 }
3123 let seg_bs = [
3124 bs(edge, 0, false),
3125 bs(edge, 1, false),
3126 bs(edge, 2, false),
3127 bs(edge, 3, false),
3128 ];
3129 if seg_bs[0] == seg_bs[1] && seg_bs[1] == seg_bs[2] && seg_bs[2] == seg_bs[3] {
3130 if seg_bs[0] != 0 {
3131 let ep = edge_params(qp, 0, 0, seg_bs[0], 8);
3132 filter_luma_h_edge16(&mut scratch, (A + y) * S + A, S, &ep);
3133 }
3134 continue;
3135 }
3136 for seg in 0..4 {
3137 if seg_bs[seg] == 0 {
3138 continue;
3139 }
3140 let ep = edge_params(qp, 0, 0, seg_bs[seg], 8);
3141 for col in seg * 4..seg * 4 + 4 {
3142 filter_luma_line(&mut scratch, 255, (A + y) * S + A + col, S, &ep);
3143 }
3144 }
3145 }
3146 let mut sum = ssd_mb(pic, e, mb_x, mb_y) - ssd_luma(pic, e, mb_x, mb_y);
3147 for row in 0..16 {
3148 let src = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
3149 for x in 0..16 {
3150 let d = i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]);
3151 sum += d * d;
3152 }
3153 }
3154 sum
3155}
3156
3157/// Boundary strengths an intra candidate forces (8.7.2.1): 4 on its
3158/// macroblock edges, 3 on the internal luma edges.
3159fn intra_bs(edge: usize, _seg: usize, _vertical: bool) -> u8 {
3160 if edge == 0 { 4 } else { 3 }
3161}
3162
3163/// Rough bit cost of a macroblock's luma residual.
3164fn estimate_luma_bits(lv: &Levels) -> i64 {
3165 let mut bits = 0;
3166 if lv.trans8 {
3167 for blk8 in 0..4 {
3168 if lv.cbp_luma & (1 << blk8) != 0 {
3169 // A level's position costs two more bits in a 64-coefficient
3170 // significance map than in a 16-coefficient one; measured
3171 // against the coded size on the text clip, without this the
3172 // estimate undercharges Intra_8x8 by ~44 bits a macroblock.
3173 let b = &lv.luma8[blk8];
3174 bits += block_bits(b) + 2 * b.iter().filter(|&&l| l != 0).count() as i64;
3175 }
3176 }
3177 return bits;
3178 }
3179 for blk in 0..16 {
3180 if lv.cbp_luma & (1 << (blk >> 2)) != 0 {
3181 bits += block_bits(&lv.luma[blk]);
3182 }
3183 }
3184 if lv.cbp_luma == 15 {
3185 // Intra_16x16 also carries the DC block.
3186 bits += block_bits(&lv.dc);
3187 }
3188 bits
3189}
3190
3191/// Bits one residual block costs, to the accuracy a mode decision needs.
3192fn block_bits(b: &[i32]) -> i64 {
3193 let mut n = 0i64;
3194 for &l in b {
3195 if l != 0 {
3196 n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1;
3197 }
3198 }
3199 if n > 0 { n + 6 } else { 2 }
3200}
3201
3202/// Rough bit cost of a macroblock's residual, for the skip decision: a level
3203/// costs its magnitude's exp-Golomb-ish width, a coded block its token.
3204fn estimate_bits(lv: &Levels) -> i64 {
3205 let mut bits = 10 + estimate_luma_bits(lv);
3206 if lv.cbp_chroma != 0 {
3207 for comp in 0..2 {
3208 bits += block_bits(&lv.chroma_dc[comp][..4]);
3209 if lv.cbp_chroma == 2 {
3210 for blk in 0..4 {
3211 bits += block_bits(&lv.chroma[comp][blk][..15]);
3212 }
3213 }
3214 }
3215 }
3216 bits
3217}
3218
3219/// Motion-compensate one partition into the picture planes.
3220fn compensate_part(
3221 pic: &mut Picture,
3222 reference: &Picture,
3223 mb_x: usize,
3224 mb_y: usize,
3225 (bx, by): (usize, usize),
3226 (w, h): (usize, usize),
3227 mv: [i16; 2],
3228) {
3229 let (x0, y0) = ((mb_x * 16 + bx * 4) as i32, (mb_y * 16 + by * 4) as i32);
3230 let plane = RefPlane {
3231 data: &reference.y.data,
3232 stride: reference.y.stride,
3233 origin: reference.y.origin,
3234 width: reference.y.width,
3235 height: reference.y.height,
3236 pad: reference.y.pad,
3237 };
3238 let stride = pic.y.stride;
3239 let origin = pic.y.at(mb_x * 16 + bx * 4, mb_y * 16 + by * 4);
3240 mc_luma(
3241 &plane,
3242 x0,
3243 y0,
3244 mv,
3245 w,
3246 h,
3247 stride,
3248 &mut pic.y.data[origin..],
3249 Put::Set,
3250 );
3251 for comp in 0..2 {
3252 let src = if comp == 0 {
3253 &reference.cb
3254 } else {
3255 &reference.cr
3256 };
3257 let plane = RefPlane {
3258 data: &src.data,
3259 stride: src.stride,
3260 origin: src.origin,
3261 width: src.width,
3262 height: src.height,
3263 pad: src.pad,
3264 };
3265 let dst = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
3266 let stride = dst.stride;
3267 let origin = dst.at(mb_x * 8 + bx * 2, mb_y * 8 + by * 2);
3268 mc_chroma(
3269 &plane,
3270 x0 / 2,
3271 y0 / 2,
3272 mv,
3273 w / 2,
3274 h / 2,
3275 stride,
3276 &mut dst.data[origin..],
3277 Put::Set,
3278 );
3279 }
3280}
3281
3282/// Code a P macroblock: skip, one 16x16 partition, two halves or four
3283/// quarters.
3284fn encode_inter_mb(
3285 pic: &mut Picture,
3286 e: &mut MbEnc<'_>,
3287 w: &mut EncEntropy,
3288 mb_addr: usize,
3289 nbr: MbNeighbors,
3290 choice: InterChoice,
3291) {
3292 let mb_x = mb_addr % pic.mb_w;
3293 let mb_y = mb_addr / pic.mb_w;
3294 let reference = e.reference.expect("a P macroblock has a reference");
3295 let ref_id = reference.id;
3296 let qp = e.target_qp;
3297 let shape = if choice.prefer_skip {
3298 PShape::Whole
3299 } else {
3300 choice.shape
3301 };
3302
3303 // Motion vectors, their predictors and the reconstruction, partition by
3304 // partition and in coding order: a partition's predictor reads the motion
3305 // of the partitions before it (8.4.1.3), so the order is not free.
3306 let mut ctx = MvCtx {
3307 mb_x,
3308 mb_y,
3309 slice_id: e.slice_id,
3310 written: 0,
3311 pos: Default::default(),
3312 };
3313 let (part_w, part_h) = shape.part_blocks();
3314 let mut mvd = [[0i16; 2]; 4];
3315 let mut inc = [[0usize; 2]; 4];
3316 for part in 0..shape.parts() {
3317 let ((bx, by), (pw, ph)) = shape.geometry(part);
3318 let mv = if choice.prefer_skip {
3319 choice.skip_mv
3320 } else {
3321 choice.mv[part]
3322 };
3323 let n = ctx.neighbours(pic, bx, by, part_w, 0);
3324 let mvp = predict_mv(&n, 0, part_w, part_h, part);
3325 // ctxIdxInc from the neighbouring partitions' absolute mvd
3326 // (9.3.3.1.1.7), read before this partition writes its own.
3327 let (gx, gy) = ((mb_x * 4 + bx) as i32, (mb_y * 4 + by) as i32);
3328 for comp in 0..2 {
3329 let sum = neighbour_mvd(pic, &ctx, gx - 1, gy, 0)[comp]
3330 + neighbour_mvd(pic, &ctx, gx, gy - 1, 0)[comp];
3331 inc[part][comp] = if sum > 32 {
3332 2
3333 } else if sum > 2 {
3334 1
3335 } else {
3336 0
3337 };
3338 }
3339 mvd[part] = [mv[0] - mvp[0], mv[1] - mvp[1]];
3340 compensate_part(pic, reference, mb_x, mb_y, (bx, by), (pw, ph), mv);
3341 for py in by..by + ph / 4 {
3342 for px in bx..bx + pw / 4 {
3343 write_block(
3344 pic,
3345 &mut ctx,
3346 px,
3347 py,
3348 [mv, [0, 0]],
3349 [0, -1],
3350 [ref_id, -1],
3351 0,
3352 );
3353 write_mvd(pic, mb_x, mb_y, px, py, 0, mvd[part]);
3354 }
3355 }
3356 }
3357
3358 // Skipping is only *available* on the P_Skip vector of a whole macroblock,
3359 // and only worth taking when the residual it drops is worth less than the
3360 // bits it saves: on static content a macroblock whose residual is pure
3361 // quantisation churn costs bits every picture and improves nothing.
3362 let may_skip = choice.prefer_skip;
3363 let (lv, skip) = if choice.force_skip {
3364 (Levels::default(), true)
3365 } else {
3366 let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y));
3367 let mut chroma_lv = Levels::default();
3368 code_chroma(pic, e, w, mb_x, mb_y, qp, false, &mut chroma_lv);
3369 let mut lv = chroma_lv.clone();
3370 let tx_mode = if e.preset == Preset::Fast {
3371 e.fast.inter_tx
3372 } else {
3373 0
3374 };
3375 if e.t8x8_inter(mb_y) && tx_mode == 1 {
3376 code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv);
3377 } else if e.t8x8_inter(mb_y) && tx_mode != 2 {
3378 // Both transform sizes on the same prediction; the cheaper
3379 // rate-distortion cost is coded.
3380 let mut pred = [0u8; 256];
3381 save_luma(pic, mb_x, mb_y, &mut pred);
3382 let mut lv4 = chroma_lv.clone();
3383 code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv4);
3384 // At Fast the 8x8 trial is only worth its time when the 4x4 coding
3385 // left a few levels in a smooth residual: an empty one cannot be
3386 // beaten and a dense one rarely is.
3387 let nz4: u32 = lv4.luma_nz.iter().map(|&n| u32::from(n)).sum();
3388 if tx_mode == 3 && (lv4.cbp_luma == 0 || nz4 > e.fast.tx8_nz_limit) {
3389 lv = lv4;
3390 } else {
3391 let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4);
3392 let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 as f64;
3393 let mut recon4 = [0u8; 256];
3394 save_luma(pic, mb_x, mb_y, &mut recon4);
3395 restore_luma(pic, mb_x, mb_y, &pred);
3396 let mut lv8 = chroma_lv;
3397 code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv8);
3398 let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8);
3399 let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64;
3400 if cost8 + e.lambda * e.t8x8_margin_bits < cost4 {
3401 lv = lv8;
3402 } else {
3403 lv = lv4;
3404 restore_luma(pic, mb_x, mb_y, &recon4);
3405 }
3406 }
3407 } else {
3408 code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv);
3409 }
3410 let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0;
3411 let skip = match ssd_skip {
3412 None => false,
3413 Some(_) if empty => true,
3414 Some(ssd_skip) => {
3415 let coded = if e.t8x8_inter(mb_y) {
3416 let bits = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv);
3417 ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64
3418 } else {
3419 ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64
3420 };
3421 if ssd_skip as f64 <= coded {
3422 // Put the prediction back: the residual has been added to it.
3423 compensate_part(pic, reference, mb_x, mb_y, (0, 0), (16, 16), choice.skip_mv);
3424 true
3425 } else {
3426 false
3427 }
3428 }
3429 };
3430 (lv, skip)
3431 };
3432
3433 let w4 = pic.mb_w * 4;
3434 if skip {
3435 for py in 0..4 {
3436 for px in 0..4 {
3437 let idx = (mb_y * 4 + py) * w4 + mb_x * 4 + px;
3438 pic.blk[idx] = BLK_SKIP;
3439 pic.mvd_abs[idx] = [0; 4];
3440 }
3441 }
3442 for dy in 0..4 {
3443 let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
3444 pic.nz_y[base..base + 4].fill(0);
3445 pic.i4_modes[base..base + 4].fill(2);
3446 }
3447 for comp in 0..2 {
3448 for dy in 0..2 {
3449 let base = (mb_y * 2 + dy) * pic.mb_w * 2 + mb_x * 2;
3450 pic.nz_c[comp][base..base + 2].fill(0);
3451 }
3452 }
3453 pic.mb_qp[mb_addr] = e.qp as i8;
3454 pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_INTER | FLAG_SKIP;
3455 pic.mb_cbp[mb_addr] = 0;
3456 pic.mb_dc_cbf[mb_addr] = 0;
3457 pic.mb_slice[mb_addr] = e.slice_id;
3458 pic.decoded_mbs += 1;
3459 e.qp_delta_inc = 0;
3460 w.skipped_mb(e.skip_inc);
3461 return;
3462 }
3463 for dy in 0..4 {
3464 let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
3465 pic.i4_modes[base..base + 4].fill(2);
3466 }
3467
3468 // ---- syntax ----
3469 w.begin_mb(&e.mb_ctx);
3470 w.coded_mb(true, e.skip_inc);
3471 w.set_intra(false);
3472 w.mb_type(true, shape.mb_type());
3473 if shape == PShape::Quad {
3474 for _ in 0..4 {
3475 w.sub_mb_type_p(0); // P_L0_8x8
3476 }
3477 }
3478 // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded.
3479 for part in 0..shape.parts() {
3480 for comp in 0..2 {
3481 w.mvd(comp, inc[part][comp], i32::from(mvd[part][comp]));
3482 }
3483 }
3484 w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false);
3485 // Every shape this encoder emits is 8x8-aligned, so the decoder reads the
3486 // flag whenever luma is coded.
3487 if lv.cbp_luma != 0 && e.transform_8x8 {
3488 w.transform_size_8x8_flag(lv.trans8);
3489 }
3490 finish_mb(
3491 pic,
3492 e,
3493 w,
3494 mb_addr,
3495 &nbr,
3496 &lv,
3497 MbRecord {
3498 intra: false,
3499 is_i16: false,
3500 chroma_mode: 0,
3501 qp,
3502 },
3503 );
3504}
3505
3506/// What the residual writer needs to know about the macroblock it closes.
3507struct MbRecord {
3508 intra: bool,
3509 is_i16: bool,
3510 chroma_mode: u8,
3511 /// The QP the residual was quantised at.
3512 qp: i32,
3513}
3514
3515/// mb_qp_delta, the residual blocks and the per-macroblock metadata: the
3516/// writing half of [`crate::decoder::finish_macroblock`].
3517fn finish_mb(
3518 pic: &mut Picture,
3519 e: &mut MbEnc<'_>,
3520 w: &mut EncEntropy,
3521 mb_addr: usize,
3522 nbr: &MbNeighbors,
3523 lv: &Levels,
3524 m: MbRecord,
3525) {
3526 let mb_x = mb_addr % pic.mb_w;
3527 let mb_y = mb_addr / pic.mb_w;
3528 let w4 = pic.mb_w * 4;
3529 let w2 = pic.mb_w * 2;
3530 let (bx0, by0) = (mb_x * 4, mb_y * 4);
3531 let (cx0, cy0) = (mb_x * 2, mb_y * 2);
3532
3533 let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || m.is_i16;
3534 let qp_y = if coded {
3535 let delta = m.qp - e.qp;
3536 w.mb_qp_delta(delta);
3537 e.qp_delta_inc = u8::from(delta != 0);
3538 e.qp = m.qp;
3539 m.qp
3540 } else {
3541 // No residual: the QP prediction chain is untouched (7.4.5), and the
3542 // deblocking filter uses the chain value.
3543 e.qp_delta_inc = 0;
3544 e.qp
3545 };
3546 pic.mb_qp[mb_addr] = qp_y as i8;
3547 pic.mb_flags[mb_addr] = FLAG_DECODED
3548 | if m.is_i16 { FLAG_I16 } else { 0 }
3549 | if m.intra { 0 } else { FLAG_INTER }
3550 // The flag only reaches the stream when the decoder reads it (7.3.5).
3551 | if lv.trans8 && (m.intra || lv.cbp_luma != 0) {
3552 FLAG_TRANS8X8
3553 } else {
3554 0
3555 }
3556 | if m.intra && m.chroma_mode != 0 {
3557 FLAG_CHROMA_PRED
3558 } else {
3559 0
3560 };
3561 pic.mb_cbp[mb_addr] = lv.cbp_luma | (lv.cbp_chroma << 4);
3562 pic.mb_slice[mb_addr] = e.slice_id;
3563 pic.decoded_mbs += 1;
3564
3565 let mut dc_cbf = 0u8;
3566 // Luma DC (Intra_16x16 only), then the luma blocks in Z-order.
3567 if m.is_i16 {
3568 let (na, nb) = luma_nz_pair(pic, nbr, bx0, by0);
3569 let tc = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb);
3570 dc_cbf |= u8::from(tc != 0);
3571 }
3572 if lv.trans8 {
3573 // The decoder's 8x8 branch: CABAC codes one cat-5 block and reports
3574 // its count in every 4x4 slot; CAVLC codes four interleaved 4x4
3575 // blocks, each with its own nC and count.
3576 for blk8 in 0..4 {
3577 let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
3578 if lv.cbp_luma & (1 << blk8) == 0 {
3579 for dy in 0..2 {
3580 let base = (by + dy) * w4 + bx;
3581 pic.nz_y[base..base + 2].fill(0);
3582 }
3583 } else if w.is_cabac() {
3584 let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None);
3585 for dy in 0..2 {
3586 let base = (by + dy) * w4 + bx;
3587 pic.nz_y[base..base + 2].fill(tc.min(16));
3588 }
3589 } else {
3590 for i4 in 0..4 {
3591 let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
3592 let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
3593 let (na, nb) = luma_nz_pair(pic, nbr, sx, sy);
3594 let sub = sub_block_4x4(&lv.luma8[blk8], i4);
3595 pic.nz_y[sy * w4 + sx] = w.residual_block(&sub, BlockCat::Luma4x4, na, nb);
3596 }
3597 }
3598 }
3599 }
3600 for blk in 0..16 {
3601 if lv.trans8 {
3602 break;
3603 }
3604 let (dx, dy) = BLK4_POS[blk];
3605 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
3606 let group = 1 << (blk >> 2);
3607 let coded_block = if m.is_i16 {
3608 lv.cbp_luma != 0
3609 } else {
3610 lv.cbp_luma & group != 0
3611 };
3612 let tc = if coded_block {
3613 let (na, nb) = luma_nz_pair(pic, nbr, bx, by);
3614 let (levels, cat) = if m.is_i16 {
3615 (&lv.luma[blk][..15], BlockCat::LumaAc)
3616 } else {
3617 (&lv.luma[blk][..16], BlockCat::Luma4x4)
3618 };
3619 w.residual_block(levels, cat, na, nb)
3620 } else {
3621 0
3622 };
3623 pic.nz_y[by * w4 + bx] = tc;
3624 }
3625 // Chroma DC then chroma AC, in bitstream order.
3626 if lv.cbp_chroma != 0 {
3627 for comp in 0..2 {
3628 let tc = w.residual_block(
3629 &lv.chroma_dc[comp][..4],
3630 BlockCat::ChromaDc(comp as u8),
3631 None,
3632 None,
3633 );
3634 dc_cbf |= u8::from(tc != 0) << (1 + comp);
3635 }
3636 }
3637 for comp in 0..2 {
3638 for blk in 0..4 {
3639 let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
3640 let tc = if lv.cbp_chroma == 2 {
3641 let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy);
3642 w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb)
3643 } else {
3644 0
3645 };
3646 pic.nz_c[comp][cy * w2 + cx] = tc;
3647 }
3648 }
3649 pic.mb_dc_cbf[mb_addr] = dc_cbf;
3650}
3651
3652/// Chroma prediction mode by rate-distortion: every available mode is coded
3653/// through the real chroma path and scored on reconstructed SSD plus the bits
3654/// its levels and its own name actually cost. The SATD-plus-mode-bits chooser
3655/// this replaced picked the mode before the quantiser had a say, which reads
3656/// as a chroma deficit at matched luma: measured with `bd_psnr_vs_x264`
3657/// against x264 `-preset medium`, BD-PSNR-YUV, GOP 10, 24 pictures:
3658///
3659/// | clip | SATD | RD |
3660/// |---|---|---|
3661/// | 3840x1608 film | -0.500 dB | -0.443 dB |
3662/// | 2560x1440 screen capture | -0.220 dB | -0.146 dB |
3663/// | 2560x1440 screen capture, second scene | -0.571 dB | -0.538 dB |
3664/// | 1080p phone clip | -1.122 dB | -1.084 dB |
3665/// | 720p web clip | -0.606 dB | -0.572 dB |
3666///
3667/// Luma is unmoved (film -0.065 -> -0.070 dB) and the encode time does not
3668/// change measurably: only intra macroblocks pay, and only four trials of the
3669/// chroma path each.
3670#[allow(clippy::too_many_arguments)]
3671fn choose_chroma_mode_rd(
3672 pic: &mut Picture,
3673 e: &MbEnc<'_>,
3674 w: &EncEntropy,
3675 nbr: &MbNeighbors,
3676 mb_x: usize,
3677 mb_y: usize,
3678 qp: i32,
3679 out: &mut Levels,
3680) -> u8 {
3681 let qp_c = chroma_qp(qp, e.cqo);
3682 let lambda = lambda_ssd(qp_c);
3683 let mut best: Option<(f64, u8, Levels, [[u8; 64]; 2])> = None;
3684 for mode in [0u8, 1, 2, 3] {
3685 let ok = match mode {
3686 1 => nbr.a,
3687 2 => nbr.b,
3688 3 => nbr.a && nbr.b && nbr.d,
3689 _ => true,
3690 };
3691 if !ok {
3692 continue;
3693 }
3694 for comp in 0..2 {
3695 let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
3696 let stride = plane.stride;
3697 let origin = plane.at(mb_x * 8, mb_y * 8);
3698 let mut win = PlaneWindow {
3699 data: &mut plane.data,
3700 stride,
3701 origin,
3702 };
3703 pred_chroma_8x8(mode, 8, &mut win, nbr.b, nbr.a);
3704 }
3705 let mut lv = Levels::default();
3706 code_chroma(pic, e, w, mb_x, mb_y, qp, true, &mut lv);
3707 let mut ssd = 0i64;
3708 let mut recon = [[0u8; 64]; 2];
3709 for comp in 0..2 {
3710 let (plane, src) = if comp == 0 {
3711 (&pic.cb, &e.src.u)
3712 } else {
3713 (&pic.cr, &e.src.v)
3714 };
3715 let origin = plane.at(mb_x * 8, mb_y * 8);
3716 for ry in 0..8 {
3717 for rx in 0..8 {
3718 let r = plane.data[origin + ry * plane.stride + rx];
3719 recon[comp][ry * 8 + rx] = r;
3720 let d = i64::from(src[(mb_y * 8 + ry) * e.src.c_stride + mb_x * 8 + rx])
3721 - i64::from(r);
3722 ssd += d * d;
3723 }
3724 }
3725 }
3726 let mut bits = match mode {
3727 0 => 1.0,
3728 3 => 5.0,
3729 _ => 3.0,
3730 };
3731 for comp in 0..2 {
3732 bits += match w.residual_block_cost(
3733 &lv.chroma_dc[comp],
3734 BlockCat::ChromaDc(comp as u8),
3735 Some(1),
3736 Some(1),
3737 ) {
3738 Some(b) => f64::from(b) / 256.0,
3739 None => block_bits(&lv.chroma_dc[comp]) as f64,
3740 };
3741 for blk in 0..4 {
3742 bits += match w.residual_block_cost(
3743 &lv.chroma[comp][blk],
3744 BlockCat::ChromaAc,
3745 Some(1),
3746 Some(1),
3747 ) {
3748 Some(b) => f64::from(b) / 256.0,
3749 None => block_bits(&lv.chroma[comp][blk]) as f64,
3750 };
3751 }
3752 }
3753 let cost = ssd as f64 + lambda * bits;
3754 if best.as_ref().is_none_or(|b| cost < b.0) {
3755 best = Some((cost, mode, lv, recon));
3756 }
3757 }
3758 let (_, mode, lv, recon) = best.expect("chroma DC prediction is always available");
3759 for comp in 0..2 {
3760 let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
3761 let stride = plane.stride;
3762 let origin = plane.at(mb_x * 8, mb_y * 8);
3763 for ry in 0..8 {
3764 for rx in 0..8 {
3765 plane.data[origin + ry * stride + rx] = recon[comp][ry * 8 + rx];
3766 }
3767 }
3768 }
3769 *out = lv;
3770 mode
3771}
3772
3773/// The mode decision of [`code_intra_8x8`]: for every allowed mode, predict,
3774/// code the 8x8 residual at the real QP and score `SSD + lambda * bits`, then
3775/// keep the cheapest. The SATD chooser this replaced scored the prediction
3776/// residual before the quantiser had a say, so it optimised a proxy.
3777///
3778/// Returns the winning mode, its coded levels with whether the block has any,
3779/// and the reconstructed 8x8 to write back. Measured on BD-PSNR against x264
3780/// with the 8x8 transform on, GOP 10, 24 consecutive pictures, luma / YUV:
3781/// • 3840x1608 film: +0.475 / -0.068 -> +0.512 / -0.035
3782/// • 1138x640 web: +0.040 / -0.031 -> +0.076 / +0.003
3783/// • 854x480 web: +0.070 / +0.047 -> +0.132 / +0.108
3784/// • 2560x1440 screen: -0.206 / -0.199 -> -0.215 / -0.207
3785/// Three clips of four gain; the screen capture loses 0.008 dB. Encode time
3786/// moves from 12 s to 13 s on the 854x480 clip.
3787#[allow(clippy::too_many_arguments)]
3788fn i8_mode_by_rd(
3789 pic: &mut Picture,
3790 e: &MbEnc<'_>,
3791 w: &EncEntropy,
3792 x: usize,
3793 y: usize,
3794 qp: i32,
3795 n: &crate::pred::Nbr8,
3796 allowed: &[bool; 9],
3797 predicted: u8,
3798 p: &mut [u8; 64],
3799) -> (u8, ([i32; 64], bool), [u8; 64]) {
3800 let lambda = lambda_ssd(qp);
3801 let stride = pic.y.stride;
3802 let origin = pic.y.at(x, y);
3803 type Best = Option<(f64, u8, [i32; 64], bool, [u8; 64])>;
3804 let mut best: Best = None;
3805 for mode in 0..9u8 {
3806 if !allowed[mode as usize] {
3807 continue;
3808 }
3809 pred_8x8(mode, 8, n, p);
3810 for ry in 0..8 {
3811 let row = origin + ry * stride;
3812 pic.y.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]);
3813 }
3814 let mut levels = [0i32; 64];
3815 let nz = code_block_8x8(pic, e, w, x, y, qp, true, &mut levels);
3816 let mut ssd = 0i64;
3817 let mut recon = [0u8; 64];
3818 for ry in 0..8 {
3819 let row = origin + ry * stride;
3820 for rx in 0..8 {
3821 let r = pic.y.data[row + rx];
3822 recon[ry * 8 + rx] = r;
3823 let d = i64::from(e.src.y[(y + ry) * e.src.stride + x + rx]) - i64::from(r);
3824 ssd += d * d;
3825 }
3826 }
3827 let mut bits = if mode == predicted { 1.0 } else { 4.0 };
3828 if nz > 0 {
3829 // `Luma8x8` has no coded_block_flag of its own — the CBP carries it
3830 // — so it needs the 8x8 cost path, not the cbf-indexed one.
3831 bits += match w.residual_block_8x8_cost(&levels) {
3832 Some(b) => f64::from(b) / 256.0,
3833 None => block_bits(&levels) as f64,
3834 };
3835 }
3836 let cost = ssd as f64 + lambda * bits;
3837 if best.as_ref().is_none_or(|b| cost < b.0) {
3838 best = Some((cost, mode, levels, nz > 0, recon));
3839 }
3840 }
3841 let (_, mode, levels, coded, recon) =
3842 best.expect("Intra_8x8 always has at least the DC mode available");
3843 (mode, (levels, coded), recon)
3844}