Skip to main content

rust_j2k/
quant.rs

1//! Stage 4 — dequantization (ISO/IEC 15444-1 Annex E.1).
2//!
3//! Maps the quantized integers from Tier-1 back to wavelet-coefficient
4//! magnitudes before the inverse transform. For the **reversible** path (5/3,
5//! `QuantStyle::None`) there is no scaling — only the implicit bit-shift from
6//! the decoded bit-planes — and the inverse must stay exact. For the
7//! **irreversible** path (9/7) each subband has a scalar step size, derived or
8//! expounded, reconstructed from the QCD/QCC (exponent, mantissa) and the
9//! number of guard bits.
10//!
11//! For subband `b`, the step size (E-3) is
12//!
13//! ```text
14//! Δ_b = (1 + μ_b / 2^11) · 2^(R_I + gain_b − ε_b)
15//! ```
16//!
17//! where `ε_b`/`μ_b` are the QCD exponent/mantissa, `R_I` the component bit
18//! depth (SIZ), and `gain_b` the log2 nominal subband gain (LL 0, HL/LH 1,
19//! HH 2). Guard bits do not enter the step; they size the magnitude bit-planes,
20//! which Tier-1/Tier-2 already consumed. A decoded index `q` reconstructs to the
21//! interval mid-point (E.1.1.2, parameter r = ½): `sign(q) · (|q| + ½) · Δ_b`,
22//! with zero mapping to zero. Single-layer Phase 1 decodes every bit-plane, so
23//! the bias is exactly one half-step.
24
25use crate::Result;
26use crate::codestream::MainHeader;
27use crate::codestream::markers::{Qcd, QuantStyle};
28use crate::error::Error;
29use crate::tier1::{Band, Bands, SubbandCoeffs};
30
31/// 2^11 — the implicit denominator of the 11-bit QCD mantissa.
32const MANTISSA_DENOM: f64 = 2048.0;
33
34/// Mid-point reconstruction offset r (E.1.1.2). With every bit-plane decoded
35/// (single layer), the reconstruction bias is exactly one half-step.
36///
37/// The standard leaves r a decoder choice; the integration gate (#17) must
38/// confirm the OpenJPEG/eccodes oracle also reconstructs at the interval
39/// mid-point rather than its lower edge (r = 0), which would be a one-line change.
40const RECON_BIAS: f64 = 0.5;
41
42/// Apply per-subband dequantization in place. Reversible: identity. Irreversible:
43/// multiply by the subband step (with the standard mid-point reconstruction
44/// bias). Returns coefficients ready for the inverse DWT.
45pub fn dequantize(header: &MainHeader, coeffs: SubbandCoeffs) -> Result<SubbandCoeffs> {
46    match coeffs {
47        // Reversible (5/3): the integer coefficients are already exact.
48        SubbandCoeffs::Reversible(bands) => Ok(SubbandCoeffs::Reversible(bands)),
49        SubbandCoeffs::Irreversible(mut bands) => {
50            scale_irreversible(header, &mut bands)?;
51            Ok(SubbandCoeffs::Irreversible(bands))
52        }
53    }
54}
55
56/// Scale every subband of the 9/7 pyramid by its reconstructed step size. Bands
57/// run in QCD subband order: LL first, then each resolution level coarsest-first
58/// as `HL, LH, HH` ([`Bands`] stores `levels` coarsest-first to match).
59fn scale_irreversible(header: &MainHeader, bands: &mut Bands<f32>) -> Result<()> {
60    let prec = i32::from(
61        header
62            .siz
63            .components
64            .first()
65            .ok_or_else(|| Error::Inconsistent("SIZ declares no components".into()))?
66            .bit_depth,
67    );
68    let qcd = &header.qcd;
69
70    // Expounded QCDs carry exactly one step per subband (1 LL + 3 per level); a
71    // mismatch means the QCD and the COD decomposition depth disagree.
72    if qcd.style == QuantStyle::ScalarExpounded {
73        let expected = 1 + 3 * bands.levels.len();
74        if qcd.steps.len() != expected {
75            return Err(Error::Inconsistent(format!(
76                "expounded QCD carries {} step sizes, expected {expected} for {} levels",
77                qcd.steps.len(),
78                bands.levels.len()
79            )));
80        }
81    }
82
83    apply_band(&mut bands.ll, step_params(qcd, 0)?, 0, prec);
84    let mut b = 1;
85    for level in &mut bands.levels {
86        apply_band(&mut level.hl, step_params(qcd, b)?, 1, prec);
87        apply_band(&mut level.lh, step_params(qcd, b + 1)?, 1, prec);
88        apply_band(&mut level.hh, step_params(qcd, b + 2)?, 2, prec);
89        b += 3;
90    }
91    Ok(())
92}
93
94/// The `(exponent, mantissa)` pair for subband index `band`. Expounded styles
95/// read it straight from the QCD; the derived style stores only subband 0 and
96/// drops the exponent by one per resolution level finer (E-5, OpenJPEG's
97/// `ε_b = max(ε_0 − ⌊(b−1)/3⌋, 0)`), keeping the single mantissa.
98fn step_params(qcd: &Qcd, band: usize) -> Result<(u8, u16)> {
99    if qcd.style == QuantStyle::None {
100        return Err(Error::Inconsistent(
101            "irreversible transform needs scalar quantization, found QuantStyle::None".into(),
102        ));
103    }
104    // The per-subband exponent/mantissa mapping (expounded lookup or derived
105    // per-level drop) is shared with Tier-1's bit-plane count so the two stay
106    // numerically identical.
107    qcd.subband_step(band).ok_or_else(|| {
108        Error::Inconsistent(format!(
109            "QCD carries {} step sizes but subband {band} needs one",
110            qcd.steps.len()
111        ))
112    })
113}
114
115/// Reconstruct one subband's coefficients in place: `sign(q) · (|q| + ½) · Δ`,
116/// leaving zeros at zero. `gain` is the log2 nominal subband gain.
117///
118/// The step and the per-sample product are formed in `f64` and narrowed to
119/// `f32` only at the end: `R_I` can reach 38 bits (the SIZ depth), so the
120/// `2^(R_I + gain − ε)` factor exceeds the `f32` range, and the wider mantissa
121/// keeps `(|q| + ½)·Δ` accurate before the lossy-tolerance comparison. A `-0.0`
122/// index is filtered by the `!= 0.0` guard, so `signum` never sees it.
123fn apply_band(band: &mut Band<f32>, (exp, mant): (u8, u16), gain: i32, prec: i32) {
124    let step = (1.0 + f64::from(mant) / MANTISSA_DENOM) * 2f64.powi(prec + gain - i32::from(exp));
125    for v in &mut band.data {
126        if *v != 0.0 {
127            let q = f64::from(*v);
128            *v = (q.signum() * (q.abs() + RECON_BIAS) * step) as f32;
129        }
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use crate::codestream::markers::{Cod, Progression, Siz, SizComponent, Transform};
137    use crate::tier1::DetailBands;
138
139    /// A `prec`-bit single-component header carrying `qcd`. Only the component
140    /// depth and the QCD feed dequantization; the rest is filler.
141    fn header(prec: u8, qcd: Qcd) -> MainHeader {
142        MainHeader {
143            siz: Siz {
144                x_size: 4,
145                y_size: 4,
146                x_offset: 0,
147                y_offset: 0,
148                tile_width: 4,
149                tile_height: 4,
150                tile_x_offset: 0,
151                tile_y_offset: 0,
152                components: vec![SizComponent {
153                    bit_depth: prec,
154                    signed: false,
155                    x_sampling: 1,
156                    y_sampling: 1,
157                }],
158            },
159            cod: Cod {
160                progression: Progression::Lrcp,
161                layers: 1,
162                decomposition_levels: 1,
163                code_block_width: 4,
164                code_block_height: 4,
165                code_block_style: 0,
166                transform: Transform::Irreversible97,
167                precinct_sizes: vec![],
168            },
169            qcd,
170        }
171    }
172
173    /// A 1×1 float band holding a single coefficient.
174    fn band(value: f32) -> Band<f32> {
175        Band {
176            origin: (0, 0),
177            width: 1,
178            height: 1,
179            data: vec![value],
180        }
181    }
182
183    /// A one-decomposition-level pyramid: `ll` plus a single detail level.
184    fn one_level(ll: f32, hl: f32, lh: f32, hh: f32) -> SubbandCoeffs {
185        SubbandCoeffs::Irreversible(Bands {
186            ll: band(ll),
187            levels: vec![DetailBands {
188                hl: band(hl),
189                lh: band(lh),
190                hh: band(hh),
191            }],
192        })
193    }
194
195    /// The Annex E.1 step size, recomputed independently for the assertions.
196    fn step(prec: i32, gain: i32, exp: i32, mant: i32) -> f32 {
197        (1.0 + mant as f32 / 2048.0) * 2f32.powi(prec + gain - exp)
198    }
199
200    /// Mid-point reconstruction of one index, mirroring [`apply_band`].
201    fn recon(q: f32, step: f32) -> f32 {
202        if q == 0.0 {
203            0.0
204        } else {
205            q.signum() * (q.abs() + 0.5) * step
206        }
207    }
208
209    fn assert_close(got: f32, want: f32) {
210        assert!(
211            (got - want).abs() <= 1e-3 * want.abs().max(1.0),
212            "got {got}, want {want}"
213        );
214    }
215
216    /// Pull the irreversible bands out, failing loudly on the wrong arm.
217    fn irreversible(coeffs: SubbandCoeffs) -> Bands<f32> {
218        match coeffs {
219            SubbandCoeffs::Irreversible(b) => b,
220            SubbandCoeffs::Reversible(_) => panic!("expected irreversible coefficients"),
221        }
222    }
223
224    #[test]
225    fn reversible_is_identity() {
226        let bands = Bands {
227            ll: Band {
228                origin: (0, 0),
229                width: 2,
230                height: 1,
231                data: vec![3, -7],
232            },
233            levels: vec![],
234        };
235        let qcd = Qcd {
236            style: QuantStyle::None,
237            guard_bits: 2,
238            steps: vec![(8, 0)],
239        };
240        let out = dequantize(&header(8, qcd), SubbandCoeffs::Reversible(bands.clone())).unwrap();
241        assert_eq!(out, SubbandCoeffs::Reversible(bands));
242    }
243
244    #[test]
245    fn expounded_matches_hand_computed() {
246        let prec = 8;
247        let qcd = Qcd {
248            style: QuantStyle::ScalarExpounded,
249            guard_bits: 2,
250            // (exp, mant) for LL, HL, LH, HH of the single level.
251            steps: vec![(8, 0), (7, 512), (7, 512), (6, 1024)],
252        };
253        let out =
254            irreversible(dequantize(&header(prec, qcd), one_level(5.0, -3.0, 0.0, 2.0)).unwrap());
255
256        assert_close(out.ll.data[0], recon(5.0, step(8, 0, 8, 0)));
257        assert_close(out.levels[0].hl.data[0], recon(-3.0, step(8, 1, 7, 512)));
258        // A zero index stays exactly zero, no bias applied.
259        assert_eq!(out.levels[0].lh.data[0], 0.0);
260        assert_close(out.levels[0].hh.data[0], recon(2.0, step(8, 2, 6, 1024)));
261    }
262
263    #[test]
264    fn derived_drops_exponent_one_per_level() {
265        let prec = 8;
266        let qcd = Qcd {
267            style: QuantStyle::ScalarDerived,
268            guard_bits: 1,
269            steps: vec![(10, 100)],
270        };
271        let coeffs = SubbandCoeffs::Irreversible(Bands {
272            ll: band(1.0),
273            levels: vec![
274                // Coarsest level: exponent ε₀ = 10.
275                DetailBands {
276                    hl: band(1.0),
277                    lh: band(1.0),
278                    hh: band(1.0),
279                },
280                // Finer level: exponent drops to 9.
281                DetailBands {
282                    hl: band(1.0),
283                    lh: band(1.0),
284                    hh: band(1.0),
285                },
286            ],
287        });
288        let out = irreversible(dequantize(&header(prec, qcd), coeffs).unwrap());
289
290        assert_close(out.ll.data[0], recon(1.0, step(8, 0, 10, 100)));
291        assert_close(out.levels[0].hl.data[0], recon(1.0, step(8, 1, 10, 100)));
292        assert_close(out.levels[1].hl.data[0], recon(1.0, step(8, 1, 9, 100)));
293    }
294
295    #[test]
296    fn derived_exponent_saturates_at_zero() {
297        let qcd = Qcd {
298            style: QuantStyle::ScalarDerived,
299            guard_bits: 1,
300            steps: vec![(1, 0)],
301        };
302        // Three levels: the finest sits at level index 2, so ε = max(1 − 2, 0) = 0.
303        let levels = (0..3)
304            .map(|_| DetailBands {
305                hl: band(1.0),
306                lh: band(1.0),
307                hh: band(1.0),
308            })
309            .collect();
310        let coeffs = SubbandCoeffs::Irreversible(Bands {
311            ll: band(1.0),
312            levels,
313        });
314        let out = irreversible(dequantize(&header(8, qcd), coeffs).unwrap());
315        assert_close(out.levels[2].hl.data[0], recon(1.0, step(8, 1, 0, 0)));
316    }
317
318    #[test]
319    fn expounded_with_too_few_steps_is_inconsistent() {
320        let qcd = Qcd {
321            style: QuantStyle::ScalarExpounded,
322            guard_bits: 2,
323            // Only the LL step, but a one-level pyramid needs four.
324            steps: vec![(8, 0)],
325        };
326        let err = dequantize(&header(8, qcd), one_level(1.0, 1.0, 1.0, 1.0)).unwrap_err();
327        assert!(matches!(err, Error::Inconsistent(_)));
328    }
329
330    #[test]
331    fn expounded_with_too_many_steps_is_inconsistent() {
332        let qcd = Qcd {
333            style: QuantStyle::ScalarExpounded,
334            guard_bits: 2,
335            // Seven steps (two levels' worth) against a one-level pyramid: the
336            // QCD and COD decomposition depth disagree.
337            steps: vec![(8, 0); 7],
338        };
339        let err = dequantize(&header(8, qcd), one_level(1.0, 1.0, 1.0, 1.0)).unwrap_err();
340        assert!(matches!(err, Error::Inconsistent(_)));
341    }
342
343    #[test]
344    fn expounded_walks_two_levels_in_order() {
345        let prec = 8;
346        // LL, then coarsest HL/LH/HH, then finer HL/LH/HH — each a distinct step
347        // so a mis-indexed walk would surface.
348        let qcd = Qcd {
349            style: QuantStyle::ScalarExpounded,
350            guard_bits: 2,
351            steps: vec![
352                (9, 0),
353                (8, 16),
354                (8, 32),
355                (7, 64),
356                (6, 128),
357                (6, 256),
358                (5, 512),
359            ],
360        };
361        let coeffs = SubbandCoeffs::Irreversible(Bands {
362            ll: band(2.0),
363            levels: vec![
364                DetailBands {
365                    hl: band(2.0),
366                    lh: band(2.0),
367                    hh: band(2.0),
368                },
369                DetailBands {
370                    hl: band(2.0),
371                    lh: band(2.0),
372                    hh: band(2.0),
373                },
374            ],
375        });
376        let out = irreversible(dequantize(&header(prec, qcd), coeffs).unwrap());
377
378        assert_close(out.ll.data[0], recon(2.0, step(8, 0, 9, 0)));
379        assert_close(out.levels[0].lh.data[0], recon(2.0, step(8, 1, 8, 32)));
380        assert_close(out.levels[0].hh.data[0], recon(2.0, step(8, 2, 7, 64)));
381        assert_close(out.levels[1].hl.data[0], recon(2.0, step(8, 1, 6, 128)));
382        assert_close(out.levels[1].hh.data[0], recon(2.0, step(8, 2, 5, 512)));
383    }
384
385    #[test]
386    fn opposite_signs_reconstruct_to_negatives() {
387        let qcd = Qcd {
388            style: QuantStyle::ScalarExpounded,
389            guard_bits: 2,
390            steps: vec![(7, 300), (7, 300), (7, 300), (7, 300)],
391        };
392        let pos = irreversible(
393            dequantize(&header(10, qcd.clone()), one_level(6.0, 0.0, 0.0, 0.0)).unwrap(),
394        );
395        let neg =
396            irreversible(dequantize(&header(10, qcd), one_level(-6.0, 0.0, 0.0, 0.0)).unwrap());
397        assert_eq!(pos.ll.data[0], -neg.ll.data[0]);
398        assert!(pos.ll.data[0] > 0.0);
399    }
400
401    #[test]
402    fn irreversible_without_scalar_quant_is_inconsistent() {
403        let qcd = Qcd {
404            style: QuantStyle::None,
405            guard_bits: 2,
406            steps: vec![(8, 0)],
407        };
408        let err = dequantize(&header(8, qcd), one_level(1.0, 1.0, 1.0, 1.0)).unwrap_err();
409        assert!(matches!(err, Error::Inconsistent(_)));
410    }
411}