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 ISO 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. The `gain_b` term is **not** applied
21//! here — the inverse 9/7 carries it, one factor of two per high-pass filtering
22//! (see [`half_step_of`] and [`crate::dwt`]).
23//!
24//! **The mid-point reconstruction (E.1.1.2, r = ½) is not applied here.**
25//! Tier-1 already carries it: a coefficient that becomes significant at plane
26//! `b` is set to `2^b + 2^(b−1)`, which *is* the interval mid-point, and every
27//! refinement keeps the running half. Those magnitudes arrive at twice their
28//! weight, so the coefficient is
29//!
30//! ```text
31//! v = q_double · (Δ_b / 2)
32//! ```
33//!
34//! which is `opj_t1_clbl_decode_processor`'s `stepsize = 0.5f * band->stepsize;
35//! tmp = (float)datap * stepsize`. Adding a further `± ½ · Δ_b` here would bias
36//! every coefficient by a half step, and halving `q_double` with an integer
37//! divide first would silently cancel that bias for odd `q` while leaving it for
38//! even `q` — an easy pair of mistakes to make together, because they look
39//! correct on any coefficient that was coded to its last bit-plane.
40//!
41//! The step here therefore matches OpenJPEG's gain-free 9/7 decode step on
42//! every band; the gain moves to the inverse transform (see [`half_step_of`]).
43
44use crate::Result;
45use crate::codestream::MainHeader;
46use crate::codestream::markers::{Qcd, QuantStyle};
47use crate::error::Error;
48
49/// 2^11 — the implicit denominator of the 11-bit QCD mantissa.
50const MANTISSA_DENOM: f64 = 2048.0;
51
52/// The factor that turns one decoded 9/7 index of subband `band` of component
53/// `comp` into a coefficient: half the subband step, because Tier-1 hands over
54/// magnitudes at twice their weight and already at the interval mid-point.
55/// Tier-1 multiplies each index by it as it places the block, one `f32`
56/// multiply per coefficient. (The 5/3 path has no scaling.)
57///
58/// `band` is the subband index in QCD order: LL is 0, then each resolution
59/// level coarsest-first as `HL, LH, HH`.
60///
61/// The step depends on the component's declared bit depth, so a
62/// multi-component image with mixed depths dequantizes each one on its own
63/// scale. The quantization parameters read here are per component: the
64/// codestream stage resolves QCD's main-header default and any QCC override
65/// before this runs. A QCD without a step for `band` is an error, so a
66/// pyramid deeper than its steps is refused, as before.
67pub fn half_step(header: &MainHeader, comp: usize, band: usize) -> Result<f32> {
68    let prec = i32::from(
69        header
70            .siz
71            .components
72            .get(comp)
73            .ok_or_else(|| Error::inconsistent(format!("`SIZ` declares no component {comp}")))?
74            .bit_depth,
75    );
76    let qcd = &header
77        .components
78        .get(comp)
79        .ok_or_else(|| Error::inconsistent(format!("no coding parameters for component {comp}")))?
80        .quant;
81    Ok(half_step_of(step_params(qcd, band)?, prec))
82}
83
84/// The `(exponent, mantissa)` pair for subband index `band`. Expounded styles
85/// read it straight from the QCD; the derived style stores only subband 0 and
86/// drops the exponent by one per resolution level finer (E-5, OpenJPEG's
87/// `ε_b = max(ε_0 − ⌊(b−1)/3⌋, 0)`), keeping the single mantissa.
88fn step_params(qcd: &Qcd, band: usize) -> Result<(u8, u16)> {
89    if qcd.style == QuantStyle::None {
90        return Err(Error::inconsistent(
91            "irreversible transform needs scalar quantization, found QuantStyle::None",
92        ));
93    }
94    // The per-subband exponent/mantissa mapping (expounded lookup or derived
95    // per-level drop) is shared with Tier-1's bit-plane count so the two stay
96    // numerically identical.
97    qcd.subband_step(band).ok_or_else(|| {
98        Error::inconsistent(format!(
99            "`QCD` carries {} step sizes but subband {band} needs one",
100            qcd.steps.len()
101        ))
102    })
103}
104
105/// Half the step size of one subband.
106///
107/// The step is computed in `f64` because `R_I` can reach 38 bits (the SIZ
108/// depth), so the `2^(R_I − ε)` factor can leave the `f32` range. It is then
109/// narrowed and halved the way OpenJPEG does — `(OPJ_FLOAT32)step`, then
110/// `0.5f * band->stepsize`. Narrowing first and halving after is exact (halving
111/// only decrements the exponent), and multiplying each coefficient by
112/// `0.5 · step` in one `f32` operation is a single rounding, as the oracle has.
113/// Keeping an `f64` intermediate would be *more* accurate and would round
114/// differently near a tie.
115///
116/// The step deliberately omits the log2 nominal subband gain (Table E-1: LL 0,
117/// HL/LH 1, HH 2). OpenJPEG omits it too for the 9/7 decode (`tcd.c`'s
118/// `log2_gain = (!isEncoder && qmfbid == 0) ? 0 : …`) and folds the gain into
119/// the inverse 9/7 instead, one factor of two per high-pass filtering. This
120/// crate does the same in [`crate::dwt`] (high-pass reconstruction scaled by
121/// `2/K` rather than `1/K`). Placing the gain per-filter, not per-subband, is
122/// what makes it correct on a tile-component whose coarse resolutions are empty:
123/// there a coefficient can be high-pass a different number of times than its
124/// nominal subband gain, and a fixed `2^gain` in the step would mis-scale it
125/// (see #126). `2/K` is applied as an exact `2 · (1/K)`, so for the ordinary
126/// case — where the high-pass count equals the gain — the result is bit-for-bit
127/// what the old `2^gain`-in-step form produced, and `p0_09` stays exact.
128fn half_step_of((exp, mant): (u8, u16), prec: i32) -> f32 {
129    let step = (1.0 + f64::from(mant) / MANTISSA_DENOM) * 2f64.powi(prec - i32::from(exp));
130    0.5f32 * step as f32
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use crate::codestream::markers::Transform;
137
138    /// A `prec`-bit single-component header carrying `qcd`. Only the component
139    /// depth and the QCD feed dequantization; the rest is filler.
140    fn header(prec: u8, qcd: Qcd) -> MainHeader {
141        MainHeader::single_component((4, 4), (prec, false), (1, Transform::Irreversible97), qcd)
142    }
143
144    /// The Annex E.1 step size, recomputed independently for the assertions.
145    /// The gain is not part of the step (dequantization omits it; the inverse
146    /// 9/7 carries it, see [`half_step_of`]), so it does not appear here.
147    fn step(prec: i32, exp: i32, mant: i32) -> f32 {
148        (1.0 + mant as f32 / 2048.0) * 2f32.powi(prec - exp)
149    }
150
151    /// The factor `opj_t1_clbl_decode_processor` multiplies by:
152    /// `0.5f * band->stepsize`.
153    fn want(step: f32) -> f32 {
154        0.5f32 * step
155    }
156
157    fn assert_close(got: f32, want: f32) {
158        assert!(
159            (got - want).abs() <= 1e-3 * want.abs().max(1.0),
160            "got {got}, want {want}"
161        );
162    }
163
164    #[test]
165    fn expounded_matches_hand_computed() {
166        let qcd = Qcd {
167            style: QuantStyle::ScalarExpounded,
168            guard_bits: 2,
169            // (exp, mant) for LL, HL, LH, HH of the single level.
170            steps: vec![(8, 0), (7, 512), (7, 512), (6, 1024)],
171        };
172        let h = header(8, qcd);
173        assert_close(half_step(&h, 0, 0).unwrap(), want(step(8, 8, 0)));
174        assert_close(half_step(&h, 0, 1).unwrap(), want(step(8, 7, 512)));
175        assert_close(half_step(&h, 0, 2).unwrap(), want(step(8, 7, 512)));
176        assert_close(half_step(&h, 0, 3).unwrap(), want(step(8, 6, 1024)));
177    }
178
179    /// The factor is the exact operand the oracle multiplies by, not just a
180    /// close value: narrow the `f64` step, then halve.
181    #[test]
182    fn half_step_is_the_narrowed_step_halved() {
183        let qcd = Qcd {
184            style: QuantStyle::ScalarExpounded,
185            guard_bits: 2,
186            steps: vec![(9, 1234)],
187        };
188        let exact = (1.0 + 1234.0 / 2048.0) * 2f64.powi(12 - 9);
189        assert_eq!(
190            half_step(&header(12, qcd), 0, 0).unwrap().to_bits(),
191            (0.5f32 * exact as f32).to_bits()
192        );
193    }
194
195    #[test]
196    fn derived_drops_exponent_one_per_level() {
197        let qcd = Qcd {
198            style: QuantStyle::ScalarDerived,
199            guard_bits: 1,
200            steps: vec![(10, 100)],
201        };
202        let h = header(8, qcd);
203        assert_close(half_step(&h, 0, 0).unwrap(), want(step(8, 10, 100)));
204        // Coarsest level: exponent 10. Finer level: 9.
205        assert_close(half_step(&h, 0, 1).unwrap(), want(step(8, 10, 100)));
206        assert_close(half_step(&h, 0, 4).unwrap(), want(step(8, 9, 100)));
207    }
208
209    #[test]
210    fn derived_exponent_saturates_at_zero() {
211        let qcd = Qcd {
212            style: QuantStyle::ScalarDerived,
213            guard_bits: 1,
214            steps: vec![(1, 0)],
215        };
216        // The finest of three levels is band 7: exponent max(1 - 2, 0) = 0.
217        assert_close(
218            half_step(&header(8, qcd), 0, 7).unwrap(),
219            want(step(8, 0, 0)),
220        );
221    }
222
223    #[test]
224    fn expounded_walks_two_levels_in_order() {
225        // LL, then coarsest HL/LH/HH, then finer HL/LH/HH, each a distinct
226        // step so a mis-indexed walk would surface.
227        let steps = [
228            (9, 0),
229            (8, 16),
230            (8, 32),
231            (7, 64),
232            (6, 128),
233            (6, 256),
234            (5, 512),
235        ];
236        let qcd = Qcd {
237            style: QuantStyle::ScalarExpounded,
238            guard_bits: 2,
239            steps: steps.to_vec(),
240        };
241        let h = header(8, qcd);
242        for (band, (exp, mant)) in steps.into_iter().enumerate() {
243            assert_close(
244                half_step(&h, 0, band).unwrap(),
245                want(step(8, i32::from(exp), i32::from(mant))),
246            );
247        }
248    }
249
250    #[test]
251    fn a_band_without_a_step_is_inconsistent() {
252        let qcd = Qcd {
253            style: QuantStyle::ScalarExpounded,
254            guard_bits: 2,
255            steps: vec![(8, 0)],
256        };
257        let err = half_step(&header(8, qcd), 0, 1).unwrap_err();
258        assert!(matches!(err, Error::Inconsistent(_)));
259    }
260
261    #[test]
262    fn excess_steps_are_ignored() {
263        let qcd = Qcd {
264            style: QuantStyle::ScalarExpounded,
265            guard_bits: 2,
266            steps: vec![(8, 0); 7],
267        };
268        half_step(&header(8, qcd), 0, 3)
269            .expect("excess entries are padding, as OpenJPEG treats them");
270    }
271
272    #[test]
273    fn irreversible_without_scalar_quant_is_inconsistent() {
274        let qcd = Qcd {
275            style: QuantStyle::None,
276            guard_bits: 2,
277            steps: vec![(8, 0)],
278        };
279        let err = half_step(&header(8, qcd), 0, 0).unwrap_err();
280        assert!(matches!(err, Error::Inconsistent(_)));
281    }
282
283    #[test]
284    fn an_unknown_component_is_inconsistent() {
285        let qcd = Qcd {
286            style: QuantStyle::ScalarExpounded,
287            guard_bits: 2,
288            steps: vec![(8, 0)],
289        };
290        let err = half_step(&header(8, qcd), 1, 0).unwrap_err();
291        assert!(matches!(err, Error::Inconsistent(_)));
292    }
293}