use std::path::PathBuf;
use rust_j2k::{DecodeOptions, Error, Image, Region, Window, decode_with, read_header};
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
fn below(&mut self, n: u32) -> u32 {
(self.next() % u64::from(n.max(1))) as u32
}
}
fn image_area(bytes: &[u8]) -> (u32, u32, u32, u32) {
assert_eq!(&bytes[..4], &[0xff, 0x4f, 0xff, 0x51], "SOC then SIZ");
let word = |at: usize| u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap());
(word(16), word(20), word(8), word(12))
}
fn at(v: u32, d: u32, r: u8) -> u32 {
v.div_ceil(d).div_ceil(1 << r)
}
fn crop(whole: &Image, c: usize, image: (u32, u32, u32, u32), window: Window, r: u8) -> Vec<i32> {
let plane = &whole.components[c];
let (dx, dy) = (u32::from(plane.x_sampling), u32::from(plane.y_sampling));
let (x0, y0, x1, y1) = (
window.x0.max(image.0),
window.y0.max(image.1),
window.x1.min(image.2),
window.y1.min(image.3),
);
let (ox, oy) = (at(image.0, dx, r), at(image.1, dy, r));
let mut out = Vec::new();
for y in at(y0, dy, r)..at(y1, dy, r) {
for x in at(x0, dx, r)..at(x1, dx, r) {
out.push(plane.samples[((y - oy) * plane.width + (x - ox)) as usize]);
}
}
out
}
fn window(rng: &mut Rng, image: (u32, u32, u32, u32)) -> Window {
let (x0, y0, x1, y1) = image;
let mut axis = |lo: u32, hi: u32| {
let start = (lo + rng.below(hi - lo)).saturating_sub(rng.below(3));
let reach = [3, 12, 40, hi - lo][rng.below(4) as usize];
(start, start + 1 + rng.below(reach))
};
let (wx0, wx1) = axis(x0, x1);
let (wy0, wy1) = axis(y0, y1);
Window::new(wx0, wy0, wx1, wy1)
}
fn check(name: &str, bytes: &[u8], windows: usize, seed: u64) {
check_with(name, bytes, windows, seed, &DecodeOptions::default());
}
fn check_with(name: &str, bytes: &[u8], windows: usize, seed: u64, base: &DecodeOptions) {
let image = image_area(bytes);
let header = read_header(bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
let mut rng = Rng(seed);
for r in 0..=header.max_reduction.min(2) {
let all = base.clone().with_resolution_reduction(r);
let whole = decode_with(bytes, &all).unwrap_or_else(|e| panic!("{name} -r {r}: {e}"));
if whole.components.iter().any(|c| c.samples.is_empty()) {
continue;
}
let (mut decoded, mut drawn) = (0, 0);
while decoded < windows {
drawn += 1;
assert!(
drawn <= 20 * windows,
"{name} -r {r}: {decoded} of {drawn} decoded"
);
let window = window(&mut rng, image);
let what = format!("{name} -r {r} {window:?}");
let part = match decode_with(bytes, &all.clone().with_region(Region::Window(window))) {
Ok(part) => part,
Err(Error::InvalidOptions(_)) => continue,
Err(e) => panic!("{what}: {e}"),
};
decoded += 1;
assert_eq!(part.components.len(), whole.components.len(), "{what}");
for (c, component) in part.components.iter().enumerate() {
let expected = crop(&whole, c, image, window, r);
assert_eq!(
component.samples.len(),
expected.len(),
"{what}: component {c}"
);
if component.samples != expected {
let worst = component
.samples
.iter()
.zip(&expected)
.map(|(a, b)| (i64::from(*a) - i64::from(*b)).abs())
.max()
.unwrap_or(0);
panic!("{what}: component {c} differs from the whole decode by up to {worst}");
}
}
}
}
}
fn read(path: &str) -> Vec<u8> {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(path);
std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
}
fn optional(dir: &str, file: &str) -> Option<Vec<u8>> {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(dir);
if !root.is_dir() {
eprintln!("{dir} is not present (packaged crate?); skipping {file}");
return None;
}
Some(read(&format!("{dir}/{file}")))
}
#[test]
fn random_windows_of_the_window_fixtures_are_crops_of_the_whole_decode() {
for (seed, name) in ["tiled_53", "tiled_53_nomct", "tiled_97", "sub_53", "sub_97"]
.into_iter()
.enumerate()
{
let bytes = read(&format!("tests/fixtures/window/{name}.j2k"));
check(name, &bytes, 60, seed as u64);
}
}
#[test]
fn random_windows_of_narrow_tiles_and_empty_resolutions_are_crops() {
let lenient = DecodeOptions::default().with_strict(false);
for (seed, (path, base)) in [
(
"tests/fixtures/tiles_odd_origin_lossless.j2k",
DecodeOptions::default(),
),
(
"tests/fixtures/tiles_odd_origin_irreversible.j2k",
DecodeOptions::default(),
),
("tests/fixtures/partial/tp_r.j2k", lenient),
]
.into_iter()
.enumerate()
{
check_with(path, &read(path), 40, 200 + seed as u64, &base);
}
}
#[test]
fn random_windows_of_a_component_subset_are_crops_of_the_same_subset() {
for (seed, (name, components)) in [
("tiled_53", vec![1]),
("tiled_97", vec![2, 0]),
("tiled_53_nomct", vec![2]),
("sub_53", vec![2, 1]),
("sub_97", vec![1]),
]
.into_iter()
.enumerate()
{
let bytes = read(&format!("tests/fixtures/window/{name}.j2k"));
let base = DecodeOptions::default().with_components(Some(components.clone()));
let what = format!("{name} -c {components:?}");
check_with(&what, &bytes, 30, 300 + seed as u64, &base);
}
}
#[test]
fn random_windows_of_a_cut_codestream_are_crops_of_its_partial_decode() {
let base = DecodeOptions::default().with_strict(false);
for (seed, (name, keep)) in [("tiled_97", 3), ("sub_53", 2), ("tiled_53", 4)]
.into_iter()
.enumerate()
{
let bytes = read(&format!("tests/fixtures/window/{name}.j2k"));
let cut = &bytes[..bytes.len() * keep / 5];
let whole = decode_with(cut, &base).unwrap_or_else(|e| panic!("{name}: {e}"));
assert!(!whole.report.is_complete(), "{name}: the cut loses data");
check_with(&format!("{name} cut"), cut, 30, 400 + seed as u64, &base);
}
}
#[test]
fn random_windows_of_larger_codestreams_are_crops_of_the_whole_decode() {
const BENCH: &str = "tests/fixtures/bench";
const CONFORMANCE: &str = "tests/fixtures/conformance/codestreams";
const OPENJPH: &str = "tests/fixtures/openjph/files";
const HT: &str = "tests/fixtures/conformance/ht/codestreams";
for (seed, (dir, file)) in [
(BENCH, "tiled_2048_gray.j2k"),
(CONFORMANCE, "p0_04.j2k"),
(CONFORMANCE, "p1_04.j2k"),
(CONFORMANCE, "p1_05.j2k"),
(CONFORMANCE, "p0_05.j2k"),
(OPENJPH, "simple_enc_irv97_64x64.j2c"),
(OPENJPH, "simple_enc_rev53_64x64_yuv.j2c"),
(HT, "ds0_ht_02_b11.j2k"),
(HT, "ds1_ht_01_b11.j2k"),
(HT, "ds1_ht_05_b11.j2k"),
(HT, "ds0_ht_04_b11.j2k"),
(HT, "ds1_ht_02_b11.j2k"),
(HT, "ds0_ht_05_b11.j2k"),
(HT, "ds1_ht_04_b9.j2k"),
(HT, "ds0_ht_12_b11.j2k"),
(HT, "ds0_hm_06_b11.j2k"),
(HT, "ds0_hm_06_b18.j2k"),
(HT, "ds0_hm_15_b8.j2k"),
]
.into_iter()
.enumerate()
{
if let Some(bytes) = optional(dir, file) {
check(file, &bytes, 16, 100 + seed as u64);
}
}
}