#![allow(dead_code)]
pub mod ht;
pub mod jp2;
pub mod part4;
pub mod pgx;
pub mod synth;
use std::fmt;
use std::panic;
use std::path::{Path, PathBuf};
use rust_j2k::{
Association, ChannelType, ColorOutput, ColorSpace, Component, DecodeOptions, Error, Image,
Jp2Metadata, Res,
};
use serde::{Deserialize, Serialize};
pub fn srgb() -> DecodeOptions {
DecodeOptions::default().with_color(ColorOutput::Srgb)
}
pub fn plane_hash(component: &Component) -> String {
let bytes: Vec<u8> = component
.samples
.iter()
.flat_map(|s| s.to_be_bytes())
.collect();
jp2::sha256_hex(&bytes)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Expected {
pub image: ImageGeometry,
pub tolerance: Tolerance,
pub components: Vec<ComponentSnapshot>,
pub provenance: Provenance,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub jp2: Option<Jp2Snapshot>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub jp2_boxes: Option<Jp2Boxes>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Jp2Snapshot {
pub color: String,
pub channels: Vec<String>,
pub palette_applied: bool,
pub resolution: ResolutionSnapshot,
pub xml: Vec<usize>,
pub uuid: Vec<(String, usize)>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub ipr: Vec<usize>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub uuid_info: Vec<(Vec<String>, usize)>,
pub file_type: FileTypeSnapshot,
pub image_header: ImageHeaderSnapshot,
pub color_specifications: Vec<ColorSpecSnapshot>,
pub reader_requirements: Option<ReaderRequirementsSnapshot>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Jp2Boxes {
pub file_type: FileTypeSnapshot,
pub image_header: ImageHeaderSnapshot,
pub color_specifications: Vec<ColorSpecSnapshot>,
pub reader_requirements: Option<ReaderRequirementsSnapshot>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FileTypeSnapshot {
pub brand: String,
pub minor_version: u32,
pub compatibility: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageHeaderSnapshot {
pub compression: u8,
pub unknown_color_space: u8,
pub ipr_flag: u8,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ColorSpecSnapshot {
pub method: u8,
pub precedence: u8,
pub approximation: u8,
pub payload_len: usize,
pub payload_sha256: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enum_cs: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReaderRequirementsSnapshot {
pub mask_length: u8,
pub fully_understand: String,
pub decode_completely: String,
pub standard_features: Vec<(u16, String)>,
pub vendor_features: Vec<(String, String)>,
}
fn hex_bytes(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn code_text(code: &[u8; 4]) -> String {
code.iter()
.map(|&b| {
if (0x20..=0x7e).contains(&b) {
char::from(b).to_string()
} else {
format!("\\x{b:02x}")
}
})
.collect()
}
impl Jp2Boxes {
pub fn of(metadata: &Jp2Metadata) -> Self {
let file_type = &metadata.file_type;
let header = metadata.image_header;
Jp2Boxes {
file_type: FileTypeSnapshot {
brand: code_text(&file_type.brand),
minor_version: file_type.minor_version,
compatibility: file_type.compatibility.iter().map(code_text).collect(),
},
image_header: ImageHeaderSnapshot {
compression: header.compression,
unknown_color_space: header.unknown_color_space,
ipr_flag: header.ipr_flag,
},
color_specifications: metadata
.color_specifications
.iter()
.map(|c| ColorSpecSnapshot {
method: c.method,
precedence: c.precedence,
approximation: c.approximation,
payload_len: c.payload.len(),
payload_sha256: jp2::sha256_hex(&c.payload),
enum_cs: <[u8; 4]>::try_from(c.payload.as_slice())
.ok()
.filter(|_| c.method == 1)
.map(u32::from_be_bytes),
})
.collect(),
reader_requirements: metadata.reader_requirements.as_ref().map(|r| {
ReaderRequirementsSnapshot {
mask_length: r.mask_length,
fully_understand: hex_bytes(&r.fully_understand),
decode_completely: hex_bytes(&r.decode_completely),
standard_features: r
.standard_features
.iter()
.map(|f| (f.feature, hex_bytes(&f.mask)))
.collect(),
vendor_features: r
.vendor_features
.iter()
.map(|f| (hex_bytes(&f.id), hex_bytes(&f.mask)))
.collect(),
}
}),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResolutionSnapshot {
pub capture: Option<[i32; 6]>,
pub display: Option<[i32; 6]>,
}
impl Jp2Snapshot {
pub fn of(metadata: &Jp2Metadata) -> Self {
let color = match &metadata.color {
ColorSpace::Srgb => "srgb".to_string(),
ColorSpace::Grayscale => "grayscale".to_string(),
ColorSpace::Sycc => "sycc".to_string(),
ColorSpace::RestrictedIcc(profile) => format!("icc:{}", profile.len()),
ColorSpace::Enumerated(n) => format!("enumerated:{n}"),
ColorSpace::Unknown => "unknown".to_string(),
other => panic!("no snapshot name for {other:?}"),
};
let kind = |k: ChannelType| match k {
ChannelType::Color => "color".to_string(),
ChannelType::Opacity => "opacity".to_string(),
ChannelType::PremultipliedOpacity => "premultiplied".to_string(),
ChannelType::ApplicationDefined => "application".to_string(),
ChannelType::Unspecified => "unspecified".to_string(),
ChannelType::Other(n) => format!("other({n})"),
other => panic!("no snapshot name for {other:?}"),
};
let association = |a: Association| match a {
Association::WholeImage => "whole".to_string(),
Association::Color(n) => n.to_string(),
Association::None => "none".to_string(),
Association::ApplicationDefined(n) => format!("application({n})"),
other => panic!("no snapshot name for {other:?}"),
};
let hex = |id: &[u8; 16]| id.iter().map(|b| format!("{b:02x}")).collect::<String>();
let res = |r: Option<Res>| {
r.map(|r| {
let (v, h) = (r.vertical, r.horizontal);
[
i32::from(v.numerator),
i32::from(v.denominator),
i32::from(h.numerator),
i32::from(h.denominator),
i32::from(v.exponent),
i32::from(h.exponent),
]
})
};
let boxes = Jp2Boxes::of(metadata);
Jp2Snapshot {
file_type: boxes.file_type,
image_header: boxes.image_header,
color_specifications: boxes.color_specifications,
reader_requirements: boxes.reader_requirements,
color,
channels: metadata
.channels
.iter()
.map(|c| format!("{}/{}", kind(c.kind), association(c.association)))
.collect(),
palette_applied: metadata.palette_applied,
resolution: ResolutionSnapshot {
capture: res(metadata.resolution.capture),
display: res(metadata.resolution.display),
},
xml: metadata.xml.iter().map(|x| x.payload.len()).collect(),
uuid: metadata
.uuid
.iter()
.map(|u| (hex(&u.id), u.payload.len()))
.collect(),
ipr: metadata.ipr.iter().map(|b| b.payload.len()).collect(),
uuid_info: metadata
.uuid_info
.iter()
.map(|u| (u.ids.iter().map(hex).collect(), u.location.len()))
.collect(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageGeometry {
pub width: u32,
pub height: u32,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ComponentSnapshot {
pub width: u32,
pub height: u32,
pub bit_depth: u8,
pub signed: bool,
pub x_sampling: u8,
pub y_sampling: u8,
pub samples: Vec<i32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Geometry {
pub width: u32,
pub height: u32,
pub bit_depth: u8,
pub signed: bool,
}
impl ComponentSnapshot {
pub fn geometry(&self) -> Geometry {
Geometry {
width: self.width,
height: self.height,
bit_depth: self.bit_depth,
signed: self.signed,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum Tolerance {
Exact,
Absolute { max_abs_error: f64 },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Provenance {
pub source: String,
pub oracle_command: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub notes: Option<String>,
}
impl Expected {
pub fn from_json(text: &str) -> serde_json::Result<Self> {
serde_json::from_str(text)
}
}
impl Geometry {
pub fn sample_count(self) -> usize {
self.width as usize * self.height as usize
}
}
#[derive(Debug)]
pub struct Fixture {
pub name: String,
pub codestream: PathBuf,
pub expected: Result<Expected, String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Outcome {
Passed,
Failed(Mismatch),
LoadError(String),
}
#[derive(Debug, Clone, PartialEq)]
pub enum Mismatch {
Geometry {
component: usize,
expected: Geometry,
actual: Geometry,
},
Sample {
component: usize,
index: usize,
x: u32,
y: u32,
expected: i32,
actual: i32,
bound: f64,
},
DecodeError(String),
}
impl fmt::Display for Mismatch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Mismatch::Geometry {
component,
expected,
actual,
} => write!(
f,
"component {component} geometry mismatch: expected {}x{} (depth {}, signed {}), \
got {}x{} (depth {}, signed {})",
expected.width,
expected.height,
expected.bit_depth,
expected.signed,
actual.width,
actual.height,
actual.bit_depth,
actual.signed,
),
Mismatch::Sample {
component,
index,
x,
y,
expected,
actual,
bound,
} => write!(
f,
"component {component} sample #{index} at ({x},{y}): expected {expected}, \
got {actual} (|diff| = {} exceeds bound {bound})",
(*actual as i64 - *expected as i64).abs(),
),
Mismatch::DecodeError(msg) => {
write!(f, "decoder rejected a known-good fixture: {msg}")
}
}
}
}
pub fn discover(dir: &Path) -> std::io::Result<Vec<Fixture>> {
let mut fixtures: Vec<Fixture> = std::fs::read_dir(dir)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|ext| ext == "j2k"))
.map(|codestream| {
let name = codestream
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("<non-utf8>")
.to_string();
let snapshot = codestream.with_extension("expected.json");
let expected = load_snapshot(&snapshot);
Fixture {
name,
codestream,
expected,
}
})
.collect();
fixtures.sort_by(|a, b| a.name.cmp(&b.name));
Ok(fixtures)
}
fn load_snapshot(path: &Path) -> Result<Expected, String> {
let text = std::fs::read_to_string(path)
.map_err(|e| format!("cannot read {}: {e}", path.display()))?;
let expected =
Expected::from_json(&text).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
if expected.components.is_empty() {
return Err(format!("malformed {}: no components", path.display()));
}
for (index, component) in expected.components.iter().enumerate() {
let want = component.geometry().sample_count();
if component.samples.len() != want {
return Err(format!(
"malformed {}: component {index} is {}x{} = {want} samples but the array has {}",
path.display(),
component.width,
component.height,
component.samples.len(),
));
}
}
Ok(expected)
}
pub fn compare(actual: &Image, expected: &Expected) -> Result<(), Mismatch> {
let actual_image = ImageGeometry {
width: actual.width,
height: actual.height,
};
if actual_image != expected.image {
return Err(Mismatch::DecodeError(format!(
"image area is {}x{} but the snapshot says {}x{}",
actual.width, actual.height, expected.image.width, expected.image.height,
)));
}
if actual.components.len() != expected.components.len() {
return Err(Mismatch::DecodeError(format!(
"decoded {} components but the snapshot has {}",
actual.components.len(),
expected.components.len(),
)));
}
if let Some(want) = &expected.jp2 {
let got = actual.jp2.as_ref().map(Jp2Snapshot::of);
if got.as_ref() != Some(want) {
return Err(Mismatch::DecodeError(format!(
"JP2 metadata is {got:?} but the snapshot says {want:?}"
)));
}
}
if let Some(want) = &expected.jp2_boxes {
let got = actual.jp2.as_ref().map(Jp2Boxes::of);
if got.as_ref() != Some(want) {
return Err(Mismatch::DecodeError(format!(
"JP2 box fields are {got:?} but the snapshot says {want:?}"
)));
}
}
for (component_index, (component, want)) in actual
.components
.iter()
.zip(&expected.components)
.enumerate()
{
compare_component(component_index, component, want, expected.tolerance)?;
}
Ok(())
}
fn compare_component(
component: usize,
actual: &rust_j2k::Component,
expected: &ComponentSnapshot,
tolerance: Tolerance,
) -> Result<(), Mismatch> {
let actual_geometry = Geometry {
width: actual.width,
height: actual.height,
bit_depth: actual.bit_depth,
signed: actual.signed,
};
if actual_geometry != expected.geometry() {
return Err(Mismatch::Geometry {
component,
expected: expected.geometry(),
actual: actual_geometry,
});
}
if (actual.x_sampling, actual.y_sampling) != (expected.x_sampling, expected.y_sampling) {
return Err(Mismatch::DecodeError(format!(
"component {component} sub-samples ({}, {}) but the snapshot says ({}, {})",
actual.x_sampling, actual.y_sampling, expected.x_sampling, expected.y_sampling,
)));
}
if actual.samples.len() != expected.samples.len() {
return Err(Mismatch::DecodeError(format!(
"component {component} decoded {} samples but the snapshot has {}",
actual.samples.len(),
expected.samples.len(),
)));
}
let bound = match tolerance {
Tolerance::Exact => 0.0,
Tolerance::Absolute { max_abs_error } => max_abs_error,
};
let width = expected.width;
for (index, (&got, &want)) in actual.samples.iter().zip(&expected.samples).enumerate() {
let diff = (got as i64 - want as i64).abs() as f64;
if diff > bound {
return Err(Mismatch::Sample {
component,
index,
x: (index as u32) % width,
y: (index as u32) / width,
expected: want,
actual: got,
bound,
});
}
}
Ok(())
}
pub fn classify(
decoded: std::thread::Result<Result<Image, Error>>,
expected: &Expected,
) -> Outcome {
match decoded {
Err(_) => Outcome::Failed(Mismatch::DecodeError(
"panicked (decode must return a typed error for every input)".into(),
)),
Ok(Ok(image)) => match compare(&image, expected) {
Ok(()) => Outcome::Passed,
Err(mismatch) => Outcome::Failed(mismatch),
},
Ok(Err(e)) => Outcome::Failed(Mismatch::DecodeError(e.to_string())),
}
}
pub fn run_fixture(fixture: &Fixture) -> Outcome {
let expected = match &fixture.expected {
Ok(expected) => expected,
Err(reason) => return Outcome::LoadError(reason.clone()),
};
let bytes = match std::fs::read(&fixture.codestream) {
Ok(bytes) => bytes,
Err(e) => {
return Outcome::LoadError(format!(
"cannot read {}: {e}",
fixture.codestream.display()
));
}
};
let decoded = panic::catch_unwind(panic::AssertUnwindSafe(|| rust_j2k::decode(&bytes)));
classify(decoded, expected)
}