//! Coding tree unit encoding: the quadtree, the mode decision, the transform //! unit and the reconstruction (7.3.8.4 - 7.3.8.10). //! //! # The cost model //! //! Every decision minimises `J = SSD + lambda * bits`, where `SSD` is the sum of //! squared differences between source and *reconstructed* samples and `bits` is //! what the CABAC coder actually spends — measured by encoding the candidate //! into the real coder and rolling it back, not estimated from a table. //! `lambda = 0.57 * 2^((QP - 12) / 3)` is the usual intra Lagrangian; the 35-mode //! pre-screen uses `sqrt(lambda)` against a Hadamard SATD, because SATD //! estimates rate and distortion together where SSD estimates only distortion. //! //! # The shape of the tree //! //! Coding units are 32, 16 or 8 luma samples square, one transform unit per //! coding unit, `PART_2Nx2N` only, chroma always in derived mode (`DM`). A 64x64 //! coding tree block therefore always writes one `split_cu_flag` of 1 and //! decides freely below it. What that gives up is named rather than hidden: //! `PART_NxN` with 4x4 luma transforms would hold fine detail at low QP, and a //! 64x64 coding unit would save a few bits on flat sky. Both cost search time, //! which this encoder spends on the wavefront that makes one `encode` call use //! every core instead. use crate::cabac::{CabacEncoder, CabacState, Contexts, ctx}; use crate::encoder::TransformSkip; use crate::intra::{self, Availability, Refs}; use crate::residual::{self, encode_residual}; use crate::transform::{ chroma_qp_bd, dequantize_bd, forward_transform, forward_transform_skip, inverse_transform_bd, inverse_transform_skip_bd, quant_qp, quantize, quantize_offset, scale_forward_bd, uses_dst, }; use std::sync::atomic::{AtomicU8, AtomicU16, Ordering}; #[cfg(target_arch = "x86_64")] use archmage::{SimdToken, X64V1Token, arcane}; /// A picture sample as the encoder stores it: `u16` at every bit depth, the /// values 0..=255 for 8-bit pictures. pub type Pel = u16; /// The rounding the rate-distortion level search starts from, as a divisor of /// the quantiser step: 2 is round-to-nearest, against the 3 the plain path /// uses. A search that only takes levels down measures the rounding it was /// handed, so it gets the wider one. Swept on 1080p film at the settled /// lambda: 1/2 +0.360 dB BD-PSNR against x265, 1/3 +0.315, 1/4 +0.118. const RDOQ_DEAD_ZONE: i64 = 2; /// The same rounding for the chroma path, swept on its own because the sparser /// chroma of an intra picture answered differently in ec-h264. /// /// Here it does not: coarser chroma rounding reads better and better on luma /// BD-PSNR (1/2 +0.360, 1/6 +0.525, 1/12 +0.568, 1/24 +0.585 dB) while the /// all-plane figure falls the whole way (+0.276, +0.231, +0.169, +0.128). That /// arm is chroma being starved to buy luma bits, which only a luma-only metric /// calls a gain, so chroma keeps luma's rounding. const RDOQ_DEAD_ZONE_C: i64 = 2; /// `log2` of the smallest coding block this encoder makes: 8x8. pub const MIN_CB_LOG2: u32 = 3; /// Rate-distortion lambda for an intra picture at `qp`. pub fn lambda_for(qp: i32) -> f64 { 0.57 * 2f64.powf((qp - 12) as f64 / 3.0) } /// The samples of one CTB row that the row below may predict from: its bottom /// line, plus the coding depths along it. /// /// This is the *entire* dependency between two wavefront rows. Intra prediction /// reads one row above the block it predicts, and the only other thing a row /// below asks about the row above is `CtDepth` for one context — so a worker /// publishes a line per CTB and nothing else. pub struct RowBoundary { /// Bottom luma line, one entry per column. pub y: Vec, /// Bottom Cb line. pub cb: Vec, /// Bottom Cr line. pub cr: Vec, /// `CtDepth` along the bottom, one entry per four columns. pub depth: Vec, } impl RowBoundary { /// Storage for a picture `width` luma samples wide. pub fn new(width: usize) -> RowBoundary { let make = |n: usize| (0..n).map(|_| AtomicU16::new(0)).collect(); let make8 = |n: usize| (0..n).map(|_| AtomicU8::new(0)).collect(); RowBoundary { y: make(width), cb: make(width / 2), cr: make(width / 2), depth: make8(width / 4), } } } /// Source planes for one picture, already padded to the coded size. pub struct SourcePlanes<'a> { /// Luma plane, `width * height`. pub y: &'a [Pel], /// Cb plane, `width / 2 * height / 2`. pub cb: &'a [Pel], /// Cr plane. pub cr: &'a [Pel], } /// The mutable state one wavefront worker owns while coding one CTB row. pub struct RowState<'a> { /// Reconstructed luma for this row band. pub rec_y: &'a mut [Pel], /// Reconstructed Cb for this row band. pub rec_cb: &'a mut [Pel], /// Reconstructed Cr for this row band. pub rec_cr: &'a mut [Pel], /// The boundary this row publishes for the row below. pub publish: &'a RowBoundary, /// The boundary the row above published; absent for the first row. pub above: Option<&'a RowBoundary>, } /// Scratch buffers, allocated once per row rather than per block. struct Scratch { pred: Vec, residual: Vec, coeffs: Vec, scaled: Vec, recon: Vec, best_recon: Vec, levels: Vec, best_levels: Vec, /// Smoothed copy of the current luma reference samples (see `luma_refs`). filt: Option>, source: Vec, luma_levels: Vec, cb_levels: Vec, cr_levels: Vec, } impl Scratch { fn new() -> Scratch { Scratch { pred: vec![0; 32 * 32], residual: vec![0; 32 * 32], coeffs: vec![0; 32 * 32], scaled: vec![0; 32 * 32], recon: vec![0; 32 * 32], best_recon: vec![0; 32 * 32], levels: vec![0; 32 * 32], best_levels: vec![0; 32 * 32], filt: None, source: vec![0; 32 * 32], luma_levels: vec![0; 32 * 32], cb_levels: vec![0; 16 * 16], cr_levels: vec![0; 16 * 16], } } } /// Encoder for one CTB row. pub struct CtuEncoder<'a> { src: SourcePlanes<'a>, row: RowState<'a>, width: usize, height: usize, /// Luma and chroma bit depth (8 or 10). bit_depth: u32, /// The largest sample value, `(1 << bit_depth) - 1`. max: i32, /// The mid-grey sample a row with no row above predicts from. half: Pel, ctb_size: usize, band_y0: usize, band_rows: usize, qp: i32, qp_c: i32, lambda: f64, lambda_satd: f64, strong_smoothing: bool, /// How many of the 35 modes get a full rate-distortion trial. candidates: usize, /// Whether an 8x8 coding unit may split into four 4x4 intra partitions. intra_nxn: bool, sign_hiding: bool, /// Whether the levels get a rate-distortion search after quantisation. rdoq: bool, transform_skip: bool, /// Whether every 4x4 luma block decides transform skip by rate-distortion /// instead of taking `transform_skip` unconditionally. ts_rd: bool, /// The skip decision for the 4x4 luma block currently in the scratch. ts_luma: bool, rqt: bool, /// The counting CABAC engine that search prices its trials with. rdoq_enc: CabacEncoder, /// `log2` of the smallest coding unit the search will produce. min_cb_log2: u32, /// Intra mode per 4x4 block of the band; 255 = not coded yet. modes: Vec, /// Coding depth per 4x4 block of the band. depths: Vec, /// `log2` of the transform block covering each 4x4 block of the band, /// which is all the deblocking filter needs to find its edges. tu_log2: Vec, /// Which 4x4 blocks of the *current* CTB are reconstructed. coded: [bool; 256], ctu_x: usize, /// Whether the coding unit just coded spent no residual at all — the cue /// that splitting it further would only spend flags. last_cu_empty: bool, scratch: Scratch, } impl<'a> CtuEncoder<'a> { /// A worker for the CTB row whose first luma row is `band_y0`. #[allow(clippy::too_many_arguments)] pub fn new( src: SourcePlanes<'a>, row: RowState<'a>, width: usize, height: usize, ctb_size: usize, band_y0: usize, qp: i32, strong_smoothing: bool, candidates: usize, intra_nxn: bool, sign_hiding: bool, rdoq: bool, transform_skip: TransformSkip, rqt: bool, min_cb_log2: u32, bit_depth: u32, ) -> CtuEncoder<'a> { let band_rows = (height - band_y0).min(ctb_size); // qP is QpY + QpBdOffset (8.6.1). The quantiser, the dequantiser and the // lambda all work on qP; the QpY argument only feeds the CABAC contexts. let qp_bd = qp + 6 * (bit_depth as i32 - 8); CtuEncoder { src, row, width, height, bit_depth, max: (1 << bit_depth) - 1, half: 1 << (bit_depth - 1), ctb_size, band_y0, band_rows, qp: qp_bd, qp_c: chroma_qp_bd(qp, 0, bit_depth) + 6 * (bit_depth as i32 - 8), lambda: lambda_for(qp_bd), lambda_satd: lambda_for(qp_bd).sqrt(), strong_smoothing, candidates: candidates.clamp(1, 35), intra_nxn, sign_hiding, rdoq, transform_skip: transform_skip == TransformSkip::AlwaysFor4x4, ts_rd: transform_skip == TransformSkip::Rd, ts_luma: false, rqt, rdoq_enc: { let mut enc = CabacEncoder::counter(Contexts::new(qp.clamp(0, 51))); enc.set_estimating(true); enc }, min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5), modes: vec![255; (width / 4) * (ctb_size / 4)], depths: vec![0; (width / 4) * (ctb_size / 4)], tu_log2: vec![2; (width / 4) * (ctb_size / 4)], coded: [false; 256], ctu_x: 0, last_cu_empty: false, scratch: Scratch::new(), } } /// `log2` of the transform block covering each 4x4 unit of this row's /// band, in raster order across the whole picture width. pub fn tu_log2_band(&self) -> &[u8] { &self.tu_log2 } /// Code one coding tree unit at CTB column `ctu_x`. pub fn encode_ctu(&mut self, ctu_x: usize, enc: &mut CabacEncoder) { self.ctu_x = ctu_x; self.coded = [false; 256]; let log2_ctb = self.ctb_size.trailing_zeros(); self.code_quadtree(ctu_x * self.ctb_size, self.band_y0, log2_ctb, 0, enc); self.publish_boundary(ctu_x); } /// Copy this CTB's bottom line into the boundary the next row reads. fn publish_boundary(&self, ctu_x: usize) { let last = self.band_y0 + self.band_rows - 1; let x0 = ctu_x * self.ctb_size; let x1 = (x0 + self.ctb_size).min(self.width); for x in x0..x1 { self.row.publish.y[x].store(self.rec_y(x, last), Ordering::Relaxed); } let cy = (self.band_y0 + self.band_rows) / 2 - 1; for x in x0 / 2..x1 / 2 { self.row.publish.cb[x].store(self.rec_c(x, cy, 1), Ordering::Relaxed); self.row.publish.cr[x].store(self.rec_c(x, cy, 2), Ordering::Relaxed); } for x in x0 / 4..x1 / 4 { let depth = self.depths[((self.band_rows - 1) / 4) * (self.width / 4) + x]; self.row.publish.depth[x].store(depth, Ordering::Relaxed); } } fn rec_y(&self, x: usize, y: usize) -> Pel { if y < self.band_y0 { self.row .above .map_or(self.half, |above| above.y[x].load(Ordering::Relaxed)) } else { self.row.rec_y[(y - self.band_y0) * self.width + x] } } /// Reconstructed chroma sample, in chroma coordinates. fn rec_c(&self, x: usize, y: usize, plane: usize) -> Pel { let band_c0 = self.band_y0 / 2; if y < band_c0 { self.row.above.map_or(self.half, |above| { let line = if plane == 1 { &above.cb } else { &above.cr }; line[x].load(Ordering::Relaxed) }) } else { let data = if plane == 1 { &*self.row.rec_cb } else { &*self.row.rec_cr }; data[(y - band_c0) * (self.width / 2) + x] } } /// Availability of a luma position: inside the picture and already coded in /// raster CTB order, then z-scan order inside the current CTB. fn available(&self, x: isize, y: isize) -> bool { if x < 0 || y < 0 || x >= self.width as isize || y >= self.height as isize { return false; } let (x, y) = (x as usize, y as usize); if y < self.band_y0 { // Every CTB in a row above is coded. The wavefront guarantees the // ones a block can actually reach — at most one CTB to the right — // are also finished. debug_assert!(x < (self.ctu_x + 2) * self.ctb_size); return self.row.above.is_some(); } if y >= self.band_y0 + self.band_rows { return false; } let cx = x / self.ctb_size; match cx.cmp(&self.ctu_x) { std::cmp::Ordering::Less => true, std::cmp::Ordering::Greater => false, std::cmp::Ordering::Equal => { let bx = (x - self.ctu_x * self.ctb_size) / 4; let by = (y - self.band_y0) / 4; self.coded[by * 16 + bx] } } } fn mode_at(&self, x: usize, y: usize) -> u8 { self.modes[((y - self.band_y0) / 4) * (self.width / 4) + x / 4] } fn depth_at(&self, x: usize, y: usize) -> u8 { if y < self.band_y0 { return self .row .above .map_or(0, |above| above.depth[x / 4].load(Ordering::Relaxed)); } self.depths[((y - self.band_y0) / 4) * (self.width / 4) + x / 4] } // ---- the quadtree ---------------------------------------------------- fn code_quadtree( &mut self, x: usize, y: usize, log2: u32, depth: u8, enc: &mut CabacEncoder, ) -> f64 { let size = 1usize << log2; let half = size / 2; if x + size > self.width || y + size > self.height { // split_cu_flag is inferred to 1 and only the children inside the // picture are coded (7.3.8.4). let mut cost = 0.0; for (dx, dy) in [(0, 0), (half, 0), (0, half), (half, half)] { if x + dx < self.width && y + dy < self.height { cost += self.code_quadtree(x + dx, y + dy, log2 - 1, depth + 1, enc); } } return cost; } if log2 == MIN_CB_LOG2 { return self.code_cu(x, y, log2, depth, enc); } let split_ctx = ctx::SPLIT_CU + usize::from( self.available(x as isize - 1, y as isize) && self.depth_at(x - 1, y) > depth, ) + usize::from( self.available(x as isize, y as isize - 1) && self.depth_at(x, y - 1) > depth, ); if log2 <= self.min_cb_log2 { // The search stops here, but the sequence still allows a split, so // the flag is written: skipping it because *this* encoder will not // split is exactly the kind of "the decoder knows what I meant" // assumption that desynchronises a bitstream. let before = enc.bit_count(); enc.encode_bin(split_ctx, 0); return self.lambda * (enc.bit_count() - before) as f64 + self.code_cu(x, y, log2, depth, enc); } let start = enc.snapshot(); // The z-scan availability map has to go back with everything else: the // leaf trial marks the whole region reconstructed, and a split trial run // against that map would predict from samples the *decoder* considers // unavailable and derive its contexts from them too. That is a // desynchronisation, not an inefficiency — it was worth a whole picture // of garbage before this line existed. let coded_before = self.coded; let before = enc.bit_count(); enc.encode_bin(split_ctx, 0); let flag_bits = enc.bit_count() - before; let leaf_cost = self.lambda * flag_bits as f64 + self.code_cu(x, y, log2, depth, enc); if self.last_cu_empty { // Every coefficient quantised to zero: the four sub-trees can only // add split flags and mode bits on top of the same prediction, so // the split is not searched. This is where most of the picture is. return leaf_cost; } let leaf_state = enc.snapshot_since(&start); let leaf_rec = self.save_region(x, y, size); let leaf_meta = self.save_meta(x, y, size); enc.restore(&start); self.coded = coded_before; let before = enc.bit_count(); enc.encode_bin(split_ctx, 1); let mut split_cost = self.lambda * (enc.bit_count() - before) as f64; for (dx, dy) in [(0, 0), (half, 0), (0, half), (half, half)] { split_cost += self.code_quadtree(x + dx, y + dy, log2 - 1, depth + 1, enc); } if leaf_cost <= split_cost { enc.restore(&leaf_state); self.load_region(x, y, size, &leaf_rec); self.load_meta(x, y, size, &leaf_meta); leaf_cost } else { split_cost } } /// Reconstructed samples of a square luma region and its chroma, packed. fn save_region(&self, x: usize, y: usize, size: usize) -> Vec { let mut out = Vec::with_capacity(size * size * 3 / 2); for yy in y..y + size { for xx in x..x + size { out.push(self.rec_y(xx, yy)); } } for plane in [1usize, 2] { for yy in y / 2..y / 2 + size / 2 { for xx in x / 2..x / 2 + size / 2 { out.push(self.rec_c(xx, yy, plane)); } } } out } fn load_region(&mut self, x: usize, y: usize, size: usize, data: &[Pel]) { let mut i = 0; for yy in y..y + size { for xx in x..x + size { self.write_rec_y(xx, yy, data[i]); i += 1; } } for plane in [1usize, 2] { for yy in y / 2..y / 2 + size / 2 { for xx in x / 2..x / 2 + size / 2 { self.write_rec_c(xx, yy, plane, data[i]); i += 1; } } } } fn save_meta(&self, x: usize, y: usize, size: usize) -> Vec { let stride = self.width / 4; let mut out = Vec::with_capacity(3 * (size / 4) * (size / 4)); for by in (y..y + size).step_by(4) { for bx in (x..x + size).step_by(4) { let idx = ((by - self.band_y0) / 4) * stride + bx / 4; out.push(self.modes[idx]); out.push(self.depths[idx]); out.push(self.tu_log2[idx]); } } out } fn load_meta(&mut self, x: usize, y: usize, size: usize, data: &[u8]) { let stride = self.width / 4; let mut i = 0; for by in (y..y + size).step_by(4) { for bx in (x..x + size).step_by(4) { let idx = ((by - self.band_y0) / 4) * stride + bx / 4; self.modes[idx] = data[i]; self.depths[idx] = data[i + 1]; self.tu_log2[idx] = data[i + 2]; i += 3; } } } fn write_rec_y(&mut self, x: usize, y: usize, value: Pel) { let stride = self.width; self.row.rec_y[(y - self.band_y0) * stride + x] = value; } fn write_rec_c(&mut self, x: usize, y: usize, plane: usize, value: Pel) { let stride = self.width / 2; let band_c0 = self.band_y0 / 2; let data = if plane == 1 { &mut *self.row.rec_cb } else { &mut *self.row.rec_cr }; data[(y - band_c0) * stride + x] = value; } // ---- one coding unit ------------------------------------------------- /// Code one coding unit, returning `SSD + lambda * bits` for it. The split /// flag above it is the caller's to count. At the smallest coding unit the /// partition mode is a rate-distortion decision between one 8x8 block and /// four 4x4 ones; everywhere else there is only PART_2Nx2N. fn code_cu(&mut self, x: usize, y: usize, log2: u32, depth: u8, enc: &mut CabacEncoder) -> f64 { if log2 != MIN_CB_LOG2 || !self.intra_nxn { return self.code_cu_2nx2n(x, y, log2, depth, enc); } let start = enc.snapshot(); let coded_before = self.coded; let size = 1usize << log2; let square_cost = self.code_cu_2nx2n(x, y, log2, depth, enc); let square_state = enc.snapshot_since(&start); let square_rec = self.save_region(x, y, size); let square_meta = self.save_meta(x, y, size); let square_empty = self.last_cu_empty; enc.restore(&start); self.coded = coded_before; let nxn_cost = self.code_cu_nxn(x, y, depth, enc); if square_cost <= nxn_cost { enc.restore(&square_state); self.load_region(x, y, size, &square_rec); self.load_meta(x, y, size, &square_meta); self.last_cu_empty = square_empty; square_cost } else { nxn_cost } } /// The four-4x4-partition form of the smallest coding unit: four luma /// prediction units, each its own transform block, over one 4x4 chroma /// block that keeps the coding unit's single chroma mode. fn code_cu_nxn(&mut self, x: usize, y: usize, depth: u8, enc: &mut CabacEncoder) -> f64 { let before = enc.bit_count(); // The mode search reconstructs each partition as it goes, because the // next one predicts from it; the syntax is written afterwards in the // order the decoder reads it. let offsets = [(0usize, 0usize), (4, 0), (0, 4), (4, 4)]; let mut modes = [0u8; 4]; let mut mpms = [[0u8; 3]; 4]; let mut levels = [[0i32; 16]; 4]; let mut cbfs = [false; 4]; let mut tskip = [self.transform_skip; 4]; for (part, &(dx, dy)) in offsets.iter().enumerate() { let (px, py) = (x + dx, y + dy); let mpm = self.mpm_at(px, py); let mode = self.choose_luma_mode(px, py, 4, 2, &mpm, enc); levels[part].copy_from_slice(&self.scratch.luma_levels[..16]); if self.ts_rd { tskip[part] = self.ts_luma; } cbfs[part] = levels[part].iter().any(|&v| v != 0); modes[part] = mode; mpms[part] = mpm; self.mark_coded(px, py, 4, mode, depth); self.mark_tu(px, py, 4); } // part_mode: PART_NxN is the single bin 0. enc.encode_bin(ctx::PART_MODE, 0); for part in 0..4 { self.write_mode_prev_flag(enc, modes[part], &mpms[part]); } for part in 0..4 { self.write_mode_remainder(enc, modes[part], &mpms[part]); } // The chroma mode belongs to the coding unit and derives from the // first partition's luma mode (8.4.3). let chroma_mode = modes[0]; self.write_chroma_mode_syntax(enc); let cb_cbf = self .code_chroma(x, y, 8, chroma_mode, 1, self.transform_skip) .1; let cr_cbf = self .code_chroma(x, y, 8, chroma_mode, 2, self.transform_skip) .1; // transform_tree: the split at depth 0 is inferred from the partition // mode, so only the chroma flags are written there; every luma flag and // residual belongs to a 4x4 child at depth 1, and the chroma residual // rides along with the last of them (7.3.8.8, 7.3.8.10). enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf)); enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf)); for part in 0..4 { enc.encode_bin(ctx::CBF_LUMA, u32::from(cbfs[part])); if cbfs[part] { let scan = intra::scan_index(modes[part], 2, true); encode_residual( enc, &levels[part], 2, 0, scan, self.sign_hiding, self.ts_flag(tskip[part]), ); } if part == 3 { let chroma_scan = intra::scan_index(chroma_mode, 2, false); if cb_cbf { let l = std::mem::take(&mut self.scratch.cb_levels); encode_residual( enc, &l[..16], 2, 1, chroma_scan, self.sign_hiding, self.ts_flag(self.transform_skip), ); self.scratch.cb_levels = l; } if cr_cbf { let l = std::mem::take(&mut self.scratch.cr_levels); encode_residual( enc, &l[..16], 2, 2, chroma_scan, self.sign_hiding, self.ts_flag(self.transform_skip), ); self.scratch.cr_levels = l; } } } self.last_cu_empty = !(cbfs.iter().any(|&c| c) || cb_cbf || cr_cbf); let bits = enc.bit_count() - before; self.region_ssd(x, y, 8) + self.lambda * bits as f64 } /// Code one 64x64 coding unit. /// /// HEVC's largest transform block is 32x32, so the transform tree of a /// 64x64 coding unit is split without a `split_transform_flag` -- the /// decoder infers the split from `log2TrafoSize > MaxTbLog2SizeY` (7.4.9.8) /// -- and intra prediction runs per transform block, four 32x32 ones in /// z-order, each predicting from the reconstruction of the ones before it. /// The coding unit carries a single luma mode and a single chroma mode, so /// what it saves over four 32x32 coding units is three split flags and /// three mode signallings; what it gives up is three quarters of the /// freedom to pick a direction. /// /// The mode search runs on the first quadrant: that is the only one whose /// neighbours are settled before a mode is chosen, and it is what the /// reference encoder does for the same reason. fn code_cu_64(&mut self, x: usize, y: usize, depth: u8, enc: &mut CabacEncoder) -> f64 { const N: usize = 64; const HALF: usize = 32; const LOG2: u32 = 6; let chroma_tskip = self.transform_skip; let before = enc.bit_count(); let mpm = self.mpm_at(x, y); // Reconstructs the first quadrant under the mode it picks, leaving its // levels in the luma scratch. let mode = self.choose_luma_mode(x, y, HALF, LOG2 - 1, &mpm, enc); self.write_mode_syntax(enc, mode, &mpm); let chroma_mode = mode; self.write_chroma_mode_syntax(enc); let mut child_levels = [[0i32; 1024]; 4]; let mut child_tskip = [self.transform_skip; 4]; let mut child_cbf = [false; 4]; let mut child_cb = [[0i32; 256]; 4]; let mut child_cr = [[0i32; 256]; 4]; let mut child_cb_cbf = [false; 4]; let mut child_cr_cbf = [false; 4]; let offsets = [(0usize, 0usize), (HALF, 0), (0, HALF), (HALF, HALF)]; let q = HALF * HALF / 4; for (part, &(dx, dy)) in offsets.iter().enumerate() { let (cx, cy) = (x + dx, y + dy); if part == 0 { // Already coded by the mode search. child_levels[0][..HALF * HALF] .copy_from_slice(&self.scratch.luma_levels[..HALF * HALF]); child_cbf[0] = child_levels[0][..HALF * HALF].iter().any(|&v| v != 0); } else { let refs = self.luma_refs(cx, cy, HALF); let mut source = std::mem::take(&mut self.scratch.source); for row in 0..HALF { source[row * HALF..row * HALF + HALF].copy_from_slice( &self.src.y [(cy + row) * self.width + cx..(cy + row) * self.width + cx + HALF], ); } let (_, cbf) = self.transform_luma(HALF, mode, &source, &refs, true); if self.ts_rd { child_tskip[part] = self.ts_luma; } self.scratch.source = source; child_levels[part][..HALF * HALF] .copy_from_slice(&self.scratch.levels[..HALF * HALF]); child_cbf[part] = cbf; for row in 0..HALF { for col in 0..HALF { self.write_rec_y(cx + col, cy + row, self.scratch.recon[row * HALF + col]); } } } // The next quadrant predicts from this one, so its samples have to // read as available now: the decoder walks the tree in z-order too. self.mark_coded(cx, cy, HALF, mode, depth); self.mark_tu(cx, cy, HALF); let (_, cbf) = self.code_chroma(cx, cy, HALF, chroma_mode, 1, chroma_tskip); child_cb_cbf[part] = cbf; child_cb[part][..q].copy_from_slice(&self.scratch.cb_levels[..q]); let (_, cbf) = self.code_chroma(cx, cy, HALF, chroma_mode, 2, chroma_tskip); child_cr_cbf[part] = cbf; child_cr[part][..q].copy_from_slice(&self.scratch.cr_levels[..q]); } // The parent's flag is the OR of the children's: a clear one at depth 0 // tells the decoder to infer every child's as clear. let cb_cbf = child_cb_cbf.iter().any(|&c| c); let cr_cbf = child_cr_cbf.iter().any(|&c| c); self.write_split_tu( enc, N, LOG2, mode, chroma_mode, chroma_tskip, true, cb_cbf, cr_cbf, &child_cbf, &child_levels, &child_tskip, &child_cb_cbf, &child_cr_cbf, &child_cb, &child_cr, &[], &[], ); self.last_cu_empty = !(child_cbf.iter().any(|&c| c) || cb_cbf || cr_cbf); let bits = enc.bit_count() - before; self.region_ssd(x, y, N) + self.lambda * bits as f64 } fn code_cu_2nx2n( &mut self, x: usize, y: usize, log2: u32, depth: u8, enc: &mut CabacEncoder, ) -> f64 { if log2 > 5 { return self.code_cu_64(x, y, depth, enc); } let n = 1usize << log2; // Transform skip is a per-block flag the decoder reads for every 4x4 // residual once the picture parameter set enables it, so the decision // has to travel by the block's own size, not the coding unit's: a // transform tree splits chroma down to 4x4 from a 16x16 unit too. // `code_chroma` and `encode_residual` each apply it only at 4x4. let chroma_tskip = self.transform_skip; let before = enc.bit_count(); if log2 == MIN_CB_LOG2 { // part_mode: PART_2Nx2N is the single bin 1. enc.encode_bin(ctx::PART_MODE, 1); } let mpm = self.mpm_at(x, y); let mode = self.choose_luma_mode(x, y, n, log2, &mpm, enc); self.write_mode_syntax(enc, mode, &mpm); let chroma_mode = mode; self.write_chroma_mode_syntax(enc); // Luma was reconstructed by the mode search; chroma is coded now. let luma_cbf = self.scratch.luma_levels[..n * n].iter().any(|&v| v != 0); let cb_cbf = self.code_chroma(x, y, n, chroma_mode, 1, chroma_tskip).1; let cr_cbf = self.code_chroma(x, y, n, chroma_mode, 2, chroma_tskip).1; if self.rqt && log2 > 2 && !luma_cbf && !cb_cbf && !cr_cbf { // Every plane already quantised to zero at this size: a // transform-tree split can only re-signal the same empty leaf as // four children, adding a split_transform_flag and their mode // bits on top of an SSD that is already zero. Same reasoning as // the CU-quadtree's `last_cu_empty` early out, one level down — // skip the four-child trial and its transform/CABAC-counting // work outright instead of running it to confirm nosplit wins. enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 0); self.write_single_tu( enc, n, log2, mode, chroma_mode, chroma_tskip, luma_cbf, cb_cbf, cr_cbf, ); self.mark_coded(x, y, n, mode, depth); self.mark_tu(x, y, n); self.last_cu_empty = true; let bits = enc.bit_count() - before; return self.region_ssd(x, y, n) + self.lambda * bits as f64; } if self.rqt && log2 > 2 { // A child transform tree signals its own chroma as long as its // chroma blocks are still 4x4 or larger; only the 8x8 luma tree, // whose children are 4x4, leaves chroma at the parent size and // codes it with the last child (7.3.8.8). let chroma_split = log2 > 3; let nosplit_rec = self.save_region(x, y, n); let parent_cb = self.scratch.cb_levels[..n * n / 4].to_vec(); let parent_cr = self.scratch.cr_levels[..n * n / 4].to_vec(); let start = enc.snapshot(); enc.set_counting(true); let nb = enc.bit_count(); enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 0); self.write_single_tu( enc, n, log2, mode, chroma_mode, chroma_tskip, luma_cbf, cb_cbf, cr_cbf, ); let nosplit_bits = enc.bit_count() - nb; let nosplit_ssd = self.region_ssd(x, y, n); enc.restore(&start); let half = n / 2; let offsets = [(0usize, 0usize), (half, 0), (0, half), (half, half)]; let mut child_levels = [[0i32; 1024]; 4]; let mut child_tskip = [self.transform_skip; 4]; let mut child_cbf = [false; 4]; let mut child_cb = [[0i32; 256]; 4]; let mut child_cr = [[0i32; 256]; 4]; let mut child_cb_cbf = [false; 4]; let mut child_cr_cbf = [false; 4]; for (part, &(dx, dy)) in offsets.iter().enumerate() { let (cx, cy) = (x + dx, y + dy); let refs = self.luma_refs(cx, cy, half); let mut source = std::mem::take(&mut self.scratch.source); for row in 0..half { source[row * half..row * half + half].copy_from_slice( &self.src.y [(cy + row) * self.width + cx..(cy + row) * self.width + cx + half], ); } let (_, cbf) = self.transform_luma(half, mode, &source, &refs, true); if self.ts_rd { child_tskip[part] = self.ts_luma; } child_levels[part][..half * half] .copy_from_slice(&self.scratch.levels[..half * half]); child_cbf[part] = cbf; for row in 0..half { for col in 0..half { self.write_rec_y(cx + col, cy + row, self.scratch.recon[row * half + col]); } } self.scratch.source = source; // The next child predicts from this one, so its samples have // to read as available now rather than when the whole coding // unit is marked: a transform tree is walked in the same // z-order by the decoder. self.mark_coded(cx, cy, half, mode, depth); self.mark_tu(cx, cy, half); if chroma_split { let q = half * half / 4; let (_, cbf) = self.code_chroma(cx, cy, half, chroma_mode, 1, chroma_tskip); child_cb_cbf[part] = cbf; child_cb[part][..q].copy_from_slice(&self.scratch.cb_levels[..q]); let (_, cbf) = self.code_chroma(cx, cy, half, chroma_mode, 2, chroma_tskip); child_cr_cbf[part] = cbf; child_cr[part][..q].copy_from_slice(&self.scratch.cr_levels[..q]); } } // The parent's flag is the OR of the children's: a clear one at // depth 0 tells the decoder to infer every child's as clear. let split_cb_cbf = if chroma_split { child_cb_cbf.iter().any(|&c| c) } else { cb_cbf }; let split_cr_cbf = if chroma_split { child_cr_cbf.iter().any(|&c| c) } else { cr_cbf }; let sb = enc.bit_count(); enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 1); self.write_split_tu( enc, n, log2, mode, chroma_mode, chroma_tskip, chroma_split, split_cb_cbf, split_cr_cbf, &child_cbf, &child_levels, &child_tskip, &child_cb_cbf, &child_cr_cbf, &child_cb, &child_cr, &parent_cb, &parent_cr, ); let split_bits = enc.bit_count() - sb; let split_rec = self.save_region(x, y, n); let split_ssd = self.region_ssd(x, y, n); enc.set_counting(false); enc.restore(&start); let nosplit_cost = nosplit_ssd + self.lambda * nosplit_bits as f64; let split_cost = split_ssd + self.lambda * split_bits as f64; if nosplit_cost <= split_cost { self.load_region(x, y, n, &nosplit_rec); // The children coded over the shared chroma scratch. self.scratch.cb_levels[..n * n / 4].copy_from_slice(&parent_cb); self.scratch.cr_levels[..n * n / 4].copy_from_slice(&parent_cr); enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 0); self.write_single_tu( enc, n, log2, mode, chroma_mode, chroma_tskip, luma_cbf, cb_cbf, cr_cbf, ); // The split trial recorded four child transform blocks; this // unit keeps one, and the deblocking filter reads the map. self.mark_tu(x, y, n); self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf); } else { self.load_region(x, y, n, &split_rec); enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 1); self.write_split_tu( enc, n, log2, mode, chroma_mode, chroma_tskip, chroma_split, split_cb_cbf, split_cr_cbf, &child_cbf, &child_levels, &child_tskip, &child_cb_cbf, &child_cr_cbf, &child_cb, &child_cr, &parent_cb, &parent_cr, ); self.last_cu_empty = !(child_cbf.iter().any(|&c| c) || split_cb_cbf || split_cr_cbf); } self.mark_coded(x, y, n, mode, depth); let bits = enc.bit_count() - before; return self.region_ssd(x, y, n) + self.lambda * bits as f64; } // No-RQT: single TU, no split_transform_flag written (inferred 0). self.write_single_tu( enc, n, log2, mode, chroma_mode, chroma_tskip, luma_cbf, cb_cbf, cr_cbf, ); self.mark_coded(x, y, n, mode, depth); self.mark_tu(x, y, n); self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf); let bits = enc.bit_count() - before; self.region_ssd(x, y, n) + self.lambda * bits as f64 } /// Write cbf flags + residual for one unsplit transform tree (no /// `split_transform_flag`). #[allow(clippy::too_many_arguments)] fn write_single_tu( &mut self, enc: &mut CabacEncoder, n: usize, log2: u32, mode: u8, chroma_mode: u8, chroma_tskip: bool, luma_cbf: bool, cb_cbf: bool, cr_cbf: bool, ) { enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf)); enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf)); enc.encode_bin(ctx::CBF_LUMA + 1, u32::from(luma_cbf)); if luma_cbf { let scan = intra::scan_index(mode, log2, true); let levels = std::mem::take(&mut self.scratch.luma_levels); encode_residual( enc, &levels[..n * n], log2, 0, scan, self.sign_hiding, self.ts_flag(self.transform_skip), ); self.scratch.luma_levels = levels; } let chroma_scan = intra::scan_index(chroma_mode, log2 - 1, false); if cb_cbf { let levels = std::mem::take(&mut self.scratch.cb_levels); encode_residual( enc, &levels[..n * n / 4], log2 - 1, 1, chroma_scan, self.sign_hiding, self.ts_flag(chroma_tskip), ); self.scratch.cb_levels = levels; } if cr_cbf { let levels = std::mem::take(&mut self.scratch.cr_levels); encode_residual( enc, &levels[..n * n / 4], log2 - 1, 2, chroma_scan, self.sign_hiding, self.ts_flag(chroma_tskip), ); self.scratch.cr_levels = levels; } } /// Write cbf flags + residual for a split transform tree: chroma cbf first, /// then four half-size luma children (CBF_LUMA ctx 0 for depth 1), chroma /// residual on the last child. /// Write the syntax of a split transform tree: the parent's chroma flags, /// then four half-size children. A child carries its own chroma when the /// chroma blocks stay 4x4 or larger, and reads the depth-one contexts for /// both flags; below that the parent's chroma rides on the last child. #[allow(clippy::too_many_arguments)] fn write_split_tu( &mut self, enc: &mut CabacEncoder, n: usize, log2: u32, mode: u8, chroma_mode: u8, chroma_tskip: bool, chroma_split: bool, cb_cbf: bool, cr_cbf: bool, child_cbf: &[bool; 4], child_levels: &[[i32; 1024]; 4], child_tskip: &[bool; 4], child_cb_cbf: &[bool; 4], child_cr_cbf: &[bool; 4], child_cb: &[[i32; 256]; 4], child_cr: &[[i32; 256]; 4], parent_cb: &[i32], parent_cr: &[i32], ) { let half = n / 2; enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf)); enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf)); let luma_scan = intra::scan_index(mode, log2 - 1, true); for part in 0..4usize { if chroma_split { if cb_cbf { enc.encode_bin(ctx::CBF_CHROMA + 1, u32::from(child_cb_cbf[part])); } if cr_cbf { enc.encode_bin(ctx::CBF_CHROMA + 1, u32::from(child_cr_cbf[part])); } } enc.encode_bin(ctx::CBF_LUMA, u32::from(child_cbf[part])); if child_cbf[part] { encode_residual( enc, &child_levels[part][..half * half], log2 - 1, 0, luma_scan, self.sign_hiding, self.ts_flag(child_tskip[part]), ); } if chroma_split { let (q, scan) = ( half * half / 4, intra::scan_index(chroma_mode, log2 - 2, false), ); if cb_cbf && child_cb_cbf[part] { encode_residual( enc, &child_cb[part][..q], log2 - 2, 1, scan, self.sign_hiding, self.ts_flag(chroma_tskip), ); } if cr_cbf && child_cr_cbf[part] { encode_residual( enc, &child_cr[part][..q], log2 - 2, 2, scan, self.sign_hiding, self.ts_flag(chroma_tskip), ); } } else if part == 3 { let scan = intra::scan_index(chroma_mode, log2 - 1, false); if cb_cbf { encode_residual( enc, &parent_cb[..n * n / 4], log2 - 1, 1, scan, self.sign_hiding, self.ts_flag(chroma_tskip), ); } if cr_cbf { encode_residual( enc, &parent_cr[..n * n / 4], log2 - 1, 2, scan, self.sign_hiding, self.ts_flag(chroma_tskip), ); } } } } fn write_mode_syntax(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) { self.write_mode_prev_flag(enc, mode, mpm); self.write_mode_remainder(enc, mode, mpm); } /// `prev_intra_luma_pred_flag`. An NxN coding unit writes all four of these /// before any of the remainders (7.3.8.5), which is why the two halves are /// separate. fn write_mode_prev_flag(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) { let is_mpm = mpm.contains(&mode); enc.encode_bin(ctx::PREV_INTRA_LUMA_PRED, u32::from(is_mpm)); } /// `mpm_idx` or `rem_intra_luma_pred_mode`, whichever the flag promised. fn write_mode_remainder(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) { match mpm.iter().position(|&m| m == mode) { Some(idx) => { // mpm_idx: truncated rice, cMax 2, all bypass. if idx == 0 { enc.encode_bypass(0); } else { enc.encode_bypass(1); enc.encode_bypass(u32::from(idx == 2)); } } None => { let mut sorted = *mpm; sorted.sort_unstable(); let mut rem = mode; // The inverse of the decoder's iterative reconstruction // (`for m in sorted (ascending): if mode >= m { mode += 1 }`) // has to walk descending and compare the *running* `rem`, // not the original `mode`: decrementing across one candidate // can drop `rem` at or below the next one down, which then // must also count. Comparing against the fixed `mode` missed // that second step whenever two MPM candidates sat on either // side of it. for &m in sorted.iter().rev() { if rem > m { rem -= 1; } } enc.encode_bypass_bits(u32::from(rem), 5); } } } fn mpm_at(&self, x: usize, y: usize) -> [u8; 3] { let left = if self.available(x as isize - 1, y as isize) { let m = self.mode_at(x - 1, y); if m == 255 { None } else { Some(m) } } else { None }; // A neighbour in the CTB row above counts as DC (8.4.2 step 2), which is // also what keeps the wavefront from needing a mode line. let above = if y > self.band_y0 && self.available(x as isize, y as isize - 1) { let m = self.mode_at(x, y - 1); if m == 255 { None } else { Some(m) } } else { None }; intra::mpm_list(left, above) } /// Record the transform block of side `n` at `(x, y)`, which is what the /// deblocking filter reads its edges off. Marked at transform-tree *leaves* /// only: a coding unit that split records four children, never itself. fn mark_tu(&mut self, x: usize, y: usize, n: usize) { let stride = self.width / 4; let log2 = n.trailing_zeros() as u8; for by in (y..y + n).step_by(4) { for bx in (x..x + n).step_by(4) { self.tu_log2[((by - self.band_y0) / 4) * stride + bx / 4] = log2; } } } fn mark_coded(&mut self, x: usize, y: usize, n: usize, mode: u8, depth: u8) { let stride = self.width / 4; for by in (y..y + n).step_by(4) { for bx in (x..x + n).step_by(4) { let idx = ((by - self.band_y0) / 4) * stride + bx / 4; self.modes[idx] = mode; self.depths[idx] = depth; let cx = (bx - self.ctu_x * self.ctb_size) / 4; let cy = (by - self.band_y0) / 4; self.coded[cy * 16 + cx] = true; } } } /// Sum of squared differences over a coding unit, all three planes. fn region_ssd(&self, x: usize, y: usize, n: usize) -> f64 { let mut ssd = 0i64; for yy in y..y + n { let src_row = &self.src.y[yy * self.width + x..yy * self.width + x + n]; for (offset, &sample) in src_row.iter().enumerate() { let d = i64::from(sample) - i64::from(self.rec_y(x + offset, yy)); ssd += d * d; } } let cw = self.width / 2; for plane in [1usize, 2] { let src = if plane == 1 { self.src.cb } else { self.src.cr }; for yy in y / 2..y / 2 + n / 2 { for xx in x / 2..x / 2 + n / 2 { let d = i64::from(src[yy * cw + xx]) - i64::from(self.rec_c(xx, yy, plane)); ssd += d * d; } } } ssd as f64 } // ---- luma mode decision ---------------------------------------------- /// Pick the luma mode, leaving its levels in `scratch.luma_levels` and its /// reconstruction written into the band. fn choose_luma_mode( &mut self, x: usize, y: usize, n: usize, log2: u32, mpm: &[u8; 3], enc: &mut CabacEncoder, ) -> u8 { let refs = self.luma_refs(x, y, n); let mut source = std::mem::take(&mut self.scratch.source); for row in 0..n { let sy = y + row; source[row * n..row * n + n] .copy_from_slice(&self.src.y[sy * self.width + x..sy * self.width + x + n]); } // Pre-screen: planar, DC and every second angle, then the two // neighbours of whichever angle won. Nineteen predictions instead of // thirty-five for the same winner in all but a rounding of cases — // the SATD surface over the angles is smooth by construction. let mut scored: Vec<(f64, u8)> = Vec::with_capacity(24); let score = |this: &mut Self, mode: u8, scored: &mut Vec<(f64, u8)>| { intra::predict_cached( &refs, &mut this.scratch.filt, mode, n, true, this.strong_smoothing, this.bit_depth, &mut this.scratch.pred, ); let satd = satd(&source, &this.scratch.pred[..n * n], n) as f64; let mode_bits = if mpm.contains(&mode) { 2.0 } else { 6.0 }; scored.push((satd + this.lambda_satd * mode_bits, mode)); }; for mode in [0u8, 1] { score(self, mode, &mut scored); } for mode in (2u8..=34).step_by(2) { score(self, mode, &mut scored); } let coarse_best = scored .iter() .filter(|(_, m)| *m >= 2) .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)) .map(|&(_, m)| m) .unwrap_or(26); for delta in [-1i16, 1] { let refined = coarse_best as i16 + delta; if (2..=34).contains(&refined) { score(self, refined as u8, &mut scored); } } scored.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); // Full rate-distortion on the survivors, plus the most probable modes, // which are cheap to code and often win despite a worse SATD. let mut candidates: Vec = scored.iter().take(self.candidates).map(|s| s.1).collect(); // The first most probable mode joins the trial whatever its SATD: it is // two bins where a non-MPM mode is six, and that gap decides plenty of // flat blocks. if !candidates.contains(&mpm[0]) { candidates.push(mpm[0]); } let start = enc.snapshot(); enc.set_counting(true); let mut best = (f64::MAX, 0u8); let mut best_levels = std::mem::take(&mut self.scratch.best_levels); for &mode in &candidates { let bits_before = enc.bit_count(); self.write_mode_syntax(enc, mode, mpm); // Mode ranking runs the cheap (dead-zone-only) quantiser: RDOQ's // per-coefficient CABAC-costed search is the hottest bucket in the // encoder (measured: ~73% of encode wall time) and re-running it // for every candidate mode only to throw away all but the winner // is exactly the redundant recomputation this is worth skipping. // The winner gets the full RDOQ refinement below, once. let (ssd, cbf) = self.transform_luma(n, mode, &source, &refs, false); enc.encode_bin(ctx::CBF_LUMA + 1, u32::from(cbf)); let mut bits = (enc.bit_count() - bits_before) as f64; if cbf { // Ranking candidates against each other only needs a proxy // for encode_residual's exact bit count, not the count // itself: the real per-bin CABAC search (context updates, // greater1/greater2/remaining binarization) is the hot loop // this replaces, and only the winner ever pays for it below. let scan = intra::scan_index(mode, log2, true); bits += residual::estimate_residual_bits(&self.scratch.levels[..n * n], log2, scan); } enc.restore(&start); let cost = ssd + self.lambda * bits; if cost < best.0 { best = (cost, mode); best_levels[..n * n].copy_from_slice(&self.scratch.levels[..n * n]); self.scratch.best_recon[..n * n].copy_from_slice(&self.scratch.recon[..n * n]); } } enc.set_counting(false); // The trial above scored every candidate without RDOQ's refinement // loop; now that the mode is decided, pay for that loop exactly once, // on the winner, so the committed levels are the ones RDOQ can reach. if self.rdoq || (self.ts_rd && n == 4) { self.transform_luma(n, best.1, &source, &refs, true); best_levels[..n * n].copy_from_slice(&self.scratch.levels[..n * n]); self.scratch.best_recon[..n * n].copy_from_slice(&self.scratch.recon[..n * n]); } // Commit the winner's reconstruction and levels. for row in 0..n { for col in 0..n { self.write_rec_y(x + col, y + row, self.scratch.best_recon[row * n + col]); } } self.scratch.luma_levels[..n * n].copy_from_slice(&best_levels[..n * n]); self.scratch.best_levels = best_levels; self.scratch.source = source; best.1 } /// Predict, transform, quantise and reconstruct one luma block into /// `scratch.recon` / `scratch.levels`; returns `(SSD, cbf)`. /// /// `refine` gates RDOQ's per-coefficient CABAC-costed search on top of the /// dead-zone quantiser: callers scoring several mode candidates pass /// `false` and re-run the winner with `true`, since the refinement is /// worthless work on every candidate but the one that gets kept. fn transform_luma( &mut self, n: usize, mode: u8, source: &[Pel], refs: &Refs, refine: bool, ) -> (f64, bool) { if self.ts_rd { if n == 4 && refine { return self.transform_luma_ts_rd(mode, source, refs); } // Candidate ranking prices the mode, not the skip decision, which // the committed pass above makes once on the winner. self.ts_luma = false; } self.transform_luma_at(n, mode, source, refs, refine) } /// The `transform_skip_flag` to write for a 4x4 block: `None` when the PPS /// left transform skip off and the decoder reads no bin at all. fn ts_flag(&self, skip: bool) -> Option { (self.transform_skip || self.ts_rd).then_some(skip) } /// Code the 4x4 luma block both ways and keep the cheaper one, leaving its /// levels and reconstruction in the scratch and its flag in `ts_luma`. fn transform_luma_ts_rd(&mut self, mode: u8, source: &[Pel], refs: &Refs) -> (f64, bool) { let scan = intra::scan_index(mode, 2, true); let (mut best_cost, mut best) = (f64::MAX, (0.0, false, false, [0i32; 16], [0 as Pel; 16])); for skip in [false, true] { self.ts_luma = skip; let (ssd, cbf) = self.transform_luma_at(4, mode, source, refs, true); // The flag itself is one bin; the levels are priced by the same // proxy the mode search uses. let mut bits = 1.0; if cbf { bits += residual::estimate_residual_bits(&self.scratch.levels[..16], 2, scan); } let cost = ssd + self.lambda * bits; if cost < best_cost { let (mut levels, mut recon) = ([0i32; 16], [0 as Pel; 16]); levels.copy_from_slice(&self.scratch.levels[..16]); recon.copy_from_slice(&self.scratch.recon[..16]); best_cost = cost; best = (ssd, skip, cbf, levels, recon); } } let (ssd, skip, cbf, levels, recon) = best; self.ts_luma = skip; self.scratch.levels[..16].copy_from_slice(&levels); self.scratch.recon[..16].copy_from_slice(&recon); (ssd, cbf) } fn transform_luma_at( &mut self, n: usize, mode: u8, source: &[Pel], refs: &Refs, refine: bool, ) -> (f64, bool) { intra::predict_cached( refs, &mut self.scratch.filt, mode, n, true, self.strong_smoothing, self.bit_depth, &mut self.scratch.pred, ); for (i, &sample) in source[..n * n].iter().enumerate() { self.scratch.residual[i] = i32::from(sample) - i32::from(self.scratch.pred[i]); } let skip = n == 4 && if self.ts_rd { self.ts_luma } else { self.transform_skip }; let dst = uses_dst(n, true); if skip { forward_transform_skip(&self.scratch.residual, &mut self.scratch.coeffs, n); } else { forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst); } scale_forward_bd(&mut self.scratch.coeffs, n, self.bit_depth); let mut nonzero = if self.rdoq { quantize_offset( &self.scratch.coeffs, &mut self.scratch.levels, n, quant_qp(self.qp, self.bit_depth), RDOQ_DEAD_ZONE, ) } else { quantize( &self.scratch.coeffs, &mut self.scratch.levels, n, quant_qp(self.qp, self.bit_depth), ) }; let ts = self.ts_flag(skip); if self.rdoq && refine && nonzero > 0 { nonzero = residual::rdoq( &self.scratch.coeffs, &mut self.scratch.levels, n, self.qp, self.bit_depth, 0, intra::scan_index(mode, n.trailing_zeros(), true), ctx::CBF_LUMA + 1, if self.bit_depth > 8 { self.lambda / 16.0 } else { self.lambda }, ts, &mut self.rdoq_enc, ); } if self.sign_hiding && nonzero > 0 { nonzero = residual::hide_signs( &self.scratch.coeffs, &mut self.scratch.levels, n, quant_qp(self.qp, self.bit_depth), intra::scan_index(mode, n.trailing_zeros(), true), ); } let cbf = nonzero > 0; if cbf { dequantize_bd( &self.scratch.levels, &mut self.scratch.scaled, n, self.qp, self.bit_depth, ); if skip { inverse_transform_skip_bd( &self.scratch.scaled, &mut self.scratch.residual, n, self.bit_depth, ); } else { inverse_transform_bd( &self.scratch.scaled, &mut self.scratch.residual, n, dst, self.bit_depth, ); } } else { self.scratch.residual[..n * n].fill(0); } let mut ssd = 0i64; for (i, &sample) in source[..n * n].iter().enumerate() { let value = (i32::from(self.scratch.pred[i]) + self.scratch.residual[i]) .clamp(0, self.max) as Pel; self.scratch.recon[i] = value; let d = i64::from(sample) - i64::from(value); ssd += d * d; } (ssd as f64, cbf) } /// Code one chroma transform block in `pred_mode`; returns its `(SSD, cbf)` /// and leaves the levels in the matching scratch buffer. fn code_chroma( &mut self, x: usize, y: usize, n: usize, pred_mode: u8, plane: usize, skip: bool, ) -> (f64, bool) { let cn = n / 2; let (cx, cy) = (x / 2, y / 2); let refs = self.chroma_refs(cx, cy, cn, plane); let cw = self.width / 2; let src = if plane == 1 { self.src.cb } else { self.src.cr }; intra::predict( &refs, pred_mode, cn, false, self.strong_smoothing, self.bit_depth, &mut self.scratch.pred, ); for row in 0..cn { for col in 0..cn { let s = i32::from(src[(cy + row) * cw + cx + col]); self.scratch.residual[row * cn + col] = s - i32::from(self.scratch.pred[row * cn + col]); } } if skip && cn == 4 { forward_transform_skip(&self.scratch.residual, &mut self.scratch.coeffs, cn); } else { forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false); } scale_forward_bd(&mut self.scratch.coeffs, cn, self.bit_depth); let mut nonzero = if self.rdoq { quantize_offset( &self.scratch.coeffs, &mut self.scratch.levels, cn, quant_qp(self.qp_c, self.bit_depth), RDOQ_DEAD_ZONE_C, ) } else { quantize( &self.scratch.coeffs, &mut self.scratch.levels, cn, quant_qp(self.qp_c, self.bit_depth), ) }; let ts = self.ts_flag(skip && cn == 4); if self.rdoq && nonzero > 0 { nonzero = residual::rdoq( &self.scratch.coeffs, &mut self.scratch.levels, cn, self.qp_c, self.bit_depth, plane, intra::scan_index(pred_mode, cn.trailing_zeros(), false), ctx::CBF_CHROMA, if self.bit_depth > 8 { self.lambda / 16.0 } else { self.lambda }, ts, &mut self.rdoq_enc, ); } if self.sign_hiding && nonzero > 0 { nonzero = residual::hide_signs( &self.scratch.coeffs, &mut self.scratch.levels, cn, quant_qp(self.qp_c, self.bit_depth), intra::scan_index(pred_mode, cn.trailing_zeros(), false), ); } let cbf = nonzero > 0; if cbf { dequantize_bd( &self.scratch.levels, &mut self.scratch.scaled, cn, self.qp_c, self.bit_depth, ); if skip && cn == 4 { inverse_transform_skip_bd( &self.scratch.scaled, &mut self.scratch.residual, cn, self.bit_depth, ); } else { inverse_transform_bd( &self.scratch.scaled, &mut self.scratch.residual, cn, false, self.bit_depth, ); } } else { self.scratch.residual[..cn * cn].fill(0); } let mut ssd = 0i64; for row in 0..cn { for col in 0..cn { let value = (i32::from(self.scratch.pred[row * cn + col]) + self.scratch.residual[row * cn + col]) .clamp(0, self.max) as Pel; let d = i64::from(src[(cy + row) * cw + cx + col]) - i64::from(value); ssd += d * d; self.write_rec_c(cx + col, cy + row, plane, value); } } let levels = if plane == 1 { &mut self.scratch.cb_levels } else { &mut self.scratch.cr_levels }; levels[..cn * cn].copy_from_slice(&self.scratch.levels[..cn * cn]); (ssd as f64, cbf) } // ---- chroma mode decision -------------------------------------------- /// Write `intra_chroma_pred_mode` for the derived mode: the single bin 0. fn write_chroma_mode_syntax(&self, enc: &mut CabacEncoder) { enc.encode_bin(ctx::INTRA_CHROMA_PRED_MODE, 0); } // ---- reference samples ----------------------------------------------- fn luma_refs(&mut self, x: usize, y: usize, n: usize) -> Refs { self.scratch.filt = None; let mut refs = Refs::default(); let mut avail = Availability::default(); let span = 2 * n; avail.corner = self.available(x as isize - 1, y as isize - 1); if avail.corner { refs.corner = self.rec_y(x - 1, y - 1); } for i in 0..span { if self.available((x + i) as isize, y as isize - 1) { avail.top |= 1 << i; refs.top[i] = self.rec_y(x + i, y - 1); } if self.available(x as isize - 1, (y + i) as isize) { avail.left |= 1 << i; refs.left[i] = self.rec_y(x - 1, y + i); } } intra::substitute(&mut refs, &avail, n, self.bit_depth); refs } fn chroma_refs(&self, cx: usize, cy: usize, cn: usize, plane: usize) -> Refs { let mut refs = Refs::default(); let mut avail = Availability::default(); let span = 2 * cn; avail.corner = self.available(cx as isize * 2 - 1, cy as isize * 2 - 1); if avail.corner { refs.corner = self.rec_c(cx - 1, cy - 1, plane); } for i in 0..span { if self.available(((cx + i) * 2) as isize, cy as isize * 2 - 1) { avail.top |= 1 << i; refs.top[i] = self.rec_c(cx + i, cy - 1, plane); } if self.available(cx as isize * 2 - 1, ((cy + i) * 2) as isize) { avail.left |= 1 << i; refs.left[i] = self.rec_c(cx - 1, cy + i, plane); } } intra::substitute(&mut refs, &avail, cn, self.bit_depth); refs } } /// Sum of absolute transformed differences, 4x4 Hadamard per sub-block. fn satd(source: &[Pel], pred: &[Pel], n: usize) -> u32 { #[cfg(target_arch = "x86_64")] if n >= 4 && n.is_multiple_of(4) && (n == 4 || n.is_multiple_of(8)) && source.len() >= n * n && pred.len() >= n * n { // The SSE2 token (SSE2 is part of the x86_64 baseline, so this is always Some); the // check above puts every load (`n` samples per row, `n` rows) inside both slices. if let Some(t) = X64V1Token::summon() { return satd_sse2(t, source, pred, n); } } satd_scalar(source, pred, n) } /// [`satd`] on 16-bit lanes: the differences of 10-bit samples are within +-1023, so the /// sixteen Hadamard sums of a 4x4 block stay within +-16368. The vertical butterfly runs /// across whole rows, the horizontal one inside each group of four lanes. #[cfg(target_arch = "x86_64")] #[arcane] fn satd_sse2(_t: X64V1Token, source: &[Pel], pred: &[Pel], n: usize) -> u32 { use std::arch::x86_64::*; let sg1 = _mm_set_epi16(-1, -1, 1, 1, -1, -1, 1, 1); let sg2 = _mm_set_epi16(-1, 1, -1, 1, -1, 1, -1, 1); let ones = _mm_set1_epi16(1); let mut total = _mm_setzero_si128(); // `n` (4) or 8 samples at `i`, the upper lanes zero for the 4-wide case. let load = |v: &[Pel], i: usize| -> __m128i { if n == 4 { // Four samples in the low 64 bits, upper lanes zero. let lo: u64 = bytemuck::cast(<[Pel; 4]>::try_from(&v[i..i + 4]).unwrap()); _mm_cvtsi64_si128(lo as i64) } else { bytemuck::cast(<[Pel; 8]>::try_from(&v[i..i + 8]).unwrap()) } }; let step = if n == 4 { 4 } else { 8 }; for by in (0..n).step_by(4) { for bx in (0..n).step_by(step) { let i = by * n + bx; let d0 = _mm_sub_epi16(load(source, i), load(pred, i)); let d1 = _mm_sub_epi16(load(source, i + n), load(pred, i + n)); let d2 = _mm_sub_epi16(load(source, i + 2 * n), load(pred, i + 2 * n)); let d3 = _mm_sub_epi16(load(source, i + 3 * n), load(pred, i + 3 * n)); let (s0, s1) = (_mm_add_epi16(d0, d2), _mm_add_epi16(d1, d3)); let (s2, s3) = (_mm_sub_epi16(d0, d2), _mm_sub_epi16(d1, d3)); for v in [ _mm_add_epi16(s0, s1), _mm_sub_epi16(s0, s1), _mm_add_epi16(s2, s3), _mm_sub_epi16(s2, s3), ] { // lanes [a0 a1 a2 a3] -> [a0+a2, a1+a3, a0-a2, a1-a3] let t = _mm_shufflehi_epi16(_mm_shufflelo_epi16(v, 0x4E), 0x4E); let h1 = _mm_add_epi16(_mm_mullo_epi16(v, sg1), t); // -> [h0+h1, h0-h1, h2+h3, h2-h3] let t = _mm_shufflehi_epi16(_mm_shufflelo_epi16(h1, 0xB1), 0xB1); let h2 = _mm_add_epi16(_mm_mullo_epi16(h1, sg2), t); let abs = _mm_max_epi16(h2, _mm_sub_epi16(_mm_setzero_si128(), h2)); total = _mm_add_epi32(total, _mm_madd_epi16(abs, ones)); } } } let t = _mm_add_epi32(total, _mm_srli_si128(total, 8)); let t = _mm_add_epi32(t, _mm_srli_si128(t, 4)); (_mm_cvtsi128_si32(t) as u32).div_ceil(2) } fn satd_scalar(source: &[Pel], pred: &[Pel], n: usize) -> u32 { let mut total = 0u32; for by in (0..n).step_by(4) { for bx in (0..n).step_by(4) { let mut block = [0i32; 16]; for row in 0..4 { for col in 0..4 { let idx = (by + row) * n + bx + col; block[row * 4 + col] = i32::from(source[idx]) - i32::from(pred[idx]); } } // Rows, then columns. for row in 0..4 { let b = &mut block[row * 4..row * 4 + 4]; let (s0, s1, s2, s3) = (b[0] + b[2], b[1] + b[3], b[0] - b[2], b[1] - b[3]); b[0] = s0 + s1; b[1] = s0 - s1; b[2] = s2 + s3; b[3] = s2 - s3; } for col in 0..4 { let (a, b2, c, d) = (block[col], block[4 + col], block[8 + col], block[12 + col]); let (s0, s1, s2, s3) = (a + c, b2 + d, a - c, b2 - d); total += (s0 + s1).unsigned_abs(); total += (s0 - s1).unsigned_abs(); total += (s2 + s3).unsigned_abs(); total += (s2 - s3).unsigned_abs(); } } } total.div_ceil(2) } /// A snapshot type alias so callers do not need the cabac module for rollback. pub type EncoderState = CabacState; #[cfg(test)] mod tests { use super::*; #[test] fn satd_vector_path_matches_the_scalar_one() { let mut seed = 0x1234_5678u32; let mut next = |max: u32| { seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); (seed >> 8) % (max + 1) }; for n in [4usize, 8, 16, 32] { for max in [255u32, 1023] { for round in 0..40 { let (a, b): (Vec, Vec) = (0..n * n) .map(|_| { if round % 4 == 0 { // Extremes: the largest possible sums. ( if next(1) == 0 { 0 } else { max as Pel }, if next(1) == 0 { 0 } else { max as Pel }, ) } else { (next(max) as Pel, next(max) as Pel) } }) .unzip(); assert_eq!(satd(&a, &b, n), satd_scalar(&a, &b, n), "n={n} max={max}"); } } } } #[test] fn satd_is_zero_for_an_exact_prediction_and_grows_with_error() { let source: Vec = (0..64).map(|i| (i * 3 % 251) as Pel).collect(); assert_eq!(satd(&source, &source, 8), 0); let mut worse = source.clone(); worse[9] = worse[9].wrapping_add(40); assert!(satd(&source, &worse, 8) > 0); // A constant offset shows up entirely in the DC term. let shifted: Vec = source.iter().map(|v| v.saturating_sub(10)).collect(); assert!(satd(&source, &shifted, 8) >= 8 * 8 * 10 / 2); } #[test] fn lambda_grows_with_qp() { assert!(lambda_for(37) > lambda_for(27)); assert!((lambda_for(12) - 0.57).abs() < 1e-9); } }