use crate::Result;
use crate::codestream::MainHeader;
use crate::codestream::markers::{Qcd, QuantStyle};
use crate::error::Error;
use crate::tier1::{Band, Bands, SubbandCoeffs};
const MANTISSA_DENOM: f64 = 2048.0;
pub fn dequantize(
header: &MainHeader,
comp: usize,
coeffs: SubbandCoeffs,
) -> Result<SubbandCoeffs> {
match coeffs {
SubbandCoeffs::Reversible(bands) => Ok(SubbandCoeffs::Reversible(bands)),
SubbandCoeffs::Irreversible(mut bands) => {
scale_irreversible(header, comp, &mut bands)?;
Ok(SubbandCoeffs::Irreversible(bands))
}
}
}
fn scale_irreversible(header: &MainHeader, comp: usize, bands: &mut Bands<f32>) -> Result<()> {
let prec = i32::from(
header
.siz
.components
.get(comp)
.ok_or_else(|| Error::Inconsistent(format!("SIZ declares no component {comp}")))?
.bit_depth,
);
let qcd = &header
.components
.get(comp)
.ok_or_else(|| Error::Inconsistent(format!("no coding parameters for component {comp}")))?
.quant;
if qcd.style == QuantStyle::ScalarExpounded {
let expected = 1 + 3 * bands.levels.len();
if qcd.steps.len() < expected {
return Err(Error::Inconsistent(format!(
"expounded QCD carries {} step sizes, expected {expected} for {} levels",
qcd.steps.len(),
bands.levels.len()
)));
}
}
apply_band(&mut bands.ll, step_params(qcd, 0)?, prec);
let mut b = 1;
for level in &mut bands.levels {
apply_band(&mut level.hl, step_params(qcd, b)?, prec);
apply_band(&mut level.lh, step_params(qcd, b + 1)?, prec);
apply_band(&mut level.hh, step_params(qcd, b + 2)?, prec);
b += 3;
}
Ok(())
}
fn step_params(qcd: &Qcd, band: usize) -> Result<(u8, u16)> {
if qcd.style == QuantStyle::None {
return Err(Error::Inconsistent(
"irreversible transform needs scalar quantization, found QuantStyle::None".into(),
));
}
qcd.subband_step(band).ok_or_else(|| {
Error::Inconsistent(format!(
"QCD carries {} step sizes but subband {band} needs one",
qcd.steps.len()
))
})
}
fn apply_band(band: &mut Band<f32>, (exp, mant): (u8, u16), prec: i32) {
let step = (1.0 + f64::from(mant) / MANTISSA_DENOM) * 2f64.powi(prec - i32::from(exp));
let half_step = 0.5f32 * step as f32;
for v in &mut band.data {
*v *= half_step;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codestream::markers::{Cod, Progression, Siz, SizComponent, Transform};
use crate::tier1::DetailBands;
fn header(prec: u8, qcd: Qcd) -> MainHeader {
MainHeader::new(
Siz {
x_size: 4,
y_size: 4,
x_offset: 0,
y_offset: 0,
tile_width: 4,
tile_height: 4,
tile_x_offset: 0,
tile_y_offset: 0,
components: vec![SizComponent {
bit_depth: prec,
signed: false,
x_sampling: 1,
y_sampling: 1,
}],
},
Cod {
progression: Progression::Lrcp,
layers: 1,
decomposition_levels: 1,
code_block_width: 4,
code_block_height: 4,
code_block_style: 0,
use_sop: false,
use_eph: false,
multiple_component_transform: false,
transform: Transform::Irreversible97,
precinct_sizes: vec![],
},
qcd,
)
}
fn band(value: f32) -> Band<f32> {
Band {
origin: (0, 0),
width: 1,
height: 1,
data: vec![value],
}
}
fn one_level(ll: f32, hl: f32, lh: f32, hh: f32) -> SubbandCoeffs {
SubbandCoeffs::Irreversible(Bands {
ll: band(ll),
levels: vec![DetailBands {
hl: band(hl),
lh: band(lh),
hh: band(hh),
}],
})
}
fn step(prec: i32, exp: i32, mant: i32) -> f32 {
(1.0 + mant as f32 / 2048.0) * 2f32.powi(prec - exp)
}
fn recon(q: f32, step: f32) -> f32 {
q * (0.5f32 * step)
}
fn assert_close(got: f32, want: f32) {
assert!(
(got - want).abs() <= 1e-3 * want.abs().max(1.0),
"got {got}, want {want}"
);
}
fn irreversible(coeffs: SubbandCoeffs) -> Bands<f32> {
match coeffs {
SubbandCoeffs::Irreversible(b) => b,
SubbandCoeffs::Reversible(_) => panic!("expected irreversible coefficients"),
}
}
#[test]
fn reversible_is_identity() {
let bands = Bands {
ll: Band {
origin: (0, 0),
width: 2,
height: 1,
data: vec![3, -7],
},
levels: vec![],
};
let qcd = Qcd {
style: QuantStyle::None,
guard_bits: 2,
steps: vec![(8, 0)],
};
let out = dequantize(&header(8, qcd), 0, SubbandCoeffs::Reversible(bands.clone())).unwrap();
assert_eq!(out, SubbandCoeffs::Reversible(bands));
}
#[test]
fn expounded_matches_hand_computed() {
let prec = 8;
let qcd = Qcd {
style: QuantStyle::ScalarExpounded,
guard_bits: 2,
steps: vec![(8, 0), (7, 512), (7, 512), (6, 1024)],
};
let out = irreversible(
dequantize(&header(prec, qcd), 0, one_level(5.0, -3.0, 0.0, 2.0)).unwrap(),
);
assert_close(out.ll.data[0], recon(5.0, step(8, 8, 0)));
assert_close(out.levels[0].hl.data[0], recon(-3.0, step(8, 7, 512)));
assert_eq!(out.levels[0].lh.data[0], 0.0);
assert_close(out.levels[0].hh.data[0], recon(2.0, step(8, 6, 1024)));
}
#[test]
fn derived_drops_exponent_one_per_level() {
let prec = 8;
let qcd = Qcd {
style: QuantStyle::ScalarDerived,
guard_bits: 1,
steps: vec![(10, 100)],
};
let coeffs = SubbandCoeffs::Irreversible(Bands {
ll: band(1.0),
levels: vec![
DetailBands {
hl: band(1.0),
lh: band(1.0),
hh: band(1.0),
},
DetailBands {
hl: band(1.0),
lh: band(1.0),
hh: band(1.0),
},
],
});
let out = irreversible(dequantize(&header(prec, qcd), 0, coeffs).unwrap());
assert_close(out.ll.data[0], recon(1.0, step(8, 10, 100)));
assert_close(out.levels[0].hl.data[0], recon(1.0, step(8, 10, 100)));
assert_close(out.levels[1].hl.data[0], recon(1.0, step(8, 9, 100)));
}
#[test]
fn derived_exponent_saturates_at_zero() {
let qcd = Qcd {
style: QuantStyle::ScalarDerived,
guard_bits: 1,
steps: vec![(1, 0)],
};
let levels = (0..3)
.map(|_| DetailBands {
hl: band(1.0),
lh: band(1.0),
hh: band(1.0),
})
.collect();
let coeffs = SubbandCoeffs::Irreversible(Bands {
ll: band(1.0),
levels,
});
let out = irreversible(dequantize(&header(8, qcd), 0, coeffs).unwrap());
assert_close(out.levels[2].hl.data[0], recon(1.0, step(8, 0, 0)));
}
#[test]
fn expounded_with_too_few_steps_is_inconsistent() {
let qcd = Qcd {
style: QuantStyle::ScalarExpounded,
guard_bits: 2,
steps: vec![(8, 0)],
};
let err = dequantize(&header(8, qcd), 0, one_level(1.0, 1.0, 1.0, 1.0)).unwrap_err();
assert!(matches!(err, Error::Inconsistent(_)));
}
#[test]
fn expounded_with_excess_steps_ignores_the_tail() {
let qcd = Qcd {
style: QuantStyle::ScalarExpounded,
guard_bits: 2,
steps: vec![(8, 0); 7],
};
dequantize(&header(8, qcd), 0, one_level(1.0, 1.0, 1.0, 1.0))
.expect("excess entries are padding, not a geometry disagreement");
}
#[test]
fn expounded_walks_two_levels_in_order() {
let prec = 8;
let qcd = Qcd {
style: QuantStyle::ScalarExpounded,
guard_bits: 2,
steps: vec![
(9, 0),
(8, 16),
(8, 32),
(7, 64),
(6, 128),
(6, 256),
(5, 512),
],
};
let coeffs = SubbandCoeffs::Irreversible(Bands {
ll: band(2.0),
levels: vec![
DetailBands {
hl: band(2.0),
lh: band(2.0),
hh: band(2.0),
},
DetailBands {
hl: band(2.0),
lh: band(2.0),
hh: band(2.0),
},
],
});
let out = irreversible(dequantize(&header(prec, qcd), 0, coeffs).unwrap());
assert_close(out.ll.data[0], recon(2.0, step(8, 9, 0)));
assert_close(out.levels[0].lh.data[0], recon(2.0, step(8, 8, 32)));
assert_close(out.levels[0].hh.data[0], recon(2.0, step(8, 7, 64)));
assert_close(out.levels[1].hl.data[0], recon(2.0, step(8, 6, 128)));
assert_close(out.levels[1].hh.data[0], recon(2.0, step(8, 5, 512)));
}
#[test]
fn opposite_signs_reconstruct_to_negatives() {
let qcd = Qcd {
style: QuantStyle::ScalarExpounded,
guard_bits: 2,
steps: vec![(7, 300), (7, 300), (7, 300), (7, 300)],
};
let pos = irreversible(
dequantize(&header(10, qcd.clone()), 0, one_level(6.0, 0.0, 0.0, 0.0)).unwrap(),
);
let neg =
irreversible(dequantize(&header(10, qcd), 0, one_level(-6.0, 0.0, 0.0, 0.0)).unwrap());
assert_eq!(pos.ll.data[0], -neg.ll.data[0]);
assert!(pos.ll.data[0] > 0.0);
}
#[test]
fn irreversible_without_scalar_quant_is_inconsistent() {
let qcd = Qcd {
style: QuantStyle::None,
guard_bits: 2,
steps: vec![(8, 0)],
};
let err = dequantize(&header(8, qcd), 0, one_level(1.0, 1.0, 1.0, 1.0)).unwrap_err();
assert!(matches!(err, Error::Inconsistent(_)));
}
}