mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 22:37:12 +00:00
Report DNG linearization in decoder comparisons (#3030)
This commit is contained in:
+21
-3
@@ -248,6 +248,20 @@ sequence. It is empty for images without a CFA. Active area and crop are `x,y,wi
|
||||
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.
|
||||
|
||||
Use `--linearization` before the paths to select schema version 2:
|
||||
|
||||
```sh
|
||||
cargo run --quiet --locked --release -p craft-raw --example decode_report -- --linearization fixture-a.dng fixture-b.dng > report.tsv
|
||||
```
|
||||
|
||||
Schema 2 appends `linearization_state` and `linearization_table_sha256`. The state is `absent`,
|
||||
`applied`, or `deferred`. A deferred table is carried by the decoder for application after DNG
|
||||
`OpcodeList1`. The digest hashes all decoded table entries in index order as little-endian `u16`
|
||||
values. It is empty when the table is absent. Both fields are empty for failed inputs. The sample
|
||||
digest still describes `RawImage::data`, so two deferred inputs with identical stored samples can
|
||||
have the same sample digest and different table digests. Use a `--` separator before the paths to
|
||||
pass a path literally when its name matches an option.
|
||||
|
||||
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`,
|
||||
@@ -259,10 +273,14 @@ To compare two pinned decoder revisions, use separate clean checkouts and keep t
|
||||
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
|
||||
dependency. The schema 2-capable example requires
|
||||
[`a99c8f8e`](https://github.com/storytold/craft-libs/commit/a99c8f8e366363ac5ff2f1eee535751610c2c82c)
|
||||
or later for `RawImage::linearization_table`. For comparisons involving an older decoder, use
|
||||
both example files from [#2417](https://github.com/storytold/craft-libs/pull/2417) in each checkout
|
||||
to produce schema 1. Those files require
|
||||
[`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.
|
||||
or later for `Cfa::origin_x` and `Cfa::origin_y`. Build and save one report from each checkout, then
|
||||
compare them.
|
||||
|
||||
```sh
|
||||
git diff --no-index -- before.tsv after.tsv
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Report the decoded samples and selected metadata of explicitly supplied RAW files.
|
||||
//! `cargo run --locked -p craft-raw --example decode_report -- <file> [<file> ...]`
|
||||
//! `cargo run --locked -p craft-raw --example decode_report -- [--linearization] [--] <file> [<file> ...]`
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
@@ -20,7 +20,7 @@ fn main() -> std::process::ExitCode {
|
||||
let mut err = stderr.lock();
|
||||
match error {
|
||||
report::RunError::Usage => {
|
||||
let _ = writeln!(err, "usage: decode_report <file> [<file> ...]");
|
||||
let _ = writeln!(err, "usage: decode_report [--linearization] [--] <file> [<file> ...]");
|
||||
}
|
||||
report::RunError::Output(error) => {
|
||||
let _ = writeln!(err, "decode_report: report output failed ({:?})", error.kind());
|
||||
|
||||
@@ -8,8 +8,23 @@ 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";
|
||||
const LINEARIZATION_HEADER: &str = "\tlinearization_state\tlinearization_table_sha256";
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Schema {
|
||||
Original,
|
||||
Linearization,
|
||||
}
|
||||
|
||||
impl Schema {
|
||||
fn version(self) -> u8 {
|
||||
match self {
|
||||
Self::Original => 1,
|
||||
Self::Linearization => 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) enum RunError {
|
||||
@@ -17,12 +32,15 @@ pub(super) enum RunError {
|
||||
Output(io::Error),
|
||||
}
|
||||
|
||||
pub(super) fn run(paths: impl IntoIterator<Item = OsString>, out: &mut impl Write, max_input_bytes: u64, limits: &Limits) -> Result<(), RunError> {
|
||||
let mut paths = paths.into_iter().peekable();
|
||||
pub(super) fn run(args: impl IntoIterator<Item = OsString>, out: &mut impl Write, max_input_bytes: u64, limits: &Limits) -> Result<(), RunError> {
|
||||
let mut paths = args.into_iter().peekable();
|
||||
let (schema, extra_header) =
|
||||
if paths.next_if(|arg| arg == "--linearization").is_some() { (Schema::Linearization, LINEARIZATION_HEADER) } else { (Schema::Original, "") };
|
||||
paths.next_if(|arg| arg == "--");
|
||||
if paths.peek().is_none() {
|
||||
return Err(RunError::Usage);
|
||||
}
|
||||
writeln!(out, "{HEADER}").map_err(RunError::Output)?;
|
||||
writeln!(out, "{HEADER}{extra_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)
|
||||
@@ -32,8 +50,8 @@ pub(super) fn run(paths: impl IntoIterator<Item = OsString>, out: &mut impl Writ
|
||||
})
|
||||
.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),
|
||||
Ok(raw) => write_success(out, schema, input, &raw),
|
||||
Err(status) => write_failure(out, schema, input, status),
|
||||
}
|
||||
.map_err(RunError::Output)?;
|
||||
}
|
||||
@@ -79,12 +97,13 @@ fn decode_status(error: RawError) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
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_failure(out: &mut impl Write, schema: Schema, input: usize, status: &str) -> io::Result<()> {
|
||||
// Keep the success-only fields present and empty in both schemas.
|
||||
let extra_fields = if let Schema::Linearization = schema { "\t\t" } else { "" };
|
||||
writeln!(out, "{}\t{input}\t{status}\t\t\t\t\t\t\t\t\t\t\t\t\t{extra_fields}", schema.version())
|
||||
}
|
||||
|
||||
fn write_success(out: &mut impl Write, input: usize, raw: &RawImage) -> io::Result<()> {
|
||||
fn write_success(out: &mut impl Write, schema: Schema, input: usize, raw: &RawImage) -> io::Result<()> {
|
||||
let mut hash = Sha256::new();
|
||||
let (sample_type, count) = match &raw.data {
|
||||
RawData::U16(samples) => {
|
||||
@@ -103,7 +122,8 @@ fn write_success(out: &mut impl Write, input: usize, raw: &RawImage) -> io::Resu
|
||||
let digest = hash.finalize();
|
||||
write!(
|
||||
out,
|
||||
"{SCHEMA}\t{input}\tok\t{}\t{sample_type}\t{count}\t{digest:x}\t{}\t{}\t{}\t{}\t",
|
||||
"{}\t{input}\tok\t{}\t{sample_type}\t{count}\t{digest:x}\t{}\t{}\t{}\t{}\t",
|
||||
schema.version(),
|
||||
format_label(raw.format),
|
||||
raw.width,
|
||||
raw.height,
|
||||
@@ -122,7 +142,23 @@ fn write_success(out: &mut impl Write, input: usize, raw: &RawImage) -> io::Resu
|
||||
}
|
||||
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())
|
||||
write!(out, "\t{}\t{:016x}", raw.orientation.to_exif(), raw.color.baseline_exposure.to_bits())?;
|
||||
if let Schema::Linearization = schema {
|
||||
write_linearization(out, raw)?;
|
||||
}
|
||||
writeln!(out)
|
||||
}
|
||||
|
||||
fn write_linearization(out: &mut impl Write, raw: &RawImage) -> io::Result<()> {
|
||||
let Some(table) = &raw.linearization_table else {
|
||||
return write!(out, "\tabsent\t");
|
||||
};
|
||||
let state = if raw.linearized { "applied" } else { "deferred" };
|
||||
let mut hash = Sha256::new();
|
||||
for entry in table {
|
||||
hash.update(entry.to_le_bytes());
|
||||
}
|
||||
write!(out, "\t{state}\t{:x}", hash.finalize())
|
||||
}
|
||||
|
||||
fn write_rect(out: &mut impl Write, rect: Rect) -> io::Result<()> {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::dng::{base_ifd, dng, synthetic};
|
||||
use super::dng::{base_ifd, dng, synthetic, u16_bytes};
|
||||
use craft_raw::opcodes::{self, Area, Opcode};
|
||||
use craft_raw::{BlackLevel, Cfa, DngCompression, DngWriteOptions, Limits, Orientation, RawData, RawImage, write_dng};
|
||||
use craft_tiff::{ByteOrder, ImageData, Value, tags};
|
||||
use std::ffi::OsString;
|
||||
@@ -122,6 +123,77 @@ fn report_rows(text: &str) -> Vec<Vec<&str>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn linearization_dng(table: Option<Vec<u16>>, deferred: bool, order: ByteOrder) -> Vec<u8> {
|
||||
let mut raw = base_ifd(4, 2, 16, 1, true);
|
||||
raw.set_image(ImageData::Strips { rows_per_strip: 2, strips: vec![u16_bytes(&[2; 8], order)] });
|
||||
raw.set(tags::WHITE_LEVEL, Value::Long(vec![30]));
|
||||
if let Some(table) = table {
|
||||
raw.set(tags::LINEARIZATION_TABLE, Value::Short(table));
|
||||
}
|
||||
if deferred {
|
||||
let area = Area { top: 0, left: 0, bottom: 2, right: 4, plane: 0, planes: 1, row_pitch: 1, col_pitch: 1 };
|
||||
let list = opcodes::write_list(&[Opcode::MapTable { area, table: vec![0, 1, 3, 3] }]);
|
||||
raw.set(tags::OPCODE_LIST_1, Value::Undefined(list));
|
||||
}
|
||||
dng(raw, order)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_linearization_state_and_digest_separately_from_samples() {
|
||||
let fixtures = FixtureDir::new("linearization");
|
||||
let write = |name, table, deferred, order| write_bytes(fixtures.path(), name, &linearization_dng(table, deferred, order));
|
||||
let table = vec![0, 10, 20, 30];
|
||||
let paths = [
|
||||
OsString::from("--linearization"),
|
||||
OsString::from("--"),
|
||||
write("deferred.dng", Some(table.clone()), true, ByteOrder::Little),
|
||||
write("changed-table.dng", Some(vec![0, 10, 20, 31]), true, ByteOrder::Little),
|
||||
write("big-endian.dng", Some(table.clone()), true, ByteOrder::Big),
|
||||
write("applied.dng", Some(table), false, ByteOrder::Little),
|
||||
write("absent.dng", None, false, ByteOrder::Little),
|
||||
fixtures.path().join("missing.dng").into_os_string(),
|
||||
];
|
||||
let original = String::from_utf8(run_report(&paths[2..4], report::MAX_INPUT_BYTES, &Limits::default())).unwrap();
|
||||
let original = report_rows(&original);
|
||||
assert_eq!(original[0][2..], original[1][2..]);
|
||||
let output = || run_report(&paths, report::MAX_INPUT_BYTES, &Limits::default());
|
||||
let text = String::from_utf8(output()).unwrap();
|
||||
let mut lines = text.lines();
|
||||
let header = format!("{}\tlinearization_state\tlinearization_table_sha256", HEADER.trim_end());
|
||||
assert_eq!(lines.next(), Some(header.as_str()));
|
||||
assert_eq!(text.as_bytes(), output());
|
||||
let rows: Vec<Vec<&str>> = lines.map(|line| line.split('\t').collect()).collect();
|
||||
assert_eq!(rows.len(), 6);
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
assert_eq!(row.len(), 18);
|
||||
assert_eq!(row[..2], ["2", &(index + 1).to_string()]);
|
||||
}
|
||||
|
||||
// Hashes from the four known u16 values packed as little-endian bytes.
|
||||
let digest = "6e5d2a85c5e65eea7b6fde4ed812c7f22f3b41b99e76607a58a8141a254df12a";
|
||||
let changed = "138055ff13d0e163c85338c4221f468ee093cb792f7ecab41fd62abd3869a9c6";
|
||||
assert_eq!(rows[0][2..16], rows[1][2..16]);
|
||||
assert_eq!(rows[0][2..], rows[2][2..]);
|
||||
assert_eq!(rows[0][16..], ["deferred", digest]);
|
||||
assert_eq!(rows[1][16..], ["deferred", changed]);
|
||||
assert_eq!(rows[3][16..], ["applied", digest]);
|
||||
assert_ne!(rows[3][6], rows[0][6]);
|
||||
assert_eq!(rows[4][2], "ok");
|
||||
assert_eq!(rows[4][6], rows[0][6]);
|
||||
assert_eq!(rows[4][16..], ["absent", ""]);
|
||||
assert_eq!(rows[5][2], "read_error");
|
||||
assert!(rows[5][3..].iter().all(|field| field.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separator_allows_a_path_matching_the_linearization_option() {
|
||||
let paths = [OsString::from("--"), OsString::from("--linearization")];
|
||||
let text = String::from_utf8(run_report(&paths, report::MAX_INPUT_BYTES, &Limits::default())).unwrap();
|
||||
let rows = report_rows(&text);
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0][..2], ["1", "1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_mixed_failures_and_keeps_the_last_success() {
|
||||
let fixtures = FixtureDir::new("mixed");
|
||||
@@ -184,11 +256,13 @@ fn separates_encoded_file_and_shared_decoder_limits() {
|
||||
}
|
||||
|
||||
#[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());
|
||||
fn missing_paths_report_usage_without_writing_a_header() {
|
||||
for args in [&[][..], &["--linearization"], &["--"], &["--linearization", "--"]] {
|
||||
let mut output = Vec::new();
|
||||
let result = report::run(args.iter().map(OsString::from), &mut output, report::MAX_INPUT_BYTES, &Limits::default());
|
||||
assert!(matches!(result, Err(report::RunError::Usage)));
|
||||
assert!(output.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
struct BrokenOutput {
|
||||
|
||||
Reference in New Issue
Block a user