diff --git a/crates/raw/README.md b/crates/raw/README.md index d17dd62d7..d709e7047 100644 --- a/crates/raw/README.md +++ b/crates/raw/README.md @@ -216,3 +216,59 @@ decode bit-exactly; lossy tiles are made with `jpeg-encoder`, JPEG XL tiles with (tests only). Hostile input: every truncation of each sample, byte mutations across the header, 400 random mutations per property, random TIFF-like, lossless-JPEG, opcode-list and CIFF bytes, and a test per limit. + +## Decoder comparison reports + +The native `decode_report` example records the decoded sensor samples and selected metadata for an +explicit, ordered list of local files. It reads one regular file at a time, accepts at most 512 MiB +of encoded bytes per file, and uses `Limits::default()` for decoding. + +```sh +cargo run --quiet --locked --release -p craft-raw --example decode_report -- fixture-a.dng fixture-b.nef > report.tsv +``` + +Use shell redirection that preserves native stdout bytes. The report is UTF-8 TSV with LF line +endings, a header, and one row per argument, indexed from 1. Schema version 1 has these columns in +this order. + +```text +schema input status format sample_type sample_count sensor_sha256 width height cpp bits cfa active_area crop orientation baseline_exposure_bits +``` + +`format` is a fixed lowercase decoder label, such as `dng` or `cfa_tiff`. `sample_type` is `u16` or +`f32`. `sensor_sha256` hashes the complete decoded sample sequence (`RawImage::data`), encoding +each integer as two little-endian bytes and each float's IEEE 754 bits as four little-endian bytes. +The digest is 64 lowercase hexadecimal digits. It reflects any mapping the decoder has already +applied, such as a DNG `LinearizationTable`, so two stored codes that map to the same value give the +same digest. Shape and metadata have their own columns, so an orientation change +can be distinguished from a sample change. + +`cfa` is `width,height,origin_x,origin_y:pattern`, where the pattern is a comma-separated row-major +sequence. It is empty for images without a CFA. Active area and crop are `x,y,width,height`, with +crop coordinates relative to the active area. Orientation is the Exif integer code, and baseline +exposure is the `f64` bit pattern as 16 lowercase hexadecimal digits. + +Each row's status is `ok`, `read_error`, `input_limit`, `not_raw`, `unsupported`, `corrupt`, +`decode_limit`, or `tiff_error`. `input_limit` means the encoded-byte cap was exceeded. +`decode_limit` covers RAW and TIFF decoder limits. A failed input has empty fields after `status`, +and processing continues. The report contains input ordinals, with paths and free-form diagnostics +omitted. A completed batch exits successfully even when inputs fail. No arguments or a report +write or flush failure produces a nonzero exit and a concise diagnostic on stderr. + +To compare two pinned decoder revisions, use separate clean checkouts and keep the example source, +enabled features, and ordered fixture list identical. If a revision predates the example, copy both +`examples/decode_report/main.rs` and `examples/decode_report/report.rs` at the same relative paths +under that checkout's `crates/raw/` directory. The example uses the crate's existing `sha2` dev +dependency. It builds on `main` from +[`ecee6933`](https://github.com/storytold/craft-libs/commit/ecee693322c27acdbcafed4b57066356404e8378) +(#1171, 2026-11-13) onwards, the first revision whose `Cfa` has `origin_x` and `origin_y`. Older +revisions fail to build it. Build and save one report from each checkout, then compare them. + +```sh +git diff --no-index -- before.tsv after.tsv +``` + +Repeat on the same revision to check deterministic output. Record both decoder revisions, the +example source revision, enabled features, fixture checksums and order with the reports. A diff +exit status of 1 indicates differing reports. Inspect the status, sample digest, shape and metadata +columns to identify the change. diff --git a/crates/raw/examples/decode_report/main.rs b/crates/raw/examples/decode_report/main.rs new file mode 100644 index 000000000..94b722562 --- /dev/null +++ b/crates/raw/examples/decode_report/main.rs @@ -0,0 +1,35 @@ +//! Report the decoded samples and selected metadata of explicitly supplied RAW files. +//! `cargo run --locked -p craft-raw --example decode_report -- [ ...]` +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +#[cfg(not(target_arch = "wasm32"))] +mod report; + +#[cfg(not(target_arch = "wasm32"))] +fn main() -> std::process::ExitCode { + use std::io::{self, Write}; + use std::process::ExitCode; + + let stdout = io::stdout(); + let mut out = stdout.lock(); + match report::run(std::env::args_os().skip(1), &mut out, report::MAX_INPUT_BYTES, &craft_raw::Limits::default()) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + let stderr = io::stderr(); + let mut err = stderr.lock(); + match error { + report::RunError::Usage => { + let _ = writeln!(err, "usage: decode_report [ ...]"); + } + report::RunError::Output(error) => { + let _ = writeln!(err, "decode_report: report output failed ({:?})", error.kind()); + } + } + ExitCode::FAILURE + } + } +} + +#[cfg(target_arch = "wasm32")] +fn main() {} diff --git a/crates/raw/examples/decode_report/report.rs b/crates/raw/examples/decode_report/report.rs new file mode 100644 index 000000000..2d0c14dc0 --- /dev/null +++ b/crates/raw/examples/decode_report/report.rs @@ -0,0 +1,154 @@ +use std::ffi::OsString; +use std::fs::{self, File}; +use std::io::{self, Read, Write}; +use std::path::Path; + +use craft_raw::{Limits, RawData, RawError, RawFormat, RawImage, Rect}; +use craft_tiff::TiffError; +use sha2::{Digest, Sha256}; + +pub(super) const MAX_INPUT_BYTES: u64 = 512 * 1024 * 1024; +const SCHEMA: u8 = 1; +const HEADER: &str = "schema\tinput\tstatus\tformat\tsample_type\tsample_count\tsensor_sha256\twidth\theight\tcpp\tbits\tcfa\tactive_area\tcrop\torientation\tbaseline_exposure_bits"; + +#[derive(Debug)] +pub(super) enum RunError { + Usage, + Output(io::Error), +} + +pub(super) fn run(paths: impl IntoIterator, out: &mut impl Write, max_input_bytes: u64, limits: &Limits) -> Result<(), RunError> { + let mut paths = paths.into_iter().peekable(); + if paths.peek().is_none() { + return Err(RunError::Usage); + } + writeln!(out, "{HEADER}").map_err(RunError::Output)?; + for (index, path) in paths.enumerate() { + let input = index + 1; + let result = read_input(Path::new(&path), max_input_bytes) + .map_err(|failure| match failure { + InputFailure::Read => "read_error", + InputFailure::Limit => "input_limit", + }) + .and_then(|bytes| craft_raw::decode_with(&bytes, limits).map_err(decode_status)); + match result { + Ok(raw) => write_success(out, input, &raw), + Err(status) => write_failure(out, input, status), + } + .map_err(RunError::Output)?; + } + out.flush().map_err(RunError::Output) +} + +enum InputFailure { + Read, + Limit, +} + +fn read_input(path: &Path, max_input_bytes: u64) -> Result, InputFailure> { + // Reject non-regular paths before opening, and check the opened file again. + check_input(&fs::metadata(path).map_err(|_| InputFailure::Read)?, max_input_bytes)?; + let file = File::open(path).map_err(|_| InputFailure::Read)?; + check_input(&file.metadata().map_err(|_| InputFailure::Read)?, max_input_bytes)?; + let mut bytes = Vec::new(); + // A file may grow after the metadata check. Read at most one extra byte to detect it. + file.take(max_input_bytes.saturating_add(1)).read_to_end(&mut bytes).map_err(|_| InputFailure::Read)?; + if bytes.len() as u64 > max_input_bytes { + return Err(InputFailure::Limit); + } + Ok(bytes) +} + +fn check_input(metadata: &fs::Metadata, max_input_bytes: u64) -> Result<(), InputFailure> { + if !metadata.is_file() { + return Err(InputFailure::Read); + } + if metadata.len() > max_input_bytes { + return Err(InputFailure::Limit); + } + Ok(()) +} + +fn decode_status(error: RawError) -> &'static str { + match error { + RawError::NotRaw => "not_raw", + RawError::Unsupported(_) => "unsupported", + RawError::Corrupt(_) => "corrupt", + RawError::Limit(_) | RawError::Tiff(TiffError::Limit(_)) => "decode_limit", + RawError::Tiff(_) => "tiff_error", + } +} + +fn write_failure(out: &mut impl Write, input: usize, status: &str) -> io::Result<()> { + // Keep all 13 success-only fields present and empty. + writeln!(out, "{SCHEMA}\t{input}\t{status}\t\t\t\t\t\t\t\t\t\t\t\t\t") +} + +fn write_success(out: &mut impl Write, input: usize, raw: &RawImage) -> io::Result<()> { + let mut hash = Sha256::new(); + let (sample_type, count) = match &raw.data { + RawData::U16(samples) => { + for sample in samples { + hash.update(sample.to_le_bytes()); + } + ("u16", samples.len()) + } + RawData::F32(samples) => { + for sample in samples { + hash.update(sample.to_bits().to_le_bytes()); + } + ("f32", samples.len()) + } + }; + let digest = hash.finalize(); + write!( + out, + "{SCHEMA}\t{input}\tok\t{}\t{sample_type}\t{count}\t{digest:x}\t{}\t{}\t{}\t{}\t", + format_label(raw.format), + raw.width, + raw.height, + raw.cpp, + raw.bits, + )?; + if let Some(cfa) = &raw.cfa { + write!(out, "{},{},{},{}:", cfa.width, cfa.height, cfa.origin_x, cfa.origin_y)?; + let mut pattern = cfa.pattern.iter(); + if let Some(first) = pattern.next() { + write!(out, "{first}")?; + for channel in pattern { + write!(out, ",{channel}")?; + } + } + } + write_rect(out, raw.active_area)?; + write_rect(out, raw.crop)?; + writeln!(out, "\t{}\t{:016x}", raw.orientation.to_exif(), raw.color.baseline_exposure.to_bits()) +} + +fn write_rect(out: &mut impl Write, rect: Rect) -> io::Result<()> { + write!(out, "\t{},{},{},{}", rect.x, rect.y, rect.width, rect.height) +} + +fn format_label(format: RawFormat) -> &'static str { + match format { + RawFormat::Dng => "dng", + RawFormat::Cr2 => "cr2", + RawFormat::Cr3 => "cr3", + RawFormat::Nef => "nef", + RawFormat::Nrw => "nrw", + RawFormat::Arw => "arw", + RawFormat::Raf => "raf", + RawFormat::Orf => "orf", + RawFormat::Rw2 => "rw2", + RawFormat::Pef => "pef", + RawFormat::Srw => "srw", + RawFormat::Crw => "crw", + RawFormat::Mrw => "mrw", + RawFormat::X3f => "x3f", + RawFormat::CfaTiff => "cfa_tiff", + RawFormat::KodakDcs => "kodak_dcs", + RawFormat::Erf => "erf", + RawFormat::Mef => "mef", + RawFormat::OtherTiff => "other_tiff", + } +} diff --git a/crates/raw/tests/it/decode_report.rs b/crates/raw/tests/it/decode_report.rs new file mode 100644 index 000000000..89c800ce6 --- /dev/null +++ b/crates/raw/tests/it/decode_report.rs @@ -0,0 +1,217 @@ +use super::dng::{base_ifd, dng, synthetic}; +use craft_raw::{BlackLevel, Cfa, DngCompression, DngWriteOptions, Limits, Orientation, RawData, RawImage, write_dng}; +use craft_tiff::{ByteOrder, ImageData, Value, tags}; +use std::ffi::OsString; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; + +#[path = "../../examples/decode_report/report.rs"] +mod report; + +const HEADER: &str = concat!( + "schema\tinput\tstatus\tformat\tsample_type\tsample_count\tsensor_sha256\twidth\theight\tcpp\tbits\tcfa\t", + "active_area\tcrop\torientation\tbaseline_exposure_bits\n", +); + +struct FixtureDir(PathBuf); + +impl FixtureDir { + fn new(test: &str) -> Self { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")); + for attempt in 0..1000 { + let path = root.join(format!("decode-report-{test}-{}-{attempt}", std::process::id())); + // Only clean up a directory this test created, even if a process ID was reused. + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("create fixture directory {}: {error}", path.display()), + } + } + panic!("no free fixture directory for {test}"); + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for FixtureDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn integer_raw() -> RawImage { + let mut raw = synthetic(16, 16, Some(Cfa::bayer("RGGB").unwrap()), 1); + raw.data = RawData::U16((256..512).collect()); + raw.color.baseline_exposure = 0.5; + raw +} + +fn float_raw() -> RawImage { + let mut raw = synthetic(16, 16, None, 3); + raw.data = RawData::F32((0..16 * 16 * 3).map(|i| (i % 16) as f32 / 16.0).collect()); + raw.black = BlackLevel::uniform(0.0); + raw.white = vec![1.0]; + raw.color.baseline_exposure = 0.5; + raw +} + +fn write_fixture(dir: &Path, name: &str, raw: &RawImage, order: ByteOrder) -> OsString { + let bytes = write_dng(raw, &DngWriteOptions { compression: DngCompression::Uncompressed, order, ..Default::default() }).unwrap(); + write_bytes(dir, name, &bytes) +} + +fn write_bytes(dir: &Path, name: &str, bytes: &[u8]) -> OsString { + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + path.into_os_string() +} + +fn run_report(paths: &[OsString], max_input_bytes: u64, limits: &Limits) -> Vec { + let mut output = Vec::new(); + assert!(report::run(paths.iter().cloned(), &mut output, max_input_bytes, limits).is_ok()); + output +} + +#[test] +fn reports_exact_samples_shape_and_metadata_in_argument_order() { + let fixtures = FixtureDir::new("success"); + let dir = fixtures.path(); + let original = integer_raw(); + let integer = write_fixture(dir, "integer.dng", &original, ByteOrder::Little); + let float = write_fixture(dir, "float.dng", &float_raw(), ByteOrder::Big); + + let mut changed_sample = original.clone(); + let RawData::U16(samples) = &mut changed_sample.data else { + panic!("integer fixture must contain integer samples"); + }; + samples[127] += 1; + let changed_sample = write_fixture(dir, "changed-sample.dng", &changed_sample, ByteOrder::Little); + + let mut rotated = original; + rotated.orientation = Orientation::Normal; + let rotated = write_fixture(dir, "changed-orientation.dng", &rotated, ByteOrder::Little); + + let paths = [integer.clone(), float, changed_sample, rotated, integer]; + let limits = Limits::default(); + let first = run_report(&paths, report::MAX_INPUT_BYTES, &limits); + assert_eq!(first, run_report(&paths, report::MAX_INPUT_BYTES, &limits)); + + // The digests were generated independently from the known little-endian u16 and f32 bytes. + let rows = concat!( + "1\t1\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + "1\t2\tok\tdng\tf32\t768\tc50a4d270d6140ad9988fd8002c5b5de4a78b0b8d598b4db1a5a5385bd4119fd\t16\t16\t3\t32\t\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + "1\t3\tok\tdng\tu16\t256\t3ebf95a27aa36848dc2fc39f537625913e29fd1d390c41b50a527f27f1d5ce91\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + "1\t4\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t1\t3fe0000000000000\n", + "1\t5\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + ); + assert_eq!(String::from_utf8(first).unwrap(), format!("{HEADER}{rows}")); +} + +fn report_rows(text: &str) -> Vec> { + text.strip_prefix(HEADER) + .unwrap() + .lines() + .map(|line| { + let fields: Vec<_> = line.split('\t').collect(); + assert_eq!(fields.len(), 16); + fields + }) + .collect() +} + +#[test] +fn reports_mixed_failures_and_keeps_the_last_success() { + let fixtures = FixtureDir::new("mixed"); + let dir = fixtures.path(); + let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little); + let unreadable = dir.join("missing.dng").into_os_string(); + let text = write_bytes(dir, "private-fixture-name.txt", b"not a recognized RAW header"); + + let mut unsupported = base_ifd(8, 6, 16, 2, false); + unsupported.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![vec![0; 8 * 6 * 2 * 2]] }); + let unsupported = write_bytes(dir, "unsupported.dng", &dng(unsupported, ByteOrder::Little)); + + let mut corrupt = base_ifd(8, 6, 16, 1, true); + corrupt.set(tags::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 2])); + corrupt.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![vec![0; 8 * 6 * 2]] }); + let corrupt = write_bytes(dir, "corrupt.dng", &dng(corrupt, ByteOrder::Little)); + + let missing_strips = dng(base_ifd(8, 6, 16, 1, true), ByteOrder::Little); + let tiff_error = write_bytes(dir, "missing-strips.dng", &missing_strips); + let paths = [integer.clone(), unreadable, text, unsupported, corrupt, tiff_error, integer]; + let limits = Limits::default(); + let first = run_report(&paths, report::MAX_INPUT_BYTES, &limits); + assert_eq!(first, run_report(&paths, report::MAX_INPUT_BYTES, &limits)); + + let text = String::from_utf8(first).unwrap(); + assert!(!text.contains("private-fixture-name")); + assert!(!text.contains("CFAPattern size mismatch")); + let rows = report_rows(&text); + let statuses = ["ok", "read_error", "not_raw", "unsupported", "corrupt", "tiff_error", "ok"]; + assert_eq!(rows.len(), statuses.len()); + for (index, (row, status)) in rows.iter().zip(statuses).enumerate() { + assert_eq!(row[0], "1"); + assert_eq!(row[1], (index + 1).to_string()); + assert_eq!(row[2], status); + if status != "ok" { + assert!(row[3..].iter().all(|field| field.is_empty())); + } + } + assert_eq!(rows[0][2..], rows[6][2..]); +} + +#[test] +fn separates_encoded_file_and_shared_decoder_limits() { + let fixtures = FixtureDir::new("limits"); + let dir = fixtures.path(); + let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little); + let size = std::fs::metadata(Path::new(&integer)).unwrap().len(); + let paths = [integer]; + for (max_input_bytes, max_samples, status) in [(size, 256, "ok"), (size - 1, 256, "input_limit"), (size, 255, "decode_limit")] { + let mut limits = Limits::default(); + limits.max_samples = max_samples; + let output = String::from_utf8(run_report(&paths, max_input_bytes, &limits)).unwrap(); + let rows = report_rows(&output); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0][..3], ["1", "1", status]); + if status != "ok" { + assert!(rows[0][3..].iter().all(|field| field.is_empty())); + } + } +} + +#[test] +fn empty_arguments_report_usage_without_writing_a_header() { + let mut output = Vec::new(); + let result = report::run([], &mut output, report::MAX_INPUT_BYTES, &Limits::default()); + assert!(matches!(result, Err(report::RunError::Usage))); + assert!(output.is_empty()); +} + +struct BrokenOutput { + write_error: bool, +} + +impl Write for BrokenOutput { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if self.write_error { Err(io::Error::from(io::ErrorKind::BrokenPipe)) } else { Ok(bytes.len()) } + } + + fn flush(&mut self) -> io::Result<()> { + Err(io::Error::from(io::ErrorKind::WriteZero)) + } +} + +#[test] +fn write_and_flush_errors_fail_the_invocation() { + let fixtures = FixtureDir::new("output-error"); + let dir = fixtures.path(); + let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little); + for (write_error, kind) in [(true, io::ErrorKind::BrokenPipe), (false, io::ErrorKind::WriteZero)] { + let mut out = BrokenOutput { write_error }; + let result = report::run([integer.clone()], &mut out, report::MAX_INPUT_BYTES, &Limits::default()); + assert!(matches!(result, Err(report::RunError::Output(error)) if error.kind() == kind)); + } +} diff --git a/crates/raw/tests/it/main.rs b/crates/raw/tests/it/main.rs index 30f331263..a13bdf29f 100644 --- a/crates/raw/tests/it/main.rs +++ b/crates/raw/tests/it/main.rs @@ -1,5 +1,7 @@ //! The integration tests, one module per file, linked into one test binary. +#[cfg(all(feature = "dng", not(target_arch = "wasm32")))] +mod decode_report; #[cfg(feature = "dng")] mod dng; #[cfg(feature = "line-dng")]