use std::collections::BTreeMap;
use std::panic;
use std::path::Path;
use rust_j2k::DecodeOptions;
use serde::Deserialize;
use super::jp2::{self, Digest};
use super::part4::{self, Bound, Bounds, Cblksty, Grade};
use super::pgx::parse_pgx;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HtManifest {
#[serde(rename = "_comment")]
pub comment: String,
pub compliance_class: u8,
pub provenance: serde_json::Value,
pub codestreams: Vec<HtCodestream>,
pub jph: Vec<JphEntry>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HtCodestream {
pub name: String,
pub codestream: String,
pub source: String,
pub graded_components: usize,
pub bit_exact: bool,
pub reduction: u8,
pub references: Vec<String>,
pub bounds: Bounds,
pub tolerance: Tolerance,
pub kakadu_stats: Option<Stats>,
pub features: HtFeatures,
pub ht: HtSignaling,
pub passes: Passes,
pub file_digest: Digest,
pub reference_digests: Vec<Digest>,
pub openjpeg: OpenJpeg,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Tolerance {
pub table: String,
pub part1: Bounds,
pub additional: Option<Bounds>,
pub reference_depth: Option<u32>,
pub depth: Vec<u32>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Stats {
pub depth: Option<u32>,
pub pae: Vec<f64>,
pub mse: Vec<f64>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HtFeatures {
pub width: u32,
pub height: u32,
pub components: u32,
pub subsampling: Vec<[u32; 2]>,
pub precision: Vec<u32>,
pub signed: Vec<bool>,
pub tiles: [u32; 2],
pub progression: String,
pub layers: u32,
pub mct: u32,
pub resolutions: u32,
pub code_block: [u32; 2],
pub reversible: bool,
pub cblksty_bytes: Vec<u8>,
pub irreversible_anywhere: bool,
pub markers_main: Vec<String>,
pub markers_tile: Vec<String>,
pub tile_parts: u32,
pub sop: bool,
pub eph: bool,
pub precincts: bool,
pub cblksty: Cblksty,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HtSignaling {
pub pcap: u32,
pub ccap15: u16,
pub coder_set: String,
pub multiht: bool,
pub rgn: bool,
pub heterogeneous: bool,
pub irreversible: bool,
pub magb_bound: u32,
pub cpf: Option<i64>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Passes {
pub t803_placeholder_bset: bool,
pub placeholder: Option<bool>,
pub refinement: Option<bool>,
pub measured: Option<Measured>,
pub walked: Option<Walked>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Walked {
pub blocks: u64,
pub placeholder: u64,
pub histogram: BTreeMap<String, u64>,
pub zero_length_refinement: u64,
#[serde(default)]
pub part1: u64,
}
impl Walked {
pub fn one_ht_set(&self) -> bool {
self.histogram
.keys()
.all(|k| k.parse::<u32>().is_ok_and(|passes| passes <= 3))
}
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Measured {
pub blocks: u64,
pub histogram: BTreeMap<String, u64>,
pub zero_length_refinement: u64,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpenJpeg {
pub decoded: bool,
pub message: Option<String>,
pub warning: Option<String>,
pub metrics: Option<Bounds>,
pub matches_references: Option<bool>,
pub agreement_bound: Option<ScalarBound>,
pub snapshot: Option<Snapshot>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ScalarBound {
pub pae: f64,
pub mse: f64,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Snapshot {
pub references: Vec<String>,
pub reference_digests: Vec<Digest>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct JphEntry {
pub name: String,
pub file: String,
pub index: u32,
pub magb_bound: u32,
pub highest_bound: bool,
pub codestream_range: [usize; 2],
pub boxes: Vec<String>,
pub features: HtFeatures,
pub ht: HtSignaling,
pub passes: Passes,
pub kakadu_stats: Stats,
pub file_digest: Digest,
pub graded_as: Option<String>,
pub not_graded: Option<String>,
pub references: Vec<String>,
pub reference_digests: Vec<Digest>,
pub openjpeg: JphOpenJpeg,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct JphOpenJpeg {
pub decoded: bool,
pub message: Option<String>,
pub codestream_sha256: Vec<String>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpenJphManifest {
#[serde(rename = "_comment")]
pub comment: String,
pub provenance: serde_json::Value,
pub entries: Vec<OpenJphEntry>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpenJphEntry {
pub name: String,
pub file: String,
pub codestream_range: [usize; 2],
pub graded_components: usize,
pub bit_exact: bool,
pub bounds: Bounds,
pub references: Vec<String>,
pub features: HtFeatures,
pub ht: HtSignaling,
pub passes: Passes,
pub file_digest: Digest,
pub reference_digests: Vec<Digest>,
}
const EXACT: Bound = Bound { pae: 0.0, mse: 0.0 };
pub const KAKADU_MSE_INEXACT: &[(&str, usize)] = &[("file7_b15", 0), ("file7_b15", 1)];
pub fn kakadu_mse_slack(name: &str, component: usize) -> f64 {
if KAKADU_MSE_INEXACT.contains(&(name, component)) {
1e-5
} else {
1e-6
}
}
const CODESTREAM_ORDER: &[(&str, &[usize])] = &[("file2_b12", &[2, 1, 0])];
fn bound_of(bounds: &Bounds, bit_exact: bool, index: usize) -> Bound {
if bit_exact {
return EXACT;
}
Bound {
pae: bounds.pae[index],
mse: bounds.mse[index],
}
}
fn check_counts(graded: usize, references: usize, bounds: &Bounds) -> Result<(), Grade> {
if graded == 0
|| references != graded
|| bounds.pae.len() != graded
|| bounds.mse.len() != graded
{
return Err(Grade::Failed(format!(
"manifest: {graded} graded components but {references} references, {} PAE, {} MSE bounds",
bounds.pae.len(),
bounds.mse.len(),
)));
}
Ok(())
}
fn read(dir: &Path, path: &str) -> Result<Vec<u8>, Grade> {
std::fs::read(dir.join(path)).map_err(|e| Grade::Failed(format!("cannot read {path}: {e}")))
}
impl HtCodestream {
pub fn grade(&self, ht_dir: &Path) -> Grade {
if let Err(grade) =
check_counts(self.graded_components, self.references.len(), &self.bounds)
{
return grade;
}
let bytes = match read(ht_dir, &self.codestream) {
Ok(bytes) => bytes,
Err(grade) => return grade,
};
part4::grade_decode(ht_dir, &bytes, self.reduction, &self.references, |i| {
bound_of(&self.bounds, self.bit_exact, i)
})
}
pub fn grade_agreement(&self, ht_dir: &Path, exact: bool) -> Option<Grade> {
let bound = self.openjpeg.agreement_bound.as_ref()?;
let references = match &self.openjpeg.snapshot {
Some(snapshot) => &snapshot.references,
None => &self.references,
};
if self.graded_components == 0 || references.len() != self.graded_components {
return Some(Grade::Failed(format!(
"manifest: {} graded components but {} OpenJPEG planes",
self.graded_components,
references.len()
)));
}
let bytes = match read(ht_dir, &self.codestream) {
Ok(bytes) => bytes,
Err(grade) => return Some(grade),
};
let bound = if exact {
EXACT
} else {
Bound {
pae: bound.pae,
mse: bound.mse,
}
};
Some(part4::grade_decode(
ht_dir,
&bytes,
self.reduction,
references,
|_| bound,
))
}
}
fn decode_graded(bytes: &[u8], options: &DecodeOptions) -> Result<rust_j2k::Image, Grade> {
match panic::catch_unwind(panic::AssertUnwindSafe(|| {
rust_j2k::decode_with(bytes, options)
})) {
Err(_) => Err(Grade::Failed(
"panicked (decode must return a typed error)".into(),
)),
Ok(Err(rust_j2k::Error::Unsupported(what))) => {
Err(Grade::NotYetDecoded(what.message().to_owned()))
}
Ok(Err(e)) => Err(Grade::Failed(format!("decoder rejected a valid file: {e}"))),
Ok(Ok(image)) => Ok(image),
}
}
struct AsCodedSource<'a> {
dir: &'a Path,
references: Vec<String>,
shift: u8,
bounds: Option<Bounds>,
display: DecodeOptions,
}
impl JphEntry {
pub fn grade(&self, ht_dir: &Path, jp2_dir: &Path, set: &[JphEntry]) -> Grade {
let Some(graded_as) = self.graded_as.as_deref() else {
return self.grade_lower_bound(ht_dir, jp2_dir, set);
};
if graded_as == "references" {
let bytes = match read(ht_dir, &self.file) {
Ok(bytes) => bytes,
Err(grade) => return grade,
};
return part4::grade_decode(ht_dir, &bytes, 0, &self.references, |_| EXACT);
}
let Some(mut entry) = jp2::load_manifest(jp2_dir)
.entries
.into_iter()
.find(|e| e.name() == graded_as)
else {
return Grade::Failed(format!("no JP2 entry `{graded_as}`"));
};
entry.file = format!("../ht/{}", self.file);
jp2::grade_entry(jp2_dir, &entry)
}
fn as_coded_source<'a>(
&self,
ht_dir: &'a Path,
jp2_dir: &'a Path,
set: &[JphEntry],
) -> Result<AsCodedSource<'a>, Grade> {
let highest = set
.iter()
.find(|j| j.index == self.index && j.highest_bound)
.ok_or_else(|| {
Grade::Failed(format!("no highest-bound file for set {}", self.index))
})?;
match highest.graded_as.as_deref() {
Some("references") => Ok(AsCodedSource {
dir: ht_dir,
references: highest.references.clone(),
shift: 0,
bounds: None,
display: DecodeOptions::default(),
}),
Some(name) => {
let entry = jp2::load_manifest(jp2_dir)
.entries
.into_iter()
.find(|e| e.name() == name)
.ok_or_else(|| Grade::Failed(format!("no JP2 entry `{name}`")))?;
let display = jp2::options_for(&entry);
let (references, shift, bounds) = match entry.as_coded {
Some(as_coded) => (as_coded.references, 0, None),
None if !entry.needs_srgb => {
(entry.references, entry.shift_right, Some(entry.bounds))
}
None => {
return Err(Grade::Failed(format!(
"`{name}` has no as-coded references"
)));
}
};
Ok(AsCodedSource {
dir: jp2_dir,
references,
shift,
bounds,
display,
})
}
None => Err(Grade::Failed(format!(
"the highest-bound file of set {} is not graded",
self.index
))),
}
}
fn grade_lower_bound(&self, ht_dir: &Path, jp2_dir: &Path, set: &[JphEntry]) -> Grade {
let source = match self.as_coded_source(ht_dir, jp2_dir, set) {
Ok(source) => source,
Err(grade) => return grade,
};
let graded = source.references.len();
let stats = &self.kakadu_stats;
if graded == 0 || stats.pae.len() != graded || stats.mse.len() != graded {
return Grade::Failed(format!(
"manifest: {graded} references but {} Kakadu PAE and {} MSE figures",
stats.pae.len(),
stats.mse.len()
));
}
let bytes = match read(ht_dir, &self.file) {
Ok(bytes) => bytes,
Err(grade) => return grade,
};
let image = match decode_graded(&bytes, &DecodeOptions::default()) {
Ok(image) => image,
Err(grade) => return grade,
};
if let Err(grade) = decode_graded(&bytes, &source.display) {
return grade;
}
if image.components.len() != graded {
return Grade::Failed(format!(
"decoded {} components but the set grades {graded}",
image.components.len()
));
}
let scale = f64::from(1u32 << source.shift);
let mut all_exact = true;
for (index, path) in source.references.iter().enumerate() {
let decoded = &image.components[index];
if stats.depth != Some(u32::from(decoded.bit_depth)) {
return Grade::Failed(format!(
"component {index}: Kakadu's figures are at depth {:?}, the decode at {}",
stats.depth, decoded.bit_depth
));
}
let raw = match std::fs::read(source.dir.join(path)) {
Ok(raw) => raw,
Err(e) => return Grade::Failed(format!("cannot read {path}: {e}")),
};
let reference = match parse_pgx(&raw) {
Ok(reference) => reference,
Err(e) => return Grade::Failed(format!("cannot parse {path}: {e}")),
};
let base = source
.bounds
.as_ref()
.map_or(EXACT, |b| bound_of(b, false, index));
let mse = stats.mse[index] / (scale * scale);
let bound = Bound {
pae: base.pae + (stats.pae[index] / scale).ceil(),
mse: base.mse + mse + kakadu_mse_slack(&self.name, index) * mse.max(1.0),
};
let component = jp2::shifted(decoded, source.shift);
match part4::grade_component(&component, &reference, bound) {
Ok(measured) => all_exact &= measured.exact(),
Err(why) => return Grade::Failed(format!("component {index}: {why}")),
}
}
if all_exact {
Grade::Exact
} else {
Grade::WithinClass
}
}
pub fn grade_codestream(&self, ht_dir: &Path, jp2_dir: &Path) -> Option<Grade> {
let graded_as = self.graded_as.as_deref()?;
let (dir, references) = if graded_as == "references" {
(ht_dir, self.references.clone())
} else {
let entry = jp2::load_manifest(jp2_dir)
.entries
.into_iter()
.find(|e| e.name() == graded_as)?;
let unchanged = entry.bit_exact
&& entry.shift_right == 0
&& !entry.needs_srgb
&& !entry.boxes.jp2h.iter().any(|b| b == "pclr");
let mut references = match entry.as_coded {
Some(as_coded) => as_coded.references,
None if unchanged => entry.references,
None => return None,
};
if let Some((_, order)) = CODESTREAM_ORDER.iter().find(|(n, _)| *n == self.name) {
references = order.iter().map(|&i| references[i].clone()).collect();
}
(jp2_dir, references)
};
let bytes = match read(ht_dir, &self.file) {
Ok(bytes) => bytes,
Err(grade) => return Some(grade),
};
let [start, end] = self.codestream_range;
let Some(codestream) = bytes.get(start..end) else {
return Some(Grade::Failed(format!(
"codestream range {start}..{end} past the file"
)));
};
Some(part4::grade_decode(dir, codestream, 0, &references, |_| {
EXACT
}))
}
}
impl OpenJphEntry {
pub fn grade(&self, dir: &Path) -> Grade {
if let Err(grade) =
check_counts(self.graded_components, self.references.len(), &self.bounds)
{
return grade;
}
let bytes = match read(dir, &self.file) {
Ok(bytes) => bytes,
Err(grade) => return grade,
};
let [start, end] = self.codestream_range;
let Some(codestream) = bytes.get(start..end) else {
return Grade::Failed(format!("codestream range {start}..{end} past the file"));
};
part4::grade_decode(dir, codestream, 0, &self.references, |i| {
bound_of(&self.bounds, self.bit_exact, i)
})
}
}
fn load<T: serde::de::DeserializeOwned>(path: &Path) -> T {
let text =
std::fs::read_to_string(path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
serde_json::from_str(&text).unwrap_or_else(|e| panic!("parse {}: {e}", path.display()))
}
pub fn load_ht_manifest(ht_dir: &Path) -> HtManifest {
load(&ht_dir.join("manifest.json"))
}
pub fn load_openjph_manifest(dir: &Path) -> OpenJphManifest {
load(&dir.join("manifest.json"))
}