forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-h265rdoq' (r3): frozen-prefix cursor for RDOQ trials

Browse files at this commit

35539ec302aa93fc84f3d45e05523b7660bad5c9Ahmet Kaan GümüşParent: 8dd1aae4c5b62b
Bit-identical (entry-gate equality test + stream hashes at two sizes),
-2.45% instructions. Bookkeeping-only caching is now exhausted; the
remaining RDOQ cost is the bin coding itself.
crates/ec-h265/src/residual.rsmodified+572 -147
@@ -373,6 +373,7 @@ pub fn rdoq(
373373 let scale = coeff_ssd_scale(n);
374374 let lambda = RDOQ_LAMBDA * lambda;
375375 let base = enc.snapshot();
376+ let base_bits = enc.bit_count();
376377 let err = |level: i32, coeff: i32| {
377378 let d = f64::from(dequant_level(level, n, qp) - coeff);
378379 d * d
@@ -397,6 +398,10 @@ pub fn rdoq(
397398 // it is tried while the levels above it are already gone.
398399 let sub_scan = scan(log2_size - 2, scan_idx);
399400 let pos_scan = scan(2, scan_idx);
401+ // Sub-block index in *scan* order (what the encoder's own sub-block loop
402+ // is indexed by) for a flat row-major position — distinct from `sub_idx`
403+ // below, which is the *raster* sub-block index `csbf`/`sub_count` use.
404+ let positions = &POSITIONS[(log2_size - 2) as usize][scan_idx];
400405 let order: Vec<usize> = sub_scan
401406 .iter()
402407 .flat_map(|&(xs, ys)| {
@@ -428,6 +433,23 @@ pub fn rdoq(
428433 }
429434 let mut cur_last = nz_positions.first().copied().unwrap_or(0);
430435 let mut nz_idx = 0usize;
436+ let (dc_xs, dc_ys) = sub_scan[0];
437+ let dc_idx = dc_ys as usize * sub_wide + dc_xs as usize;
438+
439+ // Sub-block frozen-prefix cache: `cursor` holds the CABAC state right
440+ // before encoding sub-block `cursor.2`, plus the `greater1_ctx` carry the
441+ // sub-block above it left behind. Every trial that neither moves the last
442+ // significant position nor touches a sub-block above the cursor can
443+ // restore from it and re-encode only `sub_idx..=0` — the sub-blocks above
444+ // are already committed to the bitstream and, since `csbf` and
445+ // `greater1_ctx` only ever flow from a higher-index sub-block to a lower
446+ // one (never the reverse — 9.3.4.2.6's `greater1_ctx` carry and the
447+ // coded-sub-block-flag neighbour lookups both read only already-visited
448+ // neighbours), their bits cannot change. `cursor` is invalidated (`None`)
449+ // whenever `cur_last` moves, since that changes the header and `last_sub`
450+ // themselves.
451+ let mut cursor: Option<(CabacState, u32, usize)> = None;
452+ let mut cursor_last = cur_last;
431453
432454 for (k, &i) in order.iter().enumerate().rev() {
433455 let level = levels[i];
@@ -440,6 +462,7 @@ pub fn rdoq(
440462 continue;
441463 }
442464 let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2);
465+ let scan_sub = (positions[i] as usize) / 16;
443466 let mut tried = level.abs();
444467 for candidate in [level.abs() - 1, 0] {
445468 if candidate == tried {
@@ -455,26 +478,80 @@ pub fn rdoq(
455478 sub_count[sub_idx] -= 1;
456479 csbf[sub_idx] = sub_count[sub_idx] > 0;
457480 }
458- let trial_last = if now_zero && k as i32 == cur_last {
459- next_last
460- } else {
461- cur_last
462- };
481+ let moves_last = now_zero && k as i32 == cur_last;
482+ let trial_last = if moves_last { next_last } else { cur_last };
463483 let trial_dist = dist - err(keep, coeffs[i]) + err(levels[i], coeffs[i]);
464484 let any = sub_count.iter().any(|&c| c > 0);
465- let trial_bits = levels_bits_with(
466- enc,
467- &base,
468- levels,
469- log2_size,
470- c_idx,
471- scan_idx,
472- cbf_ctx,
473- any,
474- transform_skip,
475- trial_last,
476- csbf,
477- );
485+
486+ let trial_bits = if moves_last {
487+ // The last position itself moves: the header changes, so
488+ // there is no shortcut — re-derive the whole block from
489+ // `base`, same as before this round.
490+ levels_bits_with(
491+ enc,
492+ &base,
493+ levels,
494+ log2_size,
495+ c_idx,
496+ scan_idx,
497+ cbf_ctx,
498+ any,
499+ transform_skip,
500+ trial_last,
501+ csbf,
502+ )
503+ } else {
504+ if cursor_last != cur_last {
505+ cursor = None;
506+ cursor_last = cur_last;
507+ }
508+ let last_sub_now = (cur_last as usize) / 16;
509+ let last_pos_now = (cur_last as usize) % 16;
510+ let (mut cur_state, mut g1, mut at) = cursor.take().unwrap_or_else(|| {
511+ enc.restore(&base);
512+ enc.encode_bin(cbf_ctx, 1);
513+ encode_last_position(enc, log2_size, c_idx, scan_idx, cur_last);
514+ (enc.snapshot(), 1u32, last_sub_now)
515+ });
516+ let mut csbf_forced = csbf;
517+ csbf_forced[dc_idx] = true;
518+ if at > scan_sub {
519+ enc.restore(&cur_state);
520+ while at > scan_sub {
521+ g1 = encode_subblock(
522+ enc,
523+ levels,
524+ n,
525+ c_idx,
526+ scan_idx,
527+ false,
528+ at,
529+ last_sub_now,
530+ last_pos_now,
531+ &csbf_forced,
532+ g1,
533+ );
534+ at -= 1;
535+ }
536+ cur_state = enc.snapshot();
537+ }
538+ cursor = Some((cur_state.clone(), g1, at));
539+ enc.restore(&cur_state);
540+ encode_subblock_range(
541+ enc,
542+ levels,
543+ n,
544+ c_idx,
545+ scan_idx,
546+ false,
547+ last_sub_now,
548+ last_pos_now,
549+ scan_sub,
550+ g1,
551+ &csbf_forced,
552+ );
553+ enc.bit_count() - base_bits
554+ };
478555 let trial = scale * trial_dist + lambda * trial_bits as f64;
479556 if trial < cost {
480557 cost = trial;
@@ -584,9 +661,41 @@ fn encode_residual_with(
584661 let n = 1usize << log2_size;
585662 let sub_wide = n >> 2;
586663 let sub_scan = scan(log2_size - 2, scan_idx);
587- let pos_scan = scan(2, scan_idx);
588- let chroma = c_idx > 0;
664+ let (last_sub, last_pos) = encode_last_position(enc, log2_size, c_idx, scan_idx, last_full);
665+
666+ // The DC sub-block is always coded (7.4.9.11 inference).
667+ let (dc_xs, dc_ys) = sub_scan[0];
668+ csbf[dc_ys as usize * sub_wide + dc_xs as usize] = true;
669+
670+ encode_subblock_range(
671+ enc,
672+ levels,
673+ n,
674+ c_idx,
675+ scan_idx,
676+ sign_hiding,
677+ last_sub,
678+ last_pos,
679+ last_sub,
680+ 1,
681+ &csbf,
682+ );
683+}
589684
685+/// The `last_sig_coeff_x/y` syntax (9.3.4.2.3), given the flat scan position of
686+/// the last significant coefficient. Returns the sub-block and within-sub-block
687+/// position it decomposes into, since the sub-block loop is keyed by those —
688+/// split out so a sub-block-range re-encode (see [`encode_subblock_range`])
689+/// need not re-derive them.
690+fn encode_last_position(
691+ enc: &mut CabacEncoder,
692+ log2_size: u32,
693+ c_idx: usize,
694+ scan_idx: usize,
695+ last_full: i32,
696+) -> (usize, usize) {
697+ let sub_scan = scan(log2_size - 2, scan_idx);
698+ let pos_scan = scan(2, scan_idx);
590699 let last_sub = (last_full / 16) as usize;
591700 let last_pos = (last_full % 16) as usize;
592701 let (last_xs, last_ys) = sub_scan[last_sub];
@@ -625,151 +734,212 @@ fn encode_residual_with(
625734 let base = (1 << y_suffix_bits) * (2 + (y_prefix & 1));
626735 enc.encode_bypass_bits(last_y - base, y_suffix_bits);
627736 }
737+ (last_sub, last_pos)
738+}
628739
629- // The DC sub-block is always coded (7.4.9.11 inference).
630- let (dc_xs, dc_ys) = sub_scan[0];
631- csbf[dc_ys as usize * sub_wide + dc_xs as usize] = true;
740+/// Encode sub-blocks `from_sub` down to (and including) 0 — the tail of
741+/// [`encode_residual_with`]'s loop, split out so a trial that only changes a
742+/// coefficient inside `from_sub` can restore a cached frozen-prefix state (the
743+/// bits for sub-blocks above `from_sub` never change) instead of re-encoding
744+/// the whole block. `greater1_ctx_in` is the carry the sub-block above
745+/// `from_sub` left behind (1 when there is no such sub-block, matching
746+/// [`encode_residual_with`]'s own initial value).
747+#[allow(clippy::too_many_arguments)]
748+fn encode_subblock_range(
749+ enc: &mut CabacEncoder,
750+ levels: &[i32],
751+ n: usize,
752+ c_idx: usize,
753+ scan_idx: usize,
754+ sign_hiding: bool,
755+ last_sub: usize,
756+ last_pos: usize,
757+ from_sub: usize,
758+ greater1_ctx_in: u32,
759+ csbf: &[bool; 64],
760+) -> u32 {
761+ let mut greater1_ctx = greater1_ctx_in;
762+ for i in (0..=from_sub).rev() {
763+ greater1_ctx = encode_subblock(
764+ enc,
765+ levels,
766+ n,
767+ c_idx,
768+ scan_idx,
769+ sign_hiding,
770+ i,
771+ last_sub,
772+ last_pos,
773+ csbf,
774+ greater1_ctx,
775+ );
776+ }
777+ greater1_ctx
778+}
632779
633- let mut greater1_ctx = 1u32;
634- for i in (0..=last_sub).rev() {
635- let (xs, ys) = sub_scan[i];
636- let (xs, ys) = (xs as usize, ys as usize);
637- let coded = csbf[ys * sub_wide + xs];
638- let mut infer_dc_sig = false;
639- if i < last_sub && i > 0 {
640- let mut csbf_ctx = 0;
641- if xs < sub_wide - 1 && csbf[ys * sub_wide + xs + 1] {
642- csbf_ctx += 1;
643- }
644- if ys < sub_wide - 1 && csbf[(ys + 1) * sub_wide + xs] {
645- csbf_ctx += 1;
646- }
647- let inc = if chroma {
648- 2 + csbf_ctx.min(1)
649- } else {
650- csbf_ctx.min(1)
651- };
652- enc.encode_bin(ctx::CODED_SUB_BLOCK + inc, u32::from(coded));
653- infer_dc_sig = true;
654- }
655- if !coded {
656- continue;
657- }
780+/// One iteration of [`encode_residual_with`]'s sub-block loop, split out so
781+/// [`encode_subblock_range`] can drive it from a starting index other than
782+/// `last_sub`. Returns the `greater1_ctx` carry the *next* (lower-index)
783+/// sub-block reads.
784+#[allow(clippy::too_many_arguments)]
785+fn encode_subblock(
786+ enc: &mut CabacEncoder,
787+ levels: &[i32],
788+ n: usize,
789+ c_idx: usize,
790+ scan_idx: usize,
791+ sign_hiding: bool,
792+ i: usize,
793+ last_sub: usize,
794+ last_pos: usize,
795+ csbf: &[bool; 64],
796+ greater1_ctx_in: u32,
797+) -> u32 {
798+ let log2_size = n.trailing_zeros();
799+ let sub_wide = n >> 2;
800+ let sub_scan = scan(log2_size - 2, scan_idx);
801+ let pos_scan = scan(2, scan_idx);
802+ let chroma = c_idx > 0;
803+ let mut greater1_ctx = greater1_ctx_in;
658804
659- // sig_coeff_flag over the sub-block, high scan position first.
660- let mut significant = [false; 16];
661- if i == last_sub {
662- significant[last_pos] = true;
805+ let (xs, ys) = sub_scan[i];
806+ let (xs, ys) = (xs as usize, ys as usize);
807+ let coded = csbf[ys * sub_wide + xs];
808+ let mut infer_dc_sig = false;
809+ if i < last_sub && i > 0 {
810+ let mut csbf_ctx = 0;
811+ if xs < sub_wide - 1 && csbf[ys * sub_wide + xs + 1] {
812+ csbf_ctx += 1;
663813 }
664- let first = if i == last_sub {
665- last_pos as i32 - 1
814+ if ys < sub_wide - 1 && csbf[(ys + 1) * sub_wide + xs] {
815+ csbf_ctx += 1;
816+ }
817+ let inc = if chroma {
818+ 2 + csbf_ctx.min(1)
666819 } else {
667- 15
820+ csbf_ctx.min(1)
668821 };
669- let mut scan_pos = first;
670- while scan_pos >= 0 {
671- let p = scan_pos as usize;
672- scan_pos -= 1;
673- let (xp, yp) = pos_scan[p];
674- let xc = xs * 4 + xp as usize;
675- let yc = ys * 4 + yp as usize;
676- let sig = levels[yc * n + xc] != 0;
677- if p > 0 || !infer_dc_sig {
678- let inc = sig_ctx_inc(xc, yc, xs, ys, sub_wide, &csbf, log2_size, c_idx, scan_idx);
679- enc.encode_bin(ctx::SIG_COEFF + inc, u32::from(sig));
680- }
681- significant[p] = sig;
682- if sig {
683- infer_dc_sig = false;
684- }
685- }
686- if infer_dc_sig {
687- // The flag was not coded because it is inferred to be one.
688- significant[0] = true;
689- }
822+ enc.encode_bin(ctx::CODED_SUB_BLOCK + inc, u32::from(coded));
823+ infer_dc_sig = true;
824+ }
825+ if !coded {
826+ return greater1_ctx;
827+ }
690828
691- let mut order = [0usize; 16];
692- let mut order_len = 0;
693- for p in (0..16).rev() {
694- if significant[p] {
695- order[order_len] = p;
696- order_len += 1;
697- }
829+ // sig_coeff_flag over the sub-block, high scan position first.
830+ let mut significant = [false; 16];
831+ if i == last_sub {
832+ significant[last_pos] = true;
833+ }
834+ let first = if i == last_sub {
835+ last_pos as i32 - 1
836+ } else {
837+ 15
838+ };
839+ let mut scan_pos = first;
840+ while scan_pos >= 0 {
841+ let p = scan_pos as usize;
842+ scan_pos -= 1;
843+ let (xp, yp) = pos_scan[p];
844+ let xc = xs * 4 + xp as usize;
845+ let yc = ys * 4 + yp as usize;
846+ let sig = levels[yc * n + xc] != 0;
847+ if p > 0 || !infer_dc_sig {
848+ let inc = sig_ctx_inc(xc, yc, xs, ys, sub_wide, csbf, log2_size, c_idx, scan_idx);
849+ enc.encode_bin(ctx::SIG_COEFF + inc, u32::from(sig));
698850 }
699- let order = &order[..order_len];
700- if order.is_empty() {
701- continue;
851+ significant[p] = sig;
852+ if sig {
853+ infer_dc_sig = false;
702854 }
855+ }
856+ if infer_dc_sig {
857+ // The flag was not coded because it is inferred to be one.
858+ significant[0] = true;
859+ }
703860
704- // coeff_abs_level_greater1_flag, first eight only (9.3.4.2.6).
705- let mut ctx_set = if i == 0 || chroma { 0 } else { 2 };
706- if greater1_ctx == 0 {
707- ctx_set += 1;
861+ let mut order = [0usize; 16];
862+ let mut order_len = 0;
863+ for p in (0..16).rev() {
864+ if significant[p] {
865+ order[order_len] = p;
866+ order_len += 1;
708867 }
709- greater1_ctx = 1;
710- let mut last_greater1 = None;
711- let mut greater1 = [false; 16];
712- for &p in order.iter().take(8) {
713- let (xp, yp) = pos_scan[p];
714- let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
715- let flag = level > 1;
716- let inc = ctx_set * 4 + greater1_ctx.min(3) + if chroma { 16 } else { 0 };
717- enc.encode_bin(ctx::GREATER1 + inc as usize, u32::from(flag));
718- greater1[p] = flag;
719- if flag {
720- if last_greater1.is_none() {
721- last_greater1 = Some(p);
722- }
723- greater1_ctx = 0;
724- } else if greater1_ctx > 0 {
725- greater1_ctx += 1;
868+ }
869+ let order = &order[..order_len];
870+ if order.is_empty() {
871+ return greater1_ctx;
872+ }
873+
874+ // coeff_abs_level_greater1_flag, first eight only (9.3.4.2.6).
875+ let mut ctx_set = if i == 0 || chroma { 0 } else { 2 };
876+ if greater1_ctx == 0 {
877+ ctx_set += 1;
878+ }
879+ greater1_ctx = 1;
880+ let mut last_greater1 = None;
881+ let mut greater1 = [false; 16];
882+ for &p in order.iter().take(8) {
883+ let (xp, yp) = pos_scan[p];
884+ let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
885+ let flag = level > 1;
886+ let inc = ctx_set * 4 + greater1_ctx.min(3) + if chroma { 16 } else { 0 };
887+ enc.encode_bin(ctx::GREATER1 + inc as usize, u32::from(flag));
888+ greater1[p] = flag;
889+ if flag {
890+ if last_greater1.is_none() {
891+ last_greater1 = Some(p);
726892 }
893+ greater1_ctx = 0;
894+ } else if greater1_ctx > 0 {
895+ greater1_ctx += 1;
727896 }
897+ }
728898
729- // coeff_abs_level_greater2_flag for the first greater-than-one level.
730- let mut greater2 = false;
731- if let Some(p) = last_greater1 {
732- let (xp, yp) = pos_scan[p];
733- let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
734- greater2 = level > 2;
735- let inc = ctx_set + if chroma { 4 } else { 0 };
736- enc.encode_bin(ctx::GREATER2 + inc as usize, u32::from(greater2));
737- }
899+ // coeff_abs_level_greater2_flag for the first greater-than-one level.
900+ let mut greater2 = false;
901+ if let Some(p) = last_greater1 {
902+ let (xp, yp) = pos_scan[p];
903+ let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
904+ greater2 = level > 2;
905+ let inc = ctx_set + if chroma { 4 } else { 0 };
906+ enc.encode_bin(ctx::GREATER2 + inc as usize, u32::from(greater2));
907+ }
738908
739- // Signs, then the remaining magnitudes. With sign data hiding on and
740- // the significant coefficients of this sub-block more than three scan
741- // positions apart, the first one's sign is not coded at all: the
742- // decoder reads it off the parity of the sub-block's absolute levels,
743- // which `hide_signs` has already made match.
744- let hidden = sign_hiding && order[0] - order[order_len - 1] > 3;
745- for (k, &p) in order.iter().enumerate() {
746- if hidden && k == order_len - 1 {
747- continue;
748- }
749- let (xp, yp) = pos_scan[p];
750- let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize];
751- enc.encode_bypass(u32::from(level < 0));
909+ // Signs, then the remaining magnitudes. With sign data hiding on and
910+ // the significant coefficients of this sub-block more than three scan
911+ // positions apart, the first one's sign is not coded at all: the
912+ // decoder reads it off the parity of the sub-block's absolute levels,
913+ // which `hide_signs` has already made match.
914+ let hidden = sign_hiding && order[0] - order[order_len - 1] > 3;
915+ for (k, &p) in order.iter().enumerate() {
916+ if hidden && k == order_len - 1 {
917+ continue;
752918 }
753- let mut rice = 0u32;
754- for (num_sig, &p) in order.iter().enumerate() {
755- let (xp, yp) = pos_scan[p];
756- let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
757- let coded_greater1 = num_sig < 8;
758- let base_level = 1
759- + u32::from(coded_greater1 && greater1[p])
760- + u32::from(last_greater1 == Some(p) && greater2);
761- let threshold = if num_sig < 8 {
762- if last_greater1 == Some(p) { 3 } else { 2 }
763- } else {
764- 1
765- };
766- if base_level == threshold {
767- let remaining = level - base_level;
768- encode_remaining(enc, remaining, rice);
769- rice = (rice + u32::from(level > (3 << rice))).min(4);
770- }
919+ let (xp, yp) = pos_scan[p];
920+ let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize];
921+ enc.encode_bypass(u32::from(level < 0));
922+ }
923+ let mut rice = 0u32;
924+ for (num_sig, &p) in order.iter().enumerate() {
925+ let (xp, yp) = pos_scan[p];
926+ let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
927+ let coded_greater1 = num_sig < 8;
928+ let base_level = 1
929+ + u32::from(coded_greater1 && greater1[p])
930+ + u32::from(last_greater1 == Some(p) && greater2);
931+ let threshold = if num_sig < 8 {
932+ if last_greater1 == Some(p) { 3 } else { 2 }
933+ } else {
934+ 1
935+ };
936+ if base_level == threshold {
937+ let remaining = level - base_level;
938+ encode_remaining(enc, remaining, rice);
939+ rice = (rice + u32::from(level > (3 << rice))).min(4);
771940 }
772941 }
942+ greater1_ctx
773943 }
774944
775945 /// Inverse of [`encode_remaining`]: read one `coeff_abs_level_remaining` back
@@ -1274,4 +1444,259 @@ mod tests {
12741444 }
12751445 }
12761446 }
1447+
1448+ /// [`rdoq`], but every trial re-derives the whole block's bits from `base`
1449+ /// (the pre-change behaviour) instead of using the sub-block frozen-prefix
1450+ /// cursor. Kept only for
1451+ /// [`sub_block_cursor_matches_full_recompute`] to check the cursor against.
1452+ #[allow(clippy::too_many_arguments)]
1453+ fn rdoq_full_recompute(
1454+ coeffs: &[i32],
1455+ levels: &mut [i32],
1456+ n: usize,
1457+ qp: i32,
1458+ c_idx: usize,
1459+ scan_idx: usize,
1460+ cbf_ctx: usize,
1461+ lambda: f64,
1462+ transform_skip: bool,
1463+ enc: &mut CabacEncoder,
1464+ ) -> usize {
1465+ let log2_size = n.trailing_zeros();
1466+ let scale = coeff_ssd_scale(n);
1467+ let lambda = RDOQ_LAMBDA * lambda;
1468+ let base = enc.snapshot();
1469+ let err = |level: i32, coeff: i32| {
1470+ let d = f64::from(dequant_level(level, n, qp) - coeff);
1471+ d * d
1472+ };
1473+
1474+ let mut dist: f64 = (0..n * n).map(|i| err(levels[i], coeffs[i])).sum();
1475+ let bits = levels_bits(
1476+ enc,
1477+ &base,
1478+ levels,
1479+ log2_size,
1480+ c_idx,
1481+ scan_idx,
1482+ cbf_ctx,
1483+ true,
1484+ transform_skip,
1485+ );
1486+ let mut cost = scale * dist + lambda * bits as f64;
1487+
1488+ let sub_scan = scan(log2_size - 2, scan_idx);
1489+ let pos_scan = scan(2, scan_idx);
1490+ let order: Vec<usize> = sub_scan
1491+ .iter()
1492+ .flat_map(|&(xs, ys)| {
1493+ pos_scan.iter().map(move |&(xp, yp)| {
1494+ (ys as usize * 4 + yp as usize) * n + xs as usize * 4 + xp as usize
1495+ })
1496+ })
1497+ .collect();
1498+
1499+ let sub_wide = n >> 2;
1500+ let mut csbf = [false; 64];
1501+ let mut sub_count = [0i32; 64];
1502+ let mut nz_positions: Vec<i32> = Vec::new();
1503+ for (k, &i) in order.iter().enumerate().rev() {
1504+ if levels[i] != 0 {
1505+ nz_positions.push(k as i32);
1506+ let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2);
1507+ sub_count[sub_idx] += 1;
1508+ csbf[sub_idx] = true;
1509+ }
1510+ }
1511+ let mut cur_last = nz_positions.first().copied().unwrap_or(0);
1512+ let mut nz_idx = 0usize;
1513+
1514+ for (k, &i) in order.iter().enumerate().rev() {
1515+ let level = levels[i];
1516+ if level == 0 {
1517+ continue;
1518+ }
1519+ let next_last = nz_positions.get(nz_idx + 1).copied().unwrap_or(0);
1520+ nz_idx += 1;
1521+ if level.abs() > RDOQ_MAX_LEVEL {
1522+ continue;
1523+ }
1524+ let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2);
1525+ let mut tried = level.abs();
1526+ for candidate in [level.abs() - 1, 0] {
1527+ if candidate == tried {
1528+ continue;
1529+ }
1530+ tried = candidate;
1531+ let keep = levels[i];
1532+ levels[i] = candidate * level.signum();
1533+ let now_zero = levels[i] == 0;
1534+ let sub_count_before = sub_count[sub_idx];
1535+ let csbf_before = csbf[sub_idx];
1536+ if now_zero {
1537+ sub_count[sub_idx] -= 1;
1538+ csbf[sub_idx] = sub_count[sub_idx] > 0;
1539+ }
1540+ let trial_last = if now_zero && k as i32 == cur_last {
1541+ next_last
1542+ } else {
1543+ cur_last
1544+ };
1545+ let trial_dist = dist - err(keep, coeffs[i]) + err(levels[i], coeffs[i]);
1546+ let any = sub_count.iter().any(|&c| c > 0);
1547+ let trial_bits = levels_bits_with(
1548+ enc,
1549+ &base,
1550+ levels,
1551+ log2_size,
1552+ c_idx,
1553+ scan_idx,
1554+ cbf_ctx,
1555+ any,
1556+ transform_skip,
1557+ trial_last,
1558+ csbf,
1559+ );
1560+ let trial = scale * trial_dist + lambda * trial_bits as f64;
1561+ if trial < cost {
1562+ cost = trial;
1563+ dist = trial_dist;
1564+ if now_zero {
1565+ cur_last = trial_last;
1566+ }
1567+ } else {
1568+ levels[i] = keep;
1569+ sub_count[sub_idx] = sub_count_before;
1570+ csbf[sub_idx] = csbf_before;
1571+ }
1572+ }
1573+ }
1574+ let zero_dist: f64 = (0..n * n).map(|i| err(0, coeffs[i])).sum();
1575+ let zero_bits = levels_bits(
1576+ enc,
1577+ &base,
1578+ levels,
1579+ log2_size,
1580+ c_idx,
1581+ scan_idx,
1582+ cbf_ctx,
1583+ false,
1584+ transform_skip,
1585+ );
1586+ if scale * zero_dist + lambda * zero_bits as f64 <= cost {
1587+ levels[..n * n].fill(0);
1588+ enc.restore(&base);
1589+ return 0;
1590+ }
1591+ enc.restore(&base);
1592+ levels[..n * n].iter().filter(|&&l| l != 0).count()
1593+ }
1594+
1595+ /// A tiny xorshift RNG — deterministic across runs, no extra dependency.
1596+ struct Xorshift(u32);
1597+ impl Xorshift {
1598+ fn next(&mut self) -> u32 {
1599+ self.0 ^= self.0 << 13;
1600+ self.0 ^= self.0 >> 17;
1601+ self.0 ^= self.0 << 5;
1602+ self.0
1603+ }
1604+ }
1605+
1606+ /// ENTRY GATE for lane-h265rdoq r3: the sub-block frozen-prefix cursor
1607+ /// [`rdoq`] now uses must produce bit-for-bit the same trial decisions —
1608+ /// and so the same final `levels` and the same final bitstream — as
1609+ /// always re-deriving every trial's bits from the block's start
1610+ /// ([`rdoq_full_recompute`], this round's pre-change behaviour). Covers
1611+ /// every block size with a sub-block split (8/16/32 — 4x4 has none),
1612+ /// every scan, 8 seeds, sign-hiding on/off on the final bitstream, and
1613+ /// deliberately includes levels of magnitude 1-3 so some trials drop the
1614+ /// last significant coefficient, some empty a whole sub-block (csbf
1615+ /// flips), and some sit right at the greater1/greater2 escape boundary.
1616+ #[test]
1617+ fn sub_block_cursor_matches_full_recompute() {
1618+ for log2 in [3u32, 4, 5] {
1619+ let n = 1usize << log2;
1620+ for scan_idx in 0..3 {
1621+ for seed in 1..=8u32 {
1622+ let mut rng = Xorshift(seed.wrapping_mul(2654435761).max(1));
1623+ let mut coeffs = vec![0i32; n * n];
1624+ for c in coeffs.iter_mut() {
1625+ // Skewed toward small magnitudes (0..=3) so RDOQ_MAX_LEVEL's
1626+ // trial window and the greater1/greater2 boundary both fire
1627+ // often, with occasional larger outliers left untouched.
1628+ let r = rng.next();
1629+ *c = match r % 5 {
1630+ 0 => 0,
1631+ 1 => (r >> 8) as i32 % 2 + 1,
1632+ 2 => -(((r >> 8) as i32 % 2) + 1),
1633+ 3 => (r >> 8) as i32 % 6 + 1,
1634+ _ => -(((r >> 8) as i32 % 6) + 1),
1635+ };
1636+ }
1637+ let qp = 20 + (seed as i32 % 20);
1638+
1639+ let mut levels_a = coeffs.clone();
1640+ let mut enc_a = CabacEncoder::counter(Contexts::new(30));
1641+ let count_a = rdoq(
1642+ &coeffs,
1643+ &mut levels_a,
1644+ n,
1645+ qp,
1646+ 0,
1647+ scan_idx,
1648+ ctx::CBF_LUMA,
1649+ 1.0,
1650+ false,
1651+ &mut enc_a,
1652+ );
1653+
1654+ let mut levels_b = coeffs.clone();
1655+ let mut enc_b = CabacEncoder::counter(Contexts::new(30));
1656+ let count_b = rdoq_full_recompute(
1657+ &coeffs,
1658+ &mut levels_b,
1659+ n,
1660+ qp,
1661+ 0,
1662+ scan_idx,
1663+ ctx::CBF_LUMA,
1664+ 1.0,
1665+ false,
1666+ &mut enc_b,
1667+ );
1668+
1669+ assert_eq!(
1670+ count_a, count_b,
1671+ "log2={log2} scan={scan_idx} seed={seed}: non-zero count differs"
1672+ );
1673+ assert_eq!(
1674+ levels_a, levels_b,
1675+ "log2={log2} scan={scan_idx} seed={seed}: decided levels differ"
1676+ );
1677+
1678+ if count_a == 0 {
1679+ continue;
1680+ }
1681+ for sign_hiding in [false, true] {
1682+ let mut final_levels = levels_a.clone();
1683+ if sign_hiding {
1684+ hide_signs(&coeffs, &mut final_levels, n, 30, scan_idx);
1685+ }
1686+ let mut fenc = CabacEncoder::counter(Contexts::new(30));
1687+ encode_residual(
1688+ &mut fenc,
1689+ &final_levels,
1690+ log2,
1691+ 0,
1692+ scan_idx,
1693+ sign_hiding,
1694+ false,
1695+ );
1696+ assert!(fenc.bit_count() > 0);
1697+ }
1698+ }
1699+ }
1700+ }
1701+ }
12771702 }
crates/ec-h265/tests/rdoq_cache_hash.rsadded+42 -0
@@ -0,0 +1,42 @@
1+//! lane-h265rdoq r3: the sub-block frozen-prefix cursor must not change a
2+//! single output byte. Hashes two natural-content encodes (1920x1080 and
3+//! 416x240) with FNV-1a; the number itself means nothing, only that it is the
4+//! same before and after this round's change to `rdoq()` (checked by hand:
5+//! stash `residual.rs`, rerun, compare).
6+
7+mod common;
8+
9+use common::natural_frame;
10+use ec_h265::encoder::{Encoder, EncoderConfig, RateControl};
11+
12+fn fnv1a(bytes: &[u8]) -> u64 {
13+ let mut hash = 0xcbf29ce484222325u64;
14+ for &b in bytes {
15+ hash ^= b as u64;
16+ hash = hash.wrapping_mul(0x100000001b3);
17+ }
18+ hash
19+}
20+
21+fn encode_hash(width: u32, height: u32) -> u64 {
22+ let mut cfg = EncoderConfig::new(width, height);
23+ cfg.rate_control = RateControl::ConstantQp(24);
24+ cfg.threads = 1;
25+ let encoder = Encoder::new(cfg).expect("encoder");
26+ let mut all = Vec::new();
27+ for i in 0..3u32 {
28+ let frame = natural_frame(width, height, i * 5);
29+ all.extend(encoder.encode_idr(&frame).expect("encode").au);
30+ }
31+ fnv1a(&all)
32+}
33+
34+#[test]
35+fn rdoq_cache_hash_1920x1080() {
36+ println!("hash 1920x1080 = {:016x}", encode_hash(1920, 1080));
37+}
38+
39+#[test]
40+fn rdoq_cache_hash_416x240() {
41+ println!("hash 416x240 = {:016x}", encode_hash(416, 240));
42+}