forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

residual.rs1879 lines, 65.3 KiBHistoryRawDownload
1//! `residual_coding()` (7.3.8.11) and the scan orders it walks (6.5.3 - 6.5.5).
2
3use crate::cabac::{CabacDecoder, CabacEncoder, CabacState, ctx};
4use crate::transform::{coeff_ssd_scale, dequant_level_bd, ideal_level};
5use std::sync::LazyLock;
6
7/// Scan orders: `SCANS[log2BlockSize][scanIdx][pos] = (x, y)`.
8///
9/// Built once rather than typed in — the diagonal scan is four lines of the
10/// spec's own pseudo-code, and generating it cannot go wrong the way a
11/// transcribed 64-entry table can.
12/// One scan order: the `(x, y)` of every position, in scan sequence.
13type Scan = Vec<(u8, u8)>;
14
15/// Scans for block sizes 4..32 and the three scan indices.
16type ScanTable = [[Scan; 3]; 4];
17
18static SCANS: LazyLock<ScanTable> = LazyLock::new(|| {
19 std::array::from_fn(|log2_size| {
20 let size = 1usize << log2_size;
21 std::array::from_fn(|scan_idx| match scan_idx {
22 1 => (0..size * size)
23 .map(|i| ((i % size) as u8, (i / size) as u8))
24 .collect(),
25 2 => (0..size * size)
26 .map(|i| ((i / size) as u8, (i % size) as u8))
27 .collect(),
28 _ => {
29 // 6.5.3, up-right diagonal.
30 let mut out = Vec::with_capacity(size * size);
31 let (mut x, mut y) = (0usize, 0usize);
32 loop {
33 loop {
34 if x < size && y < size {
35 out.push((x as u8, y as u8));
36 }
37 if y == 0 {
38 break;
39 }
40 y -= 1;
41 x += 1;
42 }
43 y = x + 1;
44 x = 0;
45 if out.len() >= size * size {
46 break;
47 }
48 }
49 out
50 }
51 })
52 })
53});
54
55/// `POSITIONS[log2 - 2][scanIdx][y * n + x]` = that coefficient's place in the
56/// full scan of the block, sub-block major.
57///
58/// One table turns "where does the scan end" from a walk over every sub-block
59/// into a single pass over the levels, which matters because the residual coder
60/// runs once per rate-distortion trial.
61static POSITIONS: LazyLock<[[Vec<u16>; 3]; 4]> = LazyLock::new(|| {
62 std::array::from_fn(|size_idx| {
63 let log2 = size_idx as u32 + 2;
64 let n = 1usize << log2;
65 std::array::from_fn(|scan_idx| {
66 let sub_scan = &SCANS[size_idx][scan_idx];
67 let pos_scan = &SCANS[2][scan_idx];
68 let mut table = vec![0u16; n * n];
69 for (i, &(xs, ys)) in sub_scan.iter().enumerate() {
70 for (p, &(xp, yp)) in pos_scan.iter().enumerate() {
71 let xc = xs as usize * 4 + xp as usize;
72 let yc = ys as usize * 4 + yp as usize;
73 table[yc * n + xc] = (i * 16 + p) as u16;
74 }
75 }
76 table
77 })
78 })
79});
80
81/// `ctxIdxMap[i]` for 4x4 blocks (Table 9-50); index 15 is never queried
82/// because that position is always the last significant one.
83const CTX_IDX_MAP: [usize; 16] = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8];
84
85/// The scan order for one block size and scan index.
86pub fn scan(log2_size: u32, scan_idx: usize) -> &'static [(u8, u8)] {
87 &SCANS[log2_size as usize][scan_idx]
88}
89
90/// Truncated-Rice + EGk binarization of `coeff_abs_level_remaining` (9.3.3.11).
91fn encode_remaining(enc: &mut CabacEncoder, value: u32, rice: u32) {
92 let c_max = 4 << rice;
93 if value < c_max {
94 let prefix = value >> rice;
95 for _ in 0..prefix {
96 enc.encode_bypass(1);
97 }
98 enc.encode_bypass(0);
99 if rice > 0 {
100 enc.encode_bypass_bits(value & ((1 << rice) - 1), rice);
101 }
102 } else {
103 for _ in 0..4 {
104 enc.encode_bypass(1);
105 }
106 let mut rest = value - c_max;
107 let mut k = rice + 1;
108 loop {
109 if rest >= (1 << k) {
110 enc.encode_bypass(1);
111 rest -= 1 << k;
112 k += 1;
113 } else {
114 enc.encode_bypass(0);
115 enc.encode_bypass_bits(rest, k);
116 break;
117 }
118 }
119 }
120}
121
122/// `last_sig_coeff_*_prefix` for a coordinate, and its suffix bit count.
123fn last_prefix(coord: u32) -> (u32, u32) {
124 if coord < 4 {
125 (coord, 0)
126 } else {
127 let log2 = 31 - coord.leading_zeros();
128 let prefix = 2 * log2 + ((coord >> (log2 - 1)) & 1);
129 (prefix, (prefix >> 1) - 1)
130 }
131}
132
133/// Make each sub-block's absolute levels carry the sign of its first
134/// significant coefficient, so that sign need not be coded (7.3.8.11, the
135/// `sign_data_hiding_enabled_flag` path). A sub-block qualifies when its first
136/// and last significant coefficients are more than three scan positions apart;
137/// where the parity is wrong, one level is nudged by one, the cheapest being
138/// whichever coefficient the quantiser rounded furthest in that direction.
139///
140/// This runs on the levels before they are dequantised, so the encoder's own
141/// reconstruction is built from what the decoder will read back.
142pub fn hide_signs(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32, scan_idx: usize) -> usize {
143 let log2_size = n.trailing_zeros();
144 let sub_scan = scan(log2_size - 2, scan_idx);
145 let pos_scan = scan(2, scan_idx);
146 for &(xs, ys) in sub_scan {
147 let (xs, ys) = (xs as usize, ys as usize);
148 let at = |p: usize| {
149 let (xp, yp) = pos_scan[p];
150 (ys * 4 + yp as usize) * n + xs * 4 + xp as usize
151 };
152 let Some(first) = (0..16).find(|&p| levels[at(p)] != 0) else {
153 continue;
154 };
155 let last = (0..16).rev().find(|&p| levels[at(p)] != 0).unwrap_or(first);
156 if last - first <= 3 {
157 continue;
158 }
159 let sum: i32 = (0..16).map(|p| levels[at(p)].abs()).sum();
160 let negative = levels[at(first)] < 0;
161 if (sum & 1 == 1) == negative {
162 continue;
163 }
164 // The parity is wrong. Changing any level by one fixes it; take the
165 // one whose rounding error the change reduces most (or grows least).
166 // Only levels that stay non-zero are considered, so no coefficient
167 // enters or leaves the block and the scan positions above still hold.
168 let mut best: Option<(f64, usize, i32)> = None;
169 for p in 0..16 {
170 let i = at(p);
171 let level = levels[i];
172 if level == 0 {
173 continue;
174 }
175 let magnitude = f64::from(level.abs());
176 let ideal = ideal_level(coeffs[i], n, qp);
177 // Distortion alone picks the coefficient: a rate bias favouring
178 // decrements (or increments) was swept through the clip gate at
179 // +-0.25 and +-0.5 units of squared level error per bit and lost
180 // in both directions, so there is none.
181 let mut consider = |cost: f64, delta: i32| {
182 if best.is_none_or(|(b, _, _)| cost < b) {
183 best = Some((cost, i, delta));
184 }
185 };
186 consider(1.0 - 2.0 * (ideal - magnitude), 1);
187 if level.abs() > 1 {
188 consider(1.0 + 2.0 * (ideal - magnitude), -1);
189 }
190 }
191 if let Some((_, i, delta)) = best {
192 levels[i] += if levels[i] < 0 { -delta } else { delta };
193 }
194 }
195 levels[..n * n].iter().filter(|&&l| l != 0).count()
196}
197
198/// The largest level the rate-distortion search offers a smaller magnitude to.
199///
200/// A big level carries real signal and never wins by shrinking, so bounding
201/// the search is what keeps it affordable: every trial re-codes the whole
202/// block. Swept on 1080p film, BD-PSNR-YUV against x265: 1 gives +0.244, the 2
203/// kept here +0.276, and 3 +0.277 for strictly more trials.
204const RDOQ_MAX_LEVEL: i32 = 2;
205
206/// How much of the mode-decision lambda the level search uses. The bits are
207/// the coder's own count, not an estimate, so the scale starts at 1.
208///
209/// The two clips disagree above it and the disagreement is small: on
210/// BD-PSNR-YUV against x265, 1080p film reads +0.276 at 1.0, +0.294 at 1.25
211/// and +0.293 at 1.5, while a 2560x1440 screen capture reads -0.392, -0.408
212/// and -0.441. The crossing sits just above 1.0, and the screen capture is the
213/// content still behind x265, so it takes the tie.
214const RDOQ_LAMBDA: f64 = 1.0;
215
216/// How hard the significance map's per-position flag is priced in the
217/// coefficient-statistics proxy below, in bits. Swept against
218/// `bd_psnr_vs_x265` (synthetic clip + a real screen-capture clip) alongside
219/// [`ESTIMATE_MAG_SCALE`]; see that constant's comment for the numbers.
220const ESTIMATE_SIG_BIT: f64 = 0.15;
221
222/// Scale on the per-level magnitude term of [`estimate_residual_bits`].
223///
224/// Swept BD-PSNR-YUV against x265 on the synthetic clip (real-bits baseline
225/// +7.862 dB): 1.0 reads +7.790, 1.25 reads +7.817, 1.5 reads +7.868 — closest
226/// to the baseline, and confirmed on a real 2560x1440 screen capture too
227/// (real-bits baseline -0.317 dB, this scale -0.331, both other scales
228/// untried there once the synthetic sweep picked a direction).
229const ESTIMATE_MAG_SCALE: f64 = 1.5;
230
231/// A cheap stand-in for [`encode_residual`]'s exact bit count, for ranking
232/// intra-mode candidates before the real search runs once on the winner
233/// (`choose_luma_mode`). No CABAC context is touched — the last position is
234/// priced by the same closed-form binarization the real coder uses (a few
235/// arithmetic ops, not a per-bin call), and every level's cost comes from a
236/// log2 magnitude estimate instead of walking greater1/greater2/remaining
237/// bins one context update at a time. This is a ranking proxy only: the
238/// committed bitstream always goes through `encode_residual`.
239pub fn estimate_residual_bits(levels: &[i32], log2_size: u32, scan_idx: usize) -> f64 {
240 let n = 1usize << log2_size;
241 let positions = &POSITIONS[(log2_size - 2) as usize][scan_idx];
242 let mut last_full = 0i32;
243 let mut mag_bits = 0.0f64;
244 let mut any = false;
245 for (i, &level) in levels[..n * n].iter().enumerate() {
246 if level != 0 {
247 any = true;
248 last_full = last_full.max(i32::from(positions[i]));
249 let v = level.unsigned_abs();
250 // 1 (sign) + 2 for the first two magnitudes (mirroring the real
251 // coder's greater1/greater2 flags), Exp-Golomb-ish beyond that.
252 mag_bits += 1.0
253 + if v <= 2 {
254 v as f64
255 } else {
256 2.0 + 2.0 * ((v - 1) as f64).log2()
257 };
258 }
259 }
260 if !any {
261 return 0.0;
262 }
263 let last_sub = (last_full / 16) as usize;
264 let last_pos = (last_full % 16) as usize;
265 let sub_scan = scan(log2_size - 2, scan_idx);
266 let pos_scan = scan(2, scan_idx);
267 let (last_xs, last_ys) = sub_scan[last_sub];
268 let (last_xp, last_yp) = pos_scan[last_pos];
269 let mut last_x = (last_xs as u32) * 4 + last_xp as u32;
270 let mut last_y = (last_ys as u32) * 4 + last_yp as u32;
271 if scan_idx == 2 {
272 std::mem::swap(&mut last_x, &mut last_y);
273 }
274 let (x_prefix, x_suffix) = last_prefix(last_x);
275 let (y_prefix, y_suffix) = last_prefix(last_y);
276 let last_bits = (x_prefix + y_prefix + x_suffix + y_suffix) as f64;
277 last_bits + ESTIMATE_SIG_BIT * (last_full + 1) as f64 + ESTIMATE_MAG_SCALE * mag_bits
278}
279
280/// What one candidate set of levels costs in bits, priced by the CABAC coder
281/// itself against `base`'s context state.
282#[allow(clippy::too_many_arguments)]
283fn levels_bits(
284 enc: &mut CabacEncoder,
285 base: &CabacState,
286 levels: &[i32],
287 log2_size: u32,
288 c_idx: usize,
289 scan_idx: usize,
290 cbf_ctx: usize,
291 coded: bool,
292 transform_skip: Option<bool>,
293) -> f64 {
294 enc.restore(base);
295 let before = enc.bit_count_f64();
296 enc.encode_bin(cbf_ctx, u32::from(coded));
297 if coded {
298 encode_residual(
299 enc,
300 levels,
301 log2_size,
302 c_idx,
303 scan_idx,
304 false,
305 transform_skip,
306 );
307 }
308 enc.bit_count_f64() - before
309}
310
311/// [`levels_bits`], given the header state instead of deriving it from
312/// `levels` — what [`rdoq`]'s inner loop calls once the header is
313/// incrementally maintained.
314#[allow(clippy::too_many_arguments)]
315fn levels_bits_with(
316 enc: &mut CabacEncoder,
317 base: &CabacState,
318 levels: &[i32],
319 log2_size: u32,
320 c_idx: usize,
321 scan_idx: usize,
322 cbf_ctx: usize,
323 coded: bool,
324 transform_skip: Option<bool>,
325 last_full: i32,
326 csbf: [bool; 64],
327) -> f64 {
328 enc.restore(base);
329 let before = enc.bit_count_f64();
330 enc.encode_bin(cbf_ctx, u32::from(coded));
331 if coded {
332 encode_residual_with(
333 enc,
334 levels,
335 log2_size,
336 c_idx,
337 scan_idx,
338 false,
339 transform_skip,
340 last_full,
341 csbf,
342 );
343 }
344 enc.bit_count_f64() - before
345}
346
347/// Rate-distortion quantisation of one transform block: each small level is
348/// offered the magnitudes below it, and takes one when the squared error it
349/// gives up costs less than the bits it saves.
350///
351/// The rate is the CABAC coder's own price for the whole block — `enc` is a
352/// counting engine, and every trial is priced from the same context state — so
353/// dropping a level is priced together with the significance map and the last
354/// position that follow from it, which is where most of the saving is. The
355/// distortion is the transform-domain error scaled back to samples by
356/// [`coeff_ssd_scale`], so `lambda` is the caller's sample-domain lambda.
357///
358/// Returns the number of non-zero levels left.
359#[allow(clippy::too_many_arguments)]
360pub fn rdoq(
361 coeffs: &[i32],
362 levels: &mut [i32],
363 n: usize,
364 qp: i32,
365 bit_depth: u32,
366 c_idx: usize,
367 scan_idx: usize,
368 cbf_ctx: usize,
369 lambda: f64,
370 transform_skip: Option<bool>,
371 enc: &mut CabacEncoder,
372) -> usize {
373 let log2_size = n.trailing_zeros();
374 let scale = coeff_ssd_scale(n);
375 let lambda = RDOQ_LAMBDA * lambda;
376 let base = enc.snapshot();
377 let base_bits = enc.bit_count_f64();
378 let err = |level: i32, coeff: i32| {
379 let d = f64::from(dequant_level_bd(level, n, qp, bit_depth) - coeff);
380 d * d
381 };
382
383 let mut dist: f64 = (0..n * n).map(|i| err(levels[i], coeffs[i])).sum();
384 let bits = levels_bits(
385 enc,
386 &base,
387 levels,
388 log2_size,
389 c_idx,
390 scan_idx,
391 cbf_ctx,
392 true,
393 transform_skip,
394 );
395 let mut cost = scale * dist + lambda * bits;
396
397 // Highest scanning position first: dropping the last significant level is
398 // what shortens the significance map and moves the coded last position, so
399 // it is tried while the levels above it are already gone.
400 let sub_scan = scan(log2_size - 2, scan_idx);
401 let pos_scan = scan(2, scan_idx);
402 // Sub-block index in *scan* order (what the encoder's own sub-block loop
403 // is indexed by) for a flat row-major position — distinct from `sub_idx`
404 // below, which is the *raster* sub-block index `csbf`/`sub_count` use.
405 let positions = &POSITIONS[(log2_size - 2) as usize][scan_idx];
406 let order: Vec<usize> = sub_scan
407 .iter()
408 .flat_map(|&(xs, ys)| {
409 pos_scan.iter().map(move |&(xp, yp)| {
410 (ys as usize * 4 + yp as usize) * n + xs as usize * 4 + xp as usize
411 })
412 })
413 .collect();
414
415 // The header state `encode_residual` would otherwise rescan the whole
416 // block for on every trial, maintained incrementally instead: a trial
417 // only ever changes one coefficient. `nz_positions` lists the positions
418 // that started non-zero, in the same descending scan order this loop
419 // visits them in, so "what becomes the new last position if this one
420 // empties" (the one hazard: the last position moves when its own
421 // coefficient is dropped) is a lookahead into the still-untouched region
422 // below, not a rescan.
423 let sub_wide = n >> 2;
424 let mut csbf = [false; 64];
425 let mut sub_count = [0i32; 64];
426 let mut nz_positions: Vec<i32> = Vec::new();
427 for (k, &i) in order.iter().enumerate().rev() {
428 if levels[i] != 0 {
429 nz_positions.push(k as i32);
430 let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2);
431 sub_count[sub_idx] += 1;
432 csbf[sub_idx] = true;
433 }
434 }
435 let mut cur_last = nz_positions.first().copied().unwrap_or(0);
436 let mut nz_idx = 0usize;
437 let (dc_xs, dc_ys) = sub_scan[0];
438 let dc_idx = dc_ys as usize * sub_wide + dc_xs as usize;
439
440 // Sub-block frozen-prefix cache: `cursor` holds the CABAC state right
441 // before encoding sub-block `cursor.2`, plus the `greater1_ctx` carry the
442 // sub-block above it left behind. Every trial that neither moves the last
443 // significant position nor touches a sub-block above the cursor can
444 // restore from it and re-encode only `sub_idx..=0` — the sub-blocks above
445 // are already committed to the bitstream and, since `csbf` and
446 // `greater1_ctx` only ever flow from a higher-index sub-block to a lower
447 // one (never the reverse — 9.3.4.2.6's `greater1_ctx` carry and the
448 // coded-sub-block-flag neighbour lookups both read only already-visited
449 // neighbours), their bits cannot change. `cursor` is invalidated (`None`)
450 // whenever `cur_last` moves, since that changes the header and `last_sub`
451 // themselves.
452 let mut cursor: Option<(CabacState, u32, usize)> = None;
453 let mut cursor_last = cur_last;
454
455 for (k, &i) in order.iter().enumerate().rev() {
456 let level = levels[i];
457 if level == 0 {
458 continue;
459 }
460 let next_last = nz_positions.get(nz_idx + 1).copied().unwrap_or(0);
461 nz_idx += 1;
462 if level.abs() > RDOQ_MAX_LEVEL {
463 continue;
464 }
465 let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2);
466 let scan_sub = (positions[i] as usize) / 16;
467 let mut tried = level.abs();
468 for candidate in [level.abs() - 1, 0] {
469 if candidate == tried {
470 continue;
471 }
472 tried = candidate;
473 let keep = levels[i];
474 levels[i] = candidate * level.signum();
475 let now_zero = levels[i] == 0;
476 let sub_count_before = sub_count[sub_idx];
477 let csbf_before = csbf[sub_idx];
478 if now_zero {
479 sub_count[sub_idx] -= 1;
480 csbf[sub_idx] = sub_count[sub_idx] > 0;
481 }
482 let moves_last = now_zero && k as i32 == cur_last;
483 let trial_last = if moves_last { next_last } else { cur_last };
484 let trial_dist = dist - err(keep, coeffs[i]) + err(levels[i], coeffs[i]);
485 let any = sub_count.iter().any(|&c| c > 0);
486
487 let trial_bits = if moves_last {
488 // The last position itself moves: the header changes, so
489 // there is no shortcut — re-derive the whole block from
490 // `base`, same as before this round.
491 levels_bits_with(
492 enc,
493 &base,
494 levels,
495 log2_size,
496 c_idx,
497 scan_idx,
498 cbf_ctx,
499 any,
500 transform_skip,
501 trial_last,
502 csbf,
503 )
504 } else {
505 if cursor_last != cur_last {
506 cursor = None;
507 cursor_last = cur_last;
508 }
509 let last_sub_now = (cur_last as usize) / 16;
510 let last_pos_now = (cur_last as usize) % 16;
511 let (mut cur_state, mut g1, mut at) = cursor.take().unwrap_or_else(|| {
512 enc.restore(&base);
513 enc.encode_bin(cbf_ctx, 1);
514 encode_last_position(enc, log2_size, c_idx, scan_idx, cur_last);
515 (enc.snapshot(), 1u32, last_sub_now)
516 });
517 let mut csbf_forced = csbf;
518 csbf_forced[dc_idx] = true;
519 if at > scan_sub {
520 enc.restore(&cur_state);
521 while at > scan_sub {
522 g1 = encode_subblock(
523 enc,
524 levels,
525 n,
526 log2_size,
527 sub_wide,
528 sub_scan,
529 pos_scan,
530 c_idx,
531 scan_idx,
532 false,
533 at,
534 last_sub_now,
535 last_pos_now,
536 &csbf_forced,
537 g1,
538 );
539 at -= 1;
540 }
541 cur_state = enc.snapshot();
542 }
543 cursor = Some((cur_state.clone(), g1, at));
544 enc.restore(&cur_state);
545 encode_subblock_range(
546 enc,
547 levels,
548 n,
549 c_idx,
550 scan_idx,
551 false,
552 last_sub_now,
553 last_pos_now,
554 scan_sub,
555 g1,
556 &csbf_forced,
557 );
558 enc.bit_count_f64() - base_bits
559 };
560 let trial = scale * trial_dist + lambda * trial_bits;
561 if trial < cost {
562 cost = trial;
563 dist = trial_dist;
564 if now_zero {
565 cur_last = trial_last;
566 }
567 } else {
568 levels[i] = keep;
569 sub_count[sub_idx] = sub_count_before;
570 csbf[sub_idx] = csbf_before;
571 }
572 }
573 }
574 // And the block as a whole: zeroing it drops the coded-block flag as well
575 // as every level, which no single-coefficient step can see.
576 let zero_dist: f64 = (0..n * n).map(|i| err(0, coeffs[i])).sum();
577 let zero_bits = levels_bits(
578 enc,
579 &base,
580 levels,
581 log2_size,
582 c_idx,
583 scan_idx,
584 cbf_ctx,
585 false,
586 transform_skip,
587 );
588 if scale * zero_dist + lambda * zero_bits <= cost {
589 levels[..n * n].fill(0);
590 enc.restore(&base);
591 return 0;
592 }
593 enc.restore(&base);
594 levels[..n * n].iter().filter(|&&l| l != 0).count()
595}
596
597/// The coded-sub-block flags and last significant scan position that
598/// [`encode_residual`] needs, found by one pass over `levels` — the state
599/// [`rdoq`] maintains incrementally instead, since a trial only ever changes
600/// one coefficient and re-deriving this from scratch is what made the search
601/// quadratic in the block size per trial.
602fn residual_header(levels: &[i32], log2_size: u32, scan_idx: usize) -> (i32, [bool; 64]) {
603 let n = 1usize << log2_size;
604 let sub_wide = n >> 2;
605 let positions = &POSITIONS[(log2_size - 2) as usize][scan_idx];
606 let mut csbf = [false; 64];
607 let mut last_full = 0i32;
608 for yc in 0..n {
609 let row = &levels[yc * n..yc * n + n];
610 for (xc, &level) in row.iter().enumerate() {
611 if level != 0 {
612 csbf[(yc >> 2) * sub_wide + (xc >> 2)] = true;
613 last_full = last_full.max(i32::from(positions[yc * n + xc]));
614 }
615 }
616 }
617 (last_full, csbf)
618}
619
620/// Encode one transform block's levels.
621///
622/// `levels` is row-major `n x n` with `levels[y * n + x]`, `c_idx` is 0 for luma
623/// and 1/2 for chroma, and at least one level must be non-zero (the caller codes
624/// a `cbf` of zero instead).
625pub fn encode_residual(
626 enc: &mut CabacEncoder,
627 levels: &[i32],
628 log2_size: u32,
629 c_idx: usize,
630 scan_idx: usize,
631 sign_hiding: bool,
632 transform_skip: Option<bool>,
633) {
634 let (last_full, csbf) = residual_header(levels, log2_size, scan_idx);
635 encode_residual_with(
636 enc,
637 levels,
638 log2_size,
639 c_idx,
640 scan_idx,
641 sign_hiding,
642 transform_skip,
643 last_full,
644 csbf,
645 );
646}
647
648/// [`encode_residual`], given the header state ([`residual_header`]'s output)
649/// instead of deriving it from `levels`.
650#[allow(clippy::too_many_arguments)]
651fn encode_residual_with(
652 enc: &mut CabacEncoder,
653 levels: &[i32],
654 log2_size: u32,
655 c_idx: usize,
656 scan_idx: usize,
657 sign_hiding: bool,
658 transform_skip: Option<bool>,
659 last_full: i32,
660 mut csbf: [bool; 64],
661) {
662 // `Some` means the PPS turned transform skip on, so the decoder reads a
663 // bin for every 4x4 transform block whether or not this one skips.
664 if let Some(skip) = transform_skip
665 && log2_size == 2
666 {
667 let ctx_idx = ctx::TRANSFORM_SKIP + if c_idx == 0 { 0 } else { 1 };
668 enc.encode_bin(ctx_idx, u32::from(skip));
669 }
670 let n = 1usize << log2_size;
671 let sub_wide = n >> 2;
672 let sub_scan = scan(log2_size - 2, scan_idx);
673 let (last_sub, last_pos) = encode_last_position(enc, log2_size, c_idx, scan_idx, last_full);
674
675 // The DC sub-block is always coded (7.4.9.11 inference).
676 let (dc_xs, dc_ys) = sub_scan[0];
677 csbf[dc_ys as usize * sub_wide + dc_xs as usize] = true;
678
679 encode_subblock_range(
680 enc,
681 levels,
682 n,
683 c_idx,
684 scan_idx,
685 sign_hiding,
686 last_sub,
687 last_pos,
688 last_sub,
689 1,
690 &csbf,
691 );
692}
693
694/// The `last_sig_coeff_x/y` syntax (9.3.4.2.3), given the flat scan position of
695/// the last significant coefficient. Returns the sub-block and within-sub-block
696/// position it decomposes into, since the sub-block loop is keyed by those —
697/// split out so a sub-block-range re-encode (see [`encode_subblock_range`])
698/// need not re-derive them.
699fn encode_last_position(
700 enc: &mut CabacEncoder,
701 log2_size: u32,
702 c_idx: usize,
703 scan_idx: usize,
704 last_full: i32,
705) -> (usize, usize) {
706 let sub_scan = scan(log2_size - 2, scan_idx);
707 let pos_scan = scan(2, scan_idx);
708 let last_sub = (last_full / 16) as usize;
709 let last_pos = (last_full % 16) as usize;
710 let (last_xs, last_ys) = sub_scan[last_sub];
711 let (last_xp, last_yp) = pos_scan[last_pos];
712 let mut last_x = (last_xs as u32) * 4 + last_xp as u32;
713 let mut last_y = (last_ys as u32) * 4 + last_yp as u32;
714 if scan_idx == 2 {
715 std::mem::swap(&mut last_x, &mut last_y);
716 }
717
718 // last_sig_coeff_x/y prefix and suffix (9.3.4.2.3 for the contexts).
719 let (offset, shift) = if c_idx == 0 {
720 (
721 3 * (log2_size - 2) + ((log2_size - 1) >> 2),
722 (log2_size + 1) >> 2,
723 )
724 } else {
725 (15, log2_size - 2)
726 };
727 let c_max = (log2_size << 1) - 1;
728 let (x_prefix, x_suffix_bits) = last_prefix(last_x);
729 let (y_prefix, y_suffix_bits) = last_prefix(last_y);
730 for (prefix, base) in [(x_prefix, ctx::LAST_X), (y_prefix, ctx::LAST_Y)] {
731 for bin in 0..prefix {
732 enc.encode_bin(base + ((bin >> shift) + offset) as usize, 1);
733 }
734 if prefix < c_max {
735 enc.encode_bin(base + ((prefix >> shift) + offset) as usize, 0);
736 }
737 }
738 if x_suffix_bits > 0 {
739 let base = (1 << x_suffix_bits) * (2 + (x_prefix & 1));
740 enc.encode_bypass_bits(last_x - base, x_suffix_bits);
741 }
742 if y_suffix_bits > 0 {
743 let base = (1 << y_suffix_bits) * (2 + (y_prefix & 1));
744 enc.encode_bypass_bits(last_y - base, y_suffix_bits);
745 }
746 (last_sub, last_pos)
747}
748
749/// Encode sub-blocks `from_sub` down to (and including) 0 — the tail of
750/// [`encode_residual_with`]'s loop, split out so a trial that only changes a
751/// coefficient inside `from_sub` can restore a cached frozen-prefix state (the
752/// bits for sub-blocks above `from_sub` never change) instead of re-encoding
753/// the whole block. `greater1_ctx_in` is the carry the sub-block above
754/// `from_sub` left behind (1 when there is no such sub-block, matching
755/// [`encode_residual_with`]'s own initial value).
756#[allow(clippy::too_many_arguments)]
757fn encode_subblock_range(
758 enc: &mut CabacEncoder,
759 levels: &[i32],
760 n: usize,
761 c_idx: usize,
762 scan_idx: usize,
763 sign_hiding: bool,
764 last_sub: usize,
765 last_pos: usize,
766 from_sub: usize,
767 greater1_ctx_in: u32,
768 csbf: &[bool; 64],
769) -> u32 {
770 // Hoisted once for the whole range instead of re-derived by every
771 // `encode_subblock` call: `log2_size`/`sub_wide`/the scan tables are the
772 // same for every sub-block this loop visits.
773 let log2_size = n.trailing_zeros();
774 let sub_wide = n >> 2;
775 let sub_scan = scan(log2_size - 2, scan_idx);
776 let pos_scan = scan(2, scan_idx);
777 let mut greater1_ctx = greater1_ctx_in;
778 for i in (0..=from_sub).rev() {
779 greater1_ctx = encode_subblock(
780 enc,
781 levels,
782 n,
783 log2_size,
784 sub_wide,
785 sub_scan,
786 pos_scan,
787 c_idx,
788 scan_idx,
789 sign_hiding,
790 i,
791 last_sub,
792 last_pos,
793 csbf,
794 greater1_ctx,
795 );
796 }
797 greater1_ctx
798}
799
800/// One iteration of [`encode_residual_with`]'s sub-block loop, split out so
801/// [`encode_subblock_range`] can drive it from a starting index other than
802/// `last_sub`. Returns the `greater1_ctx` carry the *next* (lower-index)
803/// sub-block reads.
804#[allow(clippy::too_many_arguments)]
805fn encode_subblock(
806 enc: &mut CabacEncoder,
807 levels: &[i32],
808 n: usize,
809 log2_size: u32,
810 sub_wide: usize,
811 sub_scan: &'static [(u8, u8)],
812 pos_scan: &'static [(u8, u8)],
813 c_idx: usize,
814 scan_idx: usize,
815 sign_hiding: bool,
816 i: usize,
817 last_sub: usize,
818 last_pos: usize,
819 csbf: &[bool; 64],
820 greater1_ctx_in: u32,
821) -> u32 {
822 let chroma = c_idx > 0;
823 let mut greater1_ctx = greater1_ctx_in;
824
825 let (xs, ys) = sub_scan[i];
826 let (xs, ys) = (xs as usize, ys as usize);
827 let coded = csbf[ys * sub_wide + xs];
828 let mut infer_dc_sig = false;
829 if i < last_sub && i > 0 {
830 let mut csbf_ctx = 0;
831 if xs < sub_wide - 1 && csbf[ys * sub_wide + xs + 1] {
832 csbf_ctx += 1;
833 }
834 if ys < sub_wide - 1 && csbf[(ys + 1) * sub_wide + xs] {
835 csbf_ctx += 1;
836 }
837 let inc = if chroma {
838 2 + csbf_ctx.min(1)
839 } else {
840 csbf_ctx.min(1)
841 };
842 enc.encode_bin(ctx::CODED_SUB_BLOCK + inc, u32::from(coded));
843 infer_dc_sig = true;
844 }
845 if !coded {
846 return greater1_ctx;
847 }
848
849 // sig_coeff_flag over the sub-block, high scan position first.
850 let mut significant = [false; 16];
851 if i == last_sub {
852 significant[last_pos] = true;
853 }
854 let first = if i == last_sub {
855 last_pos as i32 - 1
856 } else {
857 15
858 };
859 let sig_base = sig_ctx_base(xs, ys, sub_wide, csbf, log2_size, c_idx, scan_idx);
860 let mut scan_pos = first;
861 while scan_pos >= 0 {
862 let p = scan_pos as usize;
863 scan_pos -= 1;
864 let (xp, yp) = pos_scan[p];
865 let xc = xs * 4 + xp as usize;
866 let yc = ys * 4 + yp as usize;
867 let sig = levels[yc * n + xc] != 0;
868 if p > 0 || !infer_dc_sig {
869 let inc = sig_ctx_inc(xc, yc, log2_size, c_idx, sig_base);
870 enc.encode_bin(ctx::SIG_COEFF + inc, u32::from(sig));
871 }
872 significant[p] = sig;
873 if sig {
874 infer_dc_sig = false;
875 }
876 }
877 if infer_dc_sig {
878 // The flag was not coded because it is inferred to be one.
879 significant[0] = true;
880 }
881
882 let mut order = [0usize; 16];
883 let mut order_len = 0;
884 for p in (0..16).rev() {
885 if significant[p] {
886 order[order_len] = p;
887 order_len += 1;
888 }
889 }
890 let order = &order[..order_len];
891 if order.is_empty() {
892 return greater1_ctx;
893 }
894
895 // coeff_abs_level_greater1_flag, first eight only (9.3.4.2.6).
896 let mut ctx_set = if i == 0 || chroma { 0 } else { 2 };
897 if greater1_ctx == 0 {
898 ctx_set += 1;
899 }
900 greater1_ctx = 1;
901 let mut last_greater1 = None;
902 let mut greater1 = [false; 16];
903 for &p in order.iter().take(8) {
904 let (xp, yp) = pos_scan[p];
905 let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
906 let flag = level > 1;
907 let inc = ctx_set * 4 + greater1_ctx.min(3) + if chroma { 16 } else { 0 };
908 enc.encode_bin(ctx::GREATER1 + inc as usize, u32::from(flag));
909 greater1[p] = flag;
910 if flag {
911 if last_greater1.is_none() {
912 last_greater1 = Some(p);
913 }
914 greater1_ctx = 0;
915 } else if greater1_ctx > 0 {
916 greater1_ctx += 1;
917 }
918 }
919
920 // coeff_abs_level_greater2_flag for the first greater-than-one level.
921 let mut greater2 = false;
922 if let Some(p) = last_greater1 {
923 let (xp, yp) = pos_scan[p];
924 let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
925 greater2 = level > 2;
926 let inc = ctx_set + if chroma { 4 } else { 0 };
927 enc.encode_bin(ctx::GREATER2 + inc as usize, u32::from(greater2));
928 }
929
930 // Signs, then the remaining magnitudes. With sign data hiding on and
931 // the significant coefficients of this sub-block more than three scan
932 // positions apart, the first one's sign is not coded at all: the
933 // decoder reads it off the parity of the sub-block's absolute levels,
934 // which `hide_signs` has already made match.
935 let hidden = sign_hiding && order[0] - order[order_len - 1] > 3;
936 for (k, &p) in order.iter().enumerate() {
937 if hidden && k == order_len - 1 {
938 continue;
939 }
940 let (xp, yp) = pos_scan[p];
941 let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize];
942 enc.encode_bypass(u32::from(level < 0));
943 }
944 let mut rice = 0u32;
945 for (num_sig, &p) in order.iter().enumerate() {
946 let (xp, yp) = pos_scan[p];
947 let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
948 let coded_greater1 = num_sig < 8;
949 let base_level = 1
950 + u32::from(coded_greater1 && greater1[p])
951 + u32::from(last_greater1 == Some(p) && greater2);
952 let threshold = if num_sig < 8 {
953 if last_greater1 == Some(p) { 3 } else { 2 }
954 } else {
955 1
956 };
957 if base_level == threshold {
958 let remaining = level - base_level;
959 encode_remaining(enc, remaining, rice);
960 rice = (rice + u32::from(level > (3 << rice))).min(4);
961 }
962 }
963 greater1_ctx
964}
965
966/// Longest EGk escape suffix (in bits) a conforming stream can produce for
967/// `coeff_abs_level_remaining`; see [`decode_remaining`].
968const MAX_ESCAPE_K: u32 = 16;
969
970/// The level a corrupt escape decodes to: the largest magnitude a 16-bit
971/// `TransCoeffLevel` can hold.
972const CORRUPT_REMAINING: u32 = 1 << 15;
973
974/// Inverse of [`encode_remaining`]: read one `coeff_abs_level_remaining` back
975/// off the bypass bins (9.3.3.11).
976fn decode_remaining(dec: &mut CabacDecoder, rice: u32) -> u32 {
977 let mut prefix = 0u32;
978 while prefix < 4 {
979 if dec.decode_bypass() == 0 {
980 break;
981 }
982 prefix += 1;
983 }
984 if prefix < 4 {
985 let suffix = if rice > 0 {
986 dec.decode_bypass_bits(rice)
987 } else {
988 0
989 };
990 (prefix << rice) + suffix
991 } else {
992 let c_max = 4 << rice;
993 let mut k = rice + 1;
994 let mut rest = 0u32;
995 loop {
996 if dec.decode_bypass() == 1 {
997 // A conforming level fits in 16 bits (7.4.9.11), so its escape prefix
998 // never reaches MAX_ESCAPE_K. Longer data is corrupt: stop reading and
999 // return a bounded level, so the shift below cannot overflow.
1000 if k >= MAX_ESCAPE_K {
1001 return CORRUPT_REMAINING;
1002 }
1003 rest += 1 << k;
1004 k += 1;
1005 } else {
1006 rest += dec.decode_bypass_bits(k);
1007 break;
1008 }
1009 }
1010 c_max + rest
1011 }
1012}
1013
1014/// What the range extension tools change in the parse of one transform block
1015/// (7.3.8.11 and 9.3.4.2.5, 9.3.3.11).
1016#[derive(Clone, Copy, Debug)]
1017pub struct ResidualCfg {
1018 /// `log2TrafoSize` of the block (in samples of its own component).
1019 pub log2_size: u32,
1020 /// Colour component, 0 luma.
1021 pub c_idx: usize,
1022 /// `scanIdx`.
1023 pub scan_idx: usize,
1024 /// `sign_data_hiding_enabled_flag`.
1025 pub sign_hiding: bool,
1026 /// `cu_transquant_bypass_flag`.
1027 pub bypass: bool,
1028 /// `transform_skip_enabled_flag`.
1029 pub ts_enabled: bool,
1030 /// `Log2MaxTransformSkipSize`.
1031 pub log2_max_ts: u32,
1032 /// `transform_skip_context_enabled_flag`.
1033 pub ts_context: bool,
1034 /// `persistent_rice_adaptation_enabled_flag`.
1035 pub persistent_rice: bool,
1036 /// `implicit_rdpcm_enabled_flag`.
1037 pub implicit_rdpcm: bool,
1038 /// `explicit_rdpcm_enabled_flag`.
1039 pub explicit_rdpcm: bool,
1040 /// `predModeIntra` of the block for an intra coding unit, `None` for an inter one.
1041 pub intra_mode: Option<u8>,
1042}
1043
1044/// What the parse of a transform block found besides its levels.
1045#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1046pub struct ResidualFlags {
1047 /// `transform_skip_flag`.
1048 pub transform_skip: bool,
1049 /// The RDPCM direction in force (implicit or explicit): 0 horizontal, 1 vertical.
1050 pub rdpcm: Option<u8>,
1051}
1052
1053/// Largest Rice parameter persistent adaptation may reach; a conforming stream stays far
1054/// below it (levels are 16 bit), so it only bounds a corrupt one.
1055const MAX_RICE: u32 = 20;
1056
1057/// Decode one transform block's levels — the mirror of [`encode_residual`],
1058/// read bin for bin through the same context derivations so the same
1059/// bitstream that a [`CabacEncoder`] wrote comes back out as the same
1060/// `levels`.
1061///
1062/// `levels` must already be zeroed and at least `n * n` long. Returns whether
1063/// `transform_skip_flag` was present and set (only possible at `log2_size ==
1064/// 2` and only when `transform_skip_enabled` is true, i.e. the PPS turned the
1065/// syntax element on).
1066pub fn decode_residual(
1067 dec: &mut CabacDecoder,
1068 levels: &mut [i32],
1069 log2_size: u32,
1070 c_idx: usize,
1071 scan_idx: usize,
1072 sign_hiding: bool,
1073 transform_skip_enabled: bool,
1074) -> bool {
1075 let cfg = ResidualCfg {
1076 log2_size,
1077 c_idx,
1078 scan_idx,
1079 sign_hiding,
1080 bypass: false,
1081 ts_enabled: transform_skip_enabled,
1082 log2_max_ts: 2,
1083 ts_context: false,
1084 persistent_rice: false,
1085 implicit_rdpcm: false,
1086 explicit_rdpcm: false,
1087 intra_mode: Some(1),
1088 };
1089 decode_residual_ext(dec, levels, &cfg).transform_skip
1090}
1091
1092/// [`decode_residual`] with the range extension tools of `cfg`.
1093pub fn decode_residual_ext(
1094 dec: &mut CabacDecoder,
1095 levels: &mut [i32],
1096 cfg: &ResidualCfg,
1097) -> ResidualFlags {
1098 let ResidualCfg {
1099 log2_size,
1100 c_idx,
1101 scan_idx,
1102 ..
1103 } = *cfg;
1104 let mut transform_skip = false;
1105 if cfg.ts_enabled && !cfg.bypass && log2_size <= cfg.log2_max_ts {
1106 let ctx_idx = ctx::TRANSFORM_SKIP + if c_idx == 0 { 0 } else { 1 };
1107 transform_skip = dec.decode_bin(ctx_idx) != 0;
1108 }
1109 let mut rdpcm = None;
1110 match cfg.intra_mode {
1111 None => {
1112 if cfg.explicit_rdpcm && (transform_skip || cfg.bypass) {
1113 let chroma = usize::from(c_idx != 0);
1114 if dec.decode_bin(ctx::EXPLICIT_RDPCM_FLAG + chroma) != 0 {
1115 rdpcm = Some(dec.decode_bin(ctx::EXPLICIT_RDPCM_DIR + chroma) as u8);
1116 }
1117 }
1118 }
1119 Some(mode) => {
1120 if cfg.implicit_rdpcm && (transform_skip || cfg.bypass) && (mode == 10 || mode == 26) {
1121 rdpcm = Some(u8::from(mode == 26));
1122 }
1123 }
1124 }
1125 let sign_hiding = cfg.sign_hiding && !cfg.bypass && rdpcm.is_none();
1126 let ts_ctx_active = cfg.ts_context && (transform_skip || cfg.bypass);
1127 let sb_type = 2 * usize::from(c_idx == 0) + usize::from(transform_skip || cfg.bypass);
1128 let n = 1usize << log2_size;
1129 let sub_wide = n >> 2;
1130 let sub_scan = scan(log2_size - 2, scan_idx);
1131 let pos_scan = scan(2, scan_idx);
1132 let chroma = c_idx > 0;
1133
1134 let (offset, shift) = if c_idx == 0 {
1135 (
1136 3 * (log2_size - 2) + ((log2_size - 1) >> 2),
1137 (log2_size + 1) >> 2,
1138 )
1139 } else {
1140 (15, log2_size - 2)
1141 };
1142 let c_max = (log2_size << 1) - 1;
1143 let decode_prefix = |dec: &mut CabacDecoder, base: usize| -> u32 {
1144 let mut prefix = 0u32;
1145 while prefix < c_max {
1146 let ctx_idx = base + ((prefix >> shift) + offset) as usize;
1147 if dec.decode_bin(ctx_idx) == 0 {
1148 break;
1149 }
1150 prefix += 1;
1151 }
1152 prefix
1153 };
1154 let x_prefix = decode_prefix(dec, ctx::LAST_X);
1155 let y_prefix = decode_prefix(dec, ctx::LAST_Y);
1156 let decode_coord = |dec: &mut CabacDecoder, prefix: u32| -> u32 {
1157 if prefix < 4 {
1158 prefix
1159 } else {
1160 let suffix_bits = (prefix >> 1) - 1;
1161 let base = (1 << suffix_bits) * (2 + (prefix & 1));
1162 base + dec.decode_bypass_bits(suffix_bits)
1163 }
1164 };
1165 let mut last_x = decode_coord(dec, x_prefix);
1166 let mut last_y = decode_coord(dec, y_prefix);
1167 if scan_idx == 2 {
1168 std::mem::swap(&mut last_x, &mut last_y);
1169 }
1170 let (xs0, ys0) = (last_x as usize / 4, last_y as usize / 4);
1171 let last_sub = sub_scan
1172 .iter()
1173 .position(|&(a, b)| a as usize == xs0 && b as usize == ys0)
1174 .expect("last coordinate's sub-block is in the scan");
1175 let (xp0, yp0) = (last_x as usize % 4, last_y as usize % 4);
1176 let last_pos = pos_scan
1177 .iter()
1178 .position(|&(a, b)| a as usize == xp0 && b as usize == yp0)
1179 .expect("last coordinate's position is in the sub-block scan");
1180
1181 let mut csbf = [false; 64];
1182 let (dc_xs, dc_ys) = sub_scan[0];
1183 csbf[dc_ys as usize * sub_wide + dc_xs as usize] = true;
1184
1185 let mut greater1_ctx = 1u32;
1186 for i in (0..=last_sub).rev() {
1187 let (xs, ys) = sub_scan[i];
1188 let (xs, ys) = (xs as usize, ys as usize);
1189 let mut infer_dc_sig = false;
1190 let coded = if i == last_sub || i == 0 {
1191 true
1192 } else {
1193 let mut csbf_ctx = 0;
1194 if xs < sub_wide - 1 && csbf[ys * sub_wide + xs + 1] {
1195 csbf_ctx += 1;
1196 }
1197 if ys < sub_wide - 1 && csbf[(ys + 1) * sub_wide + xs] {
1198 csbf_ctx += 1;
1199 }
1200 let inc = if chroma {
1201 2 + csbf_ctx.min(1)
1202 } else {
1203 csbf_ctx.min(1)
1204 };
1205 infer_dc_sig = true;
1206 dec.decode_bin(ctx::CODED_SUB_BLOCK + inc) != 0
1207 };
1208 csbf[ys * sub_wide + xs] = coded;
1209 if !coded {
1210 continue;
1211 }
1212
1213 let mut significant = [false; 16];
1214 if i == last_sub {
1215 significant[last_pos] = true;
1216 }
1217 let first = if i == last_sub {
1218 last_pos as i32 - 1
1219 } else {
1220 15
1221 };
1222 let sig_base = sig_ctx_base(xs, ys, sub_wide, &csbf, log2_size, c_idx, scan_idx);
1223 let mut scan_pos = first;
1224 while scan_pos >= 0 {
1225 let p = scan_pos as usize;
1226 scan_pos -= 1;
1227 let (xp, yp) = pos_scan[p];
1228 let xc = xs * 4 + xp as usize;
1229 let yc = ys * 4 + yp as usize;
1230 let sig = if p > 0 || !infer_dc_sig {
1231 let inc = if ts_ctx_active {
1232 if c_idx == 0 { 42 } else { 43 }
1233 } else {
1234 sig_ctx_inc(xc, yc, log2_size, c_idx, sig_base)
1235 };
1236 dec.decode_bin(ctx::SIG_COEFF + inc) != 0
1237 } else {
1238 false // filled in by the post-loop inference below
1239 };
1240 significant[p] = sig;
1241 if sig {
1242 infer_dc_sig = false;
1243 }
1244 }
1245 if infer_dc_sig {
1246 significant[0] = true;
1247 }
1248
1249 let mut order = [0usize; 16];
1250 let mut order_len = 0;
1251 for p in (0..16).rev() {
1252 if significant[p] {
1253 order[order_len] = p;
1254 order_len += 1;
1255 }
1256 }
1257 let order = &order[..order_len];
1258 if order.is_empty() {
1259 continue;
1260 }
1261
1262 let mut ctx_set = if i == 0 || chroma { 0 } else { 2 };
1263 if greater1_ctx == 0 {
1264 ctx_set += 1;
1265 }
1266 greater1_ctx = 1;
1267 let mut last_greater1 = None;
1268 let mut greater1 = [false; 16];
1269 for &p in order.iter().take(8) {
1270 let inc = ctx_set * 4 + greater1_ctx.min(3) + if chroma { 16 } else { 0 };
1271 let flag = dec.decode_bin(ctx::GREATER1 + inc as usize) != 0;
1272 greater1[p] = flag;
1273 if flag {
1274 if last_greater1.is_none() {
1275 last_greater1 = Some(p);
1276 }
1277 greater1_ctx = 0;
1278 } else if greater1_ctx > 0 {
1279 greater1_ctx += 1;
1280 }
1281 }
1282
1283 let mut greater2 = false;
1284 if last_greater1.is_some() {
1285 let inc = ctx_set + if chroma { 4 } else { 0 };
1286 greater2 = dec.decode_bin(ctx::GREATER2 + inc as usize) != 0;
1287 }
1288
1289 let hidden = sign_hiding && order[0] - order[order_len - 1] > 3;
1290 let mut signs = [false; 16];
1291 for (k, &p) in order.iter().enumerate() {
1292 if hidden && k == order_len - 1 {
1293 continue;
1294 }
1295 signs[p] = dec.decode_bypass() != 0;
1296 }
1297
1298 let mut magnitude = [0u32; 16];
1299 let mut rice = if cfg.persistent_rice {
1300 u32::from(dec.contexts.stat_coeff[sb_type] / 4).min(MAX_RICE)
1301 } else {
1302 0
1303 };
1304 let mut first_remaining = true;
1305 for (num_sig, &p) in order.iter().enumerate() {
1306 let coded_greater1 = num_sig < 8;
1307 let mut level = 1
1308 + u32::from(coded_greater1 && greater1[p])
1309 + u32::from(last_greater1 == Some(p) && greater2);
1310 let threshold = if num_sig < 8 {
1311 if last_greater1 == Some(p) { 3 } else { 2 }
1312 } else {
1313 1
1314 };
1315 if level == threshold {
1316 let remaining = decode_remaining(dec, rice);
1317 if cfg.persistent_rice && first_remaining {
1318 let stat = &mut dec.contexts.stat_coeff[sb_type];
1319 if u64::from(remaining) >= (3u64 << (*stat / 4).min(40)) {
1320 *stat = stat.saturating_add(1);
1321 } else if 2 * u64::from(remaining) < (1u64 << (*stat / 4).min(40)) && *stat > 0
1322 {
1323 *stat -= 1;
1324 }
1325 }
1326 first_remaining = false;
1327 let grow = u32::from(u64::from(level + remaining) > (3u64 << rice));
1328 rice = if cfg.persistent_rice {
1329 (rice + grow).min(MAX_RICE)
1330 } else {
1331 (rice + grow).min(4)
1332 };
1333 level += remaining;
1334 }
1335 magnitude[p] = level;
1336 }
1337 if hidden {
1338 let last = order[order_len - 1];
1339 let sum: u32 = order.iter().map(|&p| magnitude[p]).sum();
1340 signs[last] = sum & 1 == 1;
1341 }
1342 for &p in order {
1343 let (xp, yp) = pos_scan[p];
1344 let (xc, yc) = (xs * 4 + xp as usize, ys * 4 + yp as usize);
1345 let value = magnitude[p] as i32;
1346 levels[yc * n + xc] = if signs[p] { -value } else { value };
1347 }
1348 }
1349 ResidualFlags {
1350 transform_skip,
1351 rdpcm,
1352 }
1353}
1354
1355/// `ctxInc` for `sig_coeff_flag` (9.3.4.2.5).
1356#[allow(clippy::too_many_arguments)]
1357/// Sub-block-invariant part of [`sig_ctx_inc`]'s context: `prev_csbf` and the
1358/// additive base both depend only on the sub-block's own coordinates
1359/// (`xs`/`ys`), never on the position within it, so a caller stepping through
1360/// up to 15 significant positions in one sub-block computes this once instead
1361/// of on every position. `None` when `log2_size == 2` (the small-block path
1362/// doesn't use `prev_csbf`/base at all — [`sig_ctx_inc`] handles it directly).
1363fn sig_ctx_base(
1364 xs: usize,
1365 ys: usize,
1366 sub_wide: usize,
1367 csbf: &[bool],
1368 log2_size: u32,
1369 c_idx: usize,
1370 scan_idx: usize,
1371) -> Option<(usize, usize)> {
1372 if log2_size == 2 {
1373 return None;
1374 }
1375 let mut prev_csbf = 0usize;
1376 if xs < sub_wide - 1 && csbf[ys * sub_wide + xs + 1] {
1377 prev_csbf += 1;
1378 }
1379 if ys < sub_wide - 1 && csbf[(ys + 1) * sub_wide + xs] {
1380 prev_csbf += 2;
1381 }
1382 let mut base = 0usize;
1383 if c_idx == 0 {
1384 if xs + ys > 0 {
1385 base += 3;
1386 }
1387 if log2_size == 3 {
1388 base += if scan_idx == 0 { 9 } else { 15 };
1389 } else {
1390 base += 21;
1391 }
1392 } else if log2_size == 3 {
1393 base += 9;
1394 } else {
1395 base += 12;
1396 }
1397 if c_idx != 0 {
1398 base += 27;
1399 }
1400 Some((prev_csbf, base))
1401}
1402
1403fn sig_ctx_inc(
1404 xc: usize,
1405 yc: usize,
1406 log2_size: u32,
1407 c_idx: usize,
1408 base: Option<(usize, usize)>,
1409) -> usize {
1410 let sig_ctx = if log2_size == 2 {
1411 CTX_IDX_MAP[(yc << 2) + xc]
1412 } else if xc + yc == 0 {
1413 0
1414 } else {
1415 let (prev_csbf, base) = base.expect("sig_ctx_base returns Some when log2_size != 2");
1416 let (xp, yp) = (xc & 3, yc & 3);
1417 let ctx = match prev_csbf {
1418 0 => {
1419 if xp + yp == 0 {
1420 2
1421 } else if xp + yp < 3 {
1422 1
1423 } else {
1424 0
1425 }
1426 }
1427 1 => {
1428 if yp == 0 {
1429 2
1430 } else if yp == 1 {
1431 1
1432 } else {
1433 0
1434 }
1435 }
1436 2 => {
1437 if xp == 0 {
1438 2
1439 } else if xp == 1 {
1440 1
1441 } else {
1442 0
1443 }
1444 }
1445 _ => 2,
1446 };
1447 return ctx + base;
1448 };
1449 if c_idx == 0 { sig_ctx } else { 27 + sig_ctx }
1450}
1451
1452#[cfg(test)]
1453mod tests {
1454 use super::*;
1455 use crate::cabac::Contexts;
1456
1457 #[test]
1458 fn diagonal_scan_matches_the_spec_walk() {
1459 // 4x4 up-right diagonal, from 6.5.3.
1460 let expect: Vec<(u8, u8)> = vec![
1461 (0, 0),
1462 (0, 1),
1463 (1, 0),
1464 (0, 2),
1465 (1, 1),
1466 (2, 0),
1467 (0, 3),
1468 (1, 2),
1469 (2, 1),
1470 (3, 0),
1471 (1, 3),
1472 (2, 2),
1473 (3, 1),
1474 (2, 3),
1475 (3, 2),
1476 (3, 3),
1477 ];
1478 assert_eq!(scan(2, 0), &expect[..]);
1479 // Horizontal and vertical are the plain raster orders.
1480 assert_eq!(scan(2, 1)[..4], [(0, 0), (1, 0), (2, 0), (3, 0)]);
1481 assert_eq!(scan(2, 2)[..4], [(0, 0), (0, 1), (0, 2), (0, 3)]);
1482 // Every size is a permutation of its block.
1483 for log2 in 0..4u32 {
1484 for idx in 0..3 {
1485 let s = scan(log2, idx);
1486 let size = 1usize << log2;
1487 assert_eq!(s.len(), size * size);
1488 let mut seen = vec![false; size * size];
1489 for &(x, y) in s {
1490 let slot = y as usize * size + x as usize;
1491 assert!(!seen[slot]);
1492 seen[slot] = true;
1493 }
1494 }
1495 }
1496 }
1497
1498 #[test]
1499 fn last_position_binarization_inverts_the_spec_formula() {
1500 for coord in 0..32u32 {
1501 let (prefix, suffix_bits) = last_prefix(coord);
1502 let decoded = if suffix_bits == 0 {
1503 prefix
1504 } else {
1505 let base = (1 << ((prefix >> 1) - 1)) * (2 + (prefix & 1));
1506 let suffix = coord - base;
1507 assert!(suffix < (1 << suffix_bits), "coord {coord}");
1508 base + suffix
1509 };
1510 assert_eq!(decoded, coord);
1511 assert!(prefix <= 9, "coord {coord} prefix {prefix}");
1512 }
1513 }
1514
1515 #[test]
1516 fn residual_coding_costs_less_for_sparser_blocks() {
1517 // Not a bit-exactness check — that is the the oracle conformance test — but
1518 // the invariant that makes rate-distortion decisions meaningful: fewer
1519 // and smaller levels must cost fewer bits.
1520 let mut sparse = vec![0i32; 64];
1521 sparse[0] = 1;
1522 let mut dense = vec![0i32; 64];
1523 for (i, v) in dense.iter_mut().enumerate() {
1524 *v = ((i % 7) as i32) - 3;
1525 }
1526 let mut costs = Vec::new();
1527 for levels in [&sparse, &dense] {
1528 let mut enc = CabacEncoder::counter(Contexts::new(30));
1529 encode_residual(&mut enc, levels, 3, 0, 0, false, None);
1530 costs.push(enc.bit_count());
1531 }
1532 assert!(costs[0] < costs[1], "{costs:?}");
1533 assert!(costs[0] > 0);
1534 }
1535
1536 #[test]
1537 fn decode_residual_inverts_encode_residual() {
1538 use crate::cabac::CabacDecoder;
1539 for log2 in 2..=5u32 {
1540 let n = 1usize << log2;
1541 for scan_idx in 0..3 {
1542 for c_idx in [0usize, 1] {
1543 for sign_hiding in [false, true] {
1544 let mut levels = vec![0i32; n * n];
1545 for (i, v) in levels.iter_mut().enumerate() {
1546 *v = match i % 11 {
1547 0 => 0,
1548 1 => 1,
1549 2 => -2,
1550 3 => 3,
1551 4 => -17,
1552 5 => 400,
1553 6 => -1,
1554 _ => 0,
1555 };
1556 }
1557 if sign_hiding {
1558 let coeffs = levels.clone();
1559 hide_signs(&coeffs, &mut levels, n, 27, scan_idx);
1560 }
1561 let mut enc = CabacEncoder::new(Contexts::new(27));
1562 encode_residual(
1563 &mut enc,
1564 &levels,
1565 log2,
1566 c_idx,
1567 scan_idx,
1568 sign_hiding,
1569 None,
1570 );
1571 enc.encode_terminate(1);
1572 let bytes = enc.finish();
1573
1574 let mut dec = CabacDecoder::new(&bytes, Contexts::new(27));
1575 let mut decoded = vec![0i32; n * n];
1576 decode_residual(
1577 &mut dec,
1578 &mut decoded,
1579 log2,
1580 c_idx,
1581 scan_idx,
1582 sign_hiding,
1583 false,
1584 );
1585 assert_eq!(dec.decode_terminate(), 1);
1586 assert_eq!(
1587 decoded, levels,
1588 "log2={log2} scan={scan_idx} c_idx={c_idx} sign_hiding={sign_hiding}"
1589 );
1590 }
1591 }
1592 }
1593 }
1594 }
1595
1596 #[test]
1597 fn every_block_size_and_scan_codes_without_panicking() {
1598 for log2 in 2..=5u32 {
1599 let n = 1usize << log2;
1600 for scan_idx in 0..3 {
1601 for c_idx in [0usize, 1] {
1602 let mut levels = vec![0i32; n * n];
1603 for (i, v) in levels.iter_mut().enumerate() {
1604 *v = match i % 11 {
1605 0 => 0,
1606 1 => 1,
1607 2 => -2,
1608 3 => 3,
1609 4 => -17,
1610 5 => 400,
1611 _ => 0,
1612 };
1613 }
1614 let mut enc = CabacEncoder::counter(Contexts::new(27));
1615 encode_residual(&mut enc, &levels, log2, c_idx, scan_idx, false, None);
1616 assert!(enc.bit_count() > 0);
1617 }
1618 }
1619 }
1620 }
1621
1622 /// [`rdoq`], but every trial re-derives the whole block's bits from `base`
1623 /// (the pre-change behaviour) instead of using the sub-block frozen-prefix
1624 /// cursor. Kept only for
1625 /// [`sub_block_cursor_matches_full_recompute`] to check the cursor against.
1626 #[allow(clippy::too_many_arguments)]
1627 fn rdoq_full_recompute(
1628 coeffs: &[i32],
1629 levels: &mut [i32],
1630 n: usize,
1631 qp: i32,
1632 bit_depth: u32,
1633 c_idx: usize,
1634 scan_idx: usize,
1635 cbf_ctx: usize,
1636 lambda: f64,
1637 transform_skip: Option<bool>,
1638 enc: &mut CabacEncoder,
1639 ) -> usize {
1640 let log2_size = n.trailing_zeros();
1641 let scale = coeff_ssd_scale(n);
1642 let lambda = RDOQ_LAMBDA * lambda;
1643 let base = enc.snapshot();
1644 let err = |level: i32, coeff: i32| {
1645 let d = f64::from(dequant_level_bd(level, n, qp, bit_depth) - coeff);
1646 d * d
1647 };
1648
1649 let mut dist: f64 = (0..n * n).map(|i| err(levels[i], coeffs[i])).sum();
1650 let bits = levels_bits(
1651 enc,
1652 &base,
1653 levels,
1654 log2_size,
1655 c_idx,
1656 scan_idx,
1657 cbf_ctx,
1658 true,
1659 transform_skip,
1660 );
1661 let mut cost = scale * dist + lambda * bits;
1662
1663 let sub_scan = scan(log2_size - 2, scan_idx);
1664 let pos_scan = scan(2, scan_idx);
1665 let order: Vec<usize> = sub_scan
1666 .iter()
1667 .flat_map(|&(xs, ys)| {
1668 pos_scan.iter().map(move |&(xp, yp)| {
1669 (ys as usize * 4 + yp as usize) * n + xs as usize * 4 + xp as usize
1670 })
1671 })
1672 .collect();
1673
1674 let sub_wide = n >> 2;
1675 let mut csbf = [false; 64];
1676 let mut sub_count = [0i32; 64];
1677 let mut nz_positions: Vec<i32> = Vec::new();
1678 for (k, &i) in order.iter().enumerate().rev() {
1679 if levels[i] != 0 {
1680 nz_positions.push(k as i32);
1681 let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2);
1682 sub_count[sub_idx] += 1;
1683 csbf[sub_idx] = true;
1684 }
1685 }
1686 let mut cur_last = nz_positions.first().copied().unwrap_or(0);
1687 let mut nz_idx = 0usize;
1688
1689 for (k, &i) in order.iter().enumerate().rev() {
1690 let level = levels[i];
1691 if level == 0 {
1692 continue;
1693 }
1694 let next_last = nz_positions.get(nz_idx + 1).copied().unwrap_or(0);
1695 nz_idx += 1;
1696 if level.abs() > RDOQ_MAX_LEVEL {
1697 continue;
1698 }
1699 let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2);
1700 let mut tried = level.abs();
1701 for candidate in [level.abs() - 1, 0] {
1702 if candidate == tried {
1703 continue;
1704 }
1705 tried = candidate;
1706 let keep = levels[i];
1707 levels[i] = candidate * level.signum();
1708 let now_zero = levels[i] == 0;
1709 let sub_count_before = sub_count[sub_idx];
1710 let csbf_before = csbf[sub_idx];
1711 if now_zero {
1712 sub_count[sub_idx] -= 1;
1713 csbf[sub_idx] = sub_count[sub_idx] > 0;
1714 }
1715 let trial_last = if now_zero && k as i32 == cur_last {
1716 next_last
1717 } else {
1718 cur_last
1719 };
1720 let trial_dist = dist - err(keep, coeffs[i]) + err(levels[i], coeffs[i]);
1721 let any = sub_count.iter().any(|&c| c > 0);
1722 let trial_bits = levels_bits_with(
1723 enc,
1724 &base,
1725 levels,
1726 log2_size,
1727 c_idx,
1728 scan_idx,
1729 cbf_ctx,
1730 any,
1731 transform_skip,
1732 trial_last,
1733 csbf,
1734 );
1735 let trial = scale * trial_dist + lambda * trial_bits;
1736 if trial < cost {
1737 cost = trial;
1738 dist = trial_dist;
1739 if now_zero {
1740 cur_last = trial_last;
1741 }
1742 } else {
1743 levels[i] = keep;
1744 sub_count[sub_idx] = sub_count_before;
1745 csbf[sub_idx] = csbf_before;
1746 }
1747 }
1748 }
1749 let zero_dist: f64 = (0..n * n).map(|i| err(0, coeffs[i])).sum();
1750 let zero_bits = levels_bits(
1751 enc,
1752 &base,
1753 levels,
1754 log2_size,
1755 c_idx,
1756 scan_idx,
1757 cbf_ctx,
1758 false,
1759 transform_skip,
1760 );
1761 if scale * zero_dist + lambda * zero_bits <= cost {
1762 levels[..n * n].fill(0);
1763 enc.restore(&base);
1764 return 0;
1765 }
1766 enc.restore(&base);
1767 levels[..n * n].iter().filter(|&&l| l != 0).count()
1768 }
1769
1770 /// A tiny xorshift RNG — deterministic across runs, no extra dependency.
1771 struct Xorshift(u32);
1772 impl Xorshift {
1773 fn next(&mut self) -> u32 {
1774 self.0 ^= self.0 << 13;
1775 self.0 ^= self.0 >> 17;
1776 self.0 ^= self.0 << 5;
1777 self.0
1778 }
1779 }
1780
1781 /// ENTRY GATE for lane-h265rdoq r3: the sub-block frozen-prefix cursor
1782 /// [`rdoq`] now uses must produce bit-for-bit the same trial decisions —
1783 /// and so the same final `levels` and the same final bitstream — as
1784 /// always re-deriving every trial's bits from the block's start
1785 /// ([`rdoq_full_recompute`], this round's pre-change behaviour). Covers
1786 /// every block size with a sub-block split (8/16/32 — 4x4 has none),
1787 /// every scan, 8 seeds, sign-hiding on/off on the final bitstream, and
1788 /// deliberately includes levels of magnitude 1-3 so some trials drop the
1789 /// last significant coefficient, some empty a whole sub-block (csbf
1790 /// flips), and some sit right at the greater1/greater2 escape boundary.
1791 #[test]
1792 fn sub_block_cursor_matches_full_recompute() {
1793 for log2 in [3u32, 4, 5] {
1794 let n = 1usize << log2;
1795 for scan_idx in 0..3 {
1796 for seed in 1..=8u32 {
1797 let mut rng = Xorshift(seed.wrapping_mul(2654435761).max(1));
1798 let mut coeffs = vec![0i32; n * n];
1799 for c in coeffs.iter_mut() {
1800 // Skewed toward small magnitudes (0..=3) so RDOQ_MAX_LEVEL's
1801 // trial window and the greater1/greater2 boundary both fire
1802 // often, with occasional larger outliers left untouched.
1803 let r = rng.next();
1804 *c = match r % 5 {
1805 0 => 0,
1806 1 => (r >> 8) as i32 % 2 + 1,
1807 2 => -(((r >> 8) as i32 % 2) + 1),
1808 3 => (r >> 8) as i32 % 6 + 1,
1809 _ => -(((r >> 8) as i32 % 6) + 1),
1810 };
1811 }
1812 let qp = 20 + (seed as i32 % 20);
1813
1814 let mut levels_a = coeffs.clone();
1815 let mut enc_a = CabacEncoder::counter(Contexts::new(30));
1816 let count_a = rdoq(
1817 &coeffs,
1818 &mut levels_a,
1819 n,
1820 qp,
1821 8,
1822 0,
1823 scan_idx,
1824 ctx::CBF_LUMA,
1825 1.0,
1826 None,
1827 &mut enc_a,
1828 );
1829
1830 let mut levels_b = coeffs.clone();
1831 let mut enc_b = CabacEncoder::counter(Contexts::new(30));
1832 let count_b = rdoq_full_recompute(
1833 &coeffs,
1834 &mut levels_b,
1835 n,
1836 qp,
1837 8,
1838 0,
1839 scan_idx,
1840 ctx::CBF_LUMA,
1841 1.0,
1842 None,
1843 &mut enc_b,
1844 );
1845
1846 assert_eq!(
1847 count_a, count_b,
1848 "log2={log2} scan={scan_idx} seed={seed}: non-zero count differs"
1849 );
1850 assert_eq!(
1851 levels_a, levels_b,
1852 "log2={log2} scan={scan_idx} seed={seed}: decided levels differ"
1853 );
1854
1855 if count_a == 0 {
1856 continue;
1857 }
1858 for sign_hiding in [false, true] {
1859 let mut final_levels = levels_a.clone();
1860 if sign_hiding {
1861 hide_signs(&coeffs, &mut final_levels, n, 30, scan_idx);
1862 }
1863 let mut fenc = CabacEncoder::counter(Contexts::new(30));
1864 encode_residual(
1865 &mut fenc,
1866 &final_levels,
1867 log2,
1868 0,
1869 scan_idx,
1870 sign_hiding,
1871 None,
1872 );
1873 assert!(fenc.bit_count() > 0);
1874 }
1875 }
1876 }
1877 }
1878 }
1879}