forge
Explore
Log in

Don't you dare go Hollow

Hoist rdoq's per-trial csbf/last_full rescan into incremental state

Browse files at this commit

3a8dac332570c668b1ecfb00e6909dbd5b079a3dAhmet Kaan GümüşParent: 45dd615
  • perf
    • hoist rdoq's per-trial csbf/last_full rescan into incremental state
Show full message
perf(h265): hoist rdoq's per-trial csbf/last_full rescan into incremental state

encode_residual rescanned the whole block for its coded-sub-block flags and
last significant position on every rate-distortion trial, even though a
trial only ever changes one coefficient. rdoq() now maintains that header
state (a per-sub-block nonzero count plus a lookahead into the still-
untouched lower scan positions for the one case where the last position
itself moves) and feeds it straight to a new encode_residual_with, instead
of re-deriving it from levels each call. Bit-identical output verified by
hashing two natural-content streams before/after (1920x1080 and 416x240);
measured -1.1% cycles / -1.4% instructions on a 1080p bench frame under
perf stat — real but modest, since encode_residual's own CABAC coding
(not this header scan) is the dominant cost per r1's structure notes.
crates/ec-h265/src/residual.rsmodified+140 -18
@@ -308,6 +308,42 @@ fn levels_bits(
308308 enc.bit_count() - before
309309 }
310310
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)]
315+fn 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: bool,
325+ last_full: i32,
326+ csbf: [bool; 64],
327+) -> u64 {
328+ enc.restore(base);
329+ let before = enc.bit_count();
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() - before
345+}
346+
311347 /// Rate-distortion quantisation of one transform block: each small level is
312348 /// offered the magnitudes below it, and takes one when the squared error it
313349 /// gives up costs less than the bits it saves.
@@ -369,11 +405,41 @@ pub fn rdoq(
369405 })
370406 })
371407 .collect();
372- for &i in order.iter().rev() {
408+
409+ // The header state `encode_residual` would otherwise rescan the whole
410+ // block for on every trial, maintained incrementally instead: a trial
411+ // only ever changes one coefficient. `nz_positions` lists the positions
412+ // that started non-zero, in the same descending scan order this loop
413+ // visits them in, so "what becomes the new last position if this one
414+ // empties" (the one hazard: the last position moves when its own
415+ // coefficient is dropped) is a lookahead into the still-untouched region
416+ // below, not a rescan.
417+ let sub_wide = n >> 2;
418+ let mut csbf = [false; 64];
419+ let mut sub_count = [0i32; 64];
420+ let mut nz_positions: Vec<i32> = Vec::new();
421+ for (k, &i) in order.iter().enumerate().rev() {
422+ if levels[i] != 0 {
423+ nz_positions.push(k as i32);
424+ let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2);
425+ sub_count[sub_idx] += 1;
426+ csbf[sub_idx] = true;
427+ }
428+ }
429+ let mut cur_last = nz_positions.first().copied().unwrap_or(0);
430+ let mut nz_idx = 0usize;
431+
432+ for (k, &i) in order.iter().enumerate().rev() {
373433 let level = levels[i];
374- if level == 0 || level.abs() > RDOQ_MAX_LEVEL {
434+ if level == 0 {
375435 continue;
376436 }
437+ let next_last = nz_positions.get(nz_idx + 1).copied().unwrap_or(0);
438+ nz_idx += 1;
439+ if level.abs() > RDOQ_MAX_LEVEL {
440+ continue;
441+ }
442+ let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2);
377443 let mut tried = level.abs();
378444 for candidate in [level.abs() - 1, 0] {
379445 if candidate == tried {
@@ -382,9 +448,21 @@ pub fn rdoq(
382448 tried = candidate;
383449 let keep = levels[i];
384450 levels[i] = candidate * level.signum();
451+ let now_zero = levels[i] == 0;
452+ let sub_count_before = sub_count[sub_idx];
453+ let csbf_before = csbf[sub_idx];
454+ if now_zero {
455+ sub_count[sub_idx] -= 1;
456+ csbf[sub_idx] = sub_count[sub_idx] > 0;
457+ }
458+ let trial_last = if now_zero && k as i32 == cur_last {
459+ next_last
460+ } else {
461+ cur_last
462+ };
385463 let trial_dist = dist - err(keep, coeffs[i]) + err(levels[i], coeffs[i]);
386- let any = levels[..n * n].iter().any(|&l| l != 0);
387- let trial_bits = levels_bits(
464+ let any = sub_count.iter().any(|&c| c > 0);
465+ let trial_bits = levels_bits_with(
388466 enc,
389467 &base,
390468 levels,
@@ -394,13 +472,20 @@ pub fn rdoq(
394472 cbf_ctx,
395473 any,
396474 transform_skip,
475+ trial_last,
476+ csbf,
397477 );
398478 let trial = scale * trial_dist + lambda * trial_bits as f64;
399479 if trial < cost {
400480 cost = trial;
401481 dist = trial_dist;
482+ if now_zero {
483+ cur_last = trial_last;
484+ }
402485 } else {
403486 levels[i] = keep;
487+ sub_count[sub_idx] = sub_count_before;
488+ csbf[sub_idx] = csbf_before;
404489 }
405490 }
406491 }
@@ -427,6 +512,29 @@ pub fn rdoq(
427512 levels[..n * n].iter().filter(|&&l| l != 0).count()
428513 }
429514
515+/// The coded-sub-block flags and last significant scan position that
516+/// [`encode_residual`] needs, found by one pass over `levels` — the state
517+/// [`rdoq`] maintains incrementally instead, since a trial only ever changes
518+/// one coefficient and re-deriving this from scratch is what made the search
519+/// quadratic in the block size per trial.
520+fn residual_header(levels: &[i32], log2_size: u32, scan_idx: usize) -> (i32, [bool; 64]) {
521+ let n = 1usize << log2_size;
522+ let sub_wide = n >> 2;
523+ let positions = &POSITIONS[(log2_size - 2) as usize][scan_idx];
524+ let mut csbf = [false; 64];
525+ let mut last_full = 0i32;
526+ for yc in 0..n {
527+ let row = &levels[yc * n..yc * n + n];
528+ for (xc, &level) in row.iter().enumerate() {
529+ if level != 0 {
530+ csbf[(yc >> 2) * sub_wide + (xc >> 2)] = true;
531+ last_full = last_full.max(i32::from(positions[yc * n + xc]));
532+ }
533+ }
534+ }
535+ (last_full, csbf)
536+}
537+
430538 /// Encode one transform block's levels.
431539 ///
432540 /// `levels` is row-major `n x n` with `levels[y * n + x]`, `c_idx` is 0 for luma
@@ -440,6 +548,34 @@ pub fn encode_residual(
440548 scan_idx: usize,
441549 sign_hiding: bool,
442550 transform_skip: bool,
551+) {
552+ let (last_full, csbf) = residual_header(levels, log2_size, scan_idx);
553+ encode_residual_with(
554+ enc,
555+ levels,
556+ log2_size,
557+ c_idx,
558+ scan_idx,
559+ sign_hiding,
560+ transform_skip,
561+ last_full,
562+ csbf,
563+ );
564+}
565+
566+/// [`encode_residual`], given the header state ([`residual_header`]'s output)
567+/// instead of deriving it from `levels`.
568+#[allow(clippy::too_many_arguments)]
569+fn encode_residual_with(
570+ enc: &mut CabacEncoder,
571+ levels: &[i32],
572+ log2_size: u32,
573+ c_idx: usize,
574+ scan_idx: usize,
575+ sign_hiding: bool,
576+ transform_skip: bool,
577+ last_full: i32,
578+ mut csbf: [bool; 64],
443579 ) {
444580 if transform_skip && log2_size == 2 {
445581 let ctx_idx = ctx::TRANSFORM_SKIP + if c_idx == 0 { 0 } else { 1 };
@@ -451,20 +587,6 @@ pub fn encode_residual(
451587 let pos_scan = scan(2, scan_idx);
452588 let chroma = c_idx > 0;
453589
454- // One pass over the levels finds both the end of the scan and which
455- // sub-blocks hold anything.
456- let positions = &POSITIONS[(log2_size - 2) as usize][scan_idx];
457- let mut csbf = [false; 64];
458- let mut last_full = 0i32;
459- for yc in 0..n {
460- let row = &levels[yc * n..yc * n + n];
461- for (xc, &level) in row.iter().enumerate() {
462- if level != 0 {
463- csbf[(yc >> 2) * sub_wide + (xc >> 2)] = true;
464- last_full = last_full.max(i32::from(positions[yc * n + xc]));
465- }
466- }
467- }
468590 let last_sub = (last_full / 16) as usize;
469591 let last_pos = (last_full % 16) as usize;
470592 let (last_xs, last_ys) = sub_scan[last_sub];