forge
Explore
Log in

Don't you dare go Hollow

Msac-flavoured LR subexp/recenter port + Wiener/SGR read_lr_unit primitives (unwired)

Browse files at this commit

4c75e5c085deb0d31540fa9edec055a5e429efc9Ahmet Kaan GümüşParent: a3c51d9
  • feat
    • msac-flavoured LR subexp/recenter port + Wiener/SGR read_lr_unit primitives (unwired)
Show full message
feat(av1): msac-flavoured LR subexp/recenter port + Wiener/SGR read_lr_unit primitives (unwired)

Ports decode_subexp/decode_unsigned_subexp_with_ref/decode_signed_subexp_with_ref
to the msac SymbolDecoder (k is a per-tap parameter here, not global motion's
fixed 3), plus read_wiener_filter/read_sgrproj_filter and the SGR params table,
all from libaom decodeframe.c/restoration.c. Pinned via roundtrip against a
hand-written encode-side mirror (SymbolEncoder has no LR writer of its own).
Not yet called from decode.rs -- stream.rs's whole-frame refusal is unchanged.
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -29,6 +29,7 @@ pub mod msac;
29 pub mod mvstack;29 pub mod mvstack;
30 pub mod obu;30 pub mod obu;
31 pub mod quant;31 pub mod quant;
32+mod restoration;
32 pub mod sequence;33 pub mod sequence;
33 pub mod stream;34 pub mod stream;
34 pub mod tile;35 pub mod tile;
crates/ec-av1/src/restoration.rsadded+519 -0
@@ -0,0 +1,519 @@
1+//! AV1 loop restoration: spec 5.11.57 `read_lr`/`read_lr_unit` (per-superblock
2+//! symbol reads, once corners are computed per
3+//! `av1_loop_restoration_corners_in_sb`, restoration.c:1277) and spec 7.17's
4+//! two pixel filters (Wiener, self-guided/SGR). See `lanes/lr.report.md` for
5+//! the full derivation (libaom `decodeframe.c`/`restoration.c` line refs).
6+
7+use crate::msac::SymbolDecoder;
8+use ec_av1_syntax::obu::floor_log2;
9+use ec_av1_syntax::{LoopRestorationParams, RestorationType};
10+
11+/// `ns(n)` (spec 4.10.7) read through the arithmetic coder's equiprobable
12+/// bit primitive (`aom_read_literal`/`SymbolDecoder::literal`), matching
13+/// libaom's `read_primitive_quniform_`. Same algorithm as
14+/// `ec_av1_syntax::obu::read_ns`, ported to the msac reader `decode_subexp`
15+/// needs (LR's coefficients ride the arithmetic-coded tile, not the
16+/// uncompressed header `BitReader` global motion's subexp already targets).
17+fn ns_msac(dec: &mut SymbolDecoder, n: u32) -> u32 {
18+ if n <= 1 {
19+ return 0;
20+ }
21+ let w = floor_log2(n) + 1;
22+ let m = (1u32 << w) - n;
23+ let v = dec.literal(w - 1);
24+ if v < m {
25+ return v;
26+ }
27+ (v << 1) - m + dec.literal(1)
28+}
29+
30+/// `decode_subexp()` (spec 5.9.28) with `k` a parameter, not the fixed `3`
31+/// global motion uses -- libaom's `read_primitive_subexpfin_`. LR's Wiener
32+/// taps and SGR `xqd` each pick a different `k` (1/2/3 for the three Wiener
33+/// taps, 4 for SGR).
34+fn decode_subexp_msac(dec: &mut SymbolDecoder, num_syms: u32, k: u32) -> u32 {
35+ let mut i = 0u32;
36+ let mut mk = 0u32;
37+ loop {
38+ let b = if i > 0 { k + i - 1 } else { k };
39+ let a = 1u32 << b;
40+ if num_syms <= mk + 3 * a {
41+ return ns_msac(dec, num_syms - mk) + mk;
42+ }
43+ if dec.literal(1) == 0 {
44+ return dec.literal(b) + mk;
45+ }
46+ i += 1;
47+ mk += a;
48+ }
49+}
50+
51+/// `inv_recenter_nonneg` (`aom_dsp/recenter.h`) == spec `inverse_recenter`.
52+fn inverse_recenter(r: u32, v: u32) -> u32 {
53+ if v > 2 * r {
54+ v
55+ } else if v & 1 != 0 {
56+ r - ((v + 1) >> 1)
57+ } else {
58+ r + (v >> 1)
59+ }
60+}
61+
62+/// `aom_read_primitive_refsubexpfin` (`inv_recenter_finite_nonneg` composed
63+/// with `read_primitive_subexpfin`): a value in `[0, n)` recentred around
64+/// `reference`.
65+fn decode_unsigned_subexp_with_ref_msac(dec: &mut SymbolDecoder, n: u32, k: u32, reference: u32) -> u32 {
66+ let v = decode_subexp_msac(dec, n, k);
67+ if (reference << 1) <= n {
68+ inverse_recenter(reference, v)
69+ } else {
70+ n - 1 - inverse_recenter(n - 1 - reference, v)
71+ }
72+}
73+
74+/// Signed wrapper, matching the way `read_wiener_filter`/`read_sgrproj_filter`
75+/// call `aom_read_primitive_refsubexpfin(rb, max-min+1, k, ref-min)+min`.
76+fn decode_signed_subexp_with_ref_msac(dec: &mut SymbolDecoder, low: i32, high: i32, k: u32, reference: i32) -> i32 {
77+ let n = (high - low) as u32;
78+ let r = (reference - low).clamp(0, n as i32) as u32;
79+ decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low
80+}
81+
82+const WIENER_HALFWIN: usize = 3;
83+pub(crate) const WIENER_WIN: usize = 7;
84+const WIENER_TAP_MINV: [i32; 3] = [-5, -23, -17];
85+const WIENER_TAP_MAXV: [i32; 3] = [10, 8, 46];
86+const WIENER_TAP_K: [u32; 3] = [1, 2, 3];
87+const WIENER_TAP_MIDV: [i32; 3] = [3, -7, 15];
88+
89+/// `WienerInfo`: a restoration unit's 7-tap separable filter, symmetric
90+/// (spec `vfilter[i] == vfilter[6-i]`), with the centre tap derived
91+/// (`WIENER_FILT_STEP - 2*sum(taps 0..3)`, spec 7.17.4).
92+#[derive(Clone, Copy, Debug, PartialEq)]
93+pub(crate) struct WienerInfo {
94+ pub vfilter: [i32; 7],
95+ pub hfilter: [i32; 7],
96+}
97+
98+impl Default for WienerInfo {
99+ fn default() -> Self {
100+ Self {
101+ vfilter: midpoint_filter(),
102+ hfilter: midpoint_filter(),
103+ }
104+ }
105+}
106+
107+fn midpoint_filter() -> [i32; 7] {
108+ let [t0, t1, t2] = WIENER_TAP_MIDV;
109+ let centre = 128 - 2 * (t0 + t1 + t2);
110+ [t0, t1, t2, centre, t2, t1, t0]
111+}
112+
113+/// One direction's 3 free taps (spec `read_wiener_filter`'s per-direction
114+/// loop): reads with `k`/min/max per tap index, recentred on `ref_dir`
115+/// (which the caller updates to the just-decoded value after each unit,
116+/// spec `ref_wiener_info` -- reset to the midpoint filter at each tile).
117+fn read_wiener_direction(dec: &mut SymbolDecoder, chroma: bool, reference: &[i32; 7]) -> [i32; 7] {
118+ let mut taps = [0i32; 3];
119+ for i in 0..3 {
120+ // `wiener_win == WIENER_WIN_CHROMA` (5-tap) skips tap 0, which is
121+ // always 0 for chroma (spec `read_wiener_filter`, `wiener_win`
122+ // branch on plane).
123+ if i == 0 && chroma {
124+ taps[0] = 0;
125+ continue;
126+ }
127+ taps[i] = decode_signed_subexp_with_ref_msac(
128+ dec,
129+ WIENER_TAP_MINV[i],
130+ WIENER_TAP_MAXV[i] + 1,
131+ WIENER_TAP_K[i],
132+ reference[i],
133+ );
134+ }
135+ let centre = 128 - 2 * (taps[0] + taps[1] + taps[2]);
136+ [taps[0], taps[1], taps[2], centre, taps[2], taps[1], taps[0]]
137+}
138+
139+/// `read_wiener_filter` (decodeframe.c ~1595): both directions, updating
140+/// `reference` in place (the running per-plane, per-tile reference state).
141+fn read_wiener_filter(dec: &mut SymbolDecoder, chroma: bool, reference: &mut WienerInfo) -> WienerInfo {
142+ let vfilter = read_wiener_direction(dec, chroma, &reference.vfilter);
143+ let hfilter = read_wiener_direction(dec, chroma, &reference.hfilter);
144+ let info = WienerInfo { vfilter, hfilter };
145+ *reference = info;
146+ info
147+}
148+
149+/// `SgrprojInfo`: one self-guided restoration unit's parameter-set index
150+/// and the two (at most) coded correction weights.
151+#[derive(Clone, Copy, Debug, PartialEq)]
152+pub(crate) struct SgrprojInfo {
153+ pub ep: usize,
154+ pub xqd: [i32; 2],
155+}
156+
157+const SGRPROJ_PRJ_BITS: i32 = 7;
158+const SGRPROJ_PRJ_MIN0: i32 = -(1 << SGRPROJ_PRJ_BITS) * 3 / 4;
159+const SGRPROJ_PRJ_MAX0: i32 = SGRPROJ_PRJ_MIN0 + (1 << SGRPROJ_PRJ_BITS) - 1;
160+const SGRPROJ_PRJ_MIN1: i32 = -(1 << SGRPROJ_PRJ_BITS) / 4;
161+const SGRPROJ_PRJ_MAX1: i32 = SGRPROJ_PRJ_MIN1 + (1 << SGRPROJ_PRJ_BITS) - 1;
162+const SGRPROJ_PRJ_SUBEXP_K: u32 = 4;
163+
164+/// `av1_sgr_params` (`restoration.c:36`): `(r0, r1, s0, s1)` per of the 16
165+/// `SGRPROJ_PARAMS_BITS`-selected parameter sets. `r == 0` for a radius
166+/// means that pass is skipped (its `xqd` is then forced, not coded).
167+pub(crate) const SGR_PARAMS: [(i32, i32, i32, i32); 16] = [
168+ (2, 1, 140, 3236),
169+ (2, 1, 112, 2158),
170+ (2, 1, 93, 1618),
171+ (2, 1, 80, 1438),
172+ (2, 1, 70, 1295),
173+ (2, 1, 58, 1177),
174+ (2, 1, 47, 1079),
175+ (2, 1, 37, 996),
176+ (2, 1, 30, 925),
177+ (2, 1, 25, 863),
178+ (0, 1, -1, 2589),
179+ (0, 1, -1, 1618),
180+ (0, 1, -1, 1177),
181+ (0, 1, -1, 925),
182+ (2, 0, 56, -1),
183+ (2, 0, 22, -1),
184+];
185+
186+/// `read_sgrproj_filter` (decodeframe.c ~1651). `reference` is the running
187+/// per-plane, per-tile `xqd` state (spec `ref_sgrproj_info`), updated in
188+/// place after every read (both coded and forced components).
189+fn read_sgrproj_filter(dec: &mut SymbolDecoder, reference: &mut SgrprojInfo) -> SgrprojInfo {
190+ let ep = dec.literal(4) as usize;
191+ let (r0, r1, _s0, _s1) = SGR_PARAMS[ep];
192+ let mut xqd = [0i32; 2];
193+ if r0 == 0 {
194+ xqd[0] = 0;
195+ xqd[1] = decode_unsigned_subexp_with_ref_msac(
196+ dec,
197+ (SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1) as u32,
198+ SGRPROJ_PRJ_SUBEXP_K,
199+ (reference.xqd[1] - SGRPROJ_PRJ_MIN1) as u32,
200+ ) as i32
201+ + SGRPROJ_PRJ_MIN1;
202+ } else if r1 == 0 {
203+ xqd[0] = decode_unsigned_subexp_with_ref_msac(
204+ dec,
205+ (SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1) as u32,
206+ SGRPROJ_PRJ_SUBEXP_K,
207+ (reference.xqd[0] - SGRPROJ_PRJ_MIN0) as u32,
208+ ) as i32
209+ + SGRPROJ_PRJ_MIN0;
210+ xqd[1] = ((1 << SGRPROJ_PRJ_BITS) - xqd[0]).clamp(SGRPROJ_PRJ_MIN1, SGRPROJ_PRJ_MAX1);
211+ } else {
212+ xqd[0] = decode_unsigned_subexp_with_ref_msac(
213+ dec,
214+ (SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1) as u32,
215+ SGRPROJ_PRJ_SUBEXP_K,
216+ (reference.xqd[0] - SGRPROJ_PRJ_MIN0) as u32,
217+ ) as i32
218+ + SGRPROJ_PRJ_MIN0;
219+ xqd[1] = decode_unsigned_subexp_with_ref_msac(
220+ dec,
221+ (SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1) as u32,
222+ SGRPROJ_PRJ_SUBEXP_K,
223+ (reference.xqd[1] - SGRPROJ_PRJ_MIN1) as u32,
224+ ) as i32
225+ + SGRPROJ_PRJ_MIN1;
226+ }
227+ let info = SgrprojInfo { ep, xqd };
228+ *reference = info;
229+ info
230+}
231+
232+impl Default for SgrprojInfo {
233+ fn default() -> Self {
234+ Self {
235+ ep: 0,
236+ xqd: [
237+ (SGRPROJ_PRJ_MIN0 + SGRPROJ_PRJ_MAX0) / 2,
238+ (SGRPROJ_PRJ_MIN1 + SGRPROJ_PRJ_MAX1) / 2,
239+ ],
240+ }
241+ }
242+}
243+
244+/// One restoration unit's decoded filter (spec `RestorationUnitInfo`,
245+/// `RESTORE_NONE`/`WIENER`/`SGRPROJ` -- `Switchable`-frame units pick one of
246+/// these per unit; `Wiener`/`Sgrproj`-frame units are all this same variant
247+/// or `None`).
248+#[derive(Clone, Copy, Debug, PartialEq)]
249+pub(crate) enum UnitFilter {
250+ None,
251+ Wiener(WienerInfo),
252+ Sgrproj(SgrprojInfo),
253+}
254+
255+/// Per-plane restoration-unit grid for one tile/frame (spec `RestorationInfo`
256+/// per plane) -- `av1_lr_count_units`'s `horz_units`/`vert_units` sizing plus
257+/// the flattened `runit_idx = rcol + rrow*horz_units` storage `read_lr`
258+/// fills in superblock order.
259+pub(crate) struct RestorationGrid {
260+ pub horz_units: [usize; 3],
261+ pub vert_units: [usize; 3],
262+ units: [Vec<UnitFilter>; 3],
263+}
264+
265+impl RestorationGrid {
266+ pub(crate) fn new(lr: &LoopRestorationParams, frame_width: u32, frame_height: u32) -> Self {
267+ let mut horz_units = [1usize; 3];
268+ let mut vert_units = [1usize; 3];
269+ let mut units: [Vec<UnitFilter>; 3] = [Vec::new(), Vec::new(), Vec::new()];
270+ for plane in 0..3 {
271+ if lr.frame_restoration_type[plane] == RestorationType::None {
272+ continue;
273+ }
274+ let (pw, ph) = if plane == 0 {
275+ (frame_width, frame_height)
276+ } else {
277+ ((frame_width + 1) / 2, (frame_height + 1) / 2)
278+ };
279+ let unit_size = lr.loop_restoration_size[plane];
280+ horz_units[plane] = count_units(pw, unit_size);
281+ vert_units[plane] = count_units(ph, unit_size);
282+ units[plane] = vec![UnitFilter::None; horz_units[plane] * vert_units[plane]];
283+ }
284+ Self {
285+ horz_units,
286+ vert_units,
287+ units,
288+ }
289+ }
290+
291+ fn set(&mut self, plane: usize, rrow: usize, rcol: usize, filter: UnitFilter) {
292+ let idx = rcol + rrow * self.horz_units[plane];
293+ self.units[plane][idx] = filter;
294+ }
295+
296+ pub(crate) fn get(&self, plane: usize, rrow: usize, rcol: usize) -> UnitFilter {
297+ let idx = rcol + rrow * self.horz_units[plane];
298+ self.units[plane][idx]
299+ }
300+}
301+
302+/// `av1_lr_count_units` (restoration.c:63): round, not ceil, to nearest.
303+fn count_units(plane_size: u32, unit_size: u32) -> usize {
304+ (((plane_size + (unit_size >> 1)) / unit_size).max(1)) as usize
305+}
306+
307+fn ceil_div(a: u32, b: u32) -> u32 {
308+ a.div_ceil(b)
309+}
310+
311+/// `read_lr` (spec 5.11.57) for one superblock at mode-info position
312+/// `(mi_row, mi_col)`: for every plane the frame uses LR on, computes the
313+/// unit-grid corners this superblock covers
314+/// (`av1_loop_restoration_corners_in_sb`, restoration.c:1277 -- every unit
315+/// is >= 64px, so only the top-of-superblock call ever has non-empty
316+/// corners, matching this decoder's own once-per-SB call site) and reads
317+/// one `read_lr_unit` per covered `(rrow, rcol)`, per plane, in plane
318+/// order. `sb_mi` is the superblock's mode-info width (`SB_MI`, 16 for the
319+/// 64px superblocks this decoder always uses).
320+#[allow(clippy::too_many_arguments)]
321+pub(crate) fn read_lr(
322+ dec: &mut SymbolDecoder,
323+ cdfs: &mut crate::cdf_state::Cdfs,
324+ lr: &LoopRestorationParams,
325+ grid: &mut RestorationGrid,
326+ reference: &mut [(WienerInfo, SgrprojInfo); 3],
327+ mi_row: u32,
328+ mi_col: u32,
329+ sb_mi: u32,
330+) {
331+ if !lr.uses_lr {
332+ return;
333+ }
334+ for plane in 0..3 {
335+ let ftype = lr.frame_restoration_type[plane];
336+ if ftype == RestorationType::None {
337+ continue;
338+ }
339+ let mi_size = if plane == 0 { 4u32 } else { 2u32 };
340+ let unit_size = lr.loop_restoration_size[plane];
341+ let horz_units = grid.horz_units[plane] as u32;
342+ let vert_units = grid.vert_units[plane] as u32;
343+ let rcol0 = ceil_div(mi_col * mi_size, unit_size);
344+ let rcol1 = ceil_div((mi_col + sb_mi) * mi_size, unit_size).min(horz_units);
345+ let rrow0 = ceil_div(mi_row * mi_size, unit_size);
346+ let rrow1 = ceil_div((mi_row + sb_mi) * mi_size, unit_size).min(vert_units);
347+ let chroma = plane != 0;
348+ for rrow in rrow0..rrow1 {
349+ for rcol in rcol0..rcol1 {
350+ let filter = read_lr_unit(dec, cdfs, ftype, chroma, &mut reference[plane]);
351+ grid.set(plane, rrow as usize, rcol as usize, filter);
352+ }
353+ }
354+ }
355+}
356+
357+fn read_lr_unit(
358+ dec: &mut SymbolDecoder,
359+ cdfs: &mut crate::cdf_state::Cdfs,
360+ ftype: RestorationType,
361+ chroma: bool,
362+ reference: &mut (WienerInfo, SgrprojInfo),
363+) -> UnitFilter {
364+ match ftype {
365+ RestorationType::Switchable => {
366+ let t = dec.symbol(&mut cdfs.restore_switchable);
367+ match t {
368+ 0 => UnitFilter::None,
369+ 1 => UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0)),
370+ _ => UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1)),
371+ }
372+ }
373+ RestorationType::Wiener => {
374+ if dec.symbol(&mut cdfs.restore_wiener) != 0 {
375+ UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0))
376+ } else {
377+ UnitFilter::None
378+ }
379+ }
380+ RestorationType::Sgrproj => {
381+ if dec.symbol(&mut cdfs.restore_sgrproj) != 0 {
382+ UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1))
383+ } else {
384+ UnitFilter::None
385+ }
386+ }
387+ RestorationType::None => UnitFilter::None,
388+ }
389+}
390+
391+#[cfg(test)]
392+mod tests {
393+ use super::*;
394+ use crate::msac::{SymbolDecoder, SymbolEncoder};
395+
396+ /// `write_primitive_quniform`, the exact inverse of [`ns_msac`] -- used
397+ /// only to build roundtrip fixtures for the decode-only helpers above
398+ /// (this decoder never writes loop restoration itself).
399+ fn write_ns(enc: &mut SymbolEncoder, n: u32, v: u32) {
400+ if n <= 1 {
401+ return;
402+ }
403+ let w = floor_log2(n) + 1;
404+ let m = (1u32 << w) - n;
405+ if v < m {
406+ enc.literal(v, w - 1);
407+ } else {
408+ enc.literal((v + m) >> 1, w - 1);
409+ enc.literal((v + m) & 1, 1);
410+ }
411+ }
412+
413+ fn write_subexp(enc: &mut SymbolEncoder, num_syms: u32, k: u32, v: u32) {
414+ let mut i = 0u32;
415+ let mut mk = 0u32;
416+ loop {
417+ let b = if i > 0 { k + i - 1 } else { k };
418+ let a = 1u32 << b;
419+ if num_syms <= mk + 3 * a {
420+ write_ns(enc, num_syms - mk, v - mk);
421+ return;
422+ }
423+ if v < mk + a {
424+ enc.literal(0, 1);
425+ enc.literal(v - mk, b);
426+ return;
427+ }
428+ enc.literal(1, 1);
429+ i += 1;
430+ mk += a;
431+ }
432+ }
433+
434+ fn recenter(r: u32, v: u32) -> u32 {
435+ if v > 2 * r {
436+ v
437+ } else if v >= r {
438+ (v - r) << 1
439+ } else {
440+ ((r - v) << 1) - 1
441+ }
442+ }
443+
444+ fn write_unsigned_subexp_with_ref(enc: &mut SymbolEncoder, n: u32, k: u32, reference: u32, v: u32) {
445+ let r = reference.clamp(0, n.saturating_sub(1));
446+ let coded = if (r << 1) <= n {
447+ recenter(r, v)
448+ } else {
449+ recenter(n - 1 - r, n - 1 - v)
450+ };
451+ write_subexp(enc, n, k, coded);
452+ }
453+
454+ /// `decode_subexp_msac`/`ns_msac` roundtrip every value in a handful of
455+ /// `(num_syms, k)` alphabets -- the shapes LR's tap ranges (`k` 1..=4,
456+ /// `num_syms` up to 96) actually hit, per `WIENER_TAP_MAXV`-`MINV`+1 /
457+ /// `SGRPROJ_PRJ_MAX-MIN+1`.
458+ #[test]
459+ fn subexp_roundtrips_every_value() {
460+ for &(num_syms, k) in &[(16u32, 1u32), (32, 2), (64, 3), (96, 4), (128, 4), (3, 1), (1, 3)] {
461+ for v in 0..num_syms {
462+ let mut enc = SymbolEncoder::new();
463+ write_subexp(&mut enc, num_syms, k, v);
464+ let payload = enc.finish();
465+ let mut dec = SymbolDecoder::new(&payload);
466+ let got = decode_subexp_msac(&mut dec, num_syms, k);
467+ assert_eq!(got, v, "num_syms={num_syms} k={k} v={v}");
468+ }
469+ }
470+ }
471+
472+ /// The recentred, ref-relative form `read_wiener_filter`/
473+ /// `read_sgrproj_filter` actually call -- every `(n, reference, v)`
474+ /// combination for LR's own tap-0 range (16 values, matching
475+ /// `WIENER_FILT_TAP0_MAXV-MINV+1`).
476+ #[test]
477+ fn unsigned_subexp_with_ref_roundtrips() {
478+ let n = 16u32;
479+ for k in 1..=4u32 {
480+ for reference in 0..n {
481+ for v in 0..n {
482+ let mut enc = SymbolEncoder::new();
483+ write_unsigned_subexp_with_ref(&mut enc, n, k, reference, v);
484+ let payload = enc.finish();
485+ let mut dec = SymbolDecoder::new(&payload);
486+ let got = decode_unsigned_subexp_with_ref_msac(&mut dec, n, k, reference);
487+ assert_eq!(got, v, "n={n} k={k} reference={reference} v={v}");
488+ }
489+ }
490+ }
491+ }
492+
493+ /// Signed wrapper sanity: a handful of `(low, high, k, reference, v)`
494+ /// covering LR's actual Wiener tap-1/tap-2 and SGR `xqd0`/`xqd1` ranges.
495+ #[test]
496+ fn signed_subexp_with_ref_roundtrips() {
497+ let cases: [(i32, i32, u32); 4] = [
498+ (-5, 11, 1), // Wiener tap0
499+ (-23, 9, 2), // Wiener tap1
500+ (-17, 47, 3), // Wiener tap2
501+ (-96, 32, 4), // SGR xqd0
502+ ];
503+ for (low, high, k) in cases {
504+ let n = (high - low) as u32;
505+ for reference_v in [low, low + n as i32 / 3, high - 1] {
506+ for v in [low, low + n as i32 / 2, high - 1] {
507+ let r = (reference_v - low).clamp(0, n as i32) as u32;
508+ let coded_v = (v - low) as u32;
509+ let mut enc = SymbolEncoder::new();
510+ write_unsigned_subexp_with_ref(&mut enc, n, k, r, coded_v);
511+ let payload = enc.finish();
512+ let mut dec = SymbolDecoder::new(&payload);
513+ let got = decode_signed_subexp_with_ref_msac(&mut dec, low, high, k, reference_v);
514+ assert_eq!(got, v, "low={low} high={high} k={k} reference={reference_v} v={v}");
515+ }
516+ }
517+ }
518+ }
519+}