use std::collections::HashMap;
use std::path::PathBuf;
use rust_j2k::{DecodeOptions, Image, Region, ReportEntry, Window, decode_with, read_header};
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 lenient() -> DecodeOptions {
DecodeOptions::default().with_strict(false)
}
fn decode_ok(bytes: &[u8], options: &DecodeOptions, what: &str) -> Image {
decode_with(bytes, options).unwrap_or_else(|e| panic!("{what}: {e}"))
}
fn cut(bytes: &[u8], percent: usize) -> &[u8] {
&bytes[..bytes.len() * percent / 100]
}
#[test]
fn a_component_whose_packets_are_all_there_is_complete() {
let bytes = read("tests/fixtures/precincts_cprl_lossless.j2k");
let first = lenient().with_components(Some(vec![0]));
let uncut = decode_ok(&bytes, &first, "uncut");
for percent in 70..=97 {
let prefix = cut(&bytes, percent);
let part = decode_ok(prefix, &first, "component 0");
assert_eq!(part.components, uncut.components, "{percent}%");
assert!(part.report.is_complete(), "{percent}%: {:?}", part.report);
assert_eq!(part.report.complete_reduction, Some(0), "{percent}%");
let whole = decode_ok(prefix, &lenient(), "the whole image");
assert!(!whole.report.is_complete(), "{percent}%");
let last = lenient().with_components(Some(vec![2]));
let part = decode_ok(prefix, &last, "component 2");
assert!(!part.report.is_complete(), "{percent}%");
assert_ne!(
part.components,
decode_ok(&bytes, &last, "uncut").components
);
}
let prefix = cut(&bytes, 20);
let part = decode_ok(prefix, &first, "component 0 at 20%");
assert_ne!(part.components, uncut.components);
assert!(!part.report.is_complete(), "{:?}", part.report);
}
#[test]
fn a_window_whose_code_blocks_are_all_there_is_complete() {
let bytes = read("tests/fixtures/precincts_cprl_lossless.j2k");
let prefix = cut(&bytes, 15);
let first = lenient().with_components(Some(vec![0]));
let window = first
.clone()
.with_region(Region::Window(Window::new(0, 0, 8, 8)));
let part = decode_ok(prefix, &window, "the window");
assert_eq!(
part.components,
decode_ok(&bytes, &window, "uncut").components
);
assert!(part.report.is_complete(), "{:?}", part.report);
assert_eq!(part.report.complete_reduction, Some(0));
let all = decode_ok(prefix, &first, "component 0");
assert!(!all.report.is_complete());
let far = first.with_region(Region::Window(Window::new(100, 80, 128, 96)));
let part = decode_ok(prefix, &far, "the far window");
assert!(!part.report.is_complete(), "{:?}", part.report);
assert_ne!(part.components, decode_ok(&bytes, &far, "uncut").components);
}
#[test]
fn complete_reduction_is_counted_with_the_finer_reductions_footprint() {
let bytes = read("tests/fixtures/precincts_cprl_lossless.j2k");
let prefix = &bytes[..32340];
let options = lenient()
.with_region(Region::Window(Window::new(38, 67, 40, 85)))
.with_components(Some(vec![2, 0]));
let fine = decode_ok(prefix, &options, "-r 0");
let coarse = decode_ok(
prefix,
&options.clone().with_resolution_reduction(1),
"-r 1",
);
assert!(!fine.report.is_complete(), "{:?}", fine.report);
assert_eq!(
coarse.report.complete_reduction,
fine.report.complete_reduction
);
assert_ne!(coarse.report.complete_reduction, Some(0));
}
#[test]
fn a_layer_cap_counts_the_first_layer_missing() {
let bytes = read("tests/fixtures/precincts_cprl_lossless.j2k");
let prefix = &bytes[..133];
let options = lenient()
.with_max_quality_layers(Some(1))
.with_components(Some(vec![2]));
let part = decode_ok(prefix, &options, "cut");
let uncut = decode_ok(&bytes, &options, "uncut");
assert_ne!(part.components, uncut.components);
assert!(!part.report.is_complete(), "{:?}", part.report);
}
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
}
}
struct Grid {
image: (u32, u32, u32, u32),
tile: (u32, u32),
origin: (u32, u32),
}
impl Grid {
fn of(bytes: &[u8]) -> Self {
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());
Grid {
image: (word(16), word(20), word(8), word(12)),
tile: (word(24), word(28)),
origin: (word(32), word(36)),
}
}
fn across(&self) -> u32 {
(self.image.2 - self.origin.0).div_ceil(self.tile.0)
}
fn tiles(&self, window: Window) -> Vec<u32> {
let (ix0, iy0, ix1, iy1) = self.image;
let (x0, y0) = (window.x0.max(ix0), window.y0.max(iy0));
let (x1, y1) = (window.x1.min(ix1), window.y1.min(iy1));
let (tw, th) = self.tile;
let (ox, oy) = self.origin;
let mut out = Vec::new();
for ty in (y0 - oy) / th..(y1 - oy).div_ceil(th) {
for tx in (x0 - ox) / tw..(x1 - ox).div_ceil(tw) {
out.push(ty * self.across() + tx);
}
}
out
}
}
fn tile_ends(bytes: &[u8]) -> Vec<usize> {
let mut at = bytes
.windows(2)
.position(|w| w == [0xFF, 0x90])
.expect("an SOT");
let mut ends = Vec::new();
while bytes[at..at + 2] == [0xFF, 0x90] {
let tile = usize::from(u16::from_be_bytes([bytes[at + 4], bytes[at + 5]]));
let psot = u32::from_be_bytes(bytes[at + 6..at + 10].try_into().unwrap()) as usize;
assert_ne!(psot, 0, "the fixtures give every Psot");
if ends.len() <= tile {
ends.resize(tile + 1, 0);
}
ends[tile] = at + psot;
at += psot;
}
ends
}
fn crop(whole: &Image, c: usize, image: (u32, u32, u32, u32), window: Window, r: u8) -> Vec<i32> {
let at = |v: u32, d: u32| v.div_ceil(d).div_ceil(1 << r);
let plane = &whole.components[c];
let (dx, dy) = (u32::from(plane.x_sampling), u32::from(plane.y_sampling));
let (x0, y0) = (window.x0.max(image.0), window.y0.max(image.1));
let (x1, y1) = (window.x1.min(image.2), window.y1.min(image.3));
let (ox, oy) = (at(image.0, dx), at(image.1, dy));
let mut out = Vec::new();
for y in at(y0, dy)..at(y1, dy) {
for x in at(x0, dx)..at(x1, dx) {
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);
let reach = [4, 16, 48, hi - lo][rng.below(4) as usize];
(start, (start + 1 + rng.below(reach)).min(hi))
};
let (wx0, wx1) = axis(x0, x1);
let (wy0, wy1) = axis(y0, y1);
Window::new(wx0, wy0, wx1, wy1)
}
type Whole = (Image, HashMap<usize, bool>);
type Outcome = (Option<u8>, bool, bool);
struct Counts {
complete: usize,
incomplete: usize,
same_incomplete: usize,
}
fn check(name: &str, draws: usize, seed: u64) -> Counts {
let bytes = read(name);
let grid = Grid::of(&bytes);
let ends = tile_ends(&bytes);
let header = read_header(&bytes).unwrap();
let components = header.components.len() as u16;
let start = bytes.windows(2).position(|w| w == [0xFF, 0x90]).unwrap() + 14;
let mut rng = Rng(seed);
let mut counts = Counts {
complete: 0,
incomplete: 0,
same_incomplete: 0,
};
let mut wholes: HashMap<(u8, Option<u16>), Whole> = HashMap::new();
for draw in 0..draws {
let mut cuts: Vec<usize> = (0..9)
.map(|i| start + (bytes.len() - start) * i / 9)
.chain((0..3).map(|_| start + rng.below(((bytes.len() - start) / 8) as u32) as usize))
.chain([bytes.len()])
.collect();
cuts.sort_unstable();
cuts.dedup();
let window = (rng.below(4) != 0).then(|| window(&mut rng, grid.image));
let subset = match rng.below(3) {
0 => None,
1 => Some(vec![rng.below(u32::from(components)) as u16]),
_ => Some(vec![components - 1, 0]),
};
let cap = [None, Some(1), Some(2)][draw % 3];
let returned: Vec<usize> = subset.as_ref().map_or_else(
|| (0..usize::from(components)).collect(),
|s| s.iter().map(|&c| usize::from(c)).collect(),
);
let mut outcomes: Vec<Option<Vec<Outcome>>> = Vec::new();
for r in 0..2u8 {
let base = lenient()
.with_resolution_reduction(r)
.with_max_quality_layers(cap);
let (uncut, whole) = wholes
.entry((r, cap))
.or_insert_with(|| (decode_ok(&bytes, &base, name), HashMap::new()));
let options = base
.clone()
.with_region(window.map_or(Region::Whole, Region::Window))
.with_components(subset.clone());
let what = format!("{name} -r {r} -l {cap:?} {window:?} {subset:?}");
let expected: Vec<Vec<i32>> = returned
.iter()
.map(|&c| match window {
Some(w) => crop(uncut, c, grid.image, w, r),
None => uncut.components[c].samples.clone(),
})
.collect();
let read_end = match window {
Some(w) => grid
.tiles(w)
.iter()
.map(|&t| ends[t as usize])
.max()
.unwrap(),
None => *ends.iter().max().unwrap(),
};
let mut was_complete = false;
let mut seen = Some(Vec::new());
for &at in &cuts {
let whole_complete = *whole
.entry(at)
.or_insert_with(|| decode_ok(&bytes[..at], &base, name).report.is_complete());
let part = match decode_with(&bytes[..at], &options) {
Ok(part) => part,
Err(rust_j2k::Error::InvalidOptions(_)) => {
seen = None;
break;
}
Err(e) => panic!("{what} at {at}: {e}"),
};
let samples: Vec<&Vec<i32>> = part.components.iter().map(|c| &c.samples).collect();
let same = samples.iter().zip(&expected).all(|(a, b)| *a == b);
let is = part.report.is_complete();
let report = &part.report;
assert!(
!is || same,
"{what} at {at}: complete, but differs: {report:?}"
);
assert!(
!whole_complete || is,
"{what} at {at}: the whole is complete: {report:?}"
);
assert!(
at < read_end || is,
"{what} at {at}: every tile read is there: {report:?}"
);
assert!(
!was_complete || is,
"{what} at {at}: was complete at a shorter cut"
);
was_complete = is;
if window.is_none() && subset.is_none() {
} else if is {
counts.complete += 1;
} else if same {
counts.same_incomplete += 1;
} else {
counts.incomplete += 1;
}
if let Some(seen) = &mut seen {
seen.push((report.complete_reduction, is, same));
}
}
outcomes.push(seen);
}
if let [Some(fine), Some(coarse)] = &outcomes[..] {
let what = format!("{name} -l {cap:?} {window:?} {subset:?}");
for ((at, f), c) in cuts.iter().zip(fine).zip(coarse) {
assert_eq!(
f.0, c.0,
"{what} at {at}: complete_reduction at -r 0 and -r 1"
);
if c.0 == Some(0) {
assert!(f.1 && f.2, "{what} at {at}: -r 1 names reduction 0");
}
}
}
}
counts
}
#[test]
fn random_windows_and_subsets_of_cut_codestreams_report_what_they_return() {
for (seed, (name, draws)) in [
("tests/fixtures/precincts_cprl_lossless.j2k", 12),
("tests/fixtures/precincts_lrcp_lossless.j2k", 6),
("tests/fixtures/precincts_tiled_cprl_lossless.j2k", 6),
("tests/fixtures/window/tiled_53.j2k", 6),
("tests/fixtures/window/sub_97.j2k", 6),
("tests/fixtures/layers/precincts_pterm.j2k", 6),
]
.into_iter()
.enumerate()
{
let Counts {
complete,
incomplete,
same_incomplete,
} = check(name, draws, 500 + seed as u64);
assert!(
complete > 0 && incomplete > 0,
"{name}: {complete} complete, {incomplete} not"
);
assert!(
same_incomplete * 10 <= complete + same_incomplete,
"{name}: {same_incomplete} of {} decodes with the uncut samples are reported \
incomplete",
complete + same_incomplete
);
}
}
fn missing_tiles(image: &Image) -> Vec<(u32, u32)> {
image
.report
.entries
.iter()
.filter_map(|e| match e {
ReportEntry::MissingTiles { tiles, .. } => Some((tiles.start, tiles.end)),
_ => None,
})
.collect()
}
#[test]
fn a_run_of_missing_tiles_is_split_at_the_tiles_a_window_does_not_read() {
let bytes = read("tests/fixtures/window/tiled_53.j2k");
let ends = tile_ends(&bytes);
let prefix = &bytes[..ends[2]];
let window = lenient().with_region(Region::Window(Window::new(5, 4, 20, 58)));
let part = decode_ok(prefix, &window, "the first column");
assert_eq!(missing_tiles(&part), [(3, 4), (6, 7)]);
assert!(!part.report.is_complete());
}