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