forge
Explore
Log in

Don't you dare go Hollow

Intra prediction and coding-unit rate-distortion decisions

Browse files at this commit

d43b87f0032a78afada922c09b88acbe3ed7b1c2Ahmet Kaan GümüşParent: 990d3ac
  • feat
    • intra prediction and coding-unit rate-distortion decisions
Show full message
feat(h265): intra prediction and coding-unit rate-distortion decisions

All 35 modes with the spec's reference substitution, smoothing and
boundary filters, then a quadtree that minimises SSD + lambda * bits with
the bits measured rather than modelled.

Two things the trial machinery has to put back that are easy to miss: the
bytes a losing trial wrote over the winner's, and the z-scan availability
map a leaf trial marked. Either one left behind desynchronises the
decoder - a whole picture of noise, not a fraction of a dB.
crates/ec-h265/src/ctu.rsadded+891 -0
@@ -0,0 +1,891 @@
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+
25+use crate::cabac::{CabacEncoder, CabacState, ctx};
26+use crate::intra::{self, Availability, Refs};
27+use crate::residual::encode_residual;
28+use crate::transform::{
29+ chroma_qp, dequantize, forward_transform, inverse_transform, quantize, uses_dst,
30+};
31+use std::sync::atomic::{AtomicU8, Ordering};
32+
33+/// `log2` of the smallest coding block this encoder makes: 8x8.
34+pub const MIN_CB_LOG2: u32 = 3;
35+
36+/// Rate-distortion lambda for an intra picture at `qp`.
37+pub fn lambda_for(qp: i32) -> f64 {
38+ 0.57 * 2f64.powf((qp - 12) as f64 / 3.0)
39+}
40+
41+/// The samples of one CTB row that the row below may predict from: its bottom
42+/// line, plus the coding depths along it.
43+///
44+/// This is the *entire* dependency between two wavefront rows. Intra prediction
45+/// reads one row above the block it predicts, and the only other thing a row
46+/// below asks about the row above is `CtDepth` for one context — so a worker
47+/// publishes a line per CTB and nothing else.
48+pub struct RowBoundary {
49+ /// Bottom luma line, one entry per column.
50+ pub y: Vec<AtomicU8>,
51+ /// Bottom Cb line.
52+ pub cb: Vec<AtomicU8>,
53+ /// Bottom Cr line.
54+ pub cr: Vec<AtomicU8>,
55+ /// `CtDepth` along the bottom, one entry per four columns.
56+ pub depth: Vec<AtomicU8>,
57+}
58+
59+impl RowBoundary {
60+ /// Storage for a picture `width` luma samples wide.
61+ pub fn new(width: usize) -> RowBoundary {
62+ let make = |n: usize| (0..n).map(|_| AtomicU8::new(0)).collect();
63+ RowBoundary {
64+ y: make(width),
65+ cb: make(width / 2),
66+ cr: make(width / 2),
67+ depth: make(width / 4),
68+ }
69+ }
70+}
71+
72+/// Source planes for one picture, already padded to the coded size.
73+pub struct SourcePlanes<'a> {
74+ /// Luma plane, `width * height`.
75+ pub y: &'a [u8],
76+ /// Cb plane, `width / 2 * height / 2`.
77+ pub cb: &'a [u8],
78+ /// Cr plane.
79+ pub cr: &'a [u8],
80+}
81+
82+/// The mutable state one wavefront worker owns while coding one CTB row.
83+pub struct RowState<'a> {
84+ /// Reconstructed luma for this row band.
85+ pub rec_y: &'a mut [u8],
86+ /// Reconstructed Cb for this row band.
87+ pub rec_cb: &'a mut [u8],
88+ /// Reconstructed Cr for this row band.
89+ pub rec_cr: &'a mut [u8],
90+ /// The boundary this row publishes for the row below.
91+ pub publish: &'a RowBoundary,
92+ /// The boundary the row above published; absent for the first row.
93+ pub above: Option<&'a RowBoundary>,
94+}
95+
96+/// Scratch buffers, allocated once per row rather than per block.
97+struct Scratch {
98+ pred: Vec<u8>,
99+ residual: Vec<i32>,
100+ coeffs: Vec<i32>,
101+ scaled: Vec<i32>,
102+ recon: Vec<u8>,
103+ best_recon: Vec<u8>,
104+ levels: Vec<i32>,
105+ best_levels: Vec<i32>,
106+ source: Vec<u8>,
107+ luma_levels: Vec<i32>,
108+ cb_levels: Vec<i32>,
109+ cr_levels: Vec<i32>,
110+}
111+
112+impl Scratch {
113+ fn new() -> Scratch {
114+ Scratch {
115+ pred: vec![0; 32 * 32],
116+ residual: vec![0; 32 * 32],
117+ coeffs: vec![0; 32 * 32],
118+ scaled: vec![0; 32 * 32],
119+ recon: vec![0; 32 * 32],
120+ best_recon: vec![0; 32 * 32],
121+ levels: vec![0; 32 * 32],
122+ best_levels: vec![0; 32 * 32],
123+ source: vec![0; 32 * 32],
124+ luma_levels: vec![0; 32 * 32],
125+ cb_levels: vec![0; 16 * 16],
126+ cr_levels: vec![0; 16 * 16],
127+ }
128+ }
129+}
130+
131+/// Encoder for one CTB row.
132+pub struct CtuEncoder<'a> {
133+ src: SourcePlanes<'a>,
134+ row: RowState<'a>,
135+ width: usize,
136+ height: usize,
137+ ctb_size: usize,
138+ band_y0: usize,
139+ band_rows: usize,
140+ qp: i32,
141+ qp_c: i32,
142+ lambda: f64,
143+ lambda_satd: f64,
144+ strong_smoothing: bool,
145+ /// How many of the 35 modes get a full rate-distortion trial.
146+ candidates: usize,
147+ /// Intra mode per 4x4 block of the band; 255 = not coded yet.
148+ modes: Vec<u8>,
149+ /// Coding depth per 4x4 block of the band.
150+ depths: Vec<u8>,
151+ /// Which 4x4 blocks of the *current* CTB are reconstructed.
152+ coded: [bool; 256],
153+ ctu_x: usize,
154+ /// Whether the coding unit just coded spent no residual at all — the cue
155+ /// that splitting it further would only spend flags.
156+ last_cu_empty: bool,
157+ scratch: Scratch,
158+}
159+
160+impl<'a> CtuEncoder<'a> {
161+ /// A worker for the CTB row whose first luma row is `band_y0`.
162+ #[allow(clippy::too_many_arguments)]
163+ pub fn new(
164+ src: SourcePlanes<'a>,
165+ row: RowState<'a>,
166+ width: usize,
167+ height: usize,
168+ ctb_size: usize,
169+ band_y0: usize,
170+ qp: i32,
171+ strong_smoothing: bool,
172+ candidates: usize,
173+ ) -> CtuEncoder<'a> {
174+ let band_rows = (height - band_y0).min(ctb_size);
175+ CtuEncoder {
176+ src,
177+ row,
178+ width,
179+ height,
180+ ctb_size,
181+ band_y0,
182+ band_rows,
183+ qp,
184+ qp_c: chroma_qp(qp, 0),
185+ lambda: lambda_for(qp),
186+ lambda_satd: lambda_for(qp).sqrt(),
187+ strong_smoothing,
188+ candidates: candidates.clamp(1, 35),
189+ modes: vec![255; (width / 4) * (ctb_size / 4)],
190+ depths: vec![0; (width / 4) * (ctb_size / 4)],
191+ coded: [false; 256],
192+ ctu_x: 0,
193+ last_cu_empty: false,
194+ scratch: Scratch::new(),
195+ }
196+ }
197+
198+ /// Code one coding tree unit at CTB column `ctu_x`.
199+ pub fn encode_ctu(&mut self, ctu_x: usize, enc: &mut CabacEncoder) {
200+ self.ctu_x = ctu_x;
201+ self.coded = [false; 256];
202+ let log2_ctb = self.ctb_size.trailing_zeros();
203+ self.code_quadtree(ctu_x * self.ctb_size, self.band_y0, log2_ctb, 0, enc);
204+ self.publish_boundary(ctu_x);
205+ }
206+
207+ /// Copy this CTB's bottom line into the boundary the next row reads.
208+ fn publish_boundary(&self, ctu_x: usize) {
209+ let last = self.band_y0 + self.band_rows - 1;
210+ let x0 = ctu_x * self.ctb_size;
211+ let x1 = (x0 + self.ctb_size).min(self.width);
212+ for x in x0..x1 {
213+ self.row.publish.y[x].store(self.rec_y(x, last), Ordering::Relaxed);
214+ }
215+ let cy = (self.band_y0 + self.band_rows) / 2 - 1;
216+ for x in x0 / 2..x1 / 2 {
217+ self.row.publish.cb[x].store(self.rec_c(x, cy, 1), Ordering::Relaxed);
218+ self.row.publish.cr[x].store(self.rec_c(x, cy, 2), Ordering::Relaxed);
219+ }
220+ for x in x0 / 4..x1 / 4 {
221+ let depth = self.depths[((self.band_rows - 1) / 4) * (self.width / 4) + x];
222+ self.row.publish.depth[x].store(depth, Ordering::Relaxed);
223+ }
224+ }
225+
226+ fn rec_y(&self, x: usize, y: usize) -> u8 {
227+ if y < self.band_y0 {
228+ self.row
229+ .above
230+ .map_or(128, |above| above.y[x].load(Ordering::Relaxed))
231+ } else {
232+ self.row.rec_y[(y - self.band_y0) * self.width + x]
233+ }
234+ }
235+
236+ /// Reconstructed chroma sample, in chroma coordinates.
237+ fn rec_c(&self, x: usize, y: usize, plane: usize) -> u8 {
238+ let band_c0 = self.band_y0 / 2;
239+ if y < band_c0 {
240+ self.row.above.map_or(128, |above| {
241+ let line = if plane == 1 { &above.cb } else { &above.cr };
242+ line[x].load(Ordering::Relaxed)
243+ })
244+ } else {
245+ let data = if plane == 1 {
246+ &*self.row.rec_cb
247+ } else {
248+ &*self.row.rec_cr
249+ };
250+ data[(y - band_c0) * (self.width / 2) + x]
251+ }
252+ }
253+
254+ /// Availability of a luma position: inside the picture and already coded in
255+ /// raster CTB order, then z-scan order inside the current CTB.
256+ fn available(&self, x: isize, y: isize) -> bool {
257+ if x < 0 || y < 0 || x >= self.width as isize || y >= self.height as isize {
258+ return false;
259+ }
260+ let (x, y) = (x as usize, y as usize);
261+ if y < self.band_y0 {
262+ // Every CTB in a row above is coded. The wavefront guarantees the
263+ // ones a block can actually reach — at most one CTB to the right —
264+ // are also finished.
265+ debug_assert!(x < (self.ctu_x + 2) * self.ctb_size);
266+ return self.row.above.is_some();
267+ }
268+ if y >= self.band_y0 + self.band_rows {
269+ return false;
270+ }
271+ let cx = x / self.ctb_size;
272+ match cx.cmp(&self.ctu_x) {
273+ std::cmp::Ordering::Less => true,
274+ std::cmp::Ordering::Greater => false,
275+ std::cmp::Ordering::Equal => {
276+ let bx = (x - self.ctu_x * self.ctb_size) / 4;
277+ let by = (y - self.band_y0) / 4;
278+ self.coded[by * 16 + bx]
279+ }
280+ }
281+ }
282+
283+ fn mode_at(&self, x: usize, y: usize) -> u8 {
284+ self.modes[((y - self.band_y0) / 4) * (self.width / 4) + x / 4]
285+ }
286+
287+ fn depth_at(&self, x: usize, y: usize) -> u8 {
288+ if y < self.band_y0 {
289+ return self
290+ .row
291+ .above
292+ .map_or(0, |above| above.depth[x / 4].load(Ordering::Relaxed));
293+ }
294+ self.depths[((y - self.band_y0) / 4) * (self.width / 4) + x / 4]
295+ }
296+
297+ // ---- the quadtree ----------------------------------------------------
298+
299+ fn code_quadtree(
300+ &mut self,
301+ x: usize,
302+ y: usize,
303+ log2: u32,
304+ depth: u8,
305+ enc: &mut CabacEncoder,
306+ ) -> f64 {
307+ let size = 1usize << log2;
308+ let half = size / 2;
309+ if x + size > self.width || y + size > self.height {
310+ // split_cu_flag is inferred to 1 and only the children inside the
311+ // picture are coded (7.3.8.4).
312+ let mut cost = 0.0;
313+ for (dx, dy) in [(0, 0), (half, 0), (0, half), (half, half)] {
314+ if x + dx < self.width && y + dy < self.height {
315+ cost += self.code_quadtree(x + dx, y + dy, log2 - 1, depth + 1, enc);
316+ }
317+ }
318+ return cost;
319+ }
320+ if log2 == MIN_CB_LOG2 {
321+ return self.code_cu(x, y, log2, depth, enc);
322+ }
323+ let split_ctx = ctx::SPLIT_CU
324+ + usize::from(
325+ self.available(x as isize - 1, y as isize) && self.depth_at(x - 1, y) > depth,
326+ )
327+ + usize::from(
328+ self.available(x as isize, y as isize - 1) && self.depth_at(x, y - 1) > depth,
329+ );
330+ if log2 > 5 {
331+ // 64x64 coding units are not searched; the decision starts at 32x32.
332+ let before = enc.bit_count();
333+ enc.encode_bin(split_ctx, 1);
334+ let mut cost = self.lambda * (enc.bit_count() - before) as f64;
335+ for (dx, dy) in [(0, 0), (half, 0), (0, half), (half, half)] {
336+ cost += self.code_quadtree(x + dx, y + dy, log2 - 1, depth + 1, enc);
337+ }
338+ return cost;
339+ }
340+
341+ let start = enc.snapshot();
342+ // The z-scan availability map has to go back with everything else: the
343+ // leaf trial marks the whole region reconstructed, and a split trial run
344+ // against that map would predict from samples the *decoder* considers
345+ // unavailable and derive its contexts from them too. That is a
346+ // desynchronisation, not an inefficiency — it was worth a whole picture
347+ // of garbage before this line existed.
348+ let coded_before = self.coded;
349+ let before = enc.bit_count();
350+ enc.encode_bin(split_ctx, 0);
351+ let flag_bits = enc.bit_count() - before;
352+ let leaf_cost = self.lambda * flag_bits as f64 + self.code_cu(x, y, log2, depth, enc);
353+ if self.last_cu_empty {
354+ // Every coefficient quantised to zero: the four sub-trees can only
355+ // add split flags and mode bits on top of the same prediction, so
356+ // the split is not searched. This is where most of the picture is.
357+ return leaf_cost;
358+ }
359+ let leaf_state = enc.snapshot_since(&start);
360+ let leaf_rec = self.save_region(x, y, size);
361+ let leaf_meta = self.save_meta(x, y, size);
362+
363+ enc.restore(&start);
364+ self.coded = coded_before;
365+ let before = enc.bit_count();
366+ enc.encode_bin(split_ctx, 1);
367+ let mut split_cost = self.lambda * (enc.bit_count() - before) as f64;
368+ for (dx, dy) in [(0, 0), (half, 0), (0, half), (half, half)] {
369+ split_cost += self.code_quadtree(x + dx, y + dy, log2 - 1, depth + 1, enc);
370+ }
371+
372+ if leaf_cost <= split_cost {
373+ enc.restore(&leaf_state);
374+ self.load_region(x, y, size, &leaf_rec);
375+ self.load_meta(x, y, size, &leaf_meta);
376+ leaf_cost
377+ } else {
378+ split_cost
379+ }
380+ }
381+
382+ /// Reconstructed samples of a square luma region and its chroma, packed.
383+ fn save_region(&self, x: usize, y: usize, size: usize) -> Vec<u8> {
384+ let mut out = Vec::with_capacity(size * size * 3 / 2);
385+ for yy in y..y + size {
386+ for xx in x..x + size {
387+ out.push(self.rec_y(xx, yy));
388+ }
389+ }
390+ for plane in [1usize, 2] {
391+ for yy in y / 2..y / 2 + size / 2 {
392+ for xx in x / 2..x / 2 + size / 2 {
393+ out.push(self.rec_c(xx, yy, plane));
394+ }
395+ }
396+ }
397+ out
398+ }
399+
400+ fn load_region(&mut self, x: usize, y: usize, size: usize, data: &[u8]) {
401+ let mut i = 0;
402+ for yy in y..y + size {
403+ for xx in x..x + size {
404+ self.write_rec_y(xx, yy, data[i]);
405+ i += 1;
406+ }
407+ }
408+ for plane in [1usize, 2] {
409+ for yy in y / 2..y / 2 + size / 2 {
410+ for xx in x / 2..x / 2 + size / 2 {
411+ self.write_rec_c(xx, yy, plane, data[i]);
412+ i += 1;
413+ }
414+ }
415+ }
416+ }
417+
418+ fn save_meta(&self, x: usize, y: usize, size: usize) -> Vec<u8> {
419+ let stride = self.width / 4;
420+ let mut out = Vec::with_capacity(2 * (size / 4) * (size / 4));
421+ for by in (y..y + size).step_by(4) {
422+ for bx in (x..x + size).step_by(4) {
423+ let idx = ((by - self.band_y0) / 4) * stride + bx / 4;
424+ out.push(self.modes[idx]);
425+ out.push(self.depths[idx]);
426+ }
427+ }
428+ out
429+ }
430+
431+ fn load_meta(&mut self, x: usize, y: usize, size: usize, data: &[u8]) {
432+ let stride = self.width / 4;
433+ let mut i = 0;
434+ for by in (y..y + size).step_by(4) {
435+ for bx in (x..x + size).step_by(4) {
436+ let idx = ((by - self.band_y0) / 4) * stride + bx / 4;
437+ self.modes[idx] = data[i];
438+ self.depths[idx] = data[i + 1];
439+ i += 2;
440+ }
441+ }
442+ }
443+
444+ fn write_rec_y(&mut self, x: usize, y: usize, value: u8) {
445+ let stride = self.width;
446+ self.row.rec_y[(y - self.band_y0) * stride + x] = value;
447+ }
448+
449+ fn write_rec_c(&mut self, x: usize, y: usize, plane: usize, value: u8) {
450+ let stride = self.width / 2;
451+ let band_c0 = self.band_y0 / 2;
452+ let data = if plane == 1 {
453+ &mut *self.row.rec_cb
454+ } else {
455+ &mut *self.row.rec_cr
456+ };
457+ data[(y - band_c0) * stride + x] = value;
458+ }
459+
460+ // ---- one coding unit -------------------------------------------------
461+
462+ /// Code one coding unit, returning `SSD + lambda * bits` for it. The split
463+ /// flag above it is the caller's to count.
464+ fn code_cu(&mut self, x: usize, y: usize, log2: u32, depth: u8, enc: &mut CabacEncoder) -> f64 {
465+ let n = 1usize << log2;
466+ let before = enc.bit_count();
467+ if log2 == MIN_CB_LOG2 {
468+ // part_mode: PART_2Nx2N is the single bin 1.
469+ enc.encode_bin(ctx::PART_MODE, 1);
470+ }
471+ let mpm = self.mpm_at(x, y);
472+ let mode = self.choose_luma_mode(x, y, n, log2, &mpm, enc);
473+ self.write_mode_syntax(enc, mode, &mpm);
474+ // intra_chroma_pred_mode = 4 (derived from luma): the single bin 0.
475+ enc.encode_bin(ctx::INTRA_CHROMA_PRED_MODE, 0);
476+
477+ // Luma was reconstructed by the mode search; chroma is coded now.
478+ let luma_cbf = self.scratch.luma_levels[..n * n].iter().any(|&v| v != 0);
479+ let cb_cbf = self.code_chroma(x, y, n, mode, 1);
480+ let cr_cbf = self.code_chroma(x, y, n, mode, 2);
481+
482+ enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf));
483+ enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf));
484+ enc.encode_bin(ctx::CBF_LUMA + 1, u32::from(luma_cbf));
485+ if luma_cbf {
486+ let scan = intra::scan_index(mode, log2, true);
487+ let levels = std::mem::take(&mut self.scratch.luma_levels);
488+ encode_residual(enc, &levels[..n * n], log2, 0, scan);
489+ self.scratch.luma_levels = levels;
490+ }
491+ let chroma_scan = intra::scan_index(mode, log2 - 1, false);
492+ if cb_cbf {
493+ let levels = std::mem::take(&mut self.scratch.cb_levels);
494+ encode_residual(enc, &levels[..n * n / 4], log2 - 1, 1, chroma_scan);
495+ self.scratch.cb_levels = levels;
496+ }
497+ if cr_cbf {
498+ let levels = std::mem::take(&mut self.scratch.cr_levels);
499+ encode_residual(enc, &levels[..n * n / 4], log2 - 1, 2, chroma_scan);
500+ self.scratch.cr_levels = levels;
501+ }
502+
503+ self.mark_coded(x, y, n, mode, depth);
504+ self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf);
505+ let bits = enc.bit_count() - before;
506+ self.region_ssd(x, y, n) + self.lambda * bits as f64
507+ }
508+
509+ fn write_mode_syntax(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) {
510+ match mpm.iter().position(|&m| m == mode) {
511+ Some(idx) => {
512+ enc.encode_bin(ctx::PREV_INTRA_LUMA_PRED, 1);
513+ // mpm_idx: truncated rice, cMax 2, all bypass.
514+ if idx == 0 {
515+ enc.encode_bypass(0);
516+ } else {
517+ enc.encode_bypass(1);
518+ enc.encode_bypass(u32::from(idx == 2));
519+ }
520+ }
521+ None => {
522+ enc.encode_bin(ctx::PREV_INTRA_LUMA_PRED, 0);
523+ let mut sorted = *mpm;
524+ sorted.sort_unstable();
525+ let mut rem = mode;
526+ for &m in sorted.iter().rev() {
527+ if mode > m {
528+ rem -= 1;
529+ }
530+ }
531+ enc.encode_bypass_bits(u32::from(rem), 5);
532+ }
533+ }
534+ }
535+
536+ fn mpm_at(&self, x: usize, y: usize) -> [u8; 3] {
537+ let left = if self.available(x as isize - 1, y as isize) {
538+ let m = self.mode_at(x - 1, y);
539+ if m == 255 { None } else { Some(m) }
540+ } else {
541+ None
542+ };
543+ // A neighbour in the CTB row above counts as DC (8.4.2 step 2), which is
544+ // also what keeps the wavefront from needing a mode line.
545+ let above = if y > self.band_y0 && self.available(x as isize, y as isize - 1) {
546+ let m = self.mode_at(x, y - 1);
547+ if m == 255 { None } else { Some(m) }
548+ } else {
549+ None
550+ };
551+ intra::mpm_list(left, above)
552+ }
553+
554+ fn mark_coded(&mut self, x: usize, y: usize, n: usize, mode: u8, depth: u8) {
555+ let stride = self.width / 4;
556+ for by in (y..y + n).step_by(4) {
557+ for bx in (x..x + n).step_by(4) {
558+ let idx = ((by - self.band_y0) / 4) * stride + bx / 4;
559+ self.modes[idx] = mode;
560+ self.depths[idx] = depth;
561+ let cx = (bx - self.ctu_x * self.ctb_size) / 4;
562+ let cy = (by - self.band_y0) / 4;
563+ self.coded[cy * 16 + cx] = true;
564+ }
565+ }
566+ }
567+
568+ /// Sum of squared differences over a coding unit, all three planes.
569+ fn region_ssd(&self, x: usize, y: usize, n: usize) -> f64 {
570+ let mut ssd = 0i64;
571+ for yy in y..y + n {
572+ let src_row = &self.src.y[yy * self.width..yy * self.width + self.width];
573+ for xx in x..x + n {
574+ let d = i64::from(src_row[xx]) - i64::from(self.rec_y(xx, yy));
575+ ssd += d * d;
576+ }
577+ }
578+ let cw = self.width / 2;
579+ for plane in [1usize, 2] {
580+ let src = if plane == 1 { self.src.cb } else { self.src.cr };
581+ for yy in y / 2..y / 2 + n / 2 {
582+ for xx in x / 2..x / 2 + n / 2 {
583+ let d = i64::from(src[yy * cw + xx]) - i64::from(self.rec_c(xx, yy, plane));
584+ ssd += d * d;
585+ }
586+ }
587+ }
588+ ssd as f64
589+ }
590+
591+ // ---- luma mode decision ----------------------------------------------
592+
593+ /// Pick the luma mode, leaving its levels in `scratch.luma_levels` and its
594+ /// reconstruction written into the band.
595+ fn choose_luma_mode(
596+ &mut self,
597+ x: usize,
598+ y: usize,
599+ n: usize,
600+ log2: u32,
601+ mpm: &[u8; 3],
602+ enc: &mut CabacEncoder,
603+ ) -> u8 {
604+ let refs = self.luma_refs(x, y, n);
605+ let mut source = std::mem::take(&mut self.scratch.source);
606+ for row in 0..n {
607+ let sy = y + row;
608+ source[row * n..row * n + n]
609+ .copy_from_slice(&self.src.y[sy * self.width + x..sy * self.width + x + n]);
610+ }
611+
612+ // Pre-screen: planar, DC and every second angle, then the two
613+ // neighbours of whichever angle won. Nineteen predictions instead of
614+ // thirty-five for the same winner in all but a rounding of cases —
615+ // the SATD surface over the angles is smooth by construction.
616+ let mut scored: Vec<(f64, u8)> = Vec::with_capacity(24);
617+ let score = |this: &mut Self, mode: u8, scored: &mut Vec<(f64, u8)>| {
618+ intra::predict(
619+ &refs,
620+ mode,
621+ n,
622+ true,
623+ this.strong_smoothing,
624+ &mut this.scratch.pred,
625+ );
626+ let satd = satd(&source, &this.scratch.pred[..n * n], n) as f64;
627+ let mode_bits = if mpm.contains(&mode) { 2.0 } else { 6.0 };
628+ scored.push((satd + this.lambda_satd * mode_bits, mode));
629+ };
630+ for mode in [0u8, 1] {
631+ score(self, mode, &mut scored);
632+ }
633+ for mode in (2u8..=34).step_by(2) {
634+ score(self, mode, &mut scored);
635+ }
636+ let coarse_best = scored
637+ .iter()
638+ .filter(|(_, m)| *m >= 2)
639+ .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal))
640+ .map(|&(_, m)| m)
641+ .unwrap_or(26);
642+ for delta in [-1i16, 1] {
643+ let refined = coarse_best as i16 + delta;
644+ if (2..=34).contains(&refined) {
645+ score(self, refined as u8, &mut scored);
646+ }
647+ }
648+ scored.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
649+
650+ // Full rate-distortion on the survivors, plus the most probable modes,
651+ // which are cheap to code and often win despite a worse SATD.
652+ let mut candidates: Vec<u8> = scored.iter().take(self.candidates).map(|s| s.1).collect();
653+ // The first most probable mode joins the trial whatever its SATD: it is
654+ // two bins where a non-MPM mode is six, and that gap decides plenty of
655+ // flat blocks.
656+ if !candidates.contains(&mpm[0]) {
657+ candidates.push(mpm[0]);
658+ }
659+
660+ let start = enc.snapshot();
661+ enc.set_counting(true);
662+ let mut best = (f64::MAX, 0u8);
663+ let mut best_levels = std::mem::take(&mut self.scratch.best_levels);
664+ for &mode in &candidates {
665+ let bits_before = enc.bit_count();
666+ self.write_mode_syntax(enc, mode, mpm);
667+ let (ssd, cbf) = self.transform_luma(n, mode, &source, &refs);
668+ enc.encode_bin(ctx::CBF_LUMA + 1, u32::from(cbf));
669+ if cbf {
670+ let scan = intra::scan_index(mode, log2, true);
671+ let levels = std::mem::take(&mut self.scratch.levels);
672+ encode_residual(enc, &levels[..n * n], log2, 0, scan);
673+ self.scratch.levels = levels;
674+ }
675+ let bits = enc.bit_count() - bits_before;
676+ enc.restore(&start);
677+ let cost = ssd + self.lambda * bits as f64;
678+ if cost < best.0 {
679+ best = (cost, mode);
680+ best_levels[..n * n].copy_from_slice(&self.scratch.levels[..n * n]);
681+ self.scratch.best_recon[..n * n].copy_from_slice(&self.scratch.recon[..n * n]);
682+ }
683+ }
684+ enc.set_counting(false);
685+ // Commit the winner's reconstruction and levels.
686+ for row in 0..n {
687+ for col in 0..n {
688+ self.write_rec_y(x + col, y + row, self.scratch.best_recon[row * n + col]);
689+ }
690+ }
691+ self.scratch.luma_levels[..n * n].copy_from_slice(&best_levels[..n * n]);
692+ self.scratch.best_levels = best_levels;
693+ self.scratch.source = source;
694+ best.1
695+ }
696+
697+ /// Predict, transform, quantise and reconstruct one luma block into
698+ /// `scratch.recon` / `scratch.levels`; returns `(SSD, cbf)`.
699+ fn transform_luma(&mut self, n: usize, mode: u8, source: &[u8], refs: &Refs) -> (f64, bool) {
700+ intra::predict(
701+ refs,
702+ mode,
703+ n,
704+ true,
705+ self.strong_smoothing,
706+ &mut self.scratch.pred,
707+ );
708+ for i in 0..n * n {
709+ self.scratch.residual[i] = i32::from(source[i]) - i32::from(self.scratch.pred[i]);
710+ }
711+ let dst = uses_dst(n, true);
712+ forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst);
713+ let nonzero = quantize(&self.scratch.coeffs, &mut self.scratch.levels, n, self.qp);
714+ let cbf = nonzero > 0;
715+ if cbf {
716+ dequantize(&self.scratch.levels, &mut self.scratch.scaled, n, self.qp);
717+ inverse_transform(&self.scratch.scaled, &mut self.scratch.residual, n, dst);
718+ } else {
719+ self.scratch.residual[..n * n].fill(0);
720+ }
721+ let mut ssd = 0i64;
722+ for i in 0..n * n {
723+ let value =
724+ (i32::from(self.scratch.pred[i]) + self.scratch.residual[i]).clamp(0, 255) as u8;
725+ self.scratch.recon[i] = value;
726+ let d = i64::from(source[i]) - i64::from(value);
727+ ssd += d * d;
728+ }
729+ (ssd as f64, cbf)
730+ }
731+
732+ /// Code one chroma transform block in derived mode; returns its `cbf` and
733+ /// leaves the levels in the matching scratch buffer.
734+ fn code_chroma(&mut self, x: usize, y: usize, n: usize, luma_mode: u8, plane: usize) -> bool {
735+ let cn = n / 2;
736+ let (cx, cy) = (x / 2, y / 2);
737+ let refs = self.chroma_refs(cx, cy, cn, plane);
738+ let cw = self.width / 2;
739+ let src = if plane == 1 { self.src.cb } else { self.src.cr };
740+ intra::predict(
741+ &refs,
742+ luma_mode,
743+ cn,
744+ false,
745+ self.strong_smoothing,
746+ &mut self.scratch.pred,
747+ );
748+ for row in 0..cn {
749+ for col in 0..cn {
750+ let s = i32::from(src[(cy + row) * cw + cx + col]);
751+ self.scratch.residual[row * cn + col] =
752+ s - i32::from(self.scratch.pred[row * cn + col]);
753+ }
754+ }
755+ forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false);
756+ let nonzero = quantize(&self.scratch.coeffs, &mut self.scratch.levels, cn, self.qp_c);
757+ let cbf = nonzero > 0;
758+ if cbf {
759+ dequantize(&self.scratch.levels, &mut self.scratch.scaled, cn, self.qp_c);
760+ inverse_transform(&self.scratch.scaled, &mut self.scratch.residual, cn, false);
761+ } else {
762+ self.scratch.residual[..cn * cn].fill(0);
763+ }
764+ for row in 0..cn {
765+ for col in 0..cn {
766+ let value = (i32::from(self.scratch.pred[row * cn + col])
767+ + self.scratch.residual[row * cn + col])
768+ .clamp(0, 255) as u8;
769+ self.write_rec_c(cx + col, cy + row, plane, value);
770+ }
771+ }
772+ let levels = if plane == 1 {
773+ &mut self.scratch.cb_levels
774+ } else {
775+ &mut self.scratch.cr_levels
776+ };
777+ levels[..cn * cn].copy_from_slice(&self.scratch.levels[..cn * cn]);
778+ cbf
779+ }
780+
781+ // ---- reference samples -----------------------------------------------
782+
783+ fn luma_refs(&self, x: usize, y: usize, n: usize) -> Refs {
784+ let mut refs = Refs::default();
785+ let mut avail = Availability::default();
786+ let span = 2 * n;
787+ avail.corner = self.available(x as isize - 1, y as isize - 1);
788+ if avail.corner {
789+ refs.corner = self.rec_y(x - 1, y - 1);
790+ }
791+ for i in 0..span {
792+ if self.available((x + i) as isize, y as isize - 1) {
793+ avail.top |= 1 << i;
794+ refs.top[i] = self.rec_y(x + i, y - 1);
795+ }
796+ if self.available(x as isize - 1, (y + i) as isize) {
797+ avail.left |= 1 << i;
798+ refs.left[i] = self.rec_y(x - 1, y + i);
799+ }
800+ }
801+ intra::substitute(&mut refs, &avail, n, 8);
802+ refs
803+ }
804+
805+ fn chroma_refs(&self, cx: usize, cy: usize, cn: usize, plane: usize) -> Refs {
806+ let mut refs = Refs::default();
807+ let mut avail = Availability::default();
808+ let span = 2 * cn;
809+ avail.corner = self.available(cx as isize * 2 - 1, cy as isize * 2 - 1);
810+ if avail.corner {
811+ refs.corner = self.rec_c(cx - 1, cy - 1, plane);
812+ }
813+ for i in 0..span {
814+ if self.available(((cx + i) * 2) as isize, cy as isize * 2 - 1) {
815+ avail.top |= 1 << i;
816+ refs.top[i] = self.rec_c(cx + i, cy - 1, plane);
817+ }
818+ if self.available(cx as isize * 2 - 1, ((cy + i) * 2) as isize) {
819+ avail.left |= 1 << i;
820+ refs.left[i] = self.rec_c(cx - 1, cy + i, plane);
821+ }
822+ }
823+ intra::substitute(&mut refs, &avail, cn, 8);
824+ refs
825+ }
826+}
827+
828+/// Sum of absolute transformed differences, 4x4 Hadamard per sub-block.
829+fn satd(source: &[u8], pred: &[u8], n: usize) -> u32 {
830+ let mut total = 0u32;
831+ for by in (0..n).step_by(4) {
832+ for bx in (0..n).step_by(4) {
833+ let mut block = [0i32; 16];
834+ for row in 0..4 {
835+ for col in 0..4 {
836+ let idx = (by + row) * n + bx + col;
837+ block[row * 4 + col] = i32::from(source[idx]) - i32::from(pred[idx]);
838+ }
839+ }
840+ // Rows, then columns.
841+ for row in 0..4 {
842+ let b = &mut block[row * 4..row * 4 + 4];
843+ let (s0, s1, s2, s3) = (b[0] + b[2], b[1] + b[3], b[0] - b[2], b[1] - b[3]);
844+ b[0] = s0 + s1;
845+ b[1] = s0 - s1;
846+ b[2] = s2 + s3;
847+ b[3] = s2 - s3;
848+ }
849+ for col in 0..4 {
850+ let (a, b2, c, d) = (
851+ block[col],
852+ block[4 + col],
853+ block[8 + col],
854+ block[12 + col],
855+ );
856+ let (s0, s1, s2, s3) = (a + c, b2 + d, a - c, b2 - d);
857+ total += (s0 + s1).unsigned_abs();
858+ total += (s0 - s1).unsigned_abs();
859+ total += (s2 + s3).unsigned_abs();
860+ total += (s2 - s3).unsigned_abs();
861+ }
862+ }
863+ }
864+ (total + 1) / 2
865+}
866+
867+/// A snapshot type alias so callers do not need the cabac module for rollback.
868+pub type EncoderState = CabacState;
869+
870+#[cfg(test)]
871+mod tests {
872+ use super::*;
873+
874+ #[test]
875+ fn satd_is_zero_for_an_exact_prediction_and_grows_with_error() {
876+ let source: Vec<u8> = (0..64).map(|i| (i * 3 % 251) as u8).collect();
877+ assert_eq!(satd(&source, &source, 8), 0);
878+ let mut worse = source.clone();
879+ worse[9] = worse[9].wrapping_add(40);
880+ assert!(satd(&source, &worse, 8) > 0);
881+ // A constant offset shows up entirely in the DC term.
882+ let shifted: Vec<u8> = source.iter().map(|v| v.saturating_sub(10)).collect();
883+ assert!(satd(&source, &shifted, 8) >= 8 * 8 * 10 / 2);
884+ }
885+
886+ #[test]
887+ fn lambda_grows_with_qp() {
888+ assert!(lambda_for(37) > lambda_for(27));
889+ assert!((lambda_for(12) - 0.57).abs() < 1e-9);
890+ }
891+}
crates/ec-h265/src/intra.rsadded+498 -0
@@ -0,0 +1,498 @@
1+//! Intra sample prediction, all 35 modes (8.4.2 - 8.4.4.2).
2+//!
3+//! Reference samples arrive as `corner` (`p[-1][-1]`), `top` (`p[x][-1]`) and
4+//! `left` (`p[-1][y]`), each up to `2 * nTbS` long, with a bitmask saying which
5+//! of them are real. Substitution, smoothing and the mode itself are then
6+//! exactly the decoder's, because the encoder reconstructs with the same code:
7+//! a prediction that differs from the decoder's by one sample is a drift that
8+//! the picture hash would catch but the eye would not.
9+
10+/// Reference samples for one transform block, before or after filtering.
11+#[derive(Clone, Copy)]
12+pub struct Refs {
13+ /// `p[-1][-1]`.
14+ pub corner: u8,
15+ /// `p[x][-1]`, `x = 0..2 * nTbS - 1`.
16+ pub top: [u8; 64],
17+ /// `p[-1][y]`, `y = 0..2 * nTbS - 1`.
18+ pub left: [u8; 64],
19+}
20+
21+impl Default for Refs {
22+ fn default() -> Self {
23+ Refs {
24+ corner: 128,
25+ top: [128; 64],
26+ left: [128; 64],
27+ }
28+ }
29+}
30+
31+/// Which reference samples are real, one bit per sample.
32+#[derive(Clone, Copy, Default)]
33+pub struct Availability {
34+ /// Whether `p[-1][-1]` is available.
35+ pub corner: bool,
36+ /// Bit `x` set when `p[x][-1]` is available.
37+ pub top: u64,
38+ /// Bit `y` set when `p[-1][y]` is available.
39+ pub left: u64,
40+}
41+
42+impl Availability {
43+ /// True when nothing at all is available and the whole block predicts flat.
44+ pub fn is_empty(&self, n: usize) -> bool {
45+ let mask = if 2 * n >= 64 {
46+ u64::MAX
47+ } else {
48+ (1u64 << (2 * n)) - 1
49+ };
50+ !self.corner && self.top & mask == 0 && self.left & mask == 0
51+ }
52+}
53+
54+/// `intraPredAngle` per mode (Table 8-5), indexed by `predModeIntra`.
55+#[rustfmt::skip]
56+const ANGLE: [i32; 35] = [
57+ 0, 0, 32, 26, 21, 17, 13, 9, 5, 2, 0, -2, -5, -9, -13, -17, -21, -26,
58+ -32, -26, -21, -17, -13, -9, -5, -2, 0, 2, 5, 9, 13, 17, 21, 26, 32,
59+];
60+
61+/// `invAngle` per mode (Table 8-6); only modes 11..25 use it.
62+#[rustfmt::skip]
63+const INV_ANGLE: [i32; 35] = [
64+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
65+ -4096, -1638, -910, -630, -482, -390, -315, -256, -315, -390, -482, -630, -910, -1638, -4096,
66+ 0, 0, 0, 0, 0, 0, 0, 0, 0,
67+];
68+
69+/// Reference sample substitution (8.4.4.2.2): fill the holes from the nearest
70+/// available sample, walking up the left edge and then along the top.
71+pub fn substitute(refs: &mut Refs, avail: &Availability, n: usize, bit_depth: u32) {
72+ let span = 2 * n;
73+ if avail.is_empty(n) {
74+ let mid = (1u8 << (bit_depth - 1)) as u8;
75+ refs.corner = mid;
76+ refs.top[..span].fill(mid);
77+ refs.left[..span].fill(mid);
78+ return;
79+ }
80+ // Step 1: the bottom-left sample, from the first available going up the
81+ // left edge, then across the top.
82+ if avail.left & (1 << (span - 1)) == 0 {
83+ let mut value = None;
84+ for y in (0..span).rev() {
85+ if avail.left & (1 << y) != 0 {
86+ value = Some(refs.left[y]);
87+ break;
88+ }
89+ }
90+ if value.is_none() && avail.corner {
91+ value = Some(refs.corner);
92+ }
93+ if value.is_none() {
94+ for x in 0..span {
95+ if avail.top & (1 << x) != 0 {
96+ value = Some(refs.top[x]);
97+ break;
98+ }
99+ }
100+ }
101+ refs.left[span - 1] = value.unwrap_or(1 << (bit_depth - 1));
102+ }
103+ // Step 2: up the left edge, each hole taking the sample below it.
104+ for y in (0..span - 1).rev() {
105+ if avail.left & (1 << y) == 0 {
106+ refs.left[y] = refs.left[y + 1];
107+ }
108+ }
109+ if !avail.corner {
110+ refs.corner = refs.left[0];
111+ }
112+ // Step 3: along the top, each hole taking the sample to its left.
113+ for x in 0..span {
114+ if avail.top & (1 << x) == 0 {
115+ refs.top[x] = if x == 0 { refs.corner } else { refs.top[x - 1] };
116+ }
117+ }
118+}
119+
120+/// `filterFlag` of 8.4.4.2.3.
121+fn filter_flag(mode: u8, n: usize, is_luma: bool) -> bool {
122+ if !is_luma || mode == 1 || n == 4 {
123+ return false;
124+ }
125+ let min_dist = (i32::from(mode) - 26).abs().min((i32::from(mode) - 10).abs());
126+ let threshold = match n {
127+ 8 => 7,
128+ 16 => 1,
129+ _ => 0,
130+ };
131+ min_dist > threshold
132+}
133+
134+/// Neighbouring sample filtering (8.4.4.2.3), including the strong bilinear
135+/// path for flat 32x32 luma blocks.
136+pub fn filter_refs(refs: &Refs, mode: u8, n: usize, is_luma: bool, strong_smoothing: bool) -> Refs {
137+ if !filter_flag(mode, n, is_luma) {
138+ return *refs;
139+ }
140+ let span = 2 * n;
141+ let mut out = *refs;
142+ let bi_int = strong_smoothing
143+ && is_luma
144+ && n == 32
145+ && (i32::from(refs.corner) + i32::from(refs.top[span - 1])
146+ - 2 * i32::from(refs.top[n - 1]))
147+ .abs()
148+ < (1 << 3)
149+ && (i32::from(refs.corner) + i32::from(refs.left[span - 1])
150+ - 2 * i32::from(refs.left[n - 1]))
151+ .abs()
152+ < (1 << 3);
153+ if bi_int {
154+ let corner = i32::from(refs.corner);
155+ let bottom_left = i32::from(refs.left[63]);
156+ let top_right = i32::from(refs.top[63]);
157+ for y in 0..63 {
158+ out.left[y] = (((63 - y as i32) * corner + (y as i32 + 1) * bottom_left + 32) >> 6) as u8;
159+ }
160+ out.left[63] = refs.left[63];
161+ for x in 0..63 {
162+ out.top[x] = (((63 - x as i32) * corner + (x as i32 + 1) * top_right + 32) >> 6) as u8;
163+ }
164+ out.top[63] = refs.top[63];
165+ return out;
166+ }
167+ out.corner = ((u32::from(refs.left[0]) + 2 * u32::from(refs.corner) + u32::from(refs.top[0]) + 2)
168+ >> 2) as u8;
169+ for y in 0..span - 1 {
170+ let below = u32::from(refs.left[y + 1]);
171+ let here = u32::from(refs.left[y]);
172+ let above = if y == 0 {
173+ u32::from(refs.corner)
174+ } else {
175+ u32::from(refs.left[y - 1])
176+ };
177+ out.left[y] = ((below + 2 * here + above + 2) >> 2) as u8;
178+ }
179+ for x in 0..span - 1 {
180+ let right = u32::from(refs.top[x + 1]);
181+ let here = u32::from(refs.top[x]);
182+ let left = if x == 0 {
183+ u32::from(refs.corner)
184+ } else {
185+ u32::from(refs.top[x - 1])
186+ };
187+ out.top[x] = ((right + 2 * here + left + 2) >> 2) as u8;
188+ }
189+ out
190+}
191+
192+/// Predict an `n x n` block into `out` (row major), for `mode` 0..=34.
193+///
194+/// `refs` must already be substituted; filtering is applied here so that a
195+/// caller trying 35 modes filters once per mode rather than per sample.
196+pub fn predict(
197+ refs: &Refs,
198+ mode: u8,
199+ n: usize,
200+ is_luma: bool,
201+ strong_smoothing: bool,
202+ out: &mut [u8],
203+) {
204+ let filtered = filter_refs(refs, mode, n, is_luma, strong_smoothing);
205+ match mode {
206+ 0 => predict_planar(&filtered, n, out),
207+ 1 => predict_dc(&filtered, n, is_luma, out),
208+ _ => predict_angular(&filtered, mode, n, is_luma, out),
209+ }
210+}
211+
212+fn predict_planar(refs: &Refs, n: usize, out: &mut [u8]) {
213+ let log2n = n.trailing_zeros();
214+ let top_right = i32::from(refs.top[n]);
215+ let bottom_left = i32::from(refs.left[n]);
216+ for y in 0..n {
217+ let left = i32::from(refs.left[y]);
218+ for x in 0..n {
219+ let value = (n as i32 - 1 - x as i32) * left
220+ + (x as i32 + 1) * top_right
221+ + (n as i32 - 1 - y as i32) * i32::from(refs.top[x])
222+ + (y as i32 + 1) * bottom_left
223+ + n as i32;
224+ out[y * n + x] = (value >> (log2n + 1)) as u8;
225+ }
226+ }
227+}
228+
229+fn predict_dc(refs: &Refs, n: usize, is_luma: bool, out: &mut [u8]) {
230+ let mut sum = n as u32;
231+ for i in 0..n {
232+ sum += u32::from(refs.top[i]) + u32::from(refs.left[i]);
233+ }
234+ let dc = (sum >> (n.trailing_zeros() + 1)) as i32;
235+ for value in out[..n * n].iter_mut() {
236+ *value = dc as u8;
237+ }
238+ if is_luma && n < 32 {
239+ out[0] = ((i32::from(refs.left[0]) + 2 * dc + i32::from(refs.top[0]) + 2) >> 2) as u8;
240+ for x in 1..n {
241+ out[x] = ((i32::from(refs.top[x]) + 3 * dc + 2) >> 2) as u8;
242+ }
243+ for y in 1..n {
244+ out[y * n] = ((i32::from(refs.left[y]) + 3 * dc + 2) >> 2) as u8;
245+ }
246+ }
247+}
248+
249+fn predict_angular(refs: &Refs, mode: u8, n: usize, is_luma: bool, out: &mut [u8]) {
250+ let angle = ANGLE[mode as usize];
251+ let inv_angle = INV_ANGLE[mode as usize];
252+ // ref[] is indexed from -nTbS to 2 * nTbS; store it shifted by 32.
253+ const BIAS: usize = 32;
254+ let mut reference = [0i32; 32 + 65];
255+ let (main, side): (&[u8; 64], &[u8; 64]) = if mode >= 18 {
256+ (&refs.top, &refs.left)
257+ } else {
258+ (&refs.left, &refs.top)
259+ };
260+ reference[BIAS] = i32::from(refs.corner);
261+ for x in 1..=n {
262+ reference[BIAS + x] = i32::from(main[x - 1]);
263+ }
264+ if angle < 0 {
265+ let last = (n as i32 * angle) >> 5;
266+ if last < -1 {
267+ for x in last..=-1 {
268+ let idx = ((x * inv_angle + 128) >> 8) - 1;
269+ reference[(BIAS as i32 + x) as usize] = if idx < 0 {
270+ i32::from(refs.corner)
271+ } else {
272+ i32::from(side[idx as usize])
273+ };
274+ }
275+ }
276+ } else {
277+ for x in n + 1..=2 * n {
278+ reference[BIAS + x] = i32::from(main[x - 1]);
279+ }
280+ }
281+ for y in 0..n {
282+ // The "row" index along the prediction direction: y for the vertical
283+ // modes, x for the horizontal ones, which is the whole difference
284+ // between the two halves of 8.4.4.2.6.
285+ for x in 0..n {
286+ let (along, across) = if mode >= 18 { (y, x) } else { (x, y) };
287+ let idx = ((along as i32 + 1) * angle) >> 5;
288+ let fact = ((along as i32 + 1) * angle) & 31;
289+ let base = (BIAS as i32 + across as i32 + idx + 1) as usize;
290+ let value = if fact != 0 {
291+ ((32 - fact) * reference[base] + fact * reference[base + 1] + 16) >> 5
292+ } else {
293+ reference[base]
294+ };
295+ out[y * n + x] = value as u8;
296+ }
297+ }
298+ // The vertical and horizontal modes carry a boundary filter on luma
299+ // blocks below 32x32 (8-60, 8-68).
300+ if is_luma && n < 32 {
301+ if mode == 26 {
302+ for y in 0..n {
303+ let value = i32::from(refs.top[0])
304+ + ((i32::from(refs.left[y]) - i32::from(refs.corner)) >> 1);
305+ out[y * n] = value.clamp(0, 255) as u8;
306+ }
307+ } else if mode == 10 {
308+ for x in 0..n {
309+ let value = i32::from(refs.left[0])
310+ + ((i32::from(refs.top[x]) - i32::from(refs.corner)) >> 1);
311+ out[x] = value.clamp(0, 255) as u8;
312+ }
313+ }
314+ }
315+}
316+
317+/// The three most probable modes (8.4.2 step 3) from the left and above
318+/// neighbours' modes; `None` means the neighbour is unavailable or not intra.
319+pub fn mpm_list(left: Option<u8>, above: Option<u8>) -> [u8; 3] {
320+ let cand_a = left.unwrap_or(1);
321+ let cand_b = above.unwrap_or(1);
322+ if cand_a == cand_b {
323+ if cand_a < 2 {
324+ [0, 1, 26]
325+ } else {
326+ [
327+ cand_a,
328+ 2 + ((u32::from(cand_a) + 29) % 32) as u8,
329+ 2 + ((u32::from(cand_a) - 2 + 1) % 32) as u8,
330+ ]
331+ }
332+ } else if cand_a != 0 && cand_b != 0 {
333+ [cand_a, cand_b, 0]
334+ } else if cand_a != 1 && cand_b != 1 {
335+ [cand_a, cand_b, 1]
336+ } else {
337+ [cand_a, cand_b, 26]
338+ }
339+}
340+
341+/// `scanIdx` for a residual block (7.4.9.11): mode-dependent for the small
342+/// luma and chroma blocks, diagonal everywhere else.
343+///
344+/// 0 = up-right diagonal, 1 = horizontal, 2 = vertical.
345+pub fn scan_index(mode: u8, log2_size: u32, is_luma: bool) -> usize {
346+ let mode_dependent = if is_luma {
347+ log2_size == 2 || log2_size == 3
348+ } else {
349+ log2_size == 2
350+ };
351+ if !mode_dependent {
352+ return 0;
353+ }
354+ if (6..=14).contains(&mode) {
355+ 2
356+ } else if (22..=30).contains(&mode) {
357+ 1
358+ } else {
359+ 0
360+ }
361+}
362+
363+#[cfg(test)]
364+mod tests {
365+ use super::*;
366+
367+ fn full_refs(value: u8, n: usize) -> (Refs, Availability) {
368+ let refs = Refs {
369+ corner: value,
370+ top: [value; 64],
371+ left: [value; 64],
372+ };
373+ let mask = if 2 * n >= 64 {
374+ u64::MAX
375+ } else {
376+ (1u64 << (2 * n)) - 1
377+ };
378+ (
379+ refs,
380+ Availability {
381+ corner: true,
382+ top: mask,
383+ left: mask,
384+ },
385+ )
386+ }
387+
388+ #[test]
389+ fn every_mode_predicts_a_flat_block_flat() {
390+ // With every neighbour equal, all 35 modes must return that value —
391+ // including the boundary filters, which are differences of equals.
392+ for &n in &[4usize, 8, 16, 32] {
393+ let (refs, _) = full_refs(96, n);
394+ let mut out = vec![0u8; n * n];
395+ for mode in 0..35u8 {
396+ predict(&refs, mode, n, true, true, &mut out);
397+ assert!(
398+ out.iter().all(|&v| v == 96),
399+ "mode {mode} n {n}: {:?}",
400+ &out[..8]
401+ );
402+ }
403+ }
404+ }
405+
406+ #[test]
407+ fn substitution_fills_from_the_nearest_real_sample() {
408+ let n = 4;
409+ let mut refs = Refs {
410+ corner: 0,
411+ top: [0; 64],
412+ left: [0; 64],
413+ };
414+ refs.left[5] = 70;
415+ let avail = Availability {
416+ corner: false,
417+ top: 0,
418+ left: 1 << 5,
419+ };
420+ substitute(&mut refs, &avail, n, 8);
421+ // Everything takes 70: below it by the bottom-left rule, above it by
422+ // the walk up, then the corner and the whole top row.
423+ assert!(refs.left[..8].iter().all(|&v| v == 70));
424+ assert!(refs.top[..8].iter().all(|&v| v == 70));
425+ assert_eq!(refs.corner, 70);
426+
427+ // Nothing available at all: mid-grey.
428+ let mut refs = Refs::default();
429+ substitute(&mut refs, &Availability::default(), n, 8);
430+ assert_eq!(refs.corner, 128);
431+ assert!(refs.top[..8].iter().all(|&v| v == 128));
432+ }
433+
434+ #[test]
435+ fn vertical_and_horizontal_modes_copy_their_edge() {
436+ let n = 8;
437+ let mut refs = Refs::default();
438+ for i in 0..64 {
439+ refs.top[i] = (10 + i) as u8;
440+ refs.left[i] = (200 - i) as u8;
441+ }
442+ refs.corner = 100;
443+ let mut out = vec![0u8; n * n];
444+ // Mode 26 on chroma has no boundary filter: every row is the top row.
445+ predict(&refs, 26, n, false, false, &mut out);
446+ for y in 0..n {
447+ for x in 0..n {
448+ assert_eq!(out[y * n + x], refs.top[x], "mode 26 at {x},{y}");
449+ }
450+ }
451+ // Mode 10 likewise copies the left column across.
452+ predict(&refs, 10, n, false, false, &mut out);
453+ for y in 0..n {
454+ for x in 0..n {
455+ assert_eq!(out[y * n + x], refs.left[y], "mode 10 at {x},{y}");
456+ }
457+ }
458+ }
459+
460+ #[test]
461+ fn diagonal_mode_2_walks_the_left_column() {
462+ // Mode 2 is the 45-degree "bottom-left" direction: angle 32 means one
463+ // whole sample of shift per row along the left reference.
464+ let n = 4;
465+ let mut refs = Refs::default();
466+ for i in 0..64 {
467+ refs.left[i] = i as u8;
468+ }
469+ let mut out = vec![0u8; n * n];
470+ predict(&refs, 2, n, false, false, &mut out);
471+ for y in 0..n {
472+ for x in 0..n {
473+ assert_eq!(out[y * n + x], (y + x + 1) as u8, "at {x},{y}");
474+ }
475+ }
476+ }
477+
478+ #[test]
479+ fn mpm_list_follows_the_spec_cases() {
480+ assert_eq!(mpm_list(None, None), [0, 1, 26]);
481+ assert_eq!(mpm_list(Some(0), Some(0)), [0, 1, 26]);
482+ assert_eq!(mpm_list(Some(10), Some(10)), [10, 9, 11]);
483+ assert_eq!(mpm_list(Some(2), Some(2)), [2, 33, 3]);
484+ assert_eq!(mpm_list(Some(10), Some(26)), [10, 26, 0]);
485+ assert_eq!(mpm_list(Some(0), Some(26)), [0, 26, 1]);
486+ assert_eq!(mpm_list(Some(0), Some(1)), [0, 1, 26]);
487+ }
488+
489+ #[test]
490+ fn scan_index_is_mode_dependent_only_for_small_blocks() {
491+ assert_eq!(scan_index(10, 2, true), 2);
492+ assert_eq!(scan_index(26, 3, true), 1);
493+ assert_eq!(scan_index(26, 4, true), 0);
494+ assert_eq!(scan_index(10, 2, false), 2);
495+ assert_eq!(scan_index(10, 3, false), 0);
496+ assert_eq!(scan_index(0, 2, true), 0);
497+ }
498+}
crates/ec-h265/src/lib.rsmodified+2 -0
@@ -3,5 +3,7 @@
3 #![warn(missing_docs)]3 #![warn(missing_docs)]
4 4
5 pub mod cabac;5 pub mod cabac;
6+pub mod ctu;
7+pub mod intra;
6 pub mod residual;8 pub mod residual;
7 pub mod transform;9 pub mod transform;