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+147 -62
@@ -558,71 +558,124 @@ impl ImdctPlan {
558 // PVQ558 // PVQ
559 // ---------------------------------------------------------------------------559 // ---------------------------------------------------------------------------
560 560
561-/// Builds the `U(n, .)` row used to count PVQ codewords, returning `V(n, k)`.561+/// Offsets of each `U` row in the flat table below (`CELT_PVQ_U_ROW`, the
562-///562+/// non-custom reference build's layout): row `m` holds `U(m, c)` at index
563-/// `V(n,k) = U(n,k) + U(n,k+1)` with `U` obeying563+/// `PVQ_U_ROW[m] + c` for `c ≥ m`, exploiting the symmetry `U(n, k) = U(k, n)`.
564-/// `u[n][k] = u[n-1][k] + u[n][k-1] + u[n-1][k-1]` (Section 4.3.4.2).564+/// The walks below only ever read entries with `min(n, k) ≤ 14`, which holds
565-fn pvq_urow(n: usize, k: usize, u: &mut [u32]) -> u32 {565+/// because every entry they read is bounded by `i < V(n, k)` — a bound the
566- u[0] = 0;566+/// range decode enforces and the cache-bounded allocation guarantees.
567- u[1] = 1;567+const PVQ_U_ROW: [usize; 16] = [
568- for (j, slot) in u.iter_mut().enumerate().take(k + 2).skip(2) {568+ 0, 176, 351, 525, 698, 870, 1041, 1131, 1178, 1207, 1226, 1240, 1248, 1254, 1257, 1272,
569- *slot = (2 * j - 1) as u32;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;
570 }603 }
571- for _ in 2..n {604+ m += 1;
572- unext(&mut u[1..k + 2], 1);
573 }605 }
574- u[k].wrapping_add(u[k + 1])606+ d
575 }607 }
576 608
577-/// Steps a `U` row up one dimension in place.609+static PVQ_U: [u32; PVQ_U_LEN] = compute_pvq_u();
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;
586-}
587 610
588-/// Steps a `U` row down one dimension in place.611+/// `U(n, k)` from the table.
589-fn uprev(u: &mut [u32], mut ui0: u32) {612+#[inline]
590- for j in 1..u.len() {613+pub(crate) fn pvq_u(n: usize, k: usize) -> u32 {
591- let ui1 = u[j].wrapping_sub(u[j - 1]).wrapping_sub(ui0);614+ let (lo, hi) = if n < k { (n, k) } else { (k, n) };
592- u[j - 1] = ui0;615+ debug_assert!(lo <= 14, "U({n},{k}) outside the reference table");
593- ui0 = ui1;616+ PVQ_U[PVQ_U_ROW[lo] + hi]
594 }617 }
595- let last = u.len() - 1;618+
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))
597 }623 }
598 624
599 /// Decodes one PVQ codeword of `k` pulses in `n` dimensions.625 /// Decodes one PVQ codeword of `k` pulses in `n` dimensions.
600-pub(crate) fn decode_pulses(626+///
601- dec: &mut RangeDecoder,627+/// The reference Appendix A unranking walk (`cwrsi`), with the `U` row read
602- n: usize,628+/// from the table instead of stepped one dimension at a time: `O(N)` lookups
603- k: usize,629+/// rather than `O(N·K)` row arithmetic.
604- y: &mut [i32],630+pub(crate) fn decode_pulses(dec: &mut RangeDecoder, n: usize, k: usize, y: &mut [i32]) {
605- u: &mut [u32],631+ let v = pvq_v(n, k);
606-) {
607- let v = pvq_urow(n, k, u);
608 let mut i = dec.dec_uint(v.max(2));632 let mut i = dec.dec_uint(v.max(2));
633+ let dims = n;
634+ let mut n = n;
609 let mut k = k;635 let mut k = k;
610- for slot in y.iter_mut().take(n) {636+ for slot in y.iter_mut().take(dims) {
611- let p = u[k + 1];637+ if n > 2 {
638+ let mut p = pvq_u(n, k + 1);
612 let neg = i >= p;639 let neg = i >= p;
613 if neg {640 if neg {
614 i -= p;641 i -= p;
615 }642 }
616 let k0 = k;643 let k0 = k;
617- let mut p = u[k];644+ p = pvq_u(n, k);
618 while p > i {645 while p > i {
619 k -= 1;646 k -= 1;
620- p = u[k];647+ p = pvq_u(n, k);
621 }648 }
622 i -= p;649 i -= p;
623 let mag = (k0 - k) as i32;650 let mag = (k0 - k) as i32;
624 *slot = if neg { -mag } else { mag };651 *slot = if neg { -mag } else { mag };
625- uprev(&mut u[..k + 2], 0);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 };
678+ }
626 }679 }
627 }680 }
628 681
@@ -1182,7 +1235,6 @@ pub struct CeltDecoder {
1182 tf_res: [i32; NB_BANDS],1235 tf_res: [i32; NB_BANDS],
1183 collapse_masks: [u8; 2 * NB_BANDS],1236 collapse_masks: [u8; 2 * NB_BANDS],
1184 iy: Vec<i32>,1237 iy: Vec<i32>,
1185- urow: Vec<u32>,
1186 mdct_buf: Vec<f32>,1238 mdct_buf: Vec<f32>,
1187 diag: CeltDecDiag,1239 diag: CeltDecDiag,
1188 }1240 }
@@ -1225,7 +1277,6 @@ impl CeltDecoder {
1225 tf_res: [0; NB_BANDS],1277 tf_res: [0; NB_BANDS],
1226 collapse_masks: [0; 2 * NB_BANDS],1278 collapse_masks: [0; 2 * NB_BANDS],
1227 iy: vec![0; max_n],1279 iy: vec![0; max_n],
1228- urow: vec![0; 256],
1229 mdct_buf: vec![0.0; max_n + OVERLAP],1280 mdct_buf: vec![0.0; max_n + OVERLAP],
1230 diag: CeltDecDiag {1281 diag: CeltDecDiag {
1231 silence: false,1282 silence: false,
@@ -2355,10 +2406,7 @@ impl CeltDecoder {
2355 b_blocks: usize,2406 b_blocks: usize,
2356 gain: f32,2407 gain: f32,
2357 ) -> u32 {2408 ) -> u32 {
2358- if self.urow.len() < k + 2 {2409+ decode_pulses(dec, n, k, &mut self.iy);
2359- self.urow.resize(k + 2, 0);
2360- }
2361- decode_pulses(dec, n, k, &mut self.iy, &mut self.urow);
2362 let mut ryy = 0.0f32;2410 let mut ryy = 0.0f32;
2363 for j in 0..n {2411 for j in 0..n {
2364 ryy += (self.iy[j] * self.iy[j]) as f32;2412 ryy += (self.iy[j] * self.iy[j]) as f32;
@@ -2946,21 +2994,58 @@ mod tests {
2946 #[test]2994 #[test]
2947 fn pvq_index_round_trips_within_v() {2995 fn pvq_index_round_trips_within_v() {
2948 // V(N,K) from the recursion in Section 4.3.4.2, checked against the2996 // V(N,K) from the recursion in Section 4.3.4.2, checked against the
2949- // closed forms the RFC gives for small N.2997+ // closed forms the RFC gives for small N, and the table against a
2950- let mut u = vec![0u32; 300];2998+ // fresh runtime build of the same recurrence over the whole stored
2951- assert_eq!(pvq_urow(2, 1, &mut u), 4);2999+ // triangle.
2952- assert_eq!(pvq_urow(2, 3, &mut u), 12);3000+ assert_eq!(pvq_v(2, 1), 4);
2953- assert_eq!(pvq_urow(3, 2, &mut u), 18);3001+ assert_eq!(pvq_v(2, 3), 12);
2954- assert_eq!(pvq_urow(4, 2, &mut u), 32);3002+ assert_eq!(pvq_v(3, 2), 18);
2955- // V(N,K) = V(N-1,K) + V(N,K-1) + V(N-1,K-1).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).
2956 for n in 3..8usize {3005 for n in 3..8usize {
2957 for k in 2..8usize {3006 for k in 2..8usize {
2958- let mut a = vec![0u32; 300];3007+ let (v1, v2, v3, v) =
2959- let v = pvq_urow(n, k, &mut a);3008+ (pvq_v(n - 1, k), pvq_v(n, k - 1), pvq_v(n - 1, k - 1), pvq_v(n, k));
2960- let v1 = pvq_urow(n - 1, k, &mut a);3009+ assert_eq!(v, v1.wrapping_add(v2).wrapping_add(v3), "V({n},{k})");
2961- let v2 = pvq_urow(n, k - 1, &mut a);3010+ }
2962- let v3 = pvq_urow(n - 1, k - 1, &mut a);3011+ }
2963- assert_eq!(v, v1 + v2 + v3, "V({n},{k})");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})");
2964 }3049 }
2965 }3050 }
2966 }3051 }
crates/ec-opus/src/celt_enc.rsmodified+12 -29
@@ -40,7 +40,6 @@ use crate::celt::{
40 SPREAD_NONE, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF,40 SPREAD_NONE, SPREAD_NORMAL, TF_SELECT, TRIM_ICDF,
41 bitexact_cos, bitexact_log2tan, bits2pulses, cache_index, compute_allocation_encode,41 bitexact_cos, bitexact_log2tan, bits2pulses, cache_index, compute_allocation_encode,
42 compute_qn, deinterleave_hadamard, exp_rotation, frac_mul16, get_pulses, haar1, pulses2bits,42 compute_qn, deinterleave_hadamard, exp_rotation, frac_mul16, get_pulses, haar1, pulses2bits,
43- unext,
44 };43 };
45 use crate::range::RangeEncoder;44 use crate::range::RangeEncoder;
46 45
@@ -296,31 +295,22 @@ fn laplace_encode(enc: &mut RangeEncoder, value: &mut i32, mut fs: u32, decay: i
296 295
297 /// `encode_pulses()` for the general case: index the pulse vector in the296 /// `encode_pulses()` for the general case: index the pulse vector in the
298 /// V(N,K) enumeration and code it as one uniform symbol (Section 5.3.4).297 /// 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) {
300 debug_assert!(n >= 2 && k > 0);299 debug_assert!(n >= 2 && k > 0);
301- u[0] = 0;300+ let mut j = n - 1;
302- for (kk, slot) in u.iter_mut().enumerate().take(k + 2).skip(1) {301+ let mut i = u32::from(iy[j] < 0);
303- *slot = (2 * kk - 1) as u32;302+ let mut kk = iy[j].unsigned_abs() as usize;
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;
314 while j > 0 {303 while j > 0 {
315 j -= 1;304 j -= 1;
316- unext(&mut u[..k + 2], 0);305+ // The row the reference stepping left in place at this dimension is
317- i = i.wrapping_add(u[kk]);306+ // `U(n - j, .)`; read it from the table instead.
307+ i = i.wrapping_add(celt::pvq_u(n - j, kk));
318 kk += iy[j].unsigned_abs() as usize;308 kk += iy[j].unsigned_abs() as usize;
319 if iy[j] < 0 {309 if iy[j] < 0 {
320- i = i.wrapping_add(u[kk + 1]);310+ i = i.wrapping_add(celt::pvq_u(n - j, kk + 1));
321 }311 }
322 }312 }
323- let nc = u[kk].wrapping_add(u[kk + 1]);313+ let nc = celt::pvq_v(n, kk);
324 enc.enc_uint(i, nc.max(2));314 enc.enc_uint(i, nc.max(2));
325 }315 }
326 316
@@ -529,7 +519,6 @@ pub struct CeltEncoder {
529 iy: Vec<i32>,519 iy: Vec<i32>,
530 pvq_y: Vec<f32>,520 pvq_y: Vec<f32>,
531 pvq_sign: Vec<i32>,521 pvq_sign: Vec<i32>,
532- urow: Vec<u32>,
533 /// Per-frame diagnostics captured at the end of the last `encode` call.522 /// Per-frame diagnostics captured at the end of the last `encode` call.
534 last_diag: CeltFrameDiag,523 last_diag: CeltFrameDiag,
535 /// libopus `st->analysis`'s per-frame output, handed in by524 /// libopus `st->analysis`'s per-frame output, handed in by
@@ -592,7 +581,6 @@ impl CeltEncoder {
592 iy: vec![0; max_n],581 iy: vec![0; max_n],
593 pvq_y: vec![0.0; max_n],582 pvq_y: vec![0.0; max_n],
594 pvq_sign: vec![0; max_n],583 pvq_sign: vec![0; max_n],
595- urow: vec![0; 1280],
596 last_diag: CeltFrameDiag::default(),584 last_diag: CeltFrameDiag::default(),
597 info: AnalysisInfo::default(),585 info: AnalysisInfo::default(),
598 }586 }
@@ -2681,10 +2669,7 @@ impl CeltEncoder {
2681 iy[j] = -iy[j];2669 iy[j] = -iy[j];
2682 }2670 }
2683 }2671 }
2684- if self.urow.len() < k + 2 {2672+ encode_pulses(enc, &self.iy[..n], n, k);
2685- self.urow.resize(k + 2, 0);
2686- }
2687- encode_pulses(enc, &self.iy[..n], n, k, &mut self.urow);
2688 }2673 }
2689 }2674 }
2690 2675
@@ -2787,15 +2772,13 @@ mod tests {
2787 }2772 }
2788 let mut enc = RangeEncoder::new();2773 let mut enc = RangeEncoder::new();
2789 enc.reset(600);2774 enc.reset(600);
2790- let mut u = vec![0u32; k + 2];2775+ encode_pulses(&mut enc, &iy, n, k);
2791- encode_pulses(&mut enc, &iy, n, k, &mut u);
2792 enc.done();2776 enc.done();
2793 assert!(!enc.error());2777 assert!(!enc.error());
2794 let data = enc.data().to_vec();2778 let data = enc.data().to_vec();
2795 let mut dec = RangeDecoder::new(&data);2779 let mut dec = RangeDecoder::new(&data);
2796 let mut got = vec![0i32; n];2780 let mut got = vec![0i32; n];
2797- let mut u2 = vec![0u32; k + 2];2781+ crate::celt::decode_pulses(&mut dec, n, k, &mut got);
2798- crate::celt::decode_pulses(&mut dec, n, k, &mut got, &mut u2);
2799 assert_eq!(got, iy, "n={n} k={k}");2782 assert_eq!(got, iy, "n={n} k={k}");
2800 }2783 }
2801 }2784 }