forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ctu.rs2110 lines, 80.9 KiBHistoryRawDownload
1//! Coding tree unit encoding: the quadtree, the mode decision, the transform
2//! unit and the reconstruction (7.3.8.4 - 7.3.8.10).
3//!
4//! # The cost model
5//!
6//! Every decision minimises `J = SSD + lambda * bits`, where `SSD` is the sum of
7//! squared differences between source and *reconstructed* samples and `bits` is
8//! what the CABAC coder actually spends — measured by encoding the candidate
9//! into the real coder and rolling it back, not estimated from a table.
10//! `lambda = 0.57 * 2^((QP - 12) / 3)` is the usual intra Lagrangian; the 35-mode
11//! pre-screen uses `sqrt(lambda)` against a Hadamard SATD, because SATD
12//! estimates rate and distortion together where SSD estimates only distortion.
13//!
14//! # The shape of the tree
15//!
16//! Coding units are 32, 16 or 8 luma samples square, one transform unit per
17//! coding unit, `PART_2Nx2N` only, chroma always in derived mode (`DM`). A 64x64
18//! coding tree block therefore always writes one `split_cu_flag` of 1 and
19//! decides freely below it. What that gives up is named rather than hidden:
20//! `PART_NxN` with 4x4 luma transforms would hold fine detail at low QP, and a
21//! 64x64 coding unit would save a few bits on flat sky. Both cost search time,
22//! which this encoder spends on the wavefront that makes one `encode` call use
23//! every core instead.
24
25use crate::cabac::{CabacEncoder, CabacState, Contexts, ctx};
26use crate::encoder::TransformSkip;
27use crate::intra::{self, Availability, Refs};
28use crate::residual::{self, encode_residual};
29use crate::transform::{
30 chroma_qp_bd, dequantize_bd, forward_transform, forward_transform_skip, inverse_transform_bd,
31 inverse_transform_skip_bd, quant_qp, quantize, quantize_offset, scale_forward_bd, uses_dst,
32};
33use std::sync::atomic::{AtomicU8, AtomicU16, Ordering};
34
35#[cfg(target_arch = "x86_64")]
36use archmage::{SimdToken, X64V1Token, arcane};
37
38/// A picture sample as the encoder stores it: `u16` at every bit depth, the
39/// values 0..=255 for 8-bit pictures.
40pub type Pel = u16;
41
42/// The rounding the rate-distortion level search starts from, as a divisor of
43/// the quantiser step: 2 is round-to-nearest, against the 3 the plain path
44/// uses. A search that only takes levels down measures the rounding it was
45/// handed, so it gets the wider one. Swept on 1080p film at the settled
46/// lambda: 1/2 +0.360 dB BD-PSNR against x265, 1/3 +0.315, 1/4 +0.118.
47const RDOQ_DEAD_ZONE: i64 = 2;
48
49/// The same rounding for the chroma path, swept on its own because the sparser
50/// chroma of an intra picture answered differently in ec-h264.
51///
52/// Here it does not: coarser chroma rounding reads better and better on luma
53/// BD-PSNR (1/2 +0.360, 1/6 +0.525, 1/12 +0.568, 1/24 +0.585 dB) while the
54/// all-plane figure falls the whole way (+0.276, +0.231, +0.169, +0.128). That
55/// arm is chroma being starved to buy luma bits, which only a luma-only metric
56/// calls a gain, so chroma keeps luma's rounding.
57const RDOQ_DEAD_ZONE_C: i64 = 2;
58
59/// `log2` of the smallest coding block this encoder makes: 8x8.
60pub const MIN_CB_LOG2: u32 = 3;
61
62/// Rate-distortion lambda for an intra picture at `qp`.
63pub fn lambda_for(qp: i32) -> f64 {
64 0.57 * 2f64.powf((qp - 12) as f64 / 3.0)
65}
66
67/// The samples of one CTB row that the row below may predict from: its bottom
68/// line, plus the coding depths along it.
69///
70/// This is the *entire* dependency between two wavefront rows. Intra prediction
71/// reads one row above the block it predicts, and the only other thing a row
72/// below asks about the row above is `CtDepth` for one context — so a worker
73/// publishes a line per CTB and nothing else.
74pub struct RowBoundary {
75 /// Bottom luma line, one entry per column.
76 pub y: Vec<AtomicU16>,
77 /// Bottom Cb line.
78 pub cb: Vec<AtomicU16>,
79 /// Bottom Cr line.
80 pub cr: Vec<AtomicU16>,
81 /// `CtDepth` along the bottom, one entry per four columns.
82 pub depth: Vec<AtomicU8>,
83}
84
85impl RowBoundary {
86 /// Storage for a picture `width` luma samples wide.
87 pub fn new(width: usize) -> RowBoundary {
88 let make = |n: usize| (0..n).map(|_| AtomicU16::new(0)).collect();
89 let make8 = |n: usize| (0..n).map(|_| AtomicU8::new(0)).collect();
90 RowBoundary {
91 y: make(width),
92 cb: make(width / 2),
93 cr: make(width / 2),
94 depth: make8(width / 4),
95 }
96 }
97}
98
99/// Source planes for one picture, already padded to the coded size.
100pub struct SourcePlanes<'a> {
101 /// Luma plane, `width * height`.
102 pub y: &'a [Pel],
103 /// Cb plane, `width / 2 * height / 2`.
104 pub cb: &'a [Pel],
105 /// Cr plane.
106 pub cr: &'a [Pel],
107}
108
109/// The mutable state one wavefront worker owns while coding one CTB row.
110pub struct RowState<'a> {
111 /// Reconstructed luma for this row band.
112 pub rec_y: &'a mut [Pel],
113 /// Reconstructed Cb for this row band.
114 pub rec_cb: &'a mut [Pel],
115 /// Reconstructed Cr for this row band.
116 pub rec_cr: &'a mut [Pel],
117 /// The boundary this row publishes for the row below.
118 pub publish: &'a RowBoundary,
119 /// The boundary the row above published; absent for the first row.
120 pub above: Option<&'a RowBoundary>,
121}
122
123/// Scratch buffers, allocated once per row rather than per block.
124struct Scratch {
125 pred: Vec<Pel>,
126 residual: Vec<i32>,
127 coeffs: Vec<i32>,
128 scaled: Vec<i32>,
129 recon: Vec<Pel>,
130 best_recon: Vec<Pel>,
131 levels: Vec<i32>,
132 best_levels: Vec<i32>,
133 /// Smoothed copy of the current luma reference samples (see `luma_refs`).
134 filt: Option<Refs<Pel>>,
135 source: Vec<Pel>,
136 luma_levels: Vec<i32>,
137 cb_levels: Vec<i32>,
138 cr_levels: Vec<i32>,
139}
140
141impl Scratch {
142 fn new() -> Scratch {
143 Scratch {
144 pred: vec![0; 32 * 32],
145 residual: vec![0; 32 * 32],
146 coeffs: vec![0; 32 * 32],
147 scaled: vec![0; 32 * 32],
148 recon: vec![0; 32 * 32],
149 best_recon: vec![0; 32 * 32],
150 levels: vec![0; 32 * 32],
151 best_levels: vec![0; 32 * 32],
152 filt: None,
153 source: vec![0; 32 * 32],
154 luma_levels: vec![0; 32 * 32],
155 cb_levels: vec![0; 16 * 16],
156 cr_levels: vec![0; 16 * 16],
157 }
158 }
159}
160
161/// Encoder for one CTB row.
162pub struct CtuEncoder<'a> {
163 src: SourcePlanes<'a>,
164 row: RowState<'a>,
165 width: usize,
166 height: usize,
167 /// Luma and chroma bit depth (8 or 10).
168 bit_depth: u32,
169 /// The largest sample value, `(1 << bit_depth) - 1`.
170 max: i32,
171 /// The mid-grey sample a row with no row above predicts from.
172 half: Pel,
173 ctb_size: usize,
174 band_y0: usize,
175 band_rows: usize,
176 qp: i32,
177 qp_c: i32,
178 lambda: f64,
179 lambda_satd: f64,
180 strong_smoothing: bool,
181 /// How many of the 35 modes get a full rate-distortion trial.
182 candidates: usize,
183 /// Whether the chroma mode is chosen by rate-distortion or always derived.
184 chroma_rd: bool,
185 /// Weight on chroma SSD in that decision, against luma's lambda.
186 chroma_rd_weight: f64,
187 /// Whether an 8x8 coding unit may split into four 4x4 intra partitions.
188 intra_nxn: bool,
189 sign_hiding: bool,
190 /// Whether the levels get a rate-distortion search after quantisation.
191 rdoq: bool,
192 transform_skip: bool,
193 /// Whether every 4x4 luma block decides transform skip by rate-distortion
194 /// instead of taking `transform_skip` unconditionally.
195 ts_rd: bool,
196 /// The skip decision for the 4x4 luma block currently in the scratch.
197 ts_luma: bool,
198 rqt: bool,
199 /// Whether a 64x64 coding tree block may stay one coding unit rather than
200 /// always splitting to 32x32.
201 cu64: bool,
202 /// The counting CABAC engine that search prices its trials with.
203 rdoq_enc: CabacEncoder,
204 /// `log2` of the smallest coding unit the search will produce.
205 min_cb_log2: u32,
206 /// Intra mode per 4x4 block of the band; 255 = not coded yet.
207 modes: Vec<u8>,
208 /// Coding depth per 4x4 block of the band.
209 depths: Vec<u8>,
210 /// `log2` of the transform block covering each 4x4 block of the band,
211 /// which is all the deblocking filter needs to find its edges.
212 tu_log2: Vec<u8>,
213 /// Which 4x4 blocks of the *current* CTB are reconstructed.
214 coded: [bool; 256],
215 ctu_x: usize,
216 /// Whether the coding unit just coded spent no residual at all — the cue
217 /// that splitting it further would only spend flags.
218 last_cu_empty: bool,
219 scratch: Scratch,
220}
221
222impl<'a> CtuEncoder<'a> {
223 /// A worker for the CTB row whose first luma row is `band_y0`.
224 #[allow(clippy::too_many_arguments)]
225 pub fn new(
226 src: SourcePlanes<'a>,
227 row: RowState<'a>,
228 width: usize,
229 height: usize,
230 ctb_size: usize,
231 band_y0: usize,
232 qp: i32,
233 strong_smoothing: bool,
234 candidates: usize,
235 chroma_rd: bool,
236 chroma_rd_weight: f64,
237 intra_nxn: bool,
238 sign_hiding: bool,
239 rdoq: bool,
240 rdoq_estimate: bool,
241 transform_skip: TransformSkip,
242 rqt: bool,
243 cu64: bool,
244 min_cb_log2: u32,
245 bit_depth: u32,
246 ) -> CtuEncoder<'a> {
247 let band_rows = (height - band_y0).min(ctb_size);
248 // qP is QpY + QpBdOffset (8.6.1). The quantiser, the dequantiser and the
249 // lambda all work on qP; the QpY argument only feeds the CABAC contexts.
250 let qp_bd = qp + 6 * (bit_depth as i32 - 8);
251 CtuEncoder {
252 src,
253 row,
254 width,
255 height,
256 bit_depth,
257 max: (1 << bit_depth) - 1,
258 half: 1 << (bit_depth - 1),
259 ctb_size,
260 band_y0,
261 band_rows,
262 qp: qp_bd,
263 qp_c: chroma_qp_bd(qp, 0, bit_depth) + 6 * (bit_depth as i32 - 8),
264 lambda: lambda_for(qp_bd),
265 lambda_satd: lambda_for(qp_bd).sqrt(),
266 strong_smoothing,
267 candidates: candidates.clamp(1, 35),
268 chroma_rd,
269 chroma_rd_weight,
270 intra_nxn,
271 sign_hiding,
272 rdoq,
273 transform_skip: transform_skip == TransformSkip::AlwaysFor4x4,
274 ts_rd: transform_skip == TransformSkip::Rd,
275 ts_luma: false,
276 rqt,
277 cu64,
278 rdoq_enc: {
279 let mut enc = CabacEncoder::counter(Contexts::new(qp.clamp(0, 51)));
280 enc.set_estimating(rdoq_estimate);
281 enc
282 },
283 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),
284 modes: vec![255; (width / 4) * (ctb_size / 4)],
285 depths: vec![0; (width / 4) * (ctb_size / 4)],
286 tu_log2: vec![2; (width / 4) * (ctb_size / 4)],
287 coded: [false; 256],
288 ctu_x: 0,
289 last_cu_empty: false,
290 scratch: Scratch::new(),
291 }
292 }
293
294 /// `log2` of the transform block covering each 4x4 unit of this row's
295 /// band, in raster order across the whole picture width.
296 pub fn tu_log2_band(&self) -> &[u8] {
297 &self.tu_log2
298 }
299
300 /// Code one coding tree unit at CTB column `ctu_x`.
301 pub fn encode_ctu(&mut self, ctu_x: usize, enc: &mut CabacEncoder) {
302 self.ctu_x = ctu_x;
303 self.coded = [false; 256];
304 let log2_ctb = self.ctb_size.trailing_zeros();
305 self.code_quadtree(ctu_x * self.ctb_size, self.band_y0, log2_ctb, 0, enc);
306 self.publish_boundary(ctu_x);
307 }
308
309 /// Copy this CTB's bottom line into the boundary the next row reads.
310 fn publish_boundary(&self, ctu_x: usize) {
311 let last = self.band_y0 + self.band_rows - 1;
312 let x0 = ctu_x * self.ctb_size;
313 let x1 = (x0 + self.ctb_size).min(self.width);
314 for x in x0..x1 {
315 self.row.publish.y[x].store(self.rec_y(x, last), Ordering::Relaxed);
316 }
317 let cy = (self.band_y0 + self.band_rows) / 2 - 1;
318 for x in x0 / 2..x1 / 2 {
319 self.row.publish.cb[x].store(self.rec_c(x, cy, 1), Ordering::Relaxed);
320 self.row.publish.cr[x].store(self.rec_c(x, cy, 2), Ordering::Relaxed);
321 }
322 for x in x0 / 4..x1 / 4 {
323 let depth = self.depths[((self.band_rows - 1) / 4) * (self.width / 4) + x];
324 self.row.publish.depth[x].store(depth, Ordering::Relaxed);
325 }
326 }
327
328 fn rec_y(&self, x: usize, y: usize) -> Pel {
329 if y < self.band_y0 {
330 self.row
331 .above
332 .map_or(self.half, |above| above.y[x].load(Ordering::Relaxed))
333 } else {
334 self.row.rec_y[(y - self.band_y0) * self.width + x]
335 }
336 }
337
338 /// Reconstructed chroma sample, in chroma coordinates.
339 fn rec_c(&self, x: usize, y: usize, plane: usize) -> Pel {
340 let band_c0 = self.band_y0 / 2;
341 if y < band_c0 {
342 self.row.above.map_or(self.half, |above| {
343 let line = if plane == 1 { &above.cb } else { &above.cr };
344 line[x].load(Ordering::Relaxed)
345 })
346 } else {
347 let data = if plane == 1 {
348 &*self.row.rec_cb
349 } else {
350 &*self.row.rec_cr
351 };
352 data[(y - band_c0) * (self.width / 2) + x]
353 }
354 }
355
356 /// Availability of a luma position: inside the picture and already coded in
357 /// raster CTB order, then z-scan order inside the current CTB.
358 fn available(&self, x: isize, y: isize) -> bool {
359 if x < 0 || y < 0 || x >= self.width as isize || y >= self.height as isize {
360 return false;
361 }
362 let (x, y) = (x as usize, y as usize);
363 if y < self.band_y0 {
364 // Every CTB in a row above is coded. The wavefront guarantees the
365 // ones a block can actually reach — at most one CTB to the right —
366 // are also finished.
367 debug_assert!(x < (self.ctu_x + 2) * self.ctb_size);
368 return self.row.above.is_some();
369 }
370 if y >= self.band_y0 + self.band_rows {
371 return false;
372 }
373 let cx = x / self.ctb_size;
374 match cx.cmp(&self.ctu_x) {
375 std::cmp::Ordering::Less => true,
376 std::cmp::Ordering::Greater => false,
377 std::cmp::Ordering::Equal => {
378 let bx = (x - self.ctu_x * self.ctb_size) / 4;
379 let by = (y - self.band_y0) / 4;
380 self.coded[by * 16 + bx]
381 }
382 }
383 }
384
385 fn mode_at(&self, x: usize, y: usize) -> u8 {
386 self.modes[((y - self.band_y0) / 4) * (self.width / 4) + x / 4]
387 }
388
389 fn depth_at(&self, x: usize, y: usize) -> u8 {
390 if y < self.band_y0 {
391 return self
392 .row
393 .above
394 .map_or(0, |above| above.depth[x / 4].load(Ordering::Relaxed));
395 }
396 self.depths[((y - self.band_y0) / 4) * (self.width / 4) + x / 4]
397 }
398
399 // ---- the quadtree ----------------------------------------------------
400
401 fn code_quadtree(
402 &mut self,
403 x: usize,
404 y: usize,
405 log2: u32,
406 depth: u8,
407 enc: &mut CabacEncoder,
408 ) -> f64 {
409 let size = 1usize << log2;
410 let half = size / 2;
411 if x + size > self.width || y + size > self.height {
412 // split_cu_flag is inferred to 1 and only the children inside the
413 // picture are coded (7.3.8.4).
414 let mut cost = 0.0;
415 for (dx, dy) in [(0, 0), (half, 0), (0, half), (half, half)] {
416 if x + dx < self.width && y + dy < self.height {
417 cost += self.code_quadtree(x + dx, y + dy, log2 - 1, depth + 1, enc);
418 }
419 }
420 return cost;
421 }
422 if log2 == MIN_CB_LOG2 {
423 return self.code_cu(x, y, log2, depth, enc);
424 }
425 let split_ctx = ctx::SPLIT_CU
426 + usize::from(
427 self.available(x as isize - 1, y as isize) && self.depth_at(x - 1, y) > depth,
428 )
429 + usize::from(
430 self.available(x as isize, y as isize - 1) && self.depth_at(x, y - 1) > depth,
431 );
432 if log2 <= self.min_cb_log2 {
433 // The search stops here, but the sequence still allows a split, so
434 // the flag is written: skipping it because *this* encoder will not
435 // split is exactly the kind of "the decoder knows what I meant"
436 // assumption that desynchronises a bitstream.
437 let before = enc.bit_count();
438 enc.encode_bin(split_ctx, 0);
439 return self.lambda * (enc.bit_count() - before) as f64
440 + self.code_cu(x, y, log2, depth, enc);
441 }
442 if log2 > 5 && !self.cu64 {
443 // 64x64 coding units are not searched; the decision starts at 32x32.
444 let before = enc.bit_count();
445 enc.encode_bin(split_ctx, 1);
446 let mut cost = self.lambda * (enc.bit_count() - before) as f64;
447 for (dx, dy) in [(0, 0), (half, 0), (0, half), (half, half)] {
448 cost += self.code_quadtree(x + dx, y + dy, log2 - 1, depth + 1, enc);
449 }
450 return cost;
451 }
452
453 let start = enc.snapshot();
454 // The z-scan availability map has to go back with everything else: the
455 // leaf trial marks the whole region reconstructed, and a split trial run
456 // against that map would predict from samples the *decoder* considers
457 // unavailable and derive its contexts from them too. That is a
458 // desynchronisation, not an inefficiency — it was worth a whole picture
459 // of garbage before this line existed.
460 let coded_before = self.coded;
461 let before = enc.bit_count();
462 enc.encode_bin(split_ctx, 0);
463 let flag_bits = enc.bit_count() - before;
464 let leaf_cost = self.lambda * flag_bits as f64 + self.code_cu(x, y, log2, depth, enc);
465 if self.last_cu_empty {
466 // Every coefficient quantised to zero: the four sub-trees can only
467 // add split flags and mode bits on top of the same prediction, so
468 // the split is not searched. This is where most of the picture is.
469 return leaf_cost;
470 }
471 let leaf_state = enc.snapshot_since(&start);
472 let leaf_rec = self.save_region(x, y, size);
473 let leaf_meta = self.save_meta(x, y, size);
474
475 enc.restore(&start);
476 self.coded = coded_before;
477 let before = enc.bit_count();
478 enc.encode_bin(split_ctx, 1);
479 let mut split_cost = self.lambda * (enc.bit_count() - before) as f64;
480 for (dx, dy) in [(0, 0), (half, 0), (0, half), (half, half)] {
481 split_cost += self.code_quadtree(x + dx, y + dy, log2 - 1, depth + 1, enc);
482 }
483
484 if leaf_cost <= split_cost {
485 enc.restore(&leaf_state);
486 self.load_region(x, y, size, &leaf_rec);
487 self.load_meta(x, y, size, &leaf_meta);
488 leaf_cost
489 } else {
490 split_cost
491 }
492 }
493
494 /// Reconstructed samples of a square luma region and its chroma, packed.
495 fn save_region(&self, x: usize, y: usize, size: usize) -> Vec<Pel> {
496 let mut out = Vec::with_capacity(size * size * 3 / 2);
497 for yy in y..y + size {
498 for xx in x..x + size {
499 out.push(self.rec_y(xx, yy));
500 }
501 }
502 for plane in [1usize, 2] {
503 for yy in y / 2..y / 2 + size / 2 {
504 for xx in x / 2..x / 2 + size / 2 {
505 out.push(self.rec_c(xx, yy, plane));
506 }
507 }
508 }
509 out
510 }
511
512 fn load_region(&mut self, x: usize, y: usize, size: usize, data: &[Pel]) {
513 let mut i = 0;
514 for yy in y..y + size {
515 for xx in x..x + size {
516 self.write_rec_y(xx, yy, data[i]);
517 i += 1;
518 }
519 }
520 for plane in [1usize, 2] {
521 for yy in y / 2..y / 2 + size / 2 {
522 for xx in x / 2..x / 2 + size / 2 {
523 self.write_rec_c(xx, yy, plane, data[i]);
524 i += 1;
525 }
526 }
527 }
528 }
529
530 fn save_meta(&self, x: usize, y: usize, size: usize) -> Vec<u8> {
531 let stride = self.width / 4;
532 let mut out = Vec::with_capacity(3 * (size / 4) * (size / 4));
533 for by in (y..y + size).step_by(4) {
534 for bx in (x..x + size).step_by(4) {
535 let idx = ((by - self.band_y0) / 4) * stride + bx / 4;
536 out.push(self.modes[idx]);
537 out.push(self.depths[idx]);
538 out.push(self.tu_log2[idx]);
539 }
540 }
541 out
542 }
543
544 fn load_meta(&mut self, x: usize, y: usize, size: usize, data: &[u8]) {
545 let stride = self.width / 4;
546 let mut i = 0;
547 for by in (y..y + size).step_by(4) {
548 for bx in (x..x + size).step_by(4) {
549 let idx = ((by - self.band_y0) / 4) * stride + bx / 4;
550 self.modes[idx] = data[i];
551 self.depths[idx] = data[i + 1];
552 self.tu_log2[idx] = data[i + 2];
553 i += 3;
554 }
555 }
556 }
557
558 fn write_rec_y(&mut self, x: usize, y: usize, value: Pel) {
559 let stride = self.width;
560 self.row.rec_y[(y - self.band_y0) * stride + x] = value;
561 }
562
563 fn write_rec_c(&mut self, x: usize, y: usize, plane: usize, value: Pel) {
564 let stride = self.width / 2;
565 let band_c0 = self.band_y0 / 2;
566 let data = if plane == 1 {
567 &mut *self.row.rec_cb
568 } else {
569 &mut *self.row.rec_cr
570 };
571 data[(y - band_c0) * stride + x] = value;
572 }
573
574 // ---- one coding unit -------------------------------------------------
575
576 /// Code one coding unit, returning `SSD + lambda * bits` for it. The split
577 /// flag above it is the caller's to count. At the smallest coding unit the
578 /// partition mode is a rate-distortion decision between one 8x8 block and
579 /// four 4x4 ones; everywhere else there is only PART_2Nx2N.
580 fn code_cu(&mut self, x: usize, y: usize, log2: u32, depth: u8, enc: &mut CabacEncoder) -> f64 {
581 if log2 != MIN_CB_LOG2 || !self.intra_nxn {
582 return self.code_cu_2nx2n(x, y, log2, depth, enc);
583 }
584 let start = enc.snapshot();
585 let coded_before = self.coded;
586 let size = 1usize << log2;
587
588 let square_cost = self.code_cu_2nx2n(x, y, log2, depth, enc);
589 let square_state = enc.snapshot_since(&start);
590 let square_rec = self.save_region(x, y, size);
591 let square_meta = self.save_meta(x, y, size);
592 let square_empty = self.last_cu_empty;
593
594 enc.restore(&start);
595 self.coded = coded_before;
596 let nxn_cost = self.code_cu_nxn(x, y, depth, enc);
597
598 if square_cost <= nxn_cost {
599 enc.restore(&square_state);
600 self.load_region(x, y, size, &square_rec);
601 self.load_meta(x, y, size, &square_meta);
602 self.last_cu_empty = square_empty;
603 square_cost
604 } else {
605 nxn_cost
606 }
607 }
608
609 /// The four-4x4-partition form of the smallest coding unit: four luma
610 /// prediction units, each its own transform block, over one 4x4 chroma
611 /// block that keeps the coding unit's single chroma mode.
612 fn code_cu_nxn(&mut self, x: usize, y: usize, depth: u8, enc: &mut CabacEncoder) -> f64 {
613 let before = enc.bit_count();
614 // The mode search reconstructs each partition as it goes, because the
615 // next one predicts from it; the syntax is written afterwards in the
616 // order the decoder reads it.
617 let offsets = [(0usize, 0usize), (4, 0), (0, 4), (4, 4)];
618 let mut modes = [0u8; 4];
619 let mut mpms = [[0u8; 3]; 4];
620 let mut levels = [[0i32; 16]; 4];
621 let mut cbfs = [false; 4];
622 let mut tskip = [self.transform_skip; 4];
623 for (part, &(dx, dy)) in offsets.iter().enumerate() {
624 let (px, py) = (x + dx, y + dy);
625 let mpm = self.mpm_at(px, py);
626 let mode = self.choose_luma_mode(px, py, 4, 2, &mpm, enc);
627 levels[part].copy_from_slice(&self.scratch.luma_levels[..16]);
628 if self.ts_rd {
629 tskip[part] = self.ts_luma;
630 }
631 cbfs[part] = levels[part].iter().any(|&v| v != 0);
632 modes[part] = mode;
633 mpms[part] = mpm;
634 self.mark_coded(px, py, 4, mode, depth);
635 self.mark_tu(px, py, 4);
636 }
637
638 // part_mode: PART_NxN is the single bin 0.
639 enc.encode_bin(ctx::PART_MODE, 0);
640 for part in 0..4 {
641 self.write_mode_prev_flag(enc, modes[part], &mpms[part]);
642 }
643 for part in 0..4 {
644 self.write_mode_remainder(enc, modes[part], &mpms[part]);
645 }
646
647 // The chroma mode belongs to the coding unit and derives from the
648 // first partition's luma mode (8.4.3).
649 let (chroma_mode, chroma_idx) = if self.chroma_rd {
650 self.choose_chroma_mode(x, y, 8, MIN_CB_LOG2, modes[0], self.transform_skip, enc)
651 } else {
652 (modes[0], None)
653 };
654 self.write_chroma_mode_syntax(enc, chroma_idx);
655 let cb_cbf = self
656 .code_chroma(x, y, 8, chroma_mode, 1, self.transform_skip)
657 .1;
658 let cr_cbf = self
659 .code_chroma(x, y, 8, chroma_mode, 2, self.transform_skip)
660 .1;
661
662 // transform_tree: the split at depth 0 is inferred from the partition
663 // mode, so only the chroma flags are written there; every luma flag and
664 // residual belongs to a 4x4 child at depth 1, and the chroma residual
665 // rides along with the last of them (7.3.8.8, 7.3.8.10).
666 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));
667 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));
668 for part in 0..4 {
669 enc.encode_bin(ctx::CBF_LUMA, u32::from(cbfs[part]));
670 if cbfs[part] {
671 let scan = intra::scan_index(modes[part], 2, true);
672 encode_residual(
673 enc,
674 &levels[part],
675 2,
676 0,
677 scan,
678 self.sign_hiding,
679 self.ts_flag(tskip[part]),
680 );
681 }
682 if part == 3 {
683 let chroma_scan = intra::scan_index(chroma_mode, 2, false);
684 if cb_cbf {
685 let l = std::mem::take(&mut self.scratch.cb_levels);
686 encode_residual(
687 enc,
688 &l[..16],
689 2,
690 1,
691 chroma_scan,
692 self.sign_hiding,
693 self.ts_flag(self.transform_skip),
694 );
695 self.scratch.cb_levels = l;
696 }
697 if cr_cbf {
698 let l = std::mem::take(&mut self.scratch.cr_levels);
699 encode_residual(
700 enc,
701 &l[..16],
702 2,
703 2,
704 chroma_scan,
705 self.sign_hiding,
706 self.ts_flag(self.transform_skip),
707 );
708 self.scratch.cr_levels = l;
709 }
710 }
711 }
712
713 self.last_cu_empty = !(cbfs.iter().any(|&c| c) || cb_cbf || cr_cbf);
714 let bits = enc.bit_count() - before;
715 self.region_ssd(x, y, 8) + self.lambda * bits as f64
716 }
717
718 /// Code one 64x64 coding unit.
719 ///
720 /// HEVC's largest transform block is 32x32, so the transform tree of a
721 /// 64x64 coding unit is split without a `split_transform_flag` -- the
722 /// decoder infers the split from `log2TrafoSize > MaxTbLog2SizeY` (7.4.9.8)
723 /// -- and intra prediction runs per transform block, four 32x32 ones in
724 /// z-order, each predicting from the reconstruction of the ones before it.
725 /// The coding unit carries a single luma mode and a single chroma mode, so
726 /// what it saves over four 32x32 coding units is three split flags and
727 /// three mode signallings; what it gives up is three quarters of the
728 /// freedom to pick a direction.
729 ///
730 /// The mode search runs on the first quadrant: that is the only one whose
731 /// neighbours are settled before a mode is chosen, and it is what the
732 /// reference encoder does for the same reason.
733 fn code_cu_64(&mut self, x: usize, y: usize, depth: u8, enc: &mut CabacEncoder) -> f64 {
734 const N: usize = 64;
735 const HALF: usize = 32;
736 const LOG2: u32 = 6;
737 let chroma_tskip = self.transform_skip;
738 let before = enc.bit_count();
739
740 let mpm = self.mpm_at(x, y);
741 // Reconstructs the first quadrant under the mode it picks, leaving its
742 // levels in the luma scratch.
743 let mode = self.choose_luma_mode(x, y, HALF, LOG2 - 1, &mpm, enc);
744 self.write_mode_syntax(enc, mode, &mpm);
745 let (chroma_mode, chroma_idx) = if self.chroma_rd {
746 self.choose_chroma_mode(x, y, HALF, LOG2 - 1, mode, chroma_tskip, enc)
747 } else {
748 (mode, None)
749 };
750 self.write_chroma_mode_syntax(enc, chroma_idx);
751
752 let mut child_levels = [[0i32; 1024]; 4];
753 let mut child_tskip = [self.transform_skip; 4];
754 let mut child_cbf = [false; 4];
755 let mut child_cb = [[0i32; 256]; 4];
756 let mut child_cr = [[0i32; 256]; 4];
757 let mut child_cb_cbf = [false; 4];
758 let mut child_cr_cbf = [false; 4];
759 let offsets = [(0usize, 0usize), (HALF, 0), (0, HALF), (HALF, HALF)];
760 let q = HALF * HALF / 4;
761 for (part, &(dx, dy)) in offsets.iter().enumerate() {
762 let (cx, cy) = (x + dx, y + dy);
763 if part == 0 {
764 // Already coded by the mode search.
765 child_levels[0][..HALF * HALF]
766 .copy_from_slice(&self.scratch.luma_levels[..HALF * HALF]);
767 child_cbf[0] = child_levels[0][..HALF * HALF].iter().any(|&v| v != 0);
768 } else {
769 let refs = self.luma_refs(cx, cy, HALF);
770 let mut source = std::mem::take(&mut self.scratch.source);
771 for row in 0..HALF {
772 source[row * HALF..row * HALF + HALF].copy_from_slice(
773 &self.src.y
774 [(cy + row) * self.width + cx..(cy + row) * self.width + cx + HALF],
775 );
776 }
777 let (_, cbf) = self.transform_luma(HALF, mode, &source, &refs, true);
778 if self.ts_rd {
779 child_tskip[part] = self.ts_luma;
780 }
781 self.scratch.source = source;
782 child_levels[part][..HALF * HALF]
783 .copy_from_slice(&self.scratch.levels[..HALF * HALF]);
784 child_cbf[part] = cbf;
785 for row in 0..HALF {
786 for col in 0..HALF {
787 self.write_rec_y(cx + col, cy + row, self.scratch.recon[row * HALF + col]);
788 }
789 }
790 }
791 // The next quadrant predicts from this one, so its samples have to
792 // read as available now: the decoder walks the tree in z-order too.
793 self.mark_coded(cx, cy, HALF, mode, depth);
794 self.mark_tu(cx, cy, HALF);
795 let (_, cbf) = self.code_chroma(cx, cy, HALF, chroma_mode, 1, chroma_tskip);
796 child_cb_cbf[part] = cbf;
797 child_cb[part][..q].copy_from_slice(&self.scratch.cb_levels[..q]);
798 let (_, cbf) = self.code_chroma(cx, cy, HALF, chroma_mode, 2, chroma_tskip);
799 child_cr_cbf[part] = cbf;
800 child_cr[part][..q].copy_from_slice(&self.scratch.cr_levels[..q]);
801 }
802
803 // The parent's flag is the OR of the children's: a clear one at depth 0
804 // tells the decoder to infer every child's as clear.
805 let cb_cbf = child_cb_cbf.iter().any(|&c| c);
806 let cr_cbf = child_cr_cbf.iter().any(|&c| c);
807 self.write_split_tu(
808 enc,
809 N,
810 LOG2,
811 mode,
812 chroma_mode,
813 chroma_tskip,
814 true,
815 cb_cbf,
816 cr_cbf,
817 &child_cbf,
818 &child_levels,
819 &child_tskip,
820 &child_cb_cbf,
821 &child_cr_cbf,
822 &child_cb,
823 &child_cr,
824 &[],
825 &[],
826 );
827 self.last_cu_empty = !(child_cbf.iter().any(|&c| c) || cb_cbf || cr_cbf);
828 let bits = enc.bit_count() - before;
829 self.region_ssd(x, y, N) + self.lambda * bits as f64
830 }
831
832 fn code_cu_2nx2n(
833 &mut self,
834 x: usize,
835 y: usize,
836 log2: u32,
837 depth: u8,
838 enc: &mut CabacEncoder,
839 ) -> f64 {
840 if log2 > 5 {
841 return self.code_cu_64(x, y, depth, enc);
842 }
843 let n = 1usize << log2;
844 // Transform skip is a per-block flag the decoder reads for every 4x4
845 // residual once the picture parameter set enables it, so the decision
846 // has to travel by the block's own size, not the coding unit's: a
847 // transform tree splits chroma down to 4x4 from a 16x16 unit too.
848 // `code_chroma` and `encode_residual` each apply it only at 4x4.
849 let chroma_tskip = self.transform_skip;
850 let before = enc.bit_count();
851 if log2 == MIN_CB_LOG2 {
852 // part_mode: PART_2Nx2N is the single bin 1.
853 enc.encode_bin(ctx::PART_MODE, 1);
854 }
855 let mpm = self.mpm_at(x, y);
856 let mode = self.choose_luma_mode(x, y, n, log2, &mpm, enc);
857 self.write_mode_syntax(enc, mode, &mpm);
858 let (chroma_mode, chroma_idx) = if self.chroma_rd {
859 self.choose_chroma_mode(x, y, n, log2, mode, chroma_tskip, enc)
860 } else {
861 (mode, None)
862 };
863 self.write_chroma_mode_syntax(enc, chroma_idx);
864
865 // Luma was reconstructed by the mode search; chroma is coded now.
866 let luma_cbf = self.scratch.luma_levels[..n * n].iter().any(|&v| v != 0);
867 let cb_cbf = self.code_chroma(x, y, n, chroma_mode, 1, chroma_tskip).1;
868 let cr_cbf = self.code_chroma(x, y, n, chroma_mode, 2, chroma_tskip).1;
869
870 if self.rqt && log2 > 2 && !luma_cbf && !cb_cbf && !cr_cbf {
871 // Every plane already quantised to zero at this size: a
872 // transform-tree split can only re-signal the same empty leaf as
873 // four children, adding a split_transform_flag and their mode
874 // bits on top of an SSD that is already zero. Same reasoning as
875 // the CU-quadtree's `last_cu_empty` early out, one level down —
876 // skip the four-child trial and its transform/CABAC-counting
877 // work outright instead of running it to confirm nosplit wins.
878 enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 0);
879 self.write_single_tu(
880 enc,
881 n,
882 log2,
883 mode,
884 chroma_mode,
885 chroma_tskip,
886 luma_cbf,
887 cb_cbf,
888 cr_cbf,
889 );
890 self.mark_coded(x, y, n, mode, depth);
891 self.mark_tu(x, y, n);
892 self.last_cu_empty = true;
893 let bits = enc.bit_count() - before;
894 return self.region_ssd(x, y, n) + self.lambda * bits as f64;
895 }
896 if self.rqt && log2 > 2 {
897 // A child transform tree signals its own chroma as long as its
898 // chroma blocks are still 4x4 or larger; only the 8x8 luma tree,
899 // whose children are 4x4, leaves chroma at the parent size and
900 // codes it with the last child (7.3.8.8).
901 let chroma_split = log2 > 3;
902 let nosplit_rec = self.save_region(x, y, n);
903 let parent_cb = self.scratch.cb_levels[..n * n / 4].to_vec();
904 let parent_cr = self.scratch.cr_levels[..n * n / 4].to_vec();
905 let start = enc.snapshot();
906 enc.set_counting(true);
907
908 let nb = enc.bit_count();
909 enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 0);
910 self.write_single_tu(
911 enc,
912 n,
913 log2,
914 mode,
915 chroma_mode,
916 chroma_tskip,
917 luma_cbf,
918 cb_cbf,
919 cr_cbf,
920 );
921 let nosplit_bits = enc.bit_count() - nb;
922 let nosplit_ssd = self.region_ssd(x, y, n);
923
924 enc.restore(&start);
925
926 let half = n / 2;
927 let offsets = [(0usize, 0usize), (half, 0), (0, half), (half, half)];
928 let mut child_levels = [[0i32; 1024]; 4];
929 let mut child_tskip = [self.transform_skip; 4];
930 let mut child_cbf = [false; 4];
931 let mut child_cb = [[0i32; 256]; 4];
932 let mut child_cr = [[0i32; 256]; 4];
933 let mut child_cb_cbf = [false; 4];
934 let mut child_cr_cbf = [false; 4];
935 for (part, &(dx, dy)) in offsets.iter().enumerate() {
936 let (cx, cy) = (x + dx, y + dy);
937 let refs = self.luma_refs(cx, cy, half);
938 let mut source = std::mem::take(&mut self.scratch.source);
939 for row in 0..half {
940 source[row * half..row * half + half].copy_from_slice(
941 &self.src.y
942 [(cy + row) * self.width + cx..(cy + row) * self.width + cx + half],
943 );
944 }
945 let (_, cbf) = self.transform_luma(half, mode, &source, &refs, true);
946 if self.ts_rd {
947 child_tskip[part] = self.ts_luma;
948 }
949 child_levels[part][..half * half]
950 .copy_from_slice(&self.scratch.levels[..half * half]);
951 child_cbf[part] = cbf;
952 for row in 0..half {
953 for col in 0..half {
954 self.write_rec_y(cx + col, cy + row, self.scratch.recon[row * half + col]);
955 }
956 }
957 self.scratch.source = source;
958 // The next child predicts from this one, so its samples have
959 // to read as available now rather than when the whole coding
960 // unit is marked: a transform tree is walked in the same
961 // z-order by the decoder.
962 self.mark_coded(cx, cy, half, mode, depth);
963 self.mark_tu(cx, cy, half);
964 if chroma_split {
965 let q = half * half / 4;
966 let (_, cbf) = self.code_chroma(cx, cy, half, chroma_mode, 1, chroma_tskip);
967 child_cb_cbf[part] = cbf;
968 child_cb[part][..q].copy_from_slice(&self.scratch.cb_levels[..q]);
969 let (_, cbf) = self.code_chroma(cx, cy, half, chroma_mode, 2, chroma_tskip);
970 child_cr_cbf[part] = cbf;
971 child_cr[part][..q].copy_from_slice(&self.scratch.cr_levels[..q]);
972 }
973 }
974 // The parent's flag is the OR of the children's: a clear one at
975 // depth 0 tells the decoder to infer every child's as clear.
976 let split_cb_cbf = if chroma_split {
977 child_cb_cbf.iter().any(|&c| c)
978 } else {
979 cb_cbf
980 };
981 let split_cr_cbf = if chroma_split {
982 child_cr_cbf.iter().any(|&c| c)
983 } else {
984 cr_cbf
985 };
986
987 let sb = enc.bit_count();
988 enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 1);
989 self.write_split_tu(
990 enc,
991 n,
992 log2,
993 mode,
994 chroma_mode,
995 chroma_tskip,
996 chroma_split,
997 split_cb_cbf,
998 split_cr_cbf,
999 &child_cbf,
1000 &child_levels,
1001 &child_tskip,
1002 &child_cb_cbf,
1003 &child_cr_cbf,
1004 &child_cb,
1005 &child_cr,
1006 &parent_cb,
1007 &parent_cr,
1008 );
1009 let split_bits = enc.bit_count() - sb;
1010 let split_rec = self.save_region(x, y, n);
1011 let split_ssd = self.region_ssd(x, y, n);
1012
1013 enc.set_counting(false);
1014 enc.restore(&start);
1015
1016 let nosplit_cost = nosplit_ssd + self.lambda * nosplit_bits as f64;
1017 let split_cost = split_ssd + self.lambda * split_bits as f64;
1018
1019 if nosplit_cost <= split_cost {
1020 self.load_region(x, y, n, &nosplit_rec);
1021 // The children coded over the shared chroma scratch.
1022 self.scratch.cb_levels[..n * n / 4].copy_from_slice(&parent_cb);
1023 self.scratch.cr_levels[..n * n / 4].copy_from_slice(&parent_cr);
1024 enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 0);
1025 self.write_single_tu(
1026 enc,
1027 n,
1028 log2,
1029 mode,
1030 chroma_mode,
1031 chroma_tskip,
1032 luma_cbf,
1033 cb_cbf,
1034 cr_cbf,
1035 );
1036 // The split trial recorded four child transform blocks; this
1037 // unit keeps one, and the deblocking filter reads the map.
1038 self.mark_tu(x, y, n);
1039 self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf);
1040 } else {
1041 self.load_region(x, y, n, &split_rec);
1042 enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 1);
1043 self.write_split_tu(
1044 enc,
1045 n,
1046 log2,
1047 mode,
1048 chroma_mode,
1049 chroma_tskip,
1050 chroma_split,
1051 split_cb_cbf,
1052 split_cr_cbf,
1053 &child_cbf,
1054 &child_levels,
1055 &child_tskip,
1056 &child_cb_cbf,
1057 &child_cr_cbf,
1058 &child_cb,
1059 &child_cr,
1060 &parent_cb,
1061 &parent_cr,
1062 );
1063 self.last_cu_empty =
1064 !(child_cbf.iter().any(|&c| c) || split_cb_cbf || split_cr_cbf);
1065 }
1066
1067 self.mark_coded(x, y, n, mode, depth);
1068 let bits = enc.bit_count() - before;
1069 return self.region_ssd(x, y, n) + self.lambda * bits as f64;
1070 }
1071
1072 // No-RQT: single TU, no split_transform_flag written (inferred 0).
1073 self.write_single_tu(
1074 enc,
1075 n,
1076 log2,
1077 mode,
1078 chroma_mode,
1079 chroma_tskip,
1080 luma_cbf,
1081 cb_cbf,
1082 cr_cbf,
1083 );
1084 self.mark_coded(x, y, n, mode, depth);
1085 self.mark_tu(x, y, n);
1086 self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf);
1087 let bits = enc.bit_count() - before;
1088 self.region_ssd(x, y, n) + self.lambda * bits as f64
1089 }
1090
1091 /// Write cbf flags + residual for one unsplit transform tree (no
1092 /// `split_transform_flag`).
1093 #[allow(clippy::too_many_arguments)]
1094 fn write_single_tu(
1095 &mut self,
1096 enc: &mut CabacEncoder,
1097 n: usize,
1098 log2: u32,
1099 mode: u8,
1100 chroma_mode: u8,
1101 chroma_tskip: bool,
1102 luma_cbf: bool,
1103 cb_cbf: bool,
1104 cr_cbf: bool,
1105 ) {
1106 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));
1107 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));
1108 enc.encode_bin(ctx::CBF_LUMA + 1, u32::from(luma_cbf));
1109 if luma_cbf {
1110 let scan = intra::scan_index(mode, log2, true);
1111 let levels = std::mem::take(&mut self.scratch.luma_levels);
1112 encode_residual(
1113 enc,
1114 &levels[..n * n],
1115 log2,
1116 0,
1117 scan,
1118 self.sign_hiding,
1119 self.ts_flag(self.transform_skip),
1120 );
1121 self.scratch.luma_levels = levels;
1122 }
1123 let chroma_scan = intra::scan_index(chroma_mode, log2 - 1, false);
1124 if cb_cbf {
1125 let levels = std::mem::take(&mut self.scratch.cb_levels);
1126 encode_residual(
1127 enc,
1128 &levels[..n * n / 4],
1129 log2 - 1,
1130 1,
1131 chroma_scan,
1132 self.sign_hiding,
1133 self.ts_flag(chroma_tskip),
1134 );
1135 self.scratch.cb_levels = levels;
1136 }
1137 if cr_cbf {
1138 let levels = std::mem::take(&mut self.scratch.cr_levels);
1139 encode_residual(
1140 enc,
1141 &levels[..n * n / 4],
1142 log2 - 1,
1143 2,
1144 chroma_scan,
1145 self.sign_hiding,
1146 self.ts_flag(chroma_tskip),
1147 );
1148 self.scratch.cr_levels = levels;
1149 }
1150 }
1151
1152 /// Write cbf flags + residual for a split transform tree: chroma cbf first,
1153 /// then four half-size luma children (CBF_LUMA ctx 0 for depth 1), chroma
1154 /// residual on the last child.
1155 /// Write the syntax of a split transform tree: the parent's chroma flags,
1156 /// then four half-size children. A child carries its own chroma when the
1157 /// chroma blocks stay 4x4 or larger, and reads the depth-one contexts for
1158 /// both flags; below that the parent's chroma rides on the last child.
1159 #[allow(clippy::too_many_arguments)]
1160 fn write_split_tu(
1161 &mut self,
1162 enc: &mut CabacEncoder,
1163 n: usize,
1164 log2: u32,
1165 mode: u8,
1166 chroma_mode: u8,
1167 chroma_tskip: bool,
1168 chroma_split: bool,
1169 cb_cbf: bool,
1170 cr_cbf: bool,
1171 child_cbf: &[bool; 4],
1172 child_levels: &[[i32; 1024]; 4],
1173 child_tskip: &[bool; 4],
1174 child_cb_cbf: &[bool; 4],
1175 child_cr_cbf: &[bool; 4],
1176 child_cb: &[[i32; 256]; 4],
1177 child_cr: &[[i32; 256]; 4],
1178 parent_cb: &[i32],
1179 parent_cr: &[i32],
1180 ) {
1181 let half = n / 2;
1182 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));
1183 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));
1184 let luma_scan = intra::scan_index(mode, log2 - 1, true);
1185 for part in 0..4usize {
1186 if chroma_split {
1187 if cb_cbf {
1188 enc.encode_bin(ctx::CBF_CHROMA + 1, u32::from(child_cb_cbf[part]));
1189 }
1190 if cr_cbf {
1191 enc.encode_bin(ctx::CBF_CHROMA + 1, u32::from(child_cr_cbf[part]));
1192 }
1193 }
1194 enc.encode_bin(ctx::CBF_LUMA, u32::from(child_cbf[part]));
1195 if child_cbf[part] {
1196 encode_residual(
1197 enc,
1198 &child_levels[part][..half * half],
1199 log2 - 1,
1200 0,
1201 luma_scan,
1202 self.sign_hiding,
1203 self.ts_flag(child_tskip[part]),
1204 );
1205 }
1206 if chroma_split {
1207 let (q, scan) = (
1208 half * half / 4,
1209 intra::scan_index(chroma_mode, log2 - 2, false),
1210 );
1211 if cb_cbf && child_cb_cbf[part] {
1212 encode_residual(
1213 enc,
1214 &child_cb[part][..q],
1215 log2 - 2,
1216 1,
1217 scan,
1218 self.sign_hiding,
1219 self.ts_flag(chroma_tskip),
1220 );
1221 }
1222 if cr_cbf && child_cr_cbf[part] {
1223 encode_residual(
1224 enc,
1225 &child_cr[part][..q],
1226 log2 - 2,
1227 2,
1228 scan,
1229 self.sign_hiding,
1230 self.ts_flag(chroma_tskip),
1231 );
1232 }
1233 } else if part == 3 {
1234 let scan = intra::scan_index(chroma_mode, log2 - 1, false);
1235 if cb_cbf {
1236 encode_residual(
1237 enc,
1238 &parent_cb[..n * n / 4],
1239 log2 - 1,
1240 1,
1241 scan,
1242 self.sign_hiding,
1243 self.ts_flag(chroma_tskip),
1244 );
1245 }
1246 if cr_cbf {
1247 encode_residual(
1248 enc,
1249 &parent_cr[..n * n / 4],
1250 log2 - 1,
1251 2,
1252 scan,
1253 self.sign_hiding,
1254 self.ts_flag(chroma_tskip),
1255 );
1256 }
1257 }
1258 }
1259 }
1260
1261 fn write_mode_syntax(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) {
1262 self.write_mode_prev_flag(enc, mode, mpm);
1263 self.write_mode_remainder(enc, mode, mpm);
1264 }
1265
1266 /// `prev_intra_luma_pred_flag`. An NxN coding unit writes all four of these
1267 /// before any of the remainders (7.3.8.5), which is why the two halves are
1268 /// separate.
1269 fn write_mode_prev_flag(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) {
1270 let is_mpm = mpm.contains(&mode);
1271 enc.encode_bin(ctx::PREV_INTRA_LUMA_PRED, u32::from(is_mpm));
1272 }
1273
1274 /// `mpm_idx` or `rem_intra_luma_pred_mode`, whichever the flag promised.
1275 fn write_mode_remainder(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) {
1276 match mpm.iter().position(|&m| m == mode) {
1277 Some(idx) => {
1278 // mpm_idx: truncated rice, cMax 2, all bypass.
1279 if idx == 0 {
1280 enc.encode_bypass(0);
1281 } else {
1282 enc.encode_bypass(1);
1283 enc.encode_bypass(u32::from(idx == 2));
1284 }
1285 }
1286 None => {
1287 let mut sorted = *mpm;
1288 sorted.sort_unstable();
1289 let mut rem = mode;
1290 // The inverse of the decoder's iterative reconstruction
1291 // (`for m in sorted (ascending): if mode >= m { mode += 1 }`)
1292 // has to walk descending and compare the *running* `rem`,
1293 // not the original `mode`: decrementing across one candidate
1294 // can drop `rem` at or below the next one down, which then
1295 // must also count. Comparing against the fixed `mode` missed
1296 // that second step whenever two MPM candidates sat on either
1297 // side of it.
1298 for &m in sorted.iter().rev() {
1299 if rem > m {
1300 rem -= 1;
1301 }
1302 }
1303 enc.encode_bypass_bits(u32::from(rem), 5);
1304 }
1305 }
1306 }
1307
1308 fn mpm_at(&self, x: usize, y: usize) -> [u8; 3] {
1309 let left = if self.available(x as isize - 1, y as isize) {
1310 let m = self.mode_at(x - 1, y);
1311 if m == 255 { None } else { Some(m) }
1312 } else {
1313 None
1314 };
1315 // A neighbour in the CTB row above counts as DC (8.4.2 step 2), which is
1316 // also what keeps the wavefront from needing a mode line.
1317 let above = if y > self.band_y0 && self.available(x as isize, y as isize - 1) {
1318 let m = self.mode_at(x, y - 1);
1319 if m == 255 { None } else { Some(m) }
1320 } else {
1321 None
1322 };
1323 intra::mpm_list(left, above)
1324 }
1325
1326 /// Record the transform block of side `n` at `(x, y)`, which is what the
1327 /// deblocking filter reads its edges off. Marked at transform-tree *leaves*
1328 /// only: a coding unit that split records four children, never itself.
1329 fn mark_tu(&mut self, x: usize, y: usize, n: usize) {
1330 let stride = self.width / 4;
1331 let log2 = n.trailing_zeros() as u8;
1332 for by in (y..y + n).step_by(4) {
1333 for bx in (x..x + n).step_by(4) {
1334 self.tu_log2[((by - self.band_y0) / 4) * stride + bx / 4] = log2;
1335 }
1336 }
1337 }
1338
1339 fn mark_coded(&mut self, x: usize, y: usize, n: usize, mode: u8, depth: u8) {
1340 let stride = self.width / 4;
1341 for by in (y..y + n).step_by(4) {
1342 for bx in (x..x + n).step_by(4) {
1343 let idx = ((by - self.band_y0) / 4) * stride + bx / 4;
1344 self.modes[idx] = mode;
1345 self.depths[idx] = depth;
1346 let cx = (bx - self.ctu_x * self.ctb_size) / 4;
1347 let cy = (by - self.band_y0) / 4;
1348 self.coded[cy * 16 + cx] = true;
1349 }
1350 }
1351 }
1352
1353 /// Sum of squared differences over a coding unit, all three planes.
1354 fn region_ssd(&self, x: usize, y: usize, n: usize) -> f64 {
1355 let mut ssd = 0i64;
1356 for yy in y..y + n {
1357 let src_row = &self.src.y[yy * self.width + x..yy * self.width + x + n];
1358 for (offset, &sample) in src_row.iter().enumerate() {
1359 let d = i64::from(sample) - i64::from(self.rec_y(x + offset, yy));
1360 ssd += d * d;
1361 }
1362 }
1363 let cw = self.width / 2;
1364 for plane in [1usize, 2] {
1365 let src = if plane == 1 { self.src.cb } else { self.src.cr };
1366 for yy in y / 2..y / 2 + n / 2 {
1367 for xx in x / 2..x / 2 + n / 2 {
1368 let d = i64::from(src[yy * cw + xx]) - i64::from(self.rec_c(xx, yy, plane));
1369 ssd += d * d;
1370 }
1371 }
1372 }
1373 ssd as f64
1374 }
1375
1376 // ---- luma mode decision ----------------------------------------------
1377
1378 /// Pick the luma mode, leaving its levels in `scratch.luma_levels` and its
1379 /// reconstruction written into the band.
1380 fn choose_luma_mode(
1381 &mut self,
1382 x: usize,
1383 y: usize,
1384 n: usize,
1385 log2: u32,
1386 mpm: &[u8; 3],
1387 enc: &mut CabacEncoder,
1388 ) -> u8 {
1389 let refs = self.luma_refs(x, y, n);
1390 let mut source = std::mem::take(&mut self.scratch.source);
1391 for row in 0..n {
1392 let sy = y + row;
1393 source[row * n..row * n + n]
1394 .copy_from_slice(&self.src.y[sy * self.width + x..sy * self.width + x + n]);
1395 }
1396
1397 // Pre-screen: planar, DC and every second angle, then the two
1398 // neighbours of whichever angle won. Nineteen predictions instead of
1399 // thirty-five for the same winner in all but a rounding of cases —
1400 // the SATD surface over the angles is smooth by construction.
1401 let mut scored: Vec<(f64, u8)> = Vec::with_capacity(24);
1402 let score = |this: &mut Self, mode: u8, scored: &mut Vec<(f64, u8)>| {
1403 intra::predict_cached(
1404 &refs,
1405 &mut this.scratch.filt,
1406 mode,
1407 n,
1408 true,
1409 this.strong_smoothing,
1410 this.bit_depth,
1411 &mut this.scratch.pred,
1412 );
1413 let satd = satd(&source, &this.scratch.pred[..n * n], n) as f64;
1414 let mode_bits = if mpm.contains(&mode) { 2.0 } else { 6.0 };
1415 scored.push((satd + this.lambda_satd * mode_bits, mode));
1416 };
1417 for mode in [0u8, 1] {
1418 score(self, mode, &mut scored);
1419 }
1420 for mode in (2u8..=34).step_by(2) {
1421 score(self, mode, &mut scored);
1422 }
1423 let coarse_best = scored
1424 .iter()
1425 .filter(|(_, m)| *m >= 2)
1426 .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal))
1427 .map(|&(_, m)| m)
1428 .unwrap_or(26);
1429 for delta in [-1i16, 1] {
1430 let refined = coarse_best as i16 + delta;
1431 if (2..=34).contains(&refined) {
1432 score(self, refined as u8, &mut scored);
1433 }
1434 }
1435 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
1436
1437 // Full rate-distortion on the survivors, plus the most probable modes,
1438 // which are cheap to code and often win despite a worse SATD.
1439 let mut candidates: Vec<u8> = scored.iter().take(self.candidates).map(|s| s.1).collect();
1440 // The first most probable mode joins the trial whatever its SATD: it is
1441 // two bins where a non-MPM mode is six, and that gap decides plenty of
1442 // flat blocks.
1443 if !candidates.contains(&mpm[0]) {
1444 candidates.push(mpm[0]);
1445 }
1446
1447 let start = enc.snapshot();
1448 enc.set_counting(true);
1449 let mut best = (f64::MAX, 0u8);
1450 let mut best_levels = std::mem::take(&mut self.scratch.best_levels);
1451 for &mode in &candidates {
1452 let bits_before = enc.bit_count();
1453 self.write_mode_syntax(enc, mode, mpm);
1454 // Mode ranking runs the cheap (dead-zone-only) quantiser: RDOQ's
1455 // per-coefficient CABAC-costed search is the hottest bucket in the
1456 // encoder (measured: ~73% of encode wall time) and re-running it
1457 // for every candidate mode only to throw away all but the winner
1458 // is exactly the redundant recomputation this is worth skipping.
1459 // The winner gets the full RDOQ refinement below, once.
1460 let (ssd, cbf) = self.transform_luma(n, mode, &source, &refs, false);
1461 enc.encode_bin(ctx::CBF_LUMA + 1, u32::from(cbf));
1462 let mut bits = (enc.bit_count() - bits_before) as f64;
1463 if cbf {
1464 // Ranking candidates against each other only needs a proxy
1465 // for encode_residual's exact bit count, not the count
1466 // itself: the real per-bin CABAC search (context updates,
1467 // greater1/greater2/remaining binarization) is the hot loop
1468 // this replaces, and only the winner ever pays for it below.
1469 let scan = intra::scan_index(mode, log2, true);
1470 bits += residual::estimate_residual_bits(&self.scratch.levels[..n * n], log2, scan);
1471 }
1472 enc.restore(&start);
1473 let cost = ssd + self.lambda * bits;
1474 if cost < best.0 {
1475 best = (cost, mode);
1476 best_levels[..n * n].copy_from_slice(&self.scratch.levels[..n * n]);
1477 self.scratch.best_recon[..n * n].copy_from_slice(&self.scratch.recon[..n * n]);
1478 }
1479 }
1480 enc.set_counting(false);
1481 // The trial above scored every candidate without RDOQ's refinement
1482 // loop; now that the mode is decided, pay for that loop exactly once,
1483 // on the winner, so the committed levels are the ones RDOQ can reach.
1484 if self.rdoq || (self.ts_rd && n == 4) {
1485 self.transform_luma(n, best.1, &source, &refs, true);
1486 best_levels[..n * n].copy_from_slice(&self.scratch.levels[..n * n]);
1487 self.scratch.best_recon[..n * n].copy_from_slice(&self.scratch.recon[..n * n]);
1488 }
1489 // Commit the winner's reconstruction and levels.
1490 for row in 0..n {
1491 for col in 0..n {
1492 self.write_rec_y(x + col, y + row, self.scratch.best_recon[row * n + col]);
1493 }
1494 }
1495 self.scratch.luma_levels[..n * n].copy_from_slice(&best_levels[..n * n]);
1496 self.scratch.best_levels = best_levels;
1497 self.scratch.source = source;
1498 best.1
1499 }
1500
1501 /// Predict, transform, quantise and reconstruct one luma block into
1502 /// `scratch.recon` / `scratch.levels`; returns `(SSD, cbf)`.
1503 ///
1504 /// `refine` gates RDOQ's per-coefficient CABAC-costed search on top of the
1505 /// dead-zone quantiser: callers scoring several mode candidates pass
1506 /// `false` and re-run the winner with `true`, since the refinement is
1507 /// worthless work on every candidate but the one that gets kept.
1508 fn transform_luma(
1509 &mut self,
1510 n: usize,
1511 mode: u8,
1512 source: &[Pel],
1513 refs: &Refs<Pel>,
1514 refine: bool,
1515 ) -> (f64, bool) {
1516 if self.ts_rd {
1517 if n == 4 && refine {
1518 return self.transform_luma_ts_rd(mode, source, refs);
1519 }
1520 // Candidate ranking prices the mode, not the skip decision, which
1521 // the committed pass above makes once on the winner.
1522 self.ts_luma = false;
1523 }
1524 self.transform_luma_at(n, mode, source, refs, refine)
1525 }
1526
1527 /// The `transform_skip_flag` to write for a 4x4 block: `None` when the PPS
1528 /// left transform skip off and the decoder reads no bin at all.
1529 fn ts_flag(&self, skip: bool) -> Option<bool> {
1530 (self.transform_skip || self.ts_rd).then_some(skip)
1531 }
1532
1533 /// Code the 4x4 luma block both ways and keep the cheaper one, leaving its
1534 /// levels and reconstruction in the scratch and its flag in `ts_luma`.
1535 fn transform_luma_ts_rd(&mut self, mode: u8, source: &[Pel], refs: &Refs<Pel>) -> (f64, bool) {
1536 let scan = intra::scan_index(mode, 2, true);
1537 let (mut best_cost, mut best) = (f64::MAX, (0.0, false, false, [0i32; 16], [0 as Pel; 16]));
1538 for skip in [false, true] {
1539 self.ts_luma = skip;
1540 let (ssd, cbf) = self.transform_luma_at(4, mode, source, refs, true);
1541 // The flag itself is one bin; the levels are priced by the same
1542 // proxy the mode search uses.
1543 let mut bits = 1.0;
1544 if cbf {
1545 bits += residual::estimate_residual_bits(&self.scratch.levels[..16], 2, scan);
1546 }
1547 let cost = ssd + self.lambda * bits;
1548 if cost < best_cost {
1549 let (mut levels, mut recon) = ([0i32; 16], [0 as Pel; 16]);
1550 levels.copy_from_slice(&self.scratch.levels[..16]);
1551 recon.copy_from_slice(&self.scratch.recon[..16]);
1552 best_cost = cost;
1553 best = (ssd, skip, cbf, levels, recon);
1554 }
1555 }
1556 let (ssd, skip, cbf, levels, recon) = best;
1557 self.ts_luma = skip;
1558 self.scratch.levels[..16].copy_from_slice(&levels);
1559 self.scratch.recon[..16].copy_from_slice(&recon);
1560 (ssd, cbf)
1561 }
1562
1563 fn transform_luma_at(
1564 &mut self,
1565 n: usize,
1566 mode: u8,
1567 source: &[Pel],
1568 refs: &Refs<Pel>,
1569 refine: bool,
1570 ) -> (f64, bool) {
1571 intra::predict_cached(
1572 refs,
1573 &mut self.scratch.filt,
1574 mode,
1575 n,
1576 true,
1577 self.strong_smoothing,
1578 self.bit_depth,
1579 &mut self.scratch.pred,
1580 );
1581 for (i, &sample) in source[..n * n].iter().enumerate() {
1582 self.scratch.residual[i] = i32::from(sample) - i32::from(self.scratch.pred[i]);
1583 }
1584 let skip = n == 4
1585 && if self.ts_rd {
1586 self.ts_luma
1587 } else {
1588 self.transform_skip
1589 };
1590 let dst = uses_dst(n, true);
1591 if skip {
1592 forward_transform_skip(&self.scratch.residual, &mut self.scratch.coeffs, n);
1593 } else {
1594 forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst);
1595 }
1596 scale_forward_bd(&mut self.scratch.coeffs, n, self.bit_depth);
1597 let mut nonzero = if self.rdoq {
1598 quantize_offset(
1599 &self.scratch.coeffs,
1600 &mut self.scratch.levels,
1601 n,
1602 quant_qp(self.qp, self.bit_depth),
1603 RDOQ_DEAD_ZONE,
1604 )
1605 } else {
1606 quantize(
1607 &self.scratch.coeffs,
1608 &mut self.scratch.levels,
1609 n,
1610 quant_qp(self.qp, self.bit_depth),
1611 )
1612 };
1613 let ts = self.ts_flag(skip);
1614 if self.rdoq && refine && nonzero > 0 {
1615 nonzero = residual::rdoq(
1616 &self.scratch.coeffs,
1617 &mut self.scratch.levels,
1618 n,
1619 self.qp,
1620 self.bit_depth,
1621 0,
1622 intra::scan_index(mode, n.trailing_zeros(), true),
1623 ctx::CBF_LUMA + 1,
1624 if self.bit_depth > 8 {
1625 self.lambda / 16.0
1626 } else {
1627 self.lambda
1628 },
1629 ts,
1630 &mut self.rdoq_enc,
1631 );
1632 }
1633 if self.sign_hiding && nonzero > 0 {
1634 nonzero = residual::hide_signs(
1635 &self.scratch.coeffs,
1636 &mut self.scratch.levels,
1637 n,
1638 quant_qp(self.qp, self.bit_depth),
1639 intra::scan_index(mode, n.trailing_zeros(), true),
1640 );
1641 }
1642 let cbf = nonzero > 0;
1643 if cbf {
1644 dequantize_bd(
1645 &self.scratch.levels,
1646 &mut self.scratch.scaled,
1647 n,
1648 self.qp,
1649 self.bit_depth,
1650 );
1651 if skip {
1652 inverse_transform_skip_bd(
1653 &self.scratch.scaled,
1654 &mut self.scratch.residual,
1655 n,
1656 self.bit_depth,
1657 );
1658 } else {
1659 inverse_transform_bd(
1660 &self.scratch.scaled,
1661 &mut self.scratch.residual,
1662 n,
1663 dst,
1664 self.bit_depth,
1665 );
1666 }
1667 } else {
1668 self.scratch.residual[..n * n].fill(0);
1669 }
1670 let mut ssd = 0i64;
1671 for (i, &sample) in source[..n * n].iter().enumerate() {
1672 let value = (i32::from(self.scratch.pred[i]) + self.scratch.residual[i])
1673 .clamp(0, self.max) as Pel;
1674 self.scratch.recon[i] = value;
1675 let d = i64::from(sample) - i64::from(value);
1676 ssd += d * d;
1677 }
1678 (ssd as f64, cbf)
1679 }
1680
1681 /// Code one chroma transform block in `pred_mode`; returns its `(SSD, cbf)`
1682 /// and leaves the levels in the matching scratch buffer.
1683 fn code_chroma(
1684 &mut self,
1685 x: usize,
1686 y: usize,
1687 n: usize,
1688 pred_mode: u8,
1689 plane: usize,
1690 skip: bool,
1691 ) -> (f64, bool) {
1692 let cn = n / 2;
1693 let (cx, cy) = (x / 2, y / 2);
1694 let refs = self.chroma_refs(cx, cy, cn, plane);
1695 let cw = self.width / 2;
1696 let src = if plane == 1 { self.src.cb } else { self.src.cr };
1697 intra::predict(
1698 &refs,
1699 pred_mode,
1700 cn,
1701 false,
1702 self.strong_smoothing,
1703 self.bit_depth,
1704 &mut self.scratch.pred,
1705 );
1706 for row in 0..cn {
1707 for col in 0..cn {
1708 let s = i32::from(src[(cy + row) * cw + cx + col]);
1709 self.scratch.residual[row * cn + col] =
1710 s - i32::from(self.scratch.pred[row * cn + col]);
1711 }
1712 }
1713 if skip && cn == 4 {
1714 forward_transform_skip(&self.scratch.residual, &mut self.scratch.coeffs, cn);
1715 } else {
1716 forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false);
1717 }
1718 scale_forward_bd(&mut self.scratch.coeffs, cn, self.bit_depth);
1719 let mut nonzero = if self.rdoq {
1720 quantize_offset(
1721 &self.scratch.coeffs,
1722 &mut self.scratch.levels,
1723 cn,
1724 quant_qp(self.qp_c, self.bit_depth),
1725 RDOQ_DEAD_ZONE_C,
1726 )
1727 } else {
1728 quantize(
1729 &self.scratch.coeffs,
1730 &mut self.scratch.levels,
1731 cn,
1732 quant_qp(self.qp_c, self.bit_depth),
1733 )
1734 };
1735 let ts = self.ts_flag(skip && cn == 4);
1736 if self.rdoq && nonzero > 0 {
1737 nonzero = residual::rdoq(
1738 &self.scratch.coeffs,
1739 &mut self.scratch.levels,
1740 cn,
1741 self.qp_c,
1742 self.bit_depth,
1743 plane,
1744 intra::scan_index(pred_mode, cn.trailing_zeros(), false),
1745 ctx::CBF_CHROMA,
1746 if self.bit_depth > 8 {
1747 self.lambda / 16.0
1748 } else {
1749 self.lambda
1750 },
1751 ts,
1752 &mut self.rdoq_enc,
1753 );
1754 }
1755 if self.sign_hiding && nonzero > 0 {
1756 nonzero = residual::hide_signs(
1757 &self.scratch.coeffs,
1758 &mut self.scratch.levels,
1759 cn,
1760 quant_qp(self.qp_c, self.bit_depth),
1761 intra::scan_index(pred_mode, cn.trailing_zeros(), false),
1762 );
1763 }
1764 let cbf = nonzero > 0;
1765 if cbf {
1766 dequantize_bd(
1767 &self.scratch.levels,
1768 &mut self.scratch.scaled,
1769 cn,
1770 self.qp_c,
1771 self.bit_depth,
1772 );
1773 if skip && cn == 4 {
1774 inverse_transform_skip_bd(
1775 &self.scratch.scaled,
1776 &mut self.scratch.residual,
1777 cn,
1778 self.bit_depth,
1779 );
1780 } else {
1781 inverse_transform_bd(
1782 &self.scratch.scaled,
1783 &mut self.scratch.residual,
1784 cn,
1785 false,
1786 self.bit_depth,
1787 );
1788 }
1789 } else {
1790 self.scratch.residual[..cn * cn].fill(0);
1791 }
1792 let mut ssd = 0i64;
1793 for row in 0..cn {
1794 for col in 0..cn {
1795 let value = (i32::from(self.scratch.pred[row * cn + col])
1796 + self.scratch.residual[row * cn + col])
1797 .clamp(0, self.max) as Pel;
1798 let d = i64::from(src[(cy + row) * cw + cx + col]) - i64::from(value);
1799 ssd += d * d;
1800 self.write_rec_c(cx + col, cy + row, plane, value);
1801 }
1802 }
1803 let levels = if plane == 1 {
1804 &mut self.scratch.cb_levels
1805 } else {
1806 &mut self.scratch.cr_levels
1807 };
1808 levels[..cn * cn].copy_from_slice(&self.scratch.levels[..cn * cn]);
1809 (ssd as f64, cbf)
1810 }
1811
1812 // ---- chroma mode decision --------------------------------------------
1813
1814 /// Write `intra_chroma_pred_mode`: the single bin 0 for the derived mode,
1815 /// or bin 1 and two bypass bits picking one of the four explicit modes.
1816 fn write_chroma_mode_syntax(&self, enc: &mut CabacEncoder, idx: Option<u32>) {
1817 match idx {
1818 None => enc.encode_bin(ctx::INTRA_CHROMA_PRED_MODE, 0),
1819 Some(i) => {
1820 enc.encode_bin(ctx::INTRA_CHROMA_PRED_MODE, 1);
1821 enc.encode_bypass_bits(i, 2);
1822 }
1823 }
1824 }
1825
1826 /// Pick the chroma prediction mode by rate-distortion over the five the
1827 /// syntax allows: planar, vertical, horizontal and DC — each replaced by
1828 /// angular 34 when it collides with the luma mode — plus the derived mode,
1829 /// which is the luma mode itself and costs one bin instead of three.
1830 ///
1831 /// Returns the mode and the index to code, `None` meaning derived. Neither
1832 /// the winner's reconstruction nor its levels survive the trial: the caller
1833 /// codes the winner again for real.
1834 #[allow(clippy::too_many_arguments)]
1835 fn choose_chroma_mode(
1836 &mut self,
1837 x: usize,
1838 y: usize,
1839 n: usize,
1840 log2: u32,
1841 luma_mode: u8,
1842 chroma_tskip: bool,
1843 enc: &mut CabacEncoder,
1844 ) -> (u8, Option<u32>) {
1845 let mut explicit = [0u8, 26, 10, 1];
1846 for mode in explicit.iter_mut() {
1847 if *mode == luma_mode {
1848 *mode = 34;
1849 }
1850 }
1851 let start = enc.snapshot();
1852 enc.set_counting(true);
1853 let mut best = (f64::MAX, luma_mode, None);
1854 for (i, mode) in explicit
1855 .iter()
1856 .copied()
1857 .enumerate()
1858 .map(|(i, m)| (Some(i as u32), m))
1859 .chain(std::iter::once((None, luma_mode)))
1860 {
1861 let bits_before = enc.bit_count();
1862 self.write_chroma_mode_syntax(enc, i);
1863 let (cb_ssd, cb_cbf) = self.code_chroma(x, y, n, mode, 1, chroma_tskip);
1864 let (cr_ssd, cr_cbf) = self.code_chroma(x, y, n, mode, 2, chroma_tskip);
1865 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));
1866 enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));
1867 let scan = intra::scan_index(mode, log2 - 1, false);
1868 if cb_cbf {
1869 let levels = std::mem::take(&mut self.scratch.cb_levels);
1870 encode_residual(
1871 enc,
1872 &levels[..n * n / 4],
1873 log2 - 1,
1874 1,
1875 scan,
1876 self.sign_hiding,
1877 self.ts_flag(chroma_tskip),
1878 );
1879 self.scratch.cb_levels = levels;
1880 }
1881 if cr_cbf {
1882 let levels = std::mem::take(&mut self.scratch.cr_levels);
1883 encode_residual(
1884 enc,
1885 &levels[..n * n / 4],
1886 log2 - 1,
1887 2,
1888 scan,
1889 self.sign_hiding,
1890 self.ts_flag(chroma_tskip),
1891 );
1892 self.scratch.cr_levels = levels;
1893 }
1894 let bits = enc.bit_count() - bits_before;
1895 enc.restore(&start);
1896 let cost = self.chroma_rd_weight * (cb_ssd + cr_ssd) + self.lambda * bits as f64;
1897 if cost < best.0 {
1898 best = (cost, mode, i);
1899 }
1900 }
1901 enc.set_counting(false);
1902 (best.1, best.2)
1903 }
1904
1905 // ---- reference samples -----------------------------------------------
1906
1907 fn luma_refs(&mut self, x: usize, y: usize, n: usize) -> Refs<Pel> {
1908 self.scratch.filt = None;
1909 let mut refs = Refs::default();
1910 let mut avail = Availability::default();
1911 let span = 2 * n;
1912 avail.corner = self.available(x as isize - 1, y as isize - 1);
1913 if avail.corner {
1914 refs.corner = self.rec_y(x - 1, y - 1);
1915 }
1916 for i in 0..span {
1917 if self.available((x + i) as isize, y as isize - 1) {
1918 avail.top |= 1 << i;
1919 refs.top[i] = self.rec_y(x + i, y - 1);
1920 }
1921 if self.available(x as isize - 1, (y + i) as isize) {
1922 avail.left |= 1 << i;
1923 refs.left[i] = self.rec_y(x - 1, y + i);
1924 }
1925 }
1926 intra::substitute(&mut refs, &avail, n, self.bit_depth);
1927 refs
1928 }
1929
1930 fn chroma_refs(&self, cx: usize, cy: usize, cn: usize, plane: usize) -> Refs<Pel> {
1931 let mut refs = Refs::default();
1932 let mut avail = Availability::default();
1933 let span = 2 * cn;
1934 avail.corner = self.available(cx as isize * 2 - 1, cy as isize * 2 - 1);
1935 if avail.corner {
1936 refs.corner = self.rec_c(cx - 1, cy - 1, plane);
1937 }
1938 for i in 0..span {
1939 if self.available(((cx + i) * 2) as isize, cy as isize * 2 - 1) {
1940 avail.top |= 1 << i;
1941 refs.top[i] = self.rec_c(cx + i, cy - 1, plane);
1942 }
1943 if self.available(cx as isize * 2 - 1, ((cy + i) * 2) as isize) {
1944 avail.left |= 1 << i;
1945 refs.left[i] = self.rec_c(cx - 1, cy + i, plane);
1946 }
1947 }
1948 intra::substitute(&mut refs, &avail, cn, self.bit_depth);
1949 refs
1950 }
1951}
1952
1953/// Sum of absolute transformed differences, 4x4 Hadamard per sub-block.
1954fn satd(source: &[Pel], pred: &[Pel], n: usize) -> u32 {
1955 #[cfg(target_arch = "x86_64")]
1956 if n >= 4
1957 && n.is_multiple_of(4)
1958 && (n == 4 || n.is_multiple_of(8))
1959 && source.len() >= n * n
1960 && pred.len() >= n * n
1961 {
1962 // The SSE2 token (SSE2 is part of the x86_64 baseline, so this is always Some); the
1963 // check above puts every load (`n` samples per row, `n` rows) inside both slices.
1964 if let Some(t) = X64V1Token::summon() {
1965 return satd_sse2(t, source, pred, n);
1966 }
1967 }
1968 satd_scalar(source, pred, n)
1969}
1970
1971/// [`satd`] on 16-bit lanes: the differences of 10-bit samples are within +-1023, so the
1972/// sixteen Hadamard sums of a 4x4 block stay within +-16368. The vertical butterfly runs
1973/// across whole rows, the horizontal one inside each group of four lanes.
1974#[cfg(target_arch = "x86_64")]
1975#[arcane]
1976fn satd_sse2(_t: X64V1Token, source: &[Pel], pred: &[Pel], n: usize) -> u32 {
1977 use std::arch::x86_64::*;
1978 let sg1 = _mm_set_epi16(-1, -1, 1, 1, -1, -1, 1, 1);
1979 let sg2 = _mm_set_epi16(-1, 1, -1, 1, -1, 1, -1, 1);
1980 let ones = _mm_set1_epi16(1);
1981 let mut total = _mm_setzero_si128();
1982 // `n` (4) or 8 samples at `i`, the upper lanes zero for the 4-wide case.
1983 let load = |v: &[Pel], i: usize| -> __m128i {
1984 if n == 4 {
1985 // Four samples in the low 64 bits, upper lanes zero.
1986 let lo: u64 = bytemuck::cast(<[Pel; 4]>::try_from(&v[i..i + 4]).unwrap());
1987 _mm_cvtsi64_si128(lo as i64)
1988 } else {
1989 bytemuck::cast(<[Pel; 8]>::try_from(&v[i..i + 8]).unwrap())
1990 }
1991 };
1992 let step = if n == 4 { 4 } else { 8 };
1993 for by in (0..n).step_by(4) {
1994 for bx in (0..n).step_by(step) {
1995 let i = by * n + bx;
1996 let d0 = _mm_sub_epi16(load(source, i), load(pred, i));
1997 let d1 = _mm_sub_epi16(load(source, i + n), load(pred, i + n));
1998 let d2 = _mm_sub_epi16(load(source, i + 2 * n), load(pred, i + 2 * n));
1999 let d3 = _mm_sub_epi16(load(source, i + 3 * n), load(pred, i + 3 * n));
2000 let (s0, s1) = (_mm_add_epi16(d0, d2), _mm_add_epi16(d1, d3));
2001 let (s2, s3) = (_mm_sub_epi16(d0, d2), _mm_sub_epi16(d1, d3));
2002 for v in [
2003 _mm_add_epi16(s0, s1),
2004 _mm_sub_epi16(s0, s1),
2005 _mm_add_epi16(s2, s3),
2006 _mm_sub_epi16(s2, s3),
2007 ] {
2008 // lanes [a0 a1 a2 a3] -> [a0+a2, a1+a3, a0-a2, a1-a3]
2009 let t = _mm_shufflehi_epi16(_mm_shufflelo_epi16(v, 0x4E), 0x4E);
2010 let h1 = _mm_add_epi16(_mm_mullo_epi16(v, sg1), t);
2011 // -> [h0+h1, h0-h1, h2+h3, h2-h3]
2012 let t = _mm_shufflehi_epi16(_mm_shufflelo_epi16(h1, 0xB1), 0xB1);
2013 let h2 = _mm_add_epi16(_mm_mullo_epi16(h1, sg2), t);
2014 let abs = _mm_max_epi16(h2, _mm_sub_epi16(_mm_setzero_si128(), h2));
2015 total = _mm_add_epi32(total, _mm_madd_epi16(abs, ones));
2016 }
2017 }
2018 }
2019 let t = _mm_add_epi32(total, _mm_srli_si128(total, 8));
2020 let t = _mm_add_epi32(t, _mm_srli_si128(t, 4));
2021 (_mm_cvtsi128_si32(t) as u32).div_ceil(2)
2022}
2023
2024fn satd_scalar(source: &[Pel], pred: &[Pel], n: usize) -> u32 {
2025 let mut total = 0u32;
2026 for by in (0..n).step_by(4) {
2027 for bx in (0..n).step_by(4) {
2028 let mut block = [0i32; 16];
2029 for row in 0..4 {
2030 for col in 0..4 {
2031 let idx = (by + row) * n + bx + col;
2032 block[row * 4 + col] = i32::from(source[idx]) - i32::from(pred[idx]);
2033 }
2034 }
2035 // Rows, then columns.
2036 for row in 0..4 {
2037 let b = &mut block[row * 4..row * 4 + 4];
2038 let (s0, s1, s2, s3) = (b[0] + b[2], b[1] + b[3], b[0] - b[2], b[1] - b[3]);
2039 b[0] = s0 + s1;
2040 b[1] = s0 - s1;
2041 b[2] = s2 + s3;
2042 b[3] = s2 - s3;
2043 }
2044 for col in 0..4 {
2045 let (a, b2, c, d) = (block[col], block[4 + col], block[8 + col], block[12 + col]);
2046 let (s0, s1, s2, s3) = (a + c, b2 + d, a - c, b2 - d);
2047 total += (s0 + s1).unsigned_abs();
2048 total += (s0 - s1).unsigned_abs();
2049 total += (s2 + s3).unsigned_abs();
2050 total += (s2 - s3).unsigned_abs();
2051 }
2052 }
2053 }
2054 total.div_ceil(2)
2055}
2056
2057/// A snapshot type alias so callers do not need the cabac module for rollback.
2058pub type EncoderState = CabacState;
2059
2060#[cfg(test)]
2061mod tests {
2062 use super::*;
2063
2064 #[test]
2065 fn satd_vector_path_matches_the_scalar_one() {
2066 let mut seed = 0x1234_5678u32;
2067 let mut next = |max: u32| {
2068 seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
2069 (seed >> 8) % (max + 1)
2070 };
2071 for n in [4usize, 8, 16, 32] {
2072 for max in [255u32, 1023] {
2073 for round in 0..40 {
2074 let (a, b): (Vec<Pel>, Vec<Pel>) = (0..n * n)
2075 .map(|_| {
2076 if round % 4 == 0 {
2077 // Extremes: the largest possible sums.
2078 (
2079 if next(1) == 0 { 0 } else { max as Pel },
2080 if next(1) == 0 { 0 } else { max as Pel },
2081 )
2082 } else {
2083 (next(max) as Pel, next(max) as Pel)
2084 }
2085 })
2086 .unzip();
2087 assert_eq!(satd(&a, &b, n), satd_scalar(&a, &b, n), "n={n} max={max}");
2088 }
2089 }
2090 }
2091 }
2092
2093 #[test]
2094 fn satd_is_zero_for_an_exact_prediction_and_grows_with_error() {
2095 let source: Vec<Pel> = (0..64).map(|i| (i * 3 % 251) as Pel).collect();
2096 assert_eq!(satd(&source, &source, 8), 0);
2097 let mut worse = source.clone();
2098 worse[9] = worse[9].wrapping_add(40);
2099 assert!(satd(&source, &worse, 8) > 0);
2100 // A constant offset shows up entirely in the DC term.
2101 let shifted: Vec<Pel> = source.iter().map(|v| v.saturating_sub(10)).collect();
2102 assert!(satd(&source, &shifted, 8) >= 8 * 8 * 10 / 2);
2103 }
2104
2105 #[test]
2106 fn lambda_grows_with_qp() {
2107 assert!(lambda_for(37) > lambda_for(27));
2108 assert!((lambda_for(12) - 0.57).abs() < 1e-9);
2109 }
2110}