forge
Explore
Log in

Don't you dare go Hollow

PVQ unranking walks the reference 1272-entry U table instead of stepping rows at runtime — decode_pulses/encode_pulses drop from O(N*K) row arithmetic to O(N) lookups (5.1 film decode 0.70 -> 0.82 of ruopus-FFT, stereo 0.66 -> 0.87, stereo encode 0.59 -> 0.65 of opus-rs)

Browse files at this commit

e06f8b93a855c9a86ff078c857af4063cba9d020Ahmet Kaan GümüşParent: 781bd7a
  • perf
    • PVQ unranking walks the reference 1272-entry U table instead of stepping rows at runtime — decode_pulses/encode_pulses drop from O(N*K) row arithmetic to O(N) lookups (5.1 film decode 0.70 -> 0.82 of ruopus-FFT, stereo 0.66 -> 0.87, stereo encode 0.59 -> 0.65 of opus-rs)
    • the const table is the same recurrence in wrapping arithmetic and the lib test cross-checks every stored entry against a fresh runtime build
Show full message
perf(ec-opus): PVQ unranking walks the reference 1272-entry U table instead of stepping rows at runtime — decode_pulses/encode_pulses drop from O(N*K) row arithmetic to O(N) lookups (5.1 film decode 0.70 -> 0.82 of ruopus-FFT, stereo 0.66 -> 0.87, stereo encode 0.59 -> 0.65 of opus-rs); the const table is the same recurrence in wrapping arithmetic and the lib test cross-checks every stored entry against a fresh runtime build
crates/ec-opus/src/celt.rsmodified+158 -73
@@ -558,71 +558,124 @@ impl ImdctPlan {
558558 // PVQ
559559 // ---------------------------------------------------------------------------
560560
561-/// Builds the `U(n, .)` row used to count PVQ codewords, returning `V(n, k)`.
562-///
563-/// `V(n,k) = U(n,k) + U(n,k+1)` with `U` obeying
564-/// `u[n][k] = u[n-1][k] + u[n][k-1] + u[n-1][k-1]` (Section 4.3.4.2).
565-fn pvq_urow(n: usize, k: usize, u: &mut [u32]) -> u32 {
566- u[0] = 0;
567- u[1] = 1;
568- for (j, slot) in u.iter_mut().enumerate().take(k + 2).skip(2) {
569- *slot = (2 * j - 1) as u32;
570- }
571- for _ in 2..n {
572- unext(&mut u[1..k + 2], 1);
573- }
574- u[k].wrapping_add(u[k + 1])
561+/// Offsets of each `U` row in the flat table below (`CELT_PVQ_U_ROW`, the
562+/// non-custom reference build's layout): row `m` holds `U(m, c)` at index
563+/// `PVQ_U_ROW[m] + c` for `c ≥ m`, exploiting the symmetry `U(n, k) = U(k, n)`.
564+/// The walks below only ever read entries with `min(n, k) ≤ 14`, which holds
565+/// because every entry they read is bounded by `i < V(n, k)` — a bound the
566+/// range decode enforces and the cache-bounded allocation guarantees.
567+const PVQ_U_ROW: [usize; 16] = [
568+ 0, 176, 351, 525, 698, 870, 1041, 1131, 1178, 1207, 1226, 1240, 1248, 1254, 1257, 1272,
569+];
570+const PVQ_U_LEN: usize = PVQ_U_ROW[15];
571+
572+/// The flat `U` table, computed at compile time from the same recurrence the
573+/// row-stepping used, `U(m,c) = U(m-1,c) + U(m,c-1) + U(m-1,c-1)` off
574+/// `U(0,0) = 1` (Section 4.3.4.2), in wrapping arithmetic: unreachable entries
575+/// wrap exactly as the runtime stepping wrapped.
576+const fn compute_pvq_u() -> [u32; PVQ_U_LEN] {
577+ // The full triangle for a ≤ 14, b ≤ 176 (the widest standard band),
578+ // then scattered so `U(m, c)` sits at `PVQ_U_ROW[m] + c`.
579+ let mut uu = [[0u32; 177]; 15];
580+ uu[0][0] = 1; // U(0,0)=1; U(0,b>0) = U(a>0,0) = 0.
581+ let mut a = 1;
582+ while a < 15 {
583+ let mut b = 1;
584+ while b < 177 {
585+ uu[a][b] = uu[a - 1][b].wrapping_add(uu[a][b - 1]).wrapping_add(uu[a - 1][b - 1]);
586+ b += 1;
587+ }
588+ a += 1;
589+ }
590+ let mut d = [0u32; PVQ_U_LEN];
591+ let mut m = 0;
592+ while m < 15 {
593+ let start = PVQ_U_ROW[m] + m; // raw start of row m
594+ let end = if m < 14 {
595+ PVQ_U_ROW[m + 1] + (m + 1)
596+ } else {
597+ PVQ_U_ROW[15]
598+ };
599+ let mut p = start;
600+ while p < end {
601+ d[p] = uu[m][p - PVQ_U_ROW[m]];
602+ p += 1;
603+ }
604+ m += 1;
605+ }
606+ d
575607 }
576608
577-/// Steps a `U` row up one dimension in place.
578-pub(crate) fn unext(u: &mut [u32], mut ui0: u32) {
579- for j in 1..u.len() {
580- let ui1 = u[j].wrapping_add(u[j - 1]).wrapping_add(ui0);
581- u[j - 1] = ui0;
582- ui0 = ui1;
583- }
584- let last = u.len() - 1;
585- u[last] = ui0;
609+static PVQ_U: [u32; PVQ_U_LEN] = compute_pvq_u();
610+
611+/// `U(n, k)` from the table.
612+#[inline]
613+pub(crate) fn pvq_u(n: usize, k: usize) -> u32 {
614+ let (lo, hi) = if n < k { (n, k) } else { (k, n) };
615+ debug_assert!(lo <= 14, "U({n},{k}) outside the reference table");
616+ PVQ_U[PVQ_U_ROW[lo] + hi]
586617 }
587618
588-/// Steps a `U` row down one dimension in place.
589-fn uprev(u: &mut [u32], mut ui0: u32) {
590- for j in 1..u.len() {
591- let ui1 = u[j].wrapping_sub(u[j - 1]).wrapping_sub(ui0);
592- u[j - 1] = ui0;
593- ui0 = ui1;
594- }
595- let last = u.len() - 1;
596- u[last] = ui0;
619+/// `V(n, k) = U(n,k) + U(n,k+1)`: the size of the `(n, k)` PVQ codebook.
620+#[inline]
621+pub(crate) fn pvq_v(n: usize, k: usize) -> u32 {
622+ pvq_u(n, k).wrapping_add(pvq_u(n, k + 1))
597623 }
598624
599625 /// Decodes one PVQ codeword of `k` pulses in `n` dimensions.
600-pub(crate) fn decode_pulses(
601- dec: &mut RangeDecoder,
602- n: usize,
603- k: usize,
604- y: &mut [i32],
605- u: &mut [u32],
606-) {
607- let v = pvq_urow(n, k, u);
626+///
627+/// The reference Appendix A unranking walk (`cwrsi`), with the `U` row read
628+/// from the table instead of stepped one dimension at a time: `O(N)` lookups
629+/// rather than `O(N·K)` row arithmetic.
630+pub(crate) fn decode_pulses(dec: &mut RangeDecoder, n: usize, k: usize, y: &mut [i32]) {
631+ let v = pvq_v(n, k);
608632 let mut i = dec.dec_uint(v.max(2));
633+ let dims = n;
634+ let mut n = n;
609635 let mut k = k;
610- for slot in y.iter_mut().take(n) {
611- let p = u[k + 1];
612- let neg = i >= p;
613- if neg {
636+ for slot in y.iter_mut().take(dims) {
637+ if n > 2 {
638+ let mut p = pvq_u(n, k + 1);
639+ let neg = i >= p;
640+ if neg {
641+ i -= p;
642+ }
643+ let k0 = k;
644+ p = pvq_u(n, k);
645+ while p > i {
646+ k -= 1;
647+ p = pvq_u(n, k);
648+ }
614649 i -= p;
650+ let mag = (k0 - k) as i32;
651+ *slot = if neg { -mag } else { mag };
652+ n -= 1;
653+ } else if n == 2 {
654+ // `U(2, k) = 2k-1` and `U(2, k+1) = 2k+1`: one sign, then the
655+ // largest split the index leaves room for.
656+ let p = 2 * k as u32 + 1;
657+ let neg = i >= p;
658+ if neg {
659+ i -= p;
660+ }
661+ let k0 = k;
662+ k = ((i + 1) >> 1) as usize;
663+ if k != 0 {
664+ i -= 2 * k as u32 - 1;
665+ }
666+ let mag = (k0 - k) as i32;
667+ *slot = if neg { -mag } else { mag };
668+ n -= 1;
669+ } else {
670+ // `U(1, k)` is 1 for k ≥ 1 and 0 at k = 0, so `V(1, k) = 2`: the
671+ // index is one sign plus a remainder that is already zero here.
672+ let neg = i >= 1;
673+ if neg {
674+ i -= 1;
675+ }
676+ debug_assert_eq!(i, 0, "PVQ index overrun at the last dimension");
677+ *slot = if neg { -(k as i32) } else { k as i32 };
615678 }
616- let k0 = k;
617- let mut p = u[k];
618- while p > i {
619- k -= 1;
620- p = u[k];
621- }
622- i -= p;
623- let mag = (k0 - k) as i32;
624- *slot = if neg { -mag } else { mag };
625- uprev(&mut u[..k + 2], 0);
626679 }
627680 }
628681
@@ -1182,7 +1235,6 @@ pub struct CeltDecoder {
11821235 tf_res: [i32; NB_BANDS],
11831236 collapse_masks: [u8; 2 * NB_BANDS],
11841237 iy: Vec<i32>,
1185- urow: Vec<u32>,
11861238 mdct_buf: Vec<f32>,
11871239 diag: CeltDecDiag,
11881240 }
@@ -1225,7 +1277,6 @@ impl CeltDecoder {
12251277 tf_res: [0; NB_BANDS],
12261278 collapse_masks: [0; 2 * NB_BANDS],
12271279 iy: vec![0; max_n],
1228- urow: vec![0; 256],
12291280 mdct_buf: vec![0.0; max_n + OVERLAP],
12301281 diag: CeltDecDiag {
12311282 silence: false,
@@ -2355,10 +2406,7 @@ impl CeltDecoder {
23552406 b_blocks: usize,
23562407 gain: f32,
23572408 ) -> u32 {
2358- if self.urow.len() < k + 2 {
2359- self.urow.resize(k + 2, 0);
2360- }
2361- decode_pulses(dec, n, k, &mut self.iy, &mut self.urow);
2409+ decode_pulses(dec, n, k, &mut self.iy);
23622410 let mut ryy = 0.0f32;
23632411 for j in 0..n {
23642412 ryy += (self.iy[j] * self.iy[j]) as f32;
@@ -2946,21 +2994,58 @@ mod tests {
29462994 #[test]
29472995 fn pvq_index_round_trips_within_v() {
29482996 // V(N,K) from the recursion in Section 4.3.4.2, checked against the
2949- // closed forms the RFC gives for small N.
2950- let mut u = vec![0u32; 300];
2951- assert_eq!(pvq_urow(2, 1, &mut u), 4);
2952- assert_eq!(pvq_urow(2, 3, &mut u), 12);
2953- assert_eq!(pvq_urow(3, 2, &mut u), 18);
2954- assert_eq!(pvq_urow(4, 2, &mut u), 32);
2955- // V(N,K) = V(N-1,K) + V(N,K-1) + V(N-1,K-1).
2997+ // closed forms the RFC gives for small N, and the table against a
2998+ // fresh runtime build of the same recurrence over the whole stored
2999+ // triangle.
3000+ assert_eq!(pvq_v(2, 1), 4);
3001+ assert_eq!(pvq_v(2, 3), 12);
3002+ assert_eq!(pvq_v(3, 2), 18);
3003+ assert_eq!(pvq_v(4, 2), 32);
3004+ // U(N,K) = U(N-1,K) + U(N,K-1) + U(N-1,K-1).
29563005 for n in 3..8usize {
29573006 for k in 2..8usize {
2958- let mut a = vec![0u32; 300];
2959- let v = pvq_urow(n, k, &mut a);
2960- let v1 = pvq_urow(n - 1, k, &mut a);
2961- let v2 = pvq_urow(n, k - 1, &mut a);
2962- let v3 = pvq_urow(n - 1, k - 1, &mut a);
2963- assert_eq!(v, v1 + v2 + v3, "V({n},{k})");
3007+ let (v1, v2, v3, v) =
3008+ (pvq_v(n - 1, k), pvq_v(n, k - 1), pvq_v(n - 1, k - 1), pvq_v(n, k));
3009+ assert_eq!(v, v1.wrapping_add(v2).wrapping_add(v3), "V({n},{k})");
3010+ }
3011+ }
3012+ // The table equals the runtime row-stepping everywhere it is stored:
3013+ // rows 0..15, columns as laid out by PVQ_U_ROW.
3014+ let mut u = vec![0u32; 400];
3015+ for n in 0..=176usize {
3016+ for k in 0..=176usize {
3017+ let (lo, hi) = if n < k { (n, k) } else { (k, n) };
3018+ if lo > 14 {
3019+ continue;
3020+ }
3021+ let col_max = if lo < 14 {
3022+ PVQ_U_ROW[lo + 1] - PVQ_U_ROW[lo] + lo
3023+ } else {
3024+ 14
3025+ };
3026+ if hi > col_max || hi < 2 {
3027+ // Outside the stored span, or a base row the row-stepping
3028+ // never built (rows 0 and 1 are its seeds).
3029+ continue;
3030+ }
3031+ // Runtime U via the old row-stepping, in wrapping arithmetic.
3032+ u[0] = 0;
3033+ u[1] = 1;
3034+ for (j, slot) in u.iter_mut().enumerate().take(hi + 2).skip(2) {
3035+ *slot = (2 * j - 1) as u32;
3036+ }
3037+ for _ in 2..hi {
3038+ // unext over the slice u[1..lo+2] with ui0 = 1, exactly as
3039+ // the row-stepping drove it.
3040+ let mut ui0 = 1u32;
3041+ for j in 2..lo + 2 {
3042+ let ui1 = u[j].wrapping_add(u[j - 1]).wrapping_add(ui0);
3043+ u[j - 1] = ui0;
3044+ ui0 = ui1;
3045+ }
3046+ u[lo + 1] = ui0;
3047+ }
3048+ assert_eq!(pvq_u(hi, lo), u[lo], "U({hi},{lo})");
29643049 }
29653050 }
29663051 }
crates/ec-opus/src/celt_enc.rsmodified+12 -29
@@ -40,7 +40,6 @@ use crate::celt::{
4040 SPREAD_NONE, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF,
4141 bitexact_cos, bitexact_log2tan, bits2pulses, cache_index, compute_allocation_encode,
4242 compute_qn, deinterleave_hadamard, exp_rotation, frac_mul16, get_pulses, haar1, pulses2bits,
43- unext,
4443 };
4544 use crate::range::RangeEncoder;
4645
@@ -296,31 +295,22 @@ fn laplace_encode(enc: &mut RangeEncoder, value: &mut i32, mut fs: u32, decay: i
296295
297296 /// `encode_pulses()` for the general case: index the pulse vector in the
298297 /// V(N,K) enumeration and code it as one uniform symbol (Section 5.3.4).
299-fn encode_pulses(enc: &mut RangeEncoder, iy: &[i32], n: usize, k: usize, u: &mut [u32]) {
298+fn encode_pulses(enc: &mut RangeEncoder, iy: &[i32], n: usize, k: usize) {
300299 debug_assert!(n >= 2 && k > 0);
301- u[0] = 0;
302- for (kk, slot) in u.iter_mut().enumerate().take(k + 2).skip(1) {
303- *slot = (2 * kk - 1) as u32;
304- }
305- let mut i = u32::from(iy[n - 1] < 0);
306- let mut kk = iy[n - 1].unsigned_abs() as usize;
307- let j = n - 2;
308- i = i.wrapping_add(u[kk]);
309- kk += iy[j].unsigned_abs() as usize;
310- if iy[j] < 0 {
311- i = i.wrapping_add(u[kk + 1]);
312- }
313- let mut j = j;
300+ let mut j = n - 1;
301+ let mut i = u32::from(iy[j] < 0);
302+ let mut kk = iy[j].unsigned_abs() as usize;
314303 while j > 0 {
315304 j -= 1;
316- unext(&mut u[..k + 2], 0);
317- i = i.wrapping_add(u[kk]);
305+ // The row the reference stepping left in place at this dimension is
306+ // `U(n - j, .)`; read it from the table instead.
307+ i = i.wrapping_add(celt::pvq_u(n - j, kk));
318308 kk += iy[j].unsigned_abs() as usize;
319309 if iy[j] < 0 {
320- i = i.wrapping_add(u[kk + 1]);
310+ i = i.wrapping_add(celt::pvq_u(n - j, kk + 1));
321311 }
322312 }
323- let nc = u[kk].wrapping_add(u[kk + 1]);
313+ let nc = celt::pvq_v(n, kk);
324314 enc.enc_uint(i, nc.max(2));
325315 }
326316
@@ -529,7 +519,6 @@ pub struct CeltEncoder {
529519 iy: Vec<i32>,
530520 pvq_y: Vec<f32>,
531521 pvq_sign: Vec<i32>,
532- urow: Vec<u32>,
533522 /// Per-frame diagnostics captured at the end of the last `encode` call.
534523 last_diag: CeltFrameDiag,
535524 /// libopus `st->analysis`'s per-frame output, handed in by
@@ -592,7 +581,6 @@ impl CeltEncoder {
592581 iy: vec![0; max_n],
593582 pvq_y: vec![0.0; max_n],
594583 pvq_sign: vec![0; max_n],
595- urow: vec![0; 1280],
596584 last_diag: CeltFrameDiag::default(),
597585 info: AnalysisInfo::default(),
598586 }
@@ -2681,10 +2669,7 @@ impl CeltEncoder {
26812669 iy[j] = -iy[j];
26822670 }
26832671 }
2684- if self.urow.len() < k + 2 {
2685- self.urow.resize(k + 2, 0);
2686- }
2687- encode_pulses(enc, &self.iy[..n], n, k, &mut self.urow);
2672+ encode_pulses(enc, &self.iy[..n], n, k);
26882673 }
26892674 }
26902675
@@ -2787,15 +2772,13 @@ mod tests {
27872772 }
27882773 let mut enc = RangeEncoder::new();
27892774 enc.reset(600);
2790- let mut u = vec![0u32; k + 2];
2791- encode_pulses(&mut enc, &iy, n, k, &mut u);
2775+ encode_pulses(&mut enc, &iy, n, k);
27922776 enc.done();
27932777 assert!(!enc.error());
27942778 let data = enc.data().to_vec();
27952779 let mut dec = RangeDecoder::new(&data);
27962780 let mut got = vec![0i32; n];
2797- let mut u2 = vec![0u32; k + 2];
2798- crate::celt::decode_pulses(&mut dec, n, k, &mut got, &mut u2);
2781+ crate::celt::decode_pulses(&mut dec, n, k, &mut got);
27992782 assert_eq!(got, iy, "n={n} k={k}");
28002783 }
28012784 }