From 083685a34d09e8e88003c7855413705ada056efa Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Fri, 9 Oct 2026 23:08:02 +0200 Subject: [PATCH 01/21] LR-IMP-FORMATS: RDD 34 VLD line decoder with Sony's ARW6 deviations --- crates/raw/src/lib.rs | 1 + crates/raw/src/llvc.rs | 223 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 224 insertions(+) create mode 100644 crates/raw/src/llvc.rs diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index f0331d61..b6aeca15 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -35,6 +35,7 @@ pub mod highlight; #[cfg(feature = "jxl")] mod jxl; pub mod ljpeg; +pub(crate) mod llvc; pub mod opcodes; mod preview; pub mod profile; diff --git a/crates/raw/src/llvc.rs b/crates/raw/src/llvc.rs new file mode 100644 index 00000000..31dc67ef --- /dev/null +++ b/crates/raw/src/llvc.rs @@ -0,0 +1,223 @@ +//! RDD 34:2015 LLVC codec core as Sony's ARW6 uses it; see docs/arw6-compression.md. +//! +//! Clean-room: written from SMPTE RDD 34:2015 §6.3 (Figures 6.5-6.8) and checked against its worked +//! example (Figure 6.9) and Phase 0 oracle vectors. No other raw decoder's source was consulted. + +// Consumed by the dequantiser/wavelet/ARW6 container tasks that follow. +#![allow(dead_code)] + +use crate::vendor::pef::Bits; +use crate::{RawError, Result}; + +/// Largest coefficient bit depth (DPT) a stream may select; keeps `Bits::get` in range. +pub(crate) const MAX_DPT: u32 = 24; + +fn corrupt(why: &str) -> RawError { + RawError::Corrupt(format!("ARW6 VLD: {why}")) +} + +/// One bit, failing when the reader has run past the `source_bits` of its half. +fn bit(bits: &mut Bits<'_>, source_bits: usize) -> Result { + let b = bits.get(1); + if bits.consumed_bits() > source_bits { + return Err(corrupt("past the end of its half")); + } + Ok(b) +} + +/// Count zero bits up to and including the terminating 1 (the `0^n 1` codes), bounded by `MAX_DPT`. +fn zeros_then_one(bits: &mut Bits<'_>, source_bits: usize) -> Result { + let mut n = 0; + while bit(bits, source_bits)? == 0 { + n += 1; + if n > MAX_DPT { + return Err(corrupt("DPT code exceeds MAX_DPT")); + } + } + Ok(n) +} + +/// Decode one coefficient line of `width.div_ceil(4)` sets (RDD 34 §6.3.6) and return exactly `width` values. +pub(crate) fn vld_decode_line(bits: &mut Bits<'_>, source_bits: usize, width: usize) -> Result> { + let sets = width.div_ceil(4); + let (mut abs, mut dpt, mut cnt, mut dpts) = ([0u32; 4], 0u32, sets, 0u8); + let (mut abs_v, mut abs_e, mut dpt_v, mut dpt_e, mut zr) = (false, false, true, false, 0u64); + let mut out: Vec = Vec::new(); + loop { + // DPT value decoding (Figure 6.6). + if cnt == 0 { + dpt_v = false; + } + if cnt == 1 { + dpt_e = true; + } + cnt = cnt.saturating_sub(1); + zr = zr.saturating_sub(1); + if dpt_v { + match dpts { + 0 => { + if bit(bits, source_bits)? == 0 { + // Sony deviation 1, oracle-verified in Phase 0: a zero code at DPT 0 is a zero set entering run mode. + if dpt == 0 { + dpts = 1; + } + } else if bit(bits, source_bits)? == 0 { + // "1 0 0^n 1": DPT up by n+1. + dpt = dpt.saturating_add(zeros_then_one(bits, source_bits)? + 1); + } else { + // "1 1 0^n 1" (DPT down by n+1) or "1 1 0^(DPT-1)" (DPT to 0). + let mut n = 0; + while n + 1 < dpt && bit(bits, source_bits)? == 0 { + n += 1; + } + if n + 1 >= dpt { + dpt = 0; + dpts = 1; + } else { + dpt -= n + 1; + } + } + } + 1 => { + if bit(bits, source_bits)? == 1 { + // "1 0^n 1": leave run mode at DPT n+1. + dpt = zeros_then_one(bits, source_bits)? + 1; + dpts = 0; + } else { + // Run code of ceil(log2(Cnt+2)) bits (Figure 6.6). + let lim = (cnt as u64 + 2).next_power_of_two().trailing_zeros(); + if lim > 32 { + return Err(corrupt("line too wide")); + } + let mut m = 1; + while m < lim && bit(bits, source_bits)? == 0 { + m += 1; + } + if m == lim { + // "0^lim": the rest of the line is zero. + zr = cnt as u64 + 2; + } else { + zr = 1; + for _ in 0..m { + zr = (zr << 1) | bit(bits, source_bits)? as u64; + } + } + dpts = 2; + } + } + _ => { + // Sony deviation 2, oracle-verified in Phase 0: the run ends at ZR == 1 (RDD 34 says 0). + if zr == 1 { + dpt = zeros_then_one(bits, source_bits)? + 1; + dpts = 0; + } + } + } + if dpt > MAX_DPT { + return Err(corrupt("DPT exceeds MAX_DPT")); + } + } + // SGN value decoding (Figure 6.7): signs of the previous set. + if abs_v { + for v in abs { + let v = v as i32; + out.push(if v != 0 && bit(bits, source_bits)? == 1 { -v } else { v }); + } + } + if abs_e { + out.truncate(width); + return Ok(out); + } + abs_v = dpt_v; + abs_e = dpt_e; + // ABS value decoding (Figure 6.8). + if dpt_v { + for a in abs.iter_mut() { + *a = bits.get(dpt); + } + if bits.consumed_bits() > source_bits { + return Err(corrupt("past the end of its half")); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::vendor::pef::Bits; + + fn bits_of(s: &str) -> Vec { + let mut out = vec![0u8; s.len().div_ceil(8)]; + for (i, c) in s.bytes().enumerate() { + if c == b'1' { + out[i / 8] |= 0x80 >> (i % 8); + } + } + out + } + fn line(s: &str, width: usize) -> (Vec, usize) { + let src = bits_of(s); + let mut b = Bits::new(&src); + let v = vld_decode_line(&mut b, src.len() * 8, width).unwrap(); + (v, b.consumed_bits()) + } + + #[test] + fn rdd34_figure_6_9_worked_example() { + // RDD 34:2015 §6.3.6, Figure 6.9: 8 sets, 91 bits + let s = "1000010110000010000100110000101000010100110100000000000011000010010001001010011100110000000"; + let (v, used) = line(s, 32); + assert_eq!(v, vec![6, 0, -8, 4, 0, 0, 0, 0, -9, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0]); + assert_eq!(used, 91); + } + #[test] + fn sony_zero_at_dpt0_enters_run_state() { + // Phase 0 vector "dev1": a "0" at DPT 0 is a zero set that moves to DPTs = 1; the next set uses the "1 0^n 1" code + let (v, used) = line("01001101000011001010", 8); + assert_eq!(v, vec![0, 0, 0, 0, 5, 0, -3, 1]); + assert_eq!(used, 20); + } + #[test] + fn sony_run_value_means_minus_one_zero_sets() { + // Phase 0 vector "dev2": run code value 3 = two more zero sets, then "0^n 1" post-run DPT + let (v, used) = line("001101100000000", 16); + assert_eq!(v, vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0]); + assert_eq!(used, 15); + } + #[test] + fn end_of_line_zero_code() { + let (v, used) = line("1001110100101100100", 12); + assert_eq!(v, vec![3, -1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0]); + assert_eq!(used, 19); + } + #[test] + fn dpt_moves_up_down_and_to_zero() { + let (v, used) = line("1011000100101111111110011101001011111100000", 20); + assert_eq!(v, vec![1, 0, 0, 0, 7, 7, -7, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]); + assert_eq!(used, 43); + } + #[test] + fn all_zero_line_is_two_bits_and_width_truncates() { + let (v, used) = line("00", 6); // L = 2 sets, width 6 keeps 6 of 8 values + assert_eq!(v, vec![0; 6]); + assert_eq!(used, 2); + } + #[test] + fn hostile_input_errors_instead_of_panicking() { + let mut climb = vec![0u8; 64]; + climb[0] = 0x80; // "1 0 0^n 1" with n > MAX_DPT + let mut b = Bits::new(&climb); + assert!(matches!(vld_decode_line(&mut b, 512, 16), Err(RawError::Corrupt(_)))); + let short = bits_of("10"); // needs more bits than it has + let mut b = Bits::new(&short); + assert!(matches!(vld_decode_line(&mut b, 2, 16), Err(RawError::Corrupt(_)))); + } + proptest::proptest! { + #[test] + fn random_bits_never_panic(src in proptest::collection::vec(proptest::num::u8::ANY, 0..256), width in 1usize..300) { + let mut b = Bits::new(&src); + let _ = vld_decode_line(&mut b, src.len() * 8, width); + } + } +} From 01438b897925dd7b4c698a9f00221198ad3e6e14 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Fri, 9 Oct 2026 23:10:05 +0200 Subject: [PATCH 02/21] LR-IMP-FORMATS: ARW6 VLD returns an empty line for width 0 --- crates/raw/src/llvc.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/raw/src/llvc.rs b/crates/raw/src/llvc.rs index 31dc67ef..28882c13 100644 --- a/crates/raw/src/llvc.rs +++ b/crates/raw/src/llvc.rs @@ -39,6 +39,9 @@ fn zeros_then_one(bits: &mut Bits<'_>, source_bits: usize) -> Result { /// Decode one coefficient line of `width.div_ceil(4)` sets (RDD 34 §6.3.6) and return exactly `width` values. pub(crate) fn vld_decode_line(bits: &mut Bits<'_>, source_bits: usize, width: usize) -> Result> { + if width == 0 { + return Ok(Vec::new()); // no sets: the state machine below would never terminate + } let sets = width.div_ceil(4); let (mut abs, mut dpt, mut cnt, mut dpts) = ([0u32; 4], 0u32, sets, 0u8); let (mut abs_v, mut abs_e, mut dpt_v, mut dpt_e, mut zr) = (false, false, true, false, 0u64); @@ -204,6 +207,12 @@ mod tests { assert_eq!(used, 2); } #[test] + fn width_zero_returns_empty_line() { + let (v, used) = line("1111", 0); + assert!(v.is_empty()); + assert_eq!(used, 0); + } + #[test] fn hostile_input_errors_instead_of_panicking() { let mut climb = vec![0u8; 64]; climb[0] = 0x80; // "1 0 0^n 1" with n > MAX_DPT @@ -215,7 +224,7 @@ mod tests { } proptest::proptest! { #[test] - fn random_bits_never_panic(src in proptest::collection::vec(proptest::num::u8::ANY, 0..256), width in 1usize..300) { + fn random_bits_never_panic(src in proptest::collection::vec(proptest::num::u8::ANY, 0..256), width in 0usize..300) { let mut b = Bits::new(&src); let _ = vld_decode_line(&mut b, src.len() * 8, width); } From 3a4a70fa8f06986765885e7b167bcf071a8438f2 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Fri, 9 Oct 2026 23:28:44 +0200 Subject: [PATCH 03/21] LR-IMP-FORMATS: ARW6 parity dequantiser and 5/3 inverse lifting with phases --- crates/raw/src/llvc.rs | 196 ++++++++++++++++++++++++++ crates/raw/src/vendor/arw6_testenc.rs | 79 +++++++++++ crates/raw/src/vendor/mod.rs | 2 + 3 files changed, 277 insertions(+) create mode 100644 crates/raw/src/vendor/arw6_testenc.rs diff --git a/crates/raw/src/llvc.rs b/crates/raw/src/llvc.rs index 28882c13..d99acaa6 100644 --- a/crates/raw/src/llvc.rs +++ b/crates/raw/src/llvc.rs @@ -145,6 +145,138 @@ pub(crate) fn vld_decode_line(bits: &mut Bits<'_>, source_bits: usize, width: us } } +/// Parity dequantiser, Phase 0 (oracle-verified): 0 -> 0, qi = 0 -> q, else +/// `sign(q) * (((2|q| + 1) << (qi - 1)) - (|q| & 1))`. Saturates instead of overflowing on hostile input. +pub(crate) fn dequant(q: i32, qi: u32) -> i32 { + if q == 0 || qi == 0 { + return q; + } + let a = i64::from(q).abs(); + let m = (((2 * a + 1) << (qi - 1).min(30)) - (a & 1)).min(i64::from(i32::MAX)); + (if q < 0 { -m } else { m }) as i32 +} + +/// A row-major plane of integer samples. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Plane { + pub width: usize, + pub height: usize, + pub data: Vec, +} + +impl Plane { + pub fn zeros(width: usize, height: usize) -> Plane { + Plane { width, height, data: vec![0; width.saturating_mul(height)] } + } + pub fn row(&self, y: usize) -> Option<&[i32]> { + let start = y.checked_mul(self.width)?; + self.data.get(start..start.checked_add(self.width)?) + } + fn ok(&self) -> bool { + self.width.checked_mul(self.height) == Some(self.data.len()) + } +} + +/// `(low, high)` sample counts of an `n`-sample signal whose low-pass samples sit at indices = `phase` (mod 2). +pub(crate) fn band_rows(n: usize, phase: u8) -> (usize, usize) { + let low = (n + 1).saturating_sub(usize::from(phase)) / 2; + (low, n - low) +} + +/// `v[i]` with `i` clamped into range (the whole-sample symmetric extension of the band); 0 for an empty band. +fn at(v: &[i32], i: isize) -> i32 { + let last = v.len() as isize - 1; + if last < 0 { + return 0; + } + v.get(i.clamp(0, last) as usize).copied().unwrap_or(0) +} + +/// 1-D inverse 5/3 lifting, RDD 34 §6.5, with X[-1] := X[1], X[n] := X[n-2] (see `band_rows` for the sizes). +fn inverse_1d(l: &[i32], h: &[i32], phase: u8) -> Result> { + let (n, p) = (l.len() + h.len(), isize::from(phase)); + if band_rows(n, phase) != (l.len(), h.len()) || phase > 1 { + return Err(RawError::Corrupt("ARW6 wavelet: band sizes do not match".into())); + } + let even: Vec = l.iter().enumerate().map(|(j, &lv)| lv - ((at(h, j as isize - 1 + p) + at(h, j as isize + p) + 2) >> 2)).collect(); + let mut x = vec![0; n]; + let (lo, hi) = (usize::from(phase), 1 - usize::from(phase)); + for (xv, &e) in x.iter_mut().skip(lo).step_by(2).zip(&even) { + *xv = e; + } + for (k, (xv, &hv)) in x.iter_mut().skip(hi).step_by(2).zip(h).enumerate() { + *xv = hv + ((at(&even, k as isize - p) + at(&even, k as isize + 1 - p)) >> 1); + } + Ok(x) +} + +/// Gathers the lines of `a` along one axis (columns when `vertical`), applies `f`, and scatters back. +fn lines(low: &Plane, high: &Plane, phase: u8, vertical: bool) -> Result { + if !low.ok() || !high.ok() { + return Err(RawError::Corrupt("ARW6 wavelet: plane size mismatch".into())); + } + let (across_l, across_h) = if vertical { (low.width, high.width) } else { (low.height, high.height) }; + if across_l != across_h { + return Err(RawError::Corrupt("ARW6 wavelet: band sizes do not match".into())); + } + let (nl, nh) = if vertical { (low.height, high.height) } else { (low.width, high.width) }; + let n = nl + nh; + let (w, h) = if vertical { (across_l, n) } else { (n, across_l) }; + let mut out = Plane::zeros(w, h); + let get = |p: &Plane, i: usize| -> Vec { + if vertical { p.data.iter().skip(i).step_by(p.width.max(1)).copied().collect() } else { p.row(i).map(<[i32]>::to_vec).unwrap_or_default() } + }; + for i in 0..across_l { + let x = inverse_1d(&get(low, i), &get(high, i), phase)?; + if vertical { + for (o, v) in out.data.iter_mut().skip(i).step_by(w.max(1)).zip(x) { + *o = v; + } + } else if let Some(r) = out.data.get_mut(i * w..(i + 1) * w) { + r.copy_from_slice(&x); + } + } + Ok(out) +} + +/// Vertical inverse 5/3 (along rows of samples): `low`/`high` are stacked bands of equal width. +pub(crate) fn inverse_53_1d_rows(low: &Plane, high: &Plane, phase: u8) -> Result { + lines(low, high, phase, true) +} + +/// Horizontal inverse 5/3: `low`/`high` are side-by-side bands of equal height. +pub(crate) fn inverse_53_1d_cols(low: &Plane, high: &Plane, phase: u8) -> Result { + lines(low, high, phase, false) +} + +/// 2-D inverse, RDD 34 §6.5 order: vertical IWT (phase `vphase`) on (ll, lh) and (hl, hh), then horizontal (phase 0). +pub(crate) fn inverse_53_2d(ll: &Plane, lh: &Plane, hl: &Plane, hh: &Plane, vphase: u8) -> Result { + let lo = inverse_53_1d_rows(ll, lh, vphase)?; + let hi = inverse_53_1d_rows(hl, hh, vphase)?; + inverse_53_1d_cols(&lo, &hi, 0) +} + +/// The ten bands of a 3-level decomposition (LL only at the deepest level). +pub(crate) struct Bands3 { + pub ll3: Plane, + pub hl3: Plane, + pub lh3: Plane, + pub hh3: Plane, + pub hl2: Plane, + pub lh2: Plane, + pub hh2: Plane, + pub hl1: Plane, + pub lh1: Plane, + pub hh1: Plane, +} + +/// Full inverse: level 3 uses `phases[2]`, level 2 `phases[1]`, level 1 `phases[0]`. +pub(crate) fn reconstruct3(b: &Bands3, phases: [u8; 3]) -> Result { + let ll2 = inverse_53_2d(&b.ll3, &b.lh3, &b.hl3, &b.hh3, phases[2])?; + let ll1 = inverse_53_2d(&ll2, &b.lh2, &b.hl2, &b.hh2, phases[1])?; + inverse_53_2d(&ll1, &b.lh1, &b.hl1, &b.hh1, phases[0]) +} + #[cfg(test)] mod tests { use super::*; @@ -229,4 +361,68 @@ mod tests { let _ = vld_decode_line(&mut b, src.len() * 8, width); } } + + fn col(v: &[i32]) -> Plane { + Plane { width: 1, height: v.len(), data: v.to_vec() } + } + #[test] + fn dequant_parity_rule() { + for (qi, table) in + [(0u32, [-3, -2, -1, 0, 1, 2, 3]), (1, [-6, -5, -2, 0, 2, 5, 6]), (2, [-13, -10, -5, 0, 5, 10, 13]), (3, [-27, -20, -11, 0, 11, 20, 27])] + { + for (q, v) in (-3..=3).zip(table) { + assert_eq!(dequant(q, qi), v, "q={q} qi={qi}"); + } + } + } + #[test] + fn quantize_inverts_dequant() { + for qi in 0..6 { + for q in -50..=50 { + assert_eq!(crate::vendor::arw6_testenc::quantize(dequant(q, qi), qi), q, "q={q} qi={qi}"); + } + } + } + #[test] + fn dequant_does_not_overflow() { + assert_eq!(dequant(i32::MAX, 31), i32::MAX); + assert_eq!(dequant(i32::MIN, 40), -i32::MAX); + } + #[test] + fn band_rows_counts() { + assert_eq!(band_rows(1093, 0), (547, 546)); + assert_eq!(band_rows(1093, 1), (546, 547)); + assert_eq!(band_rows(1668, 0), (834, 834)); + assert_eq!(band_rows(5, 1), (2, 3)); + assert_eq!(band_rows(1, 1), (0, 1)); + } + #[test] + fn inverse_53_hand_vectors() { + // computed by hand from RDD 34 §6.5 with X[-1] := X[1], X[n] := X[n-2]; checked against the Phase 0 model + assert_eq!(inverse_53_1d_rows(&col(&[10, 20]), &col(&[3, -4]), 0).unwrap().data, vec![8, 17, 20, 16]); + assert_eq!(inverse_53_1d_rows(&col(&[10, 20]), &col(&[3, -4]), 1).unwrap().data, vec![13, 10, 12, 22]); + assert_eq!(inverse_53_1d_rows(&col(&[10, 20, 30]), &col(&[3, -4]), 0).unwrap().data, vec![8, 17, 20, 22, 32]); + assert_eq!(inverse_53_1d_rows(&col(&[3, -4]), &col(&[10, 20, 30]), 1).unwrap().data, vec![5, -5, 9, -17, 13]); + } + #[test] + fn inverse_53_rejects_mismatched_bands() { + assert!(inverse_53_1d_rows(&col(&[1, 2, 3]), &col(&[1]), 0).is_err()); + assert!(inverse_53_1d_rows(&col(&[1, 2]), &Plane::zeros(2, 2), 0).is_err()); + assert!(inverse_53_1d_cols(&col(&[1, 2]), &col(&[1, 2, 3]), 0).is_err()); + } + proptest::proptest! { + #[test] + fn forward_then_inverse_is_identity(w in 1usize..24, h in 1usize..40, p1 in 0u8..2, p2 in 0u8..2, p3 in 0u8..2, seed in proptest::num::u64::ANY) { + use crate::vendor::arw6_testenc::{forward3, forward_53_2d}; + use proptest::prop_assert_eq; + let mut s = seed | 1; + let mut next = || { s ^= s << 13; s ^= s >> 7; s ^= s << 17; (s % 8191) as i32 - 4095 }; + let x = Plane { width: w, height: h, data: (0..w * h).map(|_| next()).collect() }; + let (ll, lh, hl, hh) = forward_53_2d(&x, p1); + prop_assert_eq!(inverse_53_2d(&ll, &lh, &hl, &hh, p1).unwrap(), x.clone()); + if w >= 8 && h >= 8 { + prop_assert_eq!(reconstruct3(&forward3(&x, [p1, p2, p3]), [p1, p2, p3]).unwrap(), x); + } + } + } } diff --git a/crates/raw/src/vendor/arw6_testenc.rs b/crates/raw/src/vendor/arw6_testenc.rs new file mode 100644 index 00000000..1bb6015a --- /dev/null +++ b/crates/raw/src/vendor/arw6_testenc.rs @@ -0,0 +1,79 @@ +//! Test-only ARW6 synthetic encoder pieces: forward 5/3 transforms (exact inverse of `llvc::inverse_*`) and `quantize`. + +use crate::llvc::{Bands3, Plane, band_rows}; + +/// Exact inverse of `dequant` on representable values: `sign(v) * (|v| >> qi)`. +pub(crate) fn quantize(v: i32, qi: u32) -> i32 { + v.signum() * (v.abs() >> qi) +} + +fn at(v: &[i32], i: isize) -> i32 { + if v.is_empty() { 0 } else { v[i.clamp(0, v.len() as isize - 1) as usize] } +} + +/// Forward 1-D 5/3 with whole-sample symmetric extension (`plan/arw6/scratch/fwd.py::fwd1d`). +fn forward_1d(x: &[i32], phase: u8) -> (Vec, Vec) { + let n = x.len() as isize; + let p = isize::from(phase); + let xs = |i: isize| -> i32 { + let r = if i < 0 { + -i + } else if i >= n { + 2 * (n - 1) - i + } else { + i + }; + if (0..n).contains(&r) { x[r as usize] } else { 0 } + }; + let (nl, nh) = band_rows(x.len(), phase); + let h: Vec = (0..nh as isize) + .map(|k| { + let pos = 2 * k + 1 - p; + xs(pos) - ((xs(pos - 1) + xs(pos + 1)) >> 1) + }) + .collect(); + let l = (0..nl as isize).map(|j| xs(2 * j + p) + ((at(&h, j - 1 + p) + at(&h, j + p) + 2) >> 2)).collect(); + (l, h) +} + +fn split(x: &Plane, phase: u8, vertical: bool) -> (Plane, Plane) { + let (across, n) = if vertical { (x.width, x.height) } else { (x.height, x.width) }; + let (nl, nh) = band_rows(n, phase); + let dims = |m| if vertical { (across, m) } else { (m, across) }; + let (mut lo, mut hi) = (Plane::zeros(dims(nl).0, dims(nl).1), Plane::zeros(dims(nh).0, dims(nh).1)); + for i in 0..across { + let line: Vec = (0..n).map(|k| if vertical { x.data[k * x.width + i] } else { x.data[i * x.width + k] }).collect(); + let (l, h) = forward_1d(&line, phase); + for (p, v) in [(&mut lo, l), (&mut hi, h)] { + for (k, v) in v.into_iter().enumerate() { + let idx = if vertical { k * p.width + i } else { i * p.width + k }; + p.data[idx] = v; + } + } + } + (lo, hi) +} + +pub(crate) fn forward_53_1d_rows(x: &Plane, phase: u8) -> (Plane, Plane) { + split(x, phase, true) +} + +pub(crate) fn forward_53_1d_cols(x: &Plane, phase: u8) -> (Plane, Plane) { + split(x, phase, false) +} + +/// Horizontal first (phase 0), then vertical; returns `(ll, lh, hl, hh)`, the exact inverse of `inverse_53_2d`. +pub(crate) fn forward_53_2d(x: &Plane, vphase: u8) -> (Plane, Plane, Plane, Plane) { + let (lo, hi) = forward_53_1d_cols(x, 0); + let (ll, lh) = forward_53_1d_rows(&lo, vphase); + let (hl, hh) = forward_53_1d_rows(&hi, vphase); + (ll, lh, hl, hh) +} + +/// 3-level forward, the exact inverse of `reconstruct3` with the same `phases`. +pub(crate) fn forward3(x: &Plane, phases: [u8; 3]) -> Bands3 { + let (ll1, lh1, hl1, hh1) = forward_53_2d(x, phases[0]); + let (ll2, lh2, hl2, hh2) = forward_53_2d(&ll1, phases[1]); + let (ll3, lh3, hl3, hh3) = forward_53_2d(&ll2, phases[2]); + Bands3 { ll3, hl3, lh3, hh3, hl2, lh2, hh2, hl1, lh1, hh1 } +} diff --git a/crates/raw/src/vendor/mod.rs b/crates/raw/src/vendor/mod.rs index fcab4eab..25f52cb5 100644 --- a/crates/raw/src/vendor/mod.rs +++ b/crates/raw/src/vendor/mod.rs @@ -1,6 +1,8 @@ //! Vendor raw formats (TIFF-based) and helpers shared by them. pub mod arw; +#[cfg(test)] +pub(crate) mod arw6_testenc; mod arw_lens; pub mod cr2; pub mod cr3; From 868ac707ddc405259af7725f91e3c74226315a46 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Fri, 9 Oct 2026 23:31:30 +0200 Subject: [PATCH 04/21] LR-IMP-FORMATS: ARW6 lifting arithmetic cannot overflow on hostile coefficients --- crates/raw/src/llvc.rs | 50 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/raw/src/llvc.rs b/crates/raw/src/llvc.rs index d99acaa6..fee6f438 100644 --- a/crates/raw/src/llvc.rs +++ b/crates/raw/src/llvc.rs @@ -192,20 +192,29 @@ fn at(v: &[i32], i: isize) -> i32 { v.get(i.clamp(0, last) as usize).copied().unwrap_or(0) } +/// Saturating narrowing: hostile coefficients clamp instead of overflowing. +fn sat(v: i64) -> i32 { + v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32 +} + /// 1-D inverse 5/3 lifting, RDD 34 §6.5, with X[-1] := X[1], X[n] := X[n-2] (see `band_rows` for the sizes). fn inverse_1d(l: &[i32], h: &[i32], phase: u8) -> Result> { let (n, p) = (l.len() + h.len(), isize::from(phase)); if band_rows(n, phase) != (l.len(), h.len()) || phase > 1 { return Err(RawError::Corrupt("ARW6 wavelet: band sizes do not match".into())); } - let even: Vec = l.iter().enumerate().map(|(j, &lv)| lv - ((at(h, j as isize - 1 + p) + at(h, j as isize + p) + 2) >> 2)).collect(); + let even: Vec = l + .iter() + .enumerate() + .map(|(j, &lv)| sat(i64::from(lv) - ((i64::from(at(h, j as isize - 1 + p)) + i64::from(at(h, j as isize + p)) + 2) >> 2))) + .collect(); let mut x = vec![0; n]; let (lo, hi) = (usize::from(phase), 1 - usize::from(phase)); for (xv, &e) in x.iter_mut().skip(lo).step_by(2).zip(&even) { *xv = e; } for (k, (xv, &hv)) in x.iter_mut().skip(hi).step_by(2).zip(h).enumerate() { - *xv = hv + ((at(&even, k as isize - p) + at(&even, k as isize + 1 - p)) >> 1); + *xv = sat(i64::from(hv) + ((i64::from(at(&even, k as isize - p)) + i64::from(at(&even, k as isize + 1 - p))) >> 1)); } Ok(x) } @@ -389,6 +398,43 @@ mod tests { assert_eq!(dequant(i32::MIN, 40), -i32::MAX); } #[test] + fn extreme_coefficients_do_not_overflow() { + for v in [i32::MAX, i32::MIN] { + for (w, h) in [(7usize, 9usize), (16, 16), (9, 16)] { + let p = |w, h| Plane { width: w, height: h, data: vec![v; w * h] }; + for ph in 0..2u8 { + let (lh, lw) = (band_rows(h, ph), band_rows(w, 0)); + assert!(inverse_53_2d(&p(lw.0, lh.0), &p(lw.0, lh.1), &p(lw.1, lh.0), &p(lw.1, lh.1), ph).is_ok()); + } + let (w3, h3) = (w * 8, h * 8); + let mut sizes = vec![]; + let (mut cw, mut ch) = (w3, h3); + for ph in [0u8; 3] { + let (a, b) = (band_rows(cw, 0), band_rows(ch, ph)); + sizes.push((a, b)); + (cw, ch) = (a.0, b.0); + } + let q = |l: usize, xh: bool, yh: bool| { + let ((a, b), (c, d)) = sizes[l]; + p(if xh { b } else { a }, if yh { d } else { c }) + }; + let b = Bands3 { + ll3: q(2, false, false), + hl3: q(2, true, false), + lh3: q(2, false, true), + hh3: q(2, true, true), + hl2: q(1, true, false), + lh2: q(1, false, true), + hh2: q(1, true, true), + hl1: q(0, true, false), + lh1: q(0, false, true), + hh1: q(0, true, true), + }; + assert!(reconstruct3(&b, [0, 1, 0]).is_ok()); + } + } + } + #[test] fn band_rows_counts() { assert_eq!(band_rows(1093, 0), (547, 546)); assert_eq!(band_rows(1093, 1), (546, 547)); From f101a091422654810c88180838a2d63d2f909b86 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Fri, 9 Oct 2026 23:43:07 +0200 Subject: [PATCH 05/21] LR-IMP-FORMATS: ARW6 tile table, tile and stream headers; synthetic ARW6 encoder for tests --- crates/raw/src/vendor/arw6.rs | 331 +++++++++++++++++++++++++ crates/raw/src/vendor/arw6_testenc.rs | 334 ++++++++++++++++++++++++++ crates/raw/src/vendor/mod.rs | 1 + 3 files changed, 666 insertions(+) create mode 100644 crates/raw/src/vendor/arw6.rs diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs new file mode 100644 index 00000000..e7615c21 --- /dev/null +++ b/crates/raw/src/vendor/arw6.rs @@ -0,0 +1,331 @@ +//! Sony ARW6 ("Compressed RAW 2" / HQ, TIFF Compression 32766): container parsing. +//! +//! Clean-room. The layout comes from SMPTE RDD 34 (Picture_info in word 0) and from Phase 0 black-box +//! inspection of real ILCE-7RM6 files (tile table, group size words, stream headers and index entries), each rule +//! checked by re-serialising parsed tiles byte-for-byte; see `docs/superpowers/specs/2026-10-09-sony-arw6-decoder-design.md` +//! (*Container (Sony)*). No other raw decoder's source was consulted. + +// Consumed by the geometry and `decode` tasks that follow. +#![allow(dead_code)] + +use crate::{RawError, Result}; + +fn corrupt(why: &str) -> RawError { + RawError::Corrupt(format!("ARW6: {why}")) +} + +fn unsupported(why: &str) -> RawError { + RawError::Unsupported(format!("ARW6 {why}")) +} + +fn u16_be(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(2)?)?; + Some(usize::from(u16::from_be_bytes([*s.first()?, *s.get(1)?]))) +} + +fn u24_be(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(3)?)?; + Some(s.iter().fold(0usize, |a, &v| (a << 8) | usize::from(v))) +} + +fn u32_le(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(4)?)?; + Some(u32::from_le_bytes(s.try_into().ok()?) as usize) +} + +/// One tile of the strip: its bytes run from `offset` to the next tile's offset (the last: the strip end). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct TileEntry { + pub offset: usize, + pub x: usize, + pub y: usize, + pub width: usize, + pub height: usize, +} + +/// Most tiles a strip may hold (real files have 1 or 4). +const MAX_TILES: usize = 16; + +/// Parse the tile table at the start of the strip (file structure, spec *Container*): `u32` count, `u32` 0, then +/// 24-byte entries `u64` offset (relative to the strip), `u32` x, y, width, height, all little-endian. +pub(crate) fn parse_tile_table(strip: &[u8], width: usize, height: usize) -> Result> { + let count = u32_le(strip, 0).ok_or_else(|| corrupt("truncated tile table"))?; + if count == 0 || count > MAX_TILES { + return Err(unsupported("tile count outside 1..=16")); + } + let mut tiles: Vec = Vec::with_capacity(count); + let mut area = 0usize; + for i in 0..count { + let at = 8 + 24 * i; + let e = strip.get(at..at + 24).ok_or_else(|| corrupt("truncated tile table"))?; + let offset = e.get(..8).and_then(|b| <[u8; 8]>::try_from(b).ok()).map(u64::from_le_bytes).and_then(|o| usize::try_from(o).ok()); + let offset = offset.filter(|&o| o < strip.len()).ok_or_else(|| corrupt("tile offset outside the strip"))?; + if tiles.last().is_some_and(|p| offset <= p.offset) { + return Err(corrupt("tile offsets do not increase")); + } + let (x, y, w, h) = (u32_le(e, 8), u32_le(e, 12), u32_le(e, 16), u32_le(e, 20)); + let (Some(x), Some(y), Some(w), Some(h)) = (x, y, w, h) else { return Err(corrupt("truncated tile table")) }; + // Even geometry; the level-3 band width w / 16 must be whole (w/2 a multiple of 8). + if w == 0 || h == 0 || x % 2 != 0 || y % 2 != 0 || w % 2 != 0 || h % 2 != 0 || (w / 2) % 8 != 0 { + return Err(unsupported("tile geometry")); + } + let fits = x.checked_add(w).is_some_and(|r| r <= width) && y.checked_add(h).is_some_and(|b| b <= height); + if !fits { + return Err(corrupt("tile outside the image")); + } + let a = w.checked_mul(h).filter(|&a| a <= crate::MAX_SAMPLES).ok_or(RawError::Limit("ARW6 tile too large"))?; + area = area.checked_add(a).ok_or(RawError::Limit("ARW6 tiles too large"))?; + tiles.push(TileEntry { offset, x, y, width: w, height: h }); + } + for (i, a) in tiles.iter().enumerate() { + for b in tiles.iter().skip(i + 1) { + if a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height { + return Err(corrupt("tiles overlap")); + } + } + } + // In-image, disjoint tiles cover the image exactly when their areas sum to it. + if width.checked_mul(height) != Some(area) { + return Err(corrupt("tiles do not cover the image")); + } + Ok(tiles) +} + +/// One of a tile's 13 streams (positions in 16-byte words from the tile start). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct StreamRef { + pub group: u8, + pub comp: u8, + pub word: usize, + pub size_words: usize, + pub index_words: usize, + pub data_words: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct TileHeader { + pub hs: usize, + pub vs: usize, + pub ntu: usize, + /// File order: g0 c0..2, g1 c0..2, g2 c0..2, g3 c0..2, g4 c0. + pub streams: Vec, +} + +/// `n` bits at bit position `pos` (MSB-first) of a tile's word 0. +fn field(w: &[u8], pos: usize, n: usize) -> Option { + let mut v = 0u32; + for i in pos..pos.checked_add(n)? { + let byte = *w.get(i / 8)?; + v = (v << 1) | u32::from((byte >> (7 - i % 8)) & 1); + } + Some(v) +} + +/// Streams per group: g0..g3 one per colour component, g4 the green residual. +const GROUP_STREAMS: [usize; 5] = [3, 3, 3, 3, 1]; + +/// Parse word 0 (RDD 34 `Picture_info`; every real file has HS = tile width, VS = tile height / 2, BBD 16, NC 3, NW 3, +/// NP 1000000000b), the group size words 3..=7 and each stream's header word (spec *Container*, Phase 0). +pub(crate) fn parse_tile_header(tile: &[u8], tw: usize, th: usize) -> Result { + let w0 = tile.get(..16).ok_or_else(|| corrupt("tile shorter than its picture header"))?; + let f = |pos, n| field(w0, pos, n).map(|v| v as usize); + let (hs, vs, bbd, nc, nw, np) = (f(64, 16), f(80, 16), f(102, 6), f(112, 3), f(115, 3), f(118, 10)); + let (Some(hs), Some(vs), Some(bbd), Some(nc), Some(nw), Some(np)) = (hs, vs, bbd, nc, nw, np) else { + return Err(corrupt("picture header")); + }; + if hs != tw || vs * 2 != th || bbd != 16 || nc != 3 || nw != 3 || np != 0b10_0000_0000 { + return Err(unsupported(&format!("picture header variant (HS {hs}, VS {vs}, BBD {bbd}, NC {nc}, NW {nw}, NP {np:#b})"))); + } + let mut streams = Vec::with_capacity(13); + let mut word = 8usize; + for (group, &n) in GROUP_STREAMS.iter().enumerate() { + let table = tile.get((3 + group) * 16..(4 + group) * 16).ok_or_else(|| corrupt("truncated group table"))?; + if usize::from(table.first().copied().unwrap_or(0)) != n { + return Err(unsupported("group stream count")); + } + for comp in 0..n { + let size_words = u24_be(table, 1 + 3 * comp).ok_or_else(|| corrupt("group table"))?; + let end = word.checked_add(size_words).filter(|e| e.checked_mul(16).is_some_and(|b| b <= tile.len())); + let end = end.ok_or_else(|| corrupt("stream outside the tile"))?; + let hdr = tile.get(word * 16..word * 16 + 16).ok_or_else(|| corrupt("stream outside the tile"))?; + let (index_words, data_words) = + (u16_be(hdr, 0).ok_or_else(|| corrupt("stream header"))?, u24_be(hdr, 2).ok_or_else(|| corrupt("stream header"))?); + if index_words.checked_add(data_words).and_then(|s| s.checked_add(1)).is_none_or(|s| s > size_words) { + return Err(corrupt("stream header sizes exceed the stream")); + } + streams.push(StreamRef { group: group as u8, comp: comp as u8, word, size_words, index_words, data_words }); + word = end; + } + } + Ok(TileHeader { hs, vs, ntu: vs.div_ceil(16), streams }) +} + +/// One half-TU of a stream: `len` bytes at byte `start` of the tile, quantiser index per band +/// (g0/g4: the single nibble repeated). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Half { + pub start: usize, + pub len: usize, + pub qi: [u32; 3], +} + +fn nibbles(b: &[u8], from: usize, n: usize) -> Option { + (from..from + n).try_fold(0u32, |a, i| Some((a << 4) | u32::from((*b.get(i / 2)? >> (4 * (1 - i % 2))) & 15))) +} + +/// The `2 * ntu` halves of a stream. Index entry per TU (file structure): `A:16 X B:16 X` with A / B the byte +/// lengths of half 0 / 1 and X the QI nibble (g0, g4: 1 nibble) or three nibbles HL, LH, HH (g1..g3); the data area +/// holds each TU's A bytes then B bytes, consecutive TUs contiguous. +pub(crate) fn stream_halves(tile: &[u8], s: &StreamRef, ntu: usize) -> Result> { + let nx = if s.group == 0 || s.group == 4 { 1 } else { 3 }; + let esz = 4 + nx; // bytes: (16 + 4nx + 16 + 4nx) / 8 + let idx_start = s.word.checked_add(1).and_then(|w| w.checked_mul(16)).ok_or_else(|| corrupt("stream position"))?; + let idx_len = s.index_words.checked_mul(16).ok_or_else(|| corrupt("stream position"))?; + if ntu.checked_mul(esz).is_none_or(|n| n > idx_len) { + return Err(corrupt("index table too small for the tile's TUs")); + } + let data_start = idx_start.checked_add(idx_len).ok_or_else(|| corrupt("stream position"))?; + let index = tile.get(idx_start..data_start).ok_or_else(|| corrupt("index table outside the tile"))?; + let data_end = s.data_words.checked_mul(16).and_then(|d| d.checked_add(data_start)).ok_or_else(|| corrupt("stream position"))?; + if data_end > tile.len() { + return Err(corrupt("stream data outside the tile")); + } + let mut halves = Vec::with_capacity(2 * ntu); + let mut pos = data_start; + for k in 0..ntu { + let e = index.get(k * esz..(k + 1) * esz).ok_or_else(|| corrupt("index table"))?; + let bad = || corrupt("index entry"); + let (a, x1) = (nibbles(e, 0, 4).ok_or_else(bad)? as usize, nibbles(e, 4, nx).ok_or_else(bad)?); + let (b, x2) = (nibbles(e, 4 + nx, 4).ok_or_else(bad)? as usize, nibbles(e, 8 + nx, nx).ok_or_else(bad)?); + for (len, x) in [(a, x1), (b, x2)] { + let end = pos.checked_add(len).filter(|&e| e <= data_end).ok_or_else(|| corrupt("half outside its stream's data"))?; + let qi = if nx == 1 { [x; 3] } else { [(x >> 8) & 15, (x >> 4) & 15, x & 15] }; + halves.push(Half { start: pos, len, qi }); + pos = end; + } + } + Ok(halves) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::llvc::Plane; + use crate::vendor::arw6_testenc::*; + use crate::vendor::pef::Bits; + use lightcraft_tiff::Tiff; + use lightcraft_tiff::image::chunk_bytes; + use lightcraft_tiff::tags as t; + + fn planes(w2: usize, h2: usize, seed: u64) -> (Plane, Plane, Plane, Plane) { + let mut x = seed.max(1); + let mut next = |span: i32| -> i32 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x % (2 * span as u64 + 1)) as i32 - span + }; + let mut mk = |centre: i32, span: i32| Plane { width: w2, height: h2, data: (0..w2 * h2).map(|_| centre + next(span)).collect() }; + (mk(2048, 200), mk(0, 60), mk(0, 60), mk(0, 24)) + } + + fn one_tile(w: usize, h: usize, s: u8, qi: Qis) -> (Vec, TileSpec) { + let (m, c1, c2, res) = planes(w / 2, h / 2, 7); + let t = TileSpec { s, qi, m, c1, c2, res }; + (encode_tile(&t), t) + } + + /// The raw strip bytes of the compression-32766 IFD, as `arw.rs` locates them. + fn strip_of(file: &[u8]) -> &[u8] { + let tiff = Tiff::parse(file).unwrap(); + let raw = tiff.all_ifds().into_iter().find(|i| i.u16(t::COMPRESSION) == Some(32766)).unwrap(); + let info = raw.image().unwrap(); + let chunks = info.chunks(file.len() as u64); + chunk_bytes(file, &chunks[0]).unwrap() + } + + #[test] + fn tile_table_round_trips() { + let (tile, _) = one_tile(64, 48, 0, Qis::ZERO); + let file = arw6_file(&[(0, 0, 64, 48, tile.clone())], 64, 48); + let strip = strip_of(&file); + let t = parse_tile_table(strip, 64, 48).unwrap(); + assert_eq!(t.len(), 1); + assert_eq!((t[0].x, t[0].y, t[0].width, t[0].height, t[0].offset), (0, 0, 64, 48, 512)); + } + + #[test] + fn tile_table_rejects_bad_layouts() { + let (tile, _) = one_tile(64, 48, 0, Qis::ZERO); + let strip = strip_of(&arw6_file(&[(0, 0, 64, 48, tile.clone())], 64, 48)).to_vec(); + let mut zero = strip.clone(); + zero[0] = 0; + assert!(parse_tile_table(&zero, 64, 48).is_err()); + let mut far = strip.clone(); + far[8..16].copy_from_slice(&u64::MAX.to_le_bytes()); + assert!(parse_tile_table(&far, 64, 48).is_err()); + let mut odd = strip.clone(); + odd[20..24].copy_from_slice(&63u32.to_le_bytes()); // the first tile's y: odd, and no longer covering + assert!(parse_tile_table(&odd, 64, 48).is_err()); + assert!(parse_tile_table(&strip, 64, 64).is_err()); // does not cover the image + let two = arw6_file(&[(0, 0, 64, 48, tile.clone()), (0, 0, 64, 48, tile.clone())], 128, 48); + assert!(parse_tile_table(strip_of(&two), 128, 48).is_err()); // overlapping + assert!(parse_tile_table(&strip[..7], 64, 48).is_err()); // truncated table + } + + #[test] + fn tile_header_and_streams() { + let (tile, _) = one_tile(64, 48, 3, Qis::REAL); + let h = parse_tile_header(&tile, 64, 48).unwrap(); + assert_eq!((h.hs, h.vs, h.ntu, h.streams.len()), (64, 24, 2, 13)); + assert_eq!( + h.streams.iter().map(|s| (s.group, s.comp)).collect::>(), + [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (4, 0)] + ); + let g3 = stream_halves(&tile, &h.streams[9], h.ntu).unwrap(); + assert_eq!(g3.len(), 4); + assert_eq!(g3[0].qi, [1, 1, 2]); + let g4 = stream_halves(&tile, &h.streams[12], h.ntu).unwrap(); + assert_eq!(g4[1].qi, [2, 2, 2]); + assert!(g4[3].start + g4[3].len <= tile.len()); + let mut bad = tile.clone(); + bad[13] = 0xff; // corrupts word 0's BBD bits: any picture-header deviation is Unsupported + assert!(matches!(parse_tile_header(&bad, 64, 48), Err(RawError::Unsupported(_)))); + assert!(parse_tile_header(&tile, 64, 50).is_err()); // VS != th / 2 + } + + #[test] + fn every_stream_of_an_encoded_tile_parses() { + for s in [0u8, 3] { + let (tile, spec) = one_tile(64, 48, s, Qis::REAL); + assert_eq!(tile.len() % 4096, 0); + let h = parse_tile_header(&tile, 64, 48).unwrap(); + for st in &h.streams { + assert_eq!(stream_halves(&tile, st, h.ntu).unwrap().len(), 2 * h.ntu); + } + // the residual stream's halves decode to the clipped, quantised rows 8n-6+s ..= 8n+1+s + let g4 = stream_halves(&tile, &h.streams[12], h.ntu).unwrap(); + for (n, half) in g4.iter().enumerate() { + let bytes = &tile[half.start..half.start + half.len]; + let mut bits = Bits::new(bytes); + for r in (8 * n as i32 - 6 + s as i32..8 * n as i32 + 2 + s as i32).filter(|&r| (0..24).contains(&r)) { + let line = crate::llvc::vld_decode_line(&mut bits, bytes.len() * 8, 32).unwrap(); + let want: Vec = spec.res.row(r as usize).unwrap().iter().map(|&v| quantize(v, 2)).collect(); + assert_eq!(line, want, "s {s} half {n} row {r}"); + } + } + // a stream that claims more halves than its index holds is rejected + assert!(stream_halves(&tile, &h.streams[0], 1000).is_err()); + } + } + + #[test] + fn encoder_decodes_its_own_lines() { + let vals: Vec = (0..100).map(|i| (i * 37) % 23 - 11).collect(); + let mut w = BitWriter::default(); + vld_encode_line(&vals, 100, &mut w); + let bytes = w.finish(); + let mut b = Bits::new(&bytes); + assert_eq!(crate::llvc::vld_decode_line(&mut b, bytes.len() * 8, 100).unwrap(), vals); + } +} diff --git a/crates/raw/src/vendor/arw6_testenc.rs b/crates/raw/src/vendor/arw6_testenc.rs index 1bb6015a..f0f781c7 100644 --- a/crates/raw/src/vendor/arw6_testenc.rs +++ b/crates/raw/src/vendor/arw6_testenc.rs @@ -1,6 +1,8 @@ //! Test-only ARW6 synthetic encoder pieces: forward 5/3 transforms (exact inverse of `llvc::inverse_*`) and `quantize`. use crate::llvc::{Bands3, Plane, band_rows}; +use lightcraft_tiff::tags as t; +use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; /// Exact inverse of `dequant` on representable values: `sign(v) * (|v| >> qi)`. pub(crate) fn quantize(v: i32, qi: u32) -> i32 { @@ -77,3 +79,335 @@ pub(crate) fn forward3(x: &Plane, phases: [u8; 3]) -> Bands3 { let (ll3, lh3, hl3, hh3) = forward_53_2d(&ll2, phases[2]); Bands3 { ll3, hl3, lh3, hh3, hl2, lh2, hh2, hl1, lh1, hh1 } } + +// ---- RDD 34 line encoder (mirror of `llvc::vld_decode_line`; `plan/arw6/scratch/tilewrite.py::vld_encode`) ---- + +/// MSB-first bit sink; one `0`/`1` per element until `finish`. +#[derive(Default)] +pub(crate) struct BitWriter { + bits: Vec, +} + +impl BitWriter { + pub(crate) fn put(&mut self, bit: bool) { + self.bits.push(u8::from(bit)); + } + pub(crate) fn put_n(&mut self, v: u32, n: u32) { + for i in (0..n).rev() { + self.put((v >> i) & 1 == 1); + } + } + fn zeros(&mut self, n: u32) { + for _ in 0..n { + self.put(false); + } + } + /// Zero-padded to a whole byte. + pub(crate) fn finish(self) -> Vec { + self.bits.chunks(8).map(|c| c.iter().enumerate().fold(0u8, |a, (i, &b)| a | (b << (7 - i)))).collect() + } +} + +/// Encode one line (`width` coefficients, padded with zeros to whole sets of 4), with Sony's two deviations. +pub(crate) fn vld_encode_line(values: &[i32], width: usize, out: &mut BitWriter) { + let sets_n = width.div_ceil(4); + let mut vals = values[..width.min(values.len())].to_vec(); + vals.resize(4 * sets_n, 0); + let sets: Vec<&[i32]> = vals.chunks(4).collect(); + let dpts: Vec = sets.iter().map(|s| 32 - s.iter().map(|v| v.unsigned_abs()).max().unwrap_or(0).leading_zeros()).collect(); + let (mut dpt, mut dpts_state, mut cnt, mut zr) = (0u32, 0u8, sets_n, 0usize); + let mut prev: Option<&[i32]> = None; + let mut k = 0usize; + loop { + let dpt_v = cnt != 0; + cnt = cnt.saturating_sub(1); + zr = zr.saturating_sub(1); + if dpt_v { + let d = dpts[k]; + match dpts_state { + 0 if d == dpt => { + out.put(false); + if dpt == 0 { + dpts_state = 1; + } + } + 0 if d > dpt => { + out.put(true); + out.put(false); + out.zeros(d - dpt - 1); + out.put(true); + dpt = d; + } + 0 => { + out.put(true); + out.put(true); + if d >= 1 { + out.zeros(dpt - d - 1); + out.put(true); + dpt = d; + } else { + out.zeros(dpt - 1); + dpt = 0; + dpts_state = 1; + } + } + 1 if d > 0 => { + out.put(true); + out.zeros(d - 1); + out.put(true); + dpt = d; + dpts_state = 0; + } + 1 => { + let r = dpts[k..].iter().take_while(|&&x| x == 0).count(); + let lim = (cnt as u64 + 2).next_power_of_two().trailing_zeros(); + if k + r >= sets_n { + out.zeros(lim); // the rest of the line is zero + zr = cnt + 2; + } else { + let v = (r + 1) as u32; + let m = 31 - v.leading_zeros(); + assert!(m < lim); + out.zeros(m); + out.put(true); + out.put_n(v - (1 << m), m); + zr = r + 1; + } + dpts_state = 2; + } + _ if zr == 1 => { + out.zeros(d - 1); + out.put(true); + dpt = d; + dpts_state = 0; + } + _ => assert_eq!(d, 0), + } + } + if let Some(p) = prev { + for &v in p { + if v != 0 { + out.put(v < 0); + } + } + } + if k >= sets_n { + return; + } + if dpt_v { + for &v in sets[k] { + out.put_n(v.unsigned_abs(), dpt); + } + prev = Some(sets[k]); + } + k += 1; + } +} + +// ---- tile / file serialiser (`tilewrite.py::TileModel.serialize`, `arw6dump.py`) ---- + +/// Per-band quantiser indices: `l1`/`l2`/`l3` per component, bands in HL, LH, HH order. +#[derive(Clone)] +pub(crate) struct Qis { + pub l1: [[u32; 3]; 3], + pub l2: [[u32; 3]; 3], + pub l3: [[u32; 3]; 3], + pub res: u32, +} + +impl Qis { + pub(crate) const ZERO: Qis = Qis { l1: [[0; 3]; 3], l2: [[0; 3]; 3], l3: [[0; 3]; 3], res: 0 }; + /// The values seen in every real file (spec *Container*). + pub(crate) const REAL: Qis = Qis { l1: [[1, 1, 2], [2, 2, 3], [2, 2, 3]], l2: [[0, 0, 1]; 3], l3: [[0; 3]; 3], res: 2 }; +} + +/// One tile to encode: `s` is the anchor offset (spec *Frame geometry*), planes are W/2 x H/2. +pub(crate) struct TileSpec { + pub s: u8, + pub qi: Qis, + pub m: Plane, + pub c1: Plane, + pub c2: Plane, + pub res: Plane, +} + +/// Band row indices of the plane rows `rows` (low: `t % 2 == p`, row `(t-p)/2`; high: row `(t-(1-p))/2`). +fn split_rows(rows: &[usize], p: usize) -> (Vec, Vec) { + let (mut lo, mut hi) = (Vec::new(), Vec::new()); + for &t in rows { + if t % 2 == p { + lo.push((t - p) / 2); + } else { + hi.push((t - (1 - p)) / 2); + } + } + (lo, hi) +} + +fn quantised_rows(plane: &Plane, rows: &[usize], qi: u32) -> Vec> { + rows.iter().map(|&r| plane.row(r).unwrap().iter().map(|&v| quantize(v, qi)).collect()).collect() +} + +fn encode_lines(lines: &[Vec]) -> Vec { + let mut w = BitWriter::default(); + for l in lines { + vld_encode_line(l, l.len(), &mut w); + } + w.finish() +} + +fn pad16(v: &mut Vec) { + v.resize(v.len().next_multiple_of(16), 0); +} + +fn u24(v: usize) -> [u8; 3] { + [(v >> 16) as u8, (v >> 8) as u8, v as u8] +} + +/// One stream: header word, index table, data area. `halves[i]` = (bytes, qi nibbles of the TU). +fn build_stream(halves: &[(Vec, Vec)]) -> Vec { + let (mut idx, mut data) = (Vec::new(), Vec::new()); + for pair in halves.chunks(2) { + let mut nib: Vec = Vec::new(); + for (bytes, qi) in pair { + nib.extend((0..4).rev().map(|i| (bytes.len() as u32 >> (4 * i)) & 15)); + nib.extend(qi); + data.extend_from_slice(bytes); + } + idx.extend(nib.chunks(2).map(|c| (c[0] << 4 | c[1]) as u8)); + } + pad16(&mut idx); + pad16(&mut data); + let mut out = (idx.len() as u16 / 16).to_be_bytes().to_vec(); + out.extend(u24(data.len() / 16)); + out.extend([0x40, 0x40, 0x01, 0x12, 0x10, 0, 0, 0, 0, 0, 0]); + out.extend(idx); + out.extend(data); + out +} + +/// Encode one tile: forward 3-level 5/3 per component with the phases of `s`, quantise, pack every half in natural +/// clipped order (spec *Frame geometry*), then add index tables, stream headers and the tile header. +pub(crate) fn encode_tile(t: &TileSpec) -> Vec { + let (vs, s) = (t.m.height, i32::from(t.s)); + let ntu = vs.div_ceil(16); + let p1 = s % 2; + let p2 = ((2 + s - p1) / 2) % 2; + let k3 = ((6 + s) % 8 - p1) / 2; + let p3 = ((k3 - p2) / 2).rem_euclid(2); + let (up1, up2, up3) = (p1 as usize, p2 as usize, p3 as usize); + let comps = [&t.m, &t.c1, &t.c2]; + let bands: Vec<_> = comps.iter().map(|p| forward3(p, [p1 as u8, p2 as u8, p3 as u8])).collect(); + let qi = &t.qi; + // streams[group][comp] -> halves + let mut streams: Vec, Vec)>>> = + vec![vec![Vec::new(); 3], vec![Vec::new(); 3], vec![Vec::new(); 3], vec![Vec::new(); 3], vec![Vec::new()]]; + for n in 0..2 * ntu as i32 { + let rows: Vec = (8 * n - 6 + s..8 * n + 2 + s).filter(|&r| r >= 0 && (r as usize) < vs).map(|r| r as usize).collect(); + let (low1, high1) = split_rows(&rows, up1); + let (low2, high2) = split_rows(&low1, up2); + let (low3, high3) = split_rows(&low2, up3); + for (c, b) in bands.iter().enumerate() { + let cat = |parts: [Vec>; 3]| parts.into_iter().flatten().collect::>(); + let dpcm = { + let mut ll = quantised_rows(&b.ll3, &low3, 0); + for l in &mut ll { + let mut prev = 2048; + for v in l.iter_mut() { + (*v, prev) = (*v - prev, *v); + } + } + ll + }; + let sets: [(usize, Vec>, Vec); 4] = [ + (0, dpcm, vec![0]), + ( + 1, + cat([ + quantised_rows(&b.hl3, &low3, qi.l3[c][0]), + quantised_rows(&b.lh3, &high3, qi.l3[c][1]), + quantised_rows(&b.hh3, &high3, qi.l3[c][2]), + ]), + qi.l3[c].to_vec(), + ), + ( + 2, + cat([ + quantised_rows(&b.hl2, &low2, qi.l2[c][0]), + quantised_rows(&b.lh2, &high2, qi.l2[c][1]), + quantised_rows(&b.hh2, &high2, qi.l2[c][2]), + ]), + qi.l2[c].to_vec(), + ), + ( + 3, + cat([ + quantised_rows(&b.hl1, &low1, qi.l1[c][0]), + quantised_rows(&b.lh1, &high1, qi.l1[c][1]), + quantised_rows(&b.hh1, &high1, qi.l1[c][2]), + ]), + qi.l1[c].to_vec(), + ), + ]; + for (g, lines, q) in sets { + streams[g][c].push((encode_lines(&lines), q)); + } + } + streams[4][0].push((encode_lines(&quantised_rows(&t.res, &rows, qi.res)), vec![qi.res])); + } + let blobs: Vec>> = streams.iter().map(|g| g.iter().map(|s| build_stream(s)).collect()).collect(); + let mut head = vec![0u8; 8 * 16]; + head[..4].copy_from_slice(b"0000"); // bytes 4..8: tile index, 0 + let tw = 2 * t.m.width; + let w0: u64 = (tw as u64) << 48 | (vs as u64) << 32 | 16 << 20 | 3 << 13 | 3 << 10 | 0b10_0000_0000; + head[8..16].copy_from_slice(&w0.to_be_bytes()); + for (g, group) in blobs.iter().enumerate() { + let words: Vec = group.iter().map(|b| b.len() / 16).collect(); + head[(3 + g) * 16] = words.len() as u8; + for (i, w) in words.iter().enumerate() { + head[(3 + g) * 16 + 1 + 3 * i..][..3].copy_from_slice(&u24(*w)); + } + head[16 + 3 * g..][..3].copy_from_slice(&u24(words.iter().sum())); + } + let mut out = head; + out.extend(blobs.into_iter().flatten().flatten()); + out.resize(out.len().next_multiple_of(4096), 0); + out +} + +/// A little-endian ARW6 TIFF: IFD0 (Sony, ILCE-7RM6) + a SubIFD with the strip = tile table, zero padding to 512, +/// then the tiles `(x, y, w, h, bytes)` back to back. +pub(crate) fn arw6_file(tiles: &[(usize, usize, usize, usize, Vec)], width: usize, height: usize) -> Vec { + let mut strip = (tiles.len() as u32).to_le_bytes().to_vec(); + strip.extend([0; 4]); + let mut offset = 512u64; + for (x, y, w, h, bytes) in tiles { + strip.extend(offset.to_le_bytes()); + for v in [x, y, w, h] { + strip.extend((*v as u32).to_le_bytes()); + } + offset += bytes.len() as u64; + } + strip.resize(512, 0); + for (.., bytes) in tiles { + strip.extend_from_slice(bytes); + } + let mut raw = IfdBuilder::new(); + raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![width as u32])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![height as u32])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![14])); + raw.set(t::COMPRESSION, Value::Short(vec![32766])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA])); + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); + raw.set(0x7310, Value::Short(vec![512; 4])); + raw.set(t::WHITE_LEVEL, Value::Long(vec![15360])); + raw.set_image(ImageData::Strips { rows_per_strip: height as u32, strips: vec![strip] }); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("SONY".into())); + ifd0.set(t::MODEL, Value::Ascii("ILCE-7RM6".into())); + ifd0.set(t::ORIENTATION, Value::Short(vec![1])); + ifd0.add_sub_ifd(raw); + TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() +} diff --git a/crates/raw/src/vendor/mod.rs b/crates/raw/src/vendor/mod.rs index 25f52cb5..0e4ca414 100644 --- a/crates/raw/src/vendor/mod.rs +++ b/crates/raw/src/vendor/mod.rs @@ -1,6 +1,7 @@ //! Vendor raw formats (TIFF-based) and helpers shared by them. pub mod arw; +pub mod arw6; #[cfg(test)] pub(crate) mod arw6_testenc; mod arw_lens; From e45c4625b4c45cc62670f33cc444a2f1fe83b394 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Fri, 9 Oct 2026 23:46:44 +0200 Subject: [PATCH 06/21] LR-IMP-FORMATS: ARW6 container rejection tests and tile byte ranges --- crates/raw/src/vendor/arw6.rs | 84 +++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index e7615c21..ee1bb65a 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -91,6 +91,16 @@ pub(crate) fn parse_tile_table(strip: &[u8], width: usize, height: usize) -> Res Ok(tiles) } +/// Tile `i`'s bytes: from its offset to the next tile's offset (the last: the strip end). +pub(crate) fn tile_bytes<'a>(strip: &'a [u8], tiles: &[TileEntry], i: usize) -> Option<&'a [u8]> { + let start = tiles.get(i)?.offset; + let end = match tiles.get(i.checked_add(1)?) { + Some(next) => next.offset, + None => strip.len(), + }; + strip.get(start..end) +} + /// One of a tile's 13 streams (positions in 16-byte words from the tile start). #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct StreamRef { @@ -294,6 +304,80 @@ mod tests { assert!(parse_tile_header(&tile, 64, 50).is_err()); // VS != th / 2 } + fn put32(b: &mut [u8], at: usize, v: u32) { + b[at..at + 4].copy_from_slice(&v.to_le_bytes()); + } + + #[test] + fn tile_table_validation_cases() { + let (tile, _) = one_tile(64, 48, 0, Qis::ZERO); + let many = |n: usize| { + let tiles: Vec<_> = (0..n).map(|i| (64 * i, 0, 64, 48, tile.clone())).collect(); + strip_of(&arw6_file(&tiles, 64 * n, 48)).to_vec() + }; + let sixteen = many(16); + assert_eq!(parse_tile_table(&sixteen, 1024, 48).unwrap().len(), 16); + let mut seventeen = sixteen.clone(); + seventeen[0] = 17; + assert!(parse_tile_table(&seventeen, 1088, 48).is_err()); + + let two = strip_of(&arw6_file(&[(0, 0, 64, 48, tile.clone()), (64, 0, 64, 48, tile.clone())], 128, 48)).to_vec(); + assert_eq!(parse_tile_table(&two, 128, 48).unwrap().len(), 2); + let mut swapped = two.clone(); + let (a, b) = (two[8..16].to_vec(), two[32..40].to_vec()); + swapped[8..16].copy_from_slice(&b); + swapped[32..40].copy_from_slice(&a); + assert!(parse_tile_table(&swapped, 128, 48).is_err()); + let mut at_end = two.clone(); + at_end[32..40].copy_from_slice(&(two.len() as u64).to_le_bytes()); + assert!(parse_tile_table(&at_end, 128, 48).is_err()); + + let one = many(1); + let mut wide = one.clone(); + put32(&mut wide, 24, 72); // w / 2 = 36 is not a multiple of 8 + assert!(parse_tile_table(&wide, 72, 48).is_err()); + let mut huge = one.clone(); + put32(&mut huge, 24, 1 << 20); + put32(&mut huge, 28, 1 << 20); + assert!(matches!(parse_tile_table(&huge, 1 << 20, 1 << 20), Err(RawError::Limit(_)))); + } + + #[test] + fn tile_bytes_span_to_the_next_offset() { + let (tile, _) = one_tile(64, 48, 0, Qis::ZERO); + let file = arw6_file(&[(0, 0, 64, 48, tile.clone()), (64, 0, 64, 48, tile.clone())], 128, 48); + let strip = strip_of(&file); + let tiles = parse_tile_table(strip, 128, 48).unwrap(); + let (t0, t1) = (tile_bytes(strip, &tiles, 0).unwrap(), tile_bytes(strip, &tiles, 1).unwrap()); + assert_eq!(t0.len(), tiles[1].offset - tiles[0].offset); + assert_eq!(t0, &tile[..]); + assert_eq!(t1.as_ptr() as usize + t1.len(), strip.as_ptr() as usize + strip.len()); + assert!(tile_bytes(strip, &tiles, 2).is_none()); + } + + #[test] + fn tile_header_and_stream_validation_cases() { + let (tile, _) = one_tile(64, 48, 0, Qis::REAL); + let h = parse_tile_header(&tile, 64, 48).unwrap(); + let mut two_streams = tile.clone(); + two_streams[3 * 16] = 2; + assert!(parse_tile_header(&two_streams, 64, 48).is_err()); + let mut big = tile.clone(); + big[3 * 16 + 1..3 * 16 + 4].copy_from_slice(&[0xff; 3]); // stream 0 larger than the tile + assert!(parse_tile_header(&big, 64, 48).is_err()); + let mut idx = tile.clone(); + idx[8 * 16..8 * 16 + 2].copy_from_slice(&[0xff, 0xff]); // index words beyond the stream + assert!(parse_tile_header(&idx, 64, 48).is_err()); + + let s = &h.streams[9]; + let mut bad_half = tile.clone(); + let idx_start = (s.word + 1) * 16; + bad_half[idx_start..idx_start + 2].copy_from_slice(&[0xff, 0xff]); // A past the data area + assert!(stream_halves(&bad_half, s, h.ntu).is_err()); + let outside = StreamRef { index_words: 0xffff, ..s.clone() }; + assert!(stream_halves(&tile, &outside, h.ntu).is_err()); + } + #[test] fn every_stream_of_an_encoded_tile_parses() { for s in [0u8, 3] { From 6cba5749900a1d1599843e77e4efe1afd79acc44 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Fri, 9 Oct 2026 23:55:28 +0200 Subject: [PATCH 07/21] LR-IMP-FORMATS: ARW6 sensor-anchored frame geometry and tile reconstruction --- crates/raw/src/vendor/arw6.rs | 332 +++++++++++++++++++++++++- crates/raw/src/vendor/arw6_testenc.rs | 49 +++- 2 files changed, 371 insertions(+), 10 deletions(-) diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index ee1bb65a..49f0ebc3 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -8,7 +8,11 @@ // Consumed by the geometry and `decode` tasks that follow. #![allow(dead_code)] +use crate::llvc::{Bands3, Plane, band_rows, dequant, reconstruct3, vld_decode_line}; +use crate::vendor::pef::Bits; use crate::{RawError, Result}; +use rayon::prelude::*; +use std::ops::Range; fn corrupt(why: &str) -> RawError { RawError::Corrupt(format!("ARW6: {why}")) @@ -116,7 +120,6 @@ pub(crate) struct StreamRef { pub(crate) struct TileHeader { pub hs: usize, pub vs: usize, - pub ntu: usize, /// File order: g0 c0..2, g1 c0..2, g2 c0..2, g3 c0..2, g4 c0. pub streams: Vec, } @@ -167,7 +170,7 @@ pub(crate) fn parse_tile_header(tile: &[u8], tw: usize, th: usize) -> Result Result usize { + let halves = vs.saturating_sub(2usize.saturating_add(usize::from(s))).div_ceil(8).saturating_add(1); + halves.div_ceil(2) +} + +/// Lifting phases of levels 1..=3 for anchor offset `s` (`plan/arw6/scratch/assemble.py::geometry`): +/// FF (s = 0) gives [0, 1, 1], the APS-C crop (s = 3) [1, 0, 0]. +pub(crate) fn phases(s: u8) -> [u8; 3] { + let s = i32::from(s); + let p1 = s % 2; + let p2 = ((2 + s - p1) / 2) % 2; + let k3 = ((6 + s) % 8 - p1).div_euclid(2); + let p3 = (k3 - p2).div_euclid(2).rem_euclid(2); + [p1 as u8, p2 as u8, p3 as u8] +} + +/// Plane rows of half `n`: `8n - 6 + s .. 8n + 2 + s`, clipped to `0..rows` (empty when disjoint). +pub(crate) fn half_rows(n: usize, s: u8, rows: usize) -> Range { + let base = n.saturating_mul(8).saturating_add(usize::from(s)); + base.saturating_sub(6).min(rows)..base.saturating_add(2).min(rows) +} + +/// First half's frame rows `lines - 2`, read before the TU count is known from g4's first index entry alone +/// (index table at word `g4.word + 1`, entry 0's `A` = big-endian u16; its bytes start after the index table). +/// Residual lines are decoded while at least 8 bits remain and fewer than 8 lines were read (spec *Frame geometry*). +pub(crate) fn first_half_shift(tile: &[u8], g4: &StreamRef, width2: usize) -> Result { + let idx = g4.word.checked_add(1).and_then(|w| w.checked_mul(16)).ok_or_else(|| corrupt("stream position"))?; + let data = g4.index_words.checked_mul(16).and_then(|l| l.checked_add(idx)).ok_or_else(|| corrupt("stream position"))?; + let a = u16_be(tile, idx).ok_or_else(|| corrupt("index table outside the tile"))?; + let bytes = tile.get(data..data.checked_add(a).ok_or_else(|| corrupt("stream position"))?).ok_or_else(|| corrupt("half outside the tile"))?; + let total = bytes.len() * 8; + let mut bits = Bits::new(bytes); + let mut lines = 0usize; + while lines < 8 && total.saturating_sub(bits.consumed_bits()) >= 8 { + vld_decode_line(&mut bits, total, width2)?; + lines += 1; + } + match lines.checked_sub(2) { + Some(s @ 0..=5) => Ok(s as u8), + _ => Err(unsupported("first-half row count outside 2..=7")), + } +} + +/// Band rows of one half: plane rows `t` and the rows they land on at each level (`split`). +struct HalfRows { + t: Range, + l1: Vec, + h1: Vec, + l2: Vec, + h2: Vec, + l3: Vec, + h3: Vec, +} + +/// Rows with `t % 2 == p` go to the low band at `(t - p) / 2`, the others to the high band at `(t - (1 - p)) / 2`. +fn split(rows: &[usize], p: u8) -> (Vec, Vec) { + let p = usize::from(p); + let (mut lo, mut hi) = (Vec::new(), Vec::new()); + for &t in rows { + if t % 2 == p { + lo.push(t.saturating_sub(p) / 2); + } else { + hi.push(t.saturating_sub(1 - p) / 2); + } + } + (lo, hi) +} + +fn half_layout(n: usize, s: u8, vs: usize, ph: [u8; 3]) -> HalfRows { + let t = half_rows(n, s, vs); + let rows: Vec = t.clone().collect(); + let (l1, h1) = split(&rows, ph[0]); + let (l2, h2) = split(&l1, ph[1]); + let (l3, h3) = split(&l2, ph[2]); + HalfRows { t, l1, h1, l2, h2, l3, h3 } +} + +/// Lines a half holds in group `g`: g0 LL3 rows; g1 HL3 + LH3 + HH3; g2 HL2 + LH2 + HH2; g3 HL1 + LH1 + HH1; g4 residual. +fn line_count(g: u8, r: &HalfRows) -> usize { + match g { + 0 => r.l3.len(), + 1 => r.l3.len() + 2 * r.h3.len(), + 2 => r.l2.len() + 2 * r.h2.len(), + 3 => r.l1.len() + 2 * r.h1.len(), + _ => r.t.len(), + } +} + +/// Line width of group `g`: level-`l` bands are `(tw / 2) >> l` wide (g0, g1: level 3; g2: 2; g3: 1; g4: the plane). +fn line_width(g: u8, w2: usize) -> usize { + match g { + 0 | 1 => w2 >> 3, + 2 => w2 >> 2, + 3 => w2 >> 1, + _ => w2, + } +} + +/// A half with its decoded (still quantised) lines. +type HalfLines = (Half, Vec>); + +/// Index the stream's halves and VLD-decode exactly the lines each holds; a line running past its half is `Corrupt`. +fn decode_stream(tile: &[u8], st: &StreamRef, ntu: usize, w2: usize, layouts: &[HalfRows]) -> Result> { + let halves = stream_halves(tile, st, ntu)?; + let width = line_width(st.group, w2); + halves + .into_iter() + .zip(layouts) + .map(|(half, rows)| { + let end = half.start.checked_add(half.len).ok_or_else(|| corrupt("half position"))?; + let bytes = tile.get(half.start..end).ok_or_else(|| corrupt("half outside the tile"))?; + let total = bytes.len() * 8; + let mut bits = Bits::new(bytes); + let mut lines = Vec::with_capacity(line_count(st.group, rows)); + for _ in 0..line_count(st.group, rows) { + lines.push(vld_decode_line(&mut bits, total, width)?); + if bits.consumed_bits() > total { + return Err(corrupt("line runs past its half")); + } + } + Ok((half, lines)) // bytes beyond the last line are ignored + }) + .collect() +} + +/// Dequantise `line` into band row `row`. +fn put(plane: &mut Plane, row: usize, line: &[i32], mut f: impl FnMut(i32) -> i32) -> Result<()> { + let start = row.checked_mul(plane.width).ok_or_else(|| corrupt("band row"))?; + let dst = plane.data.get_mut(start..start.saturating_add(plane.width)).ok_or_else(|| corrupt("band row outside its band"))?; + for (d, &v) in dst.iter_mut().zip(line) { + *d = f(v); + } + Ok(()) +} + +/// Lay a half's lines into (band, rows, QI) in order: the natural clipped assignment of spec *Frame geometry*. +fn fill(set: [(&mut Plane, &[usize], u32); 3], lines: &[Vec]) -> Result<()> { + let mut it = lines.iter(); + for (plane, rows, qi) in set { + for &r in rows { + put(plane, r, it.next().ok_or_else(|| corrupt("half holds fewer lines than rows"))?, |q| dequant(q, qi))?; + } + } + Ok(()) +} + +/// One colour component: its ten bands from streams g0..g3 (component `c`), then the 3-level inverse. +fn component(c: usize, streams: &[Vec], layouts: &[HalfRows], vs: usize, w2: usize, ph: [u8; 3]) -> Result { + let (n1l, n1h) = band_rows(vs, ph[0]); + let (n2l, n2h) = band_rows(n1l, ph[1]); + let (n3l, n3h) = band_rows(n2l, ph[2]); + let (w1, w2b, w3) = (w2 >> 1, w2 >> 2, w2 >> 3); + let z = Plane::zeros; + let mut b = Bands3 { + ll3: z(w3, n3l), + hl3: z(w3, n3l), + lh3: z(w3, n3h), + hh3: z(w3, n3h), + hl2: z(w2b, n2l), + lh2: z(w2b, n2h), + hh2: z(w2b, n2h), + hl1: z(w1, n1l), + lh1: z(w1, n1h), + hh1: z(w1, n1h), + }; + let grp = |g: usize, n: usize| streams.get(3 * g + c).and_then(|s| s.get(n)).ok_or_else(|| corrupt("missing half")); + for (n, r) in layouts.iter().enumerate() { + let (h0, l0) = grp(0, n)?; + // LL3: the nibble must be 0 (Phase 0: never seen otherwise); lines are DPCM from 2048 (spec *Container*). + if h0.qi[0] != 0 { + return Err(unsupported("LL3 quantiser index")); + } + for (&row, line) in r.l3.iter().zip(l0) { + let mut acc = 2048i32; + put(&mut b.ll3, row, line, |d| { + acc = acc.saturating_add(d); + acc + })?; + } + let (h1, l1) = grp(1, n)?; + fill([(&mut b.hl3, &r.l3, h1.qi[0]), (&mut b.lh3, &r.h3, h1.qi[1]), (&mut b.hh3, &r.h3, h1.qi[2])], l1)?; + let (h2, l2) = grp(2, n)?; + fill([(&mut b.hl2, &r.l2, h2.qi[0]), (&mut b.lh2, &r.h2, h2.qi[1]), (&mut b.hh2, &r.h2, h2.qi[2])], l2)?; + let (h3, l3) = grp(3, n)?; + fill([(&mut b.hl1, &r.l1, h3.qi[0]), (&mut b.lh1, &r.h1, h3.qi[1]), (&mut b.hh1, &r.h1, h3.qi[2])], l3)?; + } + reconstruct3(&b, ph) +} + +/// A decoded tile: the three wavelet planes (green mean, two chroma) and the green residual, each `tw/2 x th/2`. +pub(crate) struct TilePlanes { + pub m: Plane, + pub c1: Plane, + pub c2: Plane, + pub res: Plane, +} + +/// Decode a tile to its planes: header, `s` from g4's first half, TU count, all 13 streams (in parallel), band +/// assembly and the 3-level inverse per component (in parallel). +pub(crate) fn decode_tile_planes(tile: &[u8], tw: usize, th: usize) -> Result { + let h = parse_tile_header(tile, tw, th)?; + let (w2, vs) = (tw / 2, h.vs); + if vs == 0 || !tw.is_multiple_of(2) || !w2.is_multiple_of(8) || w2.checked_mul(vs).is_none_or(|a| a > crate::MAX_SAMPLES) { + return Err(unsupported("tile geometry")); + } + let g4 = h.streams.get(12).ok_or_else(|| corrupt("missing residual stream"))?; + let s = first_half_shift(tile, g4, w2)?; + let (ntu, ph) = (tu_count(vs, s), phases(s)); + let layouts: Vec = (0..2 * ntu).map(|n| half_layout(n, s, vs, ph)).collect(); + let streams = h.streams.par_iter().map(|st| decode_stream(tile, st, ntu, w2, &layouts)).collect::>>()?; + let comps = (0..3).into_par_iter().map(|c| component(c, &streams, &layouts, vs, w2, ph)).collect::>>()?; + // Residual: g4's lines are the half's plane rows, dequantised with the half's nibble. + let mut res = Plane::zeros(w2, vs); + for ((half, lines), r) in streams.get(12).ok_or_else(|| corrupt("missing residual stream"))?.iter().zip(&layouts) { + for (row, line) in r.t.clone().zip(lines) { + put(&mut res, row, line, |q| dequant(q, half.qi[0]))?; + } + } + let mut it = comps.into_iter(); + let (Some(m), Some(c1), Some(c2)) = (it.next(), it.next(), it.next()) else { return Err(corrupt("missing component")) }; + Ok(TilePlanes { m, c1, c2, res }) +} + #[cfg(test)] mod tests { use super::*; @@ -287,15 +517,17 @@ mod tests { fn tile_header_and_streams() { let (tile, _) = one_tile(64, 48, 3, Qis::REAL); let h = parse_tile_header(&tile, 64, 48).unwrap(); - assert_eq!((h.hs, h.vs, h.ntu, h.streams.len()), (64, 24, 2, 13)); + assert_eq!((h.hs, h.vs, h.streams.len()), (64, 24, 13)); + let ntu = tu_count(24, 3); + assert_eq!(ntu, 2); assert_eq!( h.streams.iter().map(|s| (s.group, s.comp)).collect::>(), [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (4, 0)] ); - let g3 = stream_halves(&tile, &h.streams[9], h.ntu).unwrap(); + let g3 = stream_halves(&tile, &h.streams[9], ntu).unwrap(); assert_eq!(g3.len(), 4); assert_eq!(g3[0].qi, [1, 1, 2]); - let g4 = stream_halves(&tile, &h.streams[12], h.ntu).unwrap(); + let g4 = stream_halves(&tile, &h.streams[12], ntu).unwrap(); assert_eq!(g4[1].qi, [2, 2, 2]); assert!(g4[3].start + g4[3].len <= tile.len()); let mut bad = tile.clone(); @@ -373,9 +605,9 @@ mod tests { let mut bad_half = tile.clone(); let idx_start = (s.word + 1) * 16; bad_half[idx_start..idx_start + 2].copy_from_slice(&[0xff, 0xff]); // A past the data area - assert!(stream_halves(&bad_half, s, h.ntu).is_err()); + assert!(stream_halves(&bad_half, s, tu_count(24, 0)).is_err()); let outside = StreamRef { index_words: 0xffff, ..s.clone() }; - assert!(stream_halves(&tile, &outside, h.ntu).is_err()); + assert!(stream_halves(&tile, &outside, tu_count(24, 0)).is_err()); } #[test] @@ -384,11 +616,12 @@ mod tests { let (tile, spec) = one_tile(64, 48, s, Qis::REAL); assert_eq!(tile.len() % 4096, 0); let h = parse_tile_header(&tile, 64, 48).unwrap(); + let ntu = tu_count(24, s); for st in &h.streams { - assert_eq!(stream_halves(&tile, st, h.ntu).unwrap().len(), 2 * h.ntu); + assert_eq!(stream_halves(&tile, st, ntu).unwrap().len(), 2 * ntu); } // the residual stream's halves decode to the clipped, quantised rows 8n-6+s ..= 8n+1+s - let g4 = stream_halves(&tile, &h.streams[12], h.ntu).unwrap(); + let g4 = stream_halves(&tile, &h.streams[12], ntu).unwrap(); for (n, half) in g4.iter().enumerate() { let bytes = &tile[half.start..half.start + half.len]; let mut bits = Bits::new(bytes); @@ -412,4 +645,85 @@ mod tests { let mut b = Bits::new(&bytes); assert_eq!(crate::llvc::vld_decode_line(&mut b, bytes.len() * 8, 100).unwrap(), vals); } + + #[test] + fn phases_and_half_rows_match_the_spec() { + assert_eq!(phases(0), [0, 1, 1]); + assert_eq!(phases(3), [1, 0, 0]); + assert_eq!(half_rows(0, 0, 1668), 0..2); + assert_eq!(half_rows(209, 0, 1668), 1666..1668); + assert_eq!(half_rows(1, 0, 1668), 2..10); + assert_eq!(half_rows(0, 3, 2186), 0..5); + assert_eq!(half_rows(273, 3, 2186), 2181..2186); + assert_eq!(half_rows(300, 3, 2186), 2186..2186); + } + + #[test] + fn tu_count_covers_every_row() { + assert_eq!((tu_count(1668, 0), tu_count(2186, 3), tu_count(24, 3), tu_count(48, 0)), (105, 137, 2, 4)); + for s in 0u8..=5 { + for vs in 1usize..200 { + let last = half_rows(2 * tu_count(vs, s) - 1, s, vs); + assert!(last.end == vs || (2 * tu_count(vs, s) - 1) * 8 + usize::from(s) + 2 >= vs, "s {s} vs {vs}"); + assert_eq!((0..2 * tu_count(vs, s)).map(|n| half_rows(n, s, vs).len()).sum::(), vs, "s {s} vs {vs}"); + } + } + } + + #[test] + fn first_half_shift_is_read_from_the_stream() { + for s in [0u8, 3, 5] { + let (tile, _) = one_tile(64, 48, s, Qis::REAL); + let h = parse_tile_header(&tile, 64, 48).unwrap(); + assert_eq!(first_half_shift(&tile, &h.streams[12], 32).unwrap(), s); + } + } + + #[test] + fn round_trip_every_shift() { + for s in 0u8..=5 { + for (w, h) in [(64usize, 48usize), (80, 96), (64, 36)] { + let (tile, spec) = one_tile(w, h, s, Qis::ZERO); // QI 0: lossless, planes must come back exactly + let p = decode_tile_planes(&tile, w, h).unwrap_or_else(|e| panic!("s={s} {w}x{h}: {e}")); + assert_eq!(p.m, spec.m, "s={s} {w}x{h} m"); + assert_eq!(p.c1, spec.c1); + assert_eq!(p.c2, spec.c2); + assert_eq!(p.res, spec.res); + } + } + } + + #[test] + fn round_trip_with_real_quantisers() { + // bands drawn as quantised integers q, planes = reconstruct3(dequant(q)); the encoder must reproduce them bit for bit + for s in [0u8, 3] { + let (tile, spec) = one_tile_quantised(96, 64, s, Qis::REAL); + let p = decode_tile_planes(&tile, 96, 64).unwrap(); + assert_eq!(p.m, spec.m); + assert_eq!(p.c1, spec.c1); + assert_eq!(p.c2, spec.c2); + assert_eq!(p.res, spec.res); + } + } + + #[test] + fn half_too_short_is_corrupt() { + let (mut tile, _) = one_tile(64, 48, 0, Qis::ZERO); + let h = parse_tile_header(&tile, 64, 48).unwrap(); + let w = h.streams[9].word * 16 + 16; // first index entry of g3 c0: shrink A by 1 byte + let a = u16::from_be_bytes([tile[w], tile[w + 1]]) - 1; + tile[w..w + 2].copy_from_slice(&a.to_be_bytes()); + assert!(matches!(decode_tile_planes(&tile, 64, 48), Err(RawError::Corrupt(_)))); + } + + proptest::proptest! { + #[test] + fn mutated_tiles_never_panic(flips in proptest::collection::vec((proptest::num::usize::ANY, proptest::num::u8::ANY), 1..12), cut in proptest::num::usize::ANY) { + let (mut tile, _) = one_tile(64, 48, 3, Qis::REAL); + for (i, b) in flips { let i = i % tile.len(); tile[i] ^= b; } + let n = cut % (tile.len() + 1); + let _ = decode_tile_planes(&tile[..n], 64, 48); + let _ = decode_tile_planes(&tile, 64, 48); + } + } } diff --git a/crates/raw/src/vendor/arw6_testenc.rs b/crates/raw/src/vendor/arw6_testenc.rs index f0f781c7..ba7e30af 100644 --- a/crates/raw/src/vendor/arw6_testenc.rs +++ b/crates/raw/src/vendor/arw6_testenc.rs @@ -290,7 +290,7 @@ fn build_stream(halves: &[(Vec, Vec)]) -> Vec { /// clipped order (spec *Frame geometry*), then add index tables, stream headers and the tile header. pub(crate) fn encode_tile(t: &TileSpec) -> Vec { let (vs, s) = (t.m.height, i32::from(t.s)); - let ntu = vs.div_ceil(16); + let ntu = crate::vendor::arw6::tu_count(vs, t.s); let p1 = s % 2; let p2 = ((2 + s - p1) / 2) % 2; let k3 = ((6 + s) % 8 - p1) / 2; @@ -411,3 +411,50 @@ pub(crate) fn arw6_file(tiles: &[(usize, usize, usize, usize, Vec)], width: ifd0.add_sub_ifd(raw); TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() } + +/// A tile whose bands are random quantised integers `q` (level 1 wider), `v = dequant(q, qi)`, planes by +/// `reconstruct3` (so `quantize` in the encoder is exact on them); LL3 is random around 2048, the residual +/// `dequant(q, qi.res)`. +pub(crate) fn one_tile_quantised(w: usize, h: usize, s: u8, qi: Qis) -> (Vec, TileSpec) { + use crate::llvc::{dequant, reconstruct3}; + let (w2, vs) = (w / 2, h / 2); + let ph = crate::vendor::arw6::phases(s); + let mut x = 0x9e37_79b9_7f4a_7c15u64; + let mut rnd = |span: i32, centre: i32, q: u32| -> i32 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + let v = (x % (2 * span as u64 + 1)) as i32 - span; + if centre == 0 { dequant(v, q) } else { centre + v } + }; + let mut plane = |wd: usize, ht: usize, span: i32, centre: i32, q: u32| Plane { + width: wd, + height: ht, + data: (0..wd * ht).map(|_| rnd(span, centre, q)).collect(), + }; + let mut comps = Vec::new(); + for c in 0..3 { + let (n1l, n1h) = band_rows(vs, ph[0]); + let (n2l, n2h) = band_rows(n1l, ph[1]); + let (n3l, n3h) = band_rows(n2l, ph[2]); + let (w1, w2b, w3) = (w2 / 2, w2 / 4, w2 / 8); + let (a, b, d) = (qi.l1[c], qi.l2[c], qi.l3[c]); + let bands = Bands3 { + ll3: plane(w3, n3l, 60, 2048, 0), + hl3: plane(w3, n3l, 7, 0, d[0]), + lh3: plane(w3, n3h, 7, 0, d[1]), + hh3: plane(w3, n3h, 7, 0, d[2]), + hl2: plane(w2b, n2l, 7, 0, b[0]), + lh2: plane(w2b, n2h, 7, 0, b[1]), + hh2: plane(w2b, n2h, 7, 0, b[2]), + hl1: plane(w1, n1l, 15, 0, a[0]), + lh1: plane(w1, n1h, 15, 0, a[1]), + hh1: plane(w1, n1h, 15, 0, a[2]), + }; + comps.push(reconstruct3(&bands, ph).unwrap()); + } + let res = plane(w2, vs, 7, 0, qi.res); + let (m, c1, c2) = (comps.remove(0), comps.remove(0), comps.remove(0)); + let t = TileSpec { s, qi, m, c1, c2, res }; + (encode_tile(&t), t) +} From 15397a712e2ecb69e6fc708b4b46b00c75f07a04 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 00:23:24 +0200 Subject: [PATCH 08/21] LR-IMP-FORMATS: ARW6 colour reconstruction, companding table and ARW dispatch --- crates/raw/src/llvc.rs | 3 - crates/raw/src/vendor/arw.rs | 12 ++ crates/raw/src/vendor/arw6.rs | 199 +++++++++++++++++++++++++++- crates/raw/src/vendor/arw6_curve.rs | 176 ++++++++++++++++++++++++ crates/raw/src/vendor/mod.rs | 1 + crates/raw/tests/vendor_robust.rs | 3 +- 6 files changed, 384 insertions(+), 10 deletions(-) create mode 100644 crates/raw/src/vendor/arw6_curve.rs diff --git a/crates/raw/src/llvc.rs b/crates/raw/src/llvc.rs index fee6f438..ef525891 100644 --- a/crates/raw/src/llvc.rs +++ b/crates/raw/src/llvc.rs @@ -3,9 +3,6 @@ //! Clean-room: written from SMPTE RDD 34:2015 §6.3 (Figures 6.5-6.8) and checked against its worked //! example (Figure 6.9) and Phase 0 oracle vectors. No other raw decoder's source was consulted. -// Consumed by the dequantiser/wavelet/ARW6 container tasks that follow. -#![allow(dead_code)] - use crate::vendor::pef::Bits; use crate::{RawError, Result}; diff --git a/crates/raw/src/vendor/arw.rs b/crates/raw/src/vendor/arw.rs index d80c67f8..f7dc1831 100644 --- a/crates/raw/src/vendor/arw.rs +++ b/crates/raw/src/vendor/arw.rs @@ -36,10 +36,13 @@ //! bytes): plain 12-bit samples, two per three bytes, least-significant-bit first ([`unpack_row12`]); linear, black 128 //! (512 on the 14-bit scale), CFA from the file's own pattern tag, crop centred on the frame (see [`default_crop`]). //! +//! ARW6 (Compressed RAW 2, compression 32766): `arw6.rs`, output in 2 × 14-bit units. +//! //! Also: uncompressed 16-bit ARW, and lossless-compressed ARW (Compression 7, ILCE-7M4 and later): LJ92 tiles whose //! frames hold one 2×2 CFA cell per four-component sample ([`read_quad_tiles`]). Other lossless-JPEG layouts go //! through the generic TIFF path. +use super::arw6; use crate::tiffraw::{Packing, check_image, read_image_in}; use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg}; use lightcraft_geom::Orientation; @@ -609,6 +612,11 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { (RawData::U16(Vec::new()), bits) } }, + 32766 if chunks.len() == 1 => { + let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("raw strip outside file".into()))?; + (RawData::U16(arw6::decode(src, w, h, mode)?), 16) + } + 32766 => return Err(RawError::Unsupported("ARW6 with more than one strip".into())), 1 => { let word16 = strip_len >= (w * h * 2) as u64; let packing = if word16 { Packing::Word16 } else { Packing::Msb }; @@ -651,6 +659,10 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { } else { raw.f64(t::WHITE_LEVEL).map(|v| v as f32).filter(|v| *v > 0.0).unwrap_or_else(|| super::white_from_data(samples, scale_bits)) }; + // ARW6 samples are in 2 x 14-bit units, so the file's 14-bit levels double + let unit = if info.compression == 32766 { 2.0 } else { 1.0 }; + let black = BlackLevel { values: black.values.iter().map(|v| v * unit).collect(), ..black }; + let white = white * unit; let model = ifd0.string(t::MODEL).unwrap_or_default(); let mn = tiff .exif() diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index 49f0ebc3..4d9cf165 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -5,10 +5,8 @@ //! checked by re-serialising parsed tiles byte-for-byte; see `docs/superpowers/specs/2026-10-09-sony-arw6-decoder-design.md` //! (*Container (Sony)*). No other raw decoder's source was consulted. -// Consumed by the geometry and `decode` tasks that follow. -#![allow(dead_code)] - use crate::llvc::{Bands3, Plane, band_rows, dequant, reconstruct3, vld_decode_line}; +use crate::vendor::arw6_curve::{ARW6_CURVE, CURVE_KNEE}; use crate::vendor::pef::Bits; use crate::{RawError, Result}; use rayon::prelude::*; @@ -433,8 +431,10 @@ pub(crate) fn decode_tile_planes(tile: &[u8], tw: usize, th: usize) -> Result = (0..2 * ntu).map(|n| half_layout(n, s, vs, ph)).collect(); - let streams = h.streams.par_iter().map(|st| decode_stream(tile, st, ntu, w2, &layouts)).collect::>>()?; - let comps = (0..3).into_par_iter().map(|c| component(c, &streams, &layouts, vs, w2, ph)).collect::>>()?; + let streams = + h.streams.par_iter().map(|st| decode_stream(tile, st, ntu, w2, &layouts)).collect::>().into_iter().collect::>>()?; + let comps = + (0..3).into_par_iter().map(|c| component(c, &streams, &layouts, vs, w2, ph)).collect::>().into_iter().collect::>>()?; // Residual: g4's lines are the half's plane rows, dequantised with the half's nibble. let mut res = Plane::zeros(w2, vs); for ((half, lines), r) in streams.get(12).ok_or_else(|| corrupt("missing residual stream"))?.iter().zip(&layouts) { @@ -447,10 +447,99 @@ pub(crate) fn decode_tile_planes(tile: &[u8], tw: usize, th: usize) -> Result u16 { + let c = code12.clamp(0, 4095) as usize; + match c.checked_sub(CURVE_KNEE) { + None => c as u16, + Some(i) => ARW6_CURVE.get(i).copied().unwrap_or(39002), + } +} + +/// Colour reconstruction (spec *Colour reconstruction*, checked against Phase 0 oracle output): the planes give a +/// `(2 W2) x (2 H2)` mosaic with R at (0,0), G1 (0,1), G2 (1,0), B (1,1) of every 2x2 cell, each value passed through +/// [`curve`]. G1 comes from the green mean minus a residual average, G2 is predicted from the (unclipped) G1 plus the +/// residual, and R/B are chroma plus the mean of the greens clipped to 12 bits. +pub(crate) fn colour(p: &TilePlanes) -> Result> { + let (w2, h2) = (p.m.width, p.m.height); + let len = w2.checked_mul(h2).ok_or_else(|| corrupt("tile size"))?; + if [&p.c1, &p.c2, &p.res].iter().any(|q| q.width != w2 || q.height != h2 || q.data.len() != len) || p.m.data.len() != len { + return Err(corrupt("plane size mismatch")); + } + let mw = w2.checked_mul(2).ok_or_else(|| corrupt("tile size"))?; + let total = len.checked_mul(4).ok_or_else(|| corrupt("tile size"))?; + let at = |q: &Plane, j: usize, x: usize| -> i64 { q.data.get(j * w2 + x).copied().unwrap_or(0) as i64 }; + let mut g1 = vec![0i64; len]; + for j in 0..h2 { + let jp = j.saturating_sub(1); + for x in 0..w2 { + let xn = (x + 1).min(w2 - 1); + let r = at(&p.res, jp, x) + at(&p.res, jp, xn) + at(&p.res, j, x) + at(&p.res, j, xn); + if let Some(g) = g1.get_mut(j * w2 + x) { + *g = at(&p.m, j, x) - ((r + 4) >> 3); + } + } + } + let g = |j: usize, x: usize| g1.get(j * w2 + x).copied().unwrap_or(0); + let mut out = vec![0u16; total]; + for j in 0..h2 { + let jn = (j + 1).min(h2 - 1); + for x in 0..w2 { + let xp = x.saturating_sub(1); + let g2 = ((g(j, xp) + g(j, x) + g(jn, xp) + g(jn, x)) >> 2) + at(&p.res, j, x); + let mean = (g(j, x).min(4095) + g2.min(4095)) >> 1; + let r = 2 * at(&p.c1, j, x) + mean; + let b = 2 * at(&p.c2, j, x) + mean; + let cells = [(0, r), (1, g(j, x)), (mw, g2), (mw + 1, b)]; + for (off, v) in cells { + if let Some(o) = out.get_mut(2 * j * mw + 2 * x + off) { + *o = curve(v.clamp(0, 4095) as i32); + } + } + } + } + Ok(out) +} + +/// One tile to its `tw x th` mosaic in output units. +pub(crate) fn decode_tile(tile: &[u8], tw: usize, th: usize) -> Result> { + colour(&decode_tile_planes(tile, tw, th)?) +} + +/// Decode a whole ARW6 strip: [`Mode::Header`](crate::Mode) validates the tile table, tile headers and stream +/// tables and returns no samples; `Full` decodes the tiles in parallel into a `width x height` mosaic. +pub(crate) fn decode(strip: &[u8], width: usize, height: usize, mode: crate::Mode) -> Result> { + let tiles = parse_tile_table(strip, width, height)?; + let bytes = |i: usize| tile_bytes(strip, &tiles, i).ok_or_else(|| corrupt("tile outside strip")); + if mode == crate::Mode::Header { + for (i, t) in tiles.iter().enumerate() { + let tile = bytes(i)?; + let h = parse_tile_header(tile, t.width, t.height)?; + let g4 = h.streams.get(12).ok_or_else(|| corrupt("missing residual stream"))?; + let s = first_half_shift(tile, g4, t.width / 2)?; + let ntu = tu_count(h.vs, s); + for st in &h.streams { + stream_halves(tile, st, ntu)?; + } + } + return Ok(Vec::new()); + } + let decoded: Vec>> = tiles.par_iter().enumerate().map(|(i, t)| decode_tile(bytes(i)?, t.width, t.height)).collect(); + let mut out = vec![0u16; width.checked_mul(height).ok_or_else(|| corrupt("image size"))?]; + for (t, d) in tiles.iter().zip(decoded) { + let d = d?; + for (r, row) in d.chunks_exact(t.width.max(1)).enumerate() { + let start = (t.y + r).checked_mul(width).and_then(|a| a.checked_add(t.x)).ok_or_else(|| corrupt("tile placement"))?; + let dst = start.checked_add(row.len()).and_then(|end| out.get_mut(start..end)).ok_or_else(|| corrupt("tile outside image"))?; + dst.copy_from_slice(row); + } + } + Ok(out) +} + #[cfg(test)] mod tests { use super::*; - use crate::llvc::Plane; use crate::vendor::arw6_testenc::*; use crate::vendor::pef::Bits; use lightcraft_tiff::Tiff; @@ -726,4 +815,102 @@ mod tests { let _ = decode_tile_planes(&tile, 64, 48); } } + + #[test] + fn curve_anchors() { + assert_eq!(ARW6_CURVE.len(), 2668); + for (c, v) in [(0, 0), (1427, 1427), (1428, 1429), (1436, 1438), (2048, 2469), (3000, 8010), (4094, 38944), (4095, 39002)] { + assert_eq!(curve(c), v, "code {c}"); + } + assert_eq!(curve(-5), 0); + assert_eq!(curve(5000), 39002); + assert!(ARW6_CURVE.windows(2).all(|w| w[0] < w[1])); + } + + fn plane(w: usize, v: &[i32]) -> Plane { + Plane { width: w, height: v.len() / w, data: v.to_vec() } + } + + fn example() -> TilePlanes { + TilePlanes { + m: plane(3, &[2048, 2052, 2060, 2050, 2049, 2070]), + res: plane(3, &[4, -8, 2, 0, 2, -6]), + c1: plane(3, &[10, -10, 0, 0, 3, -2]), + c2: plane(3, &[-5, 7, 1, 2, 0, 4]), + } + } + + #[test] + fn colour_matches_the_phase0_example() { + let out = colour(&example()).unwrap(); // 6 wide x 4 rows, curve units + let code = |r: usize, c: usize| out[r * 6 + c] as i32; + assert_eq!( + [code(0, 1), code(0, 3), code(0, 5), code(2, 1), code(2, 3), code(2, 5)], + [2049, 2053, 2059, 2050, 2050, 2071].map(|c| curve(c) as i32) + ); // G1 + assert_eq!( + [code(1, 0), code(1, 2), code(1, 4), code(3, 0), code(3, 2), code(3, 4)], + [2053, 2042, 2060, 2050, 2052, 2054].map(|c| curve(c) as i32) + ); // G2 + assert_eq!([code(0, 0), code(0, 2), code(0, 4)], [2071, 2027, 2059].map(|c| curve(c) as i32)); // R + assert_eq!([code(1, 1), code(1, 3), code(1, 5)], [2041, 2061, 2061].map(|c| curve(c) as i32)); // B + } + + #[test] + fn colour_clips_like_the_oracle() { + let mut p = example(); + p.m.data[1] = 4100; + let out = colour(&p).unwrap(); + assert_eq!(out[3], 39002); // G1 = 4101 -> clipped output + assert_eq!(out[6 + 2], curve(2554)); // G2 predicted from the unclipped G1 + assert_eq!(out[2], curve(3304)); // R = 2*(-10) + ((4095 + 2554) >> 1): chroma uses the clipped greens + } + + #[test] + fn decode_header_and_full_and_truncations() { + let (tile, _) = one_tile(64, 48, 3, Qis::REAL); + let file = arw6_file(&[(0, 0, 64, 48, tile)], 64, 48); + let strip = strip_of(&file); + assert!(decode(strip, 64, 48, crate::Mode::Header).unwrap().is_empty()); + assert_eq!(decode(strip, 64, 48, crate::Mode::Full).unwrap().len(), 64 * 48); + for n in 0..strip.len() { + let _ = decode(&strip[..n], 64, 48, crate::Mode::Full); + let _ = decode(&strip[..n], 64, 48, crate::Mode::Header); + } + } + + #[test] + fn corrupt_streams_import_then_fail() { + // Garbage VLD data is self-delimiting and decodes to *something*; what is detectable is a half whose index + // length is too short for the lines it must hold. + let (mut tile, _) = one_tile(64, 48, 0, Qis::REAL); + let h = parse_tile_header(&tile, 64, 48).unwrap(); + let at = (h.streams[9].word + 1) * 16; // g3 c0 index table, first entry: half 0's byte length (u16 BE) + tile[at] = 0; + tile[at + 1] = 1; + let strip = strip_of(&arw6_file(&[(0, 0, 64, 48, tile)], 64, 48)).to_vec(); + assert!(decode(&strip, 64, 48, crate::Mode::Header).is_ok()); + assert!(matches!(decode(&strip, 64, 48, crate::Mode::Full), Err(RawError::Corrupt(_)))); + } + + #[test] + fn four_tiles_place_correctly_and_arw_reports_doubled_levels() { + let tiles: Vec<_> = [(0, 0), (64, 0), (0, 48), (64, 48)] + .iter() + .map(|&(x, y)| { + let (t, _) = one_tile(64, 48, 0, Qis::ZERO); + (x, y, 64, 48, t) + }) + .collect(); + let file = arw6_file(&tiles, 128, 96); + let img = crate::decode(&file).unwrap(); + assert_eq!((img.width, img.height, img.bits), (128, 96, 16)); + assert_eq!(img.black.values, vec![1024.0; 4]); + assert_eq!(img.white, vec![30720.0]); + assert_eq!(img.cfa.as_ref().map(|c| c.pattern.clone()), Some(vec![0, 1, 1, 2])); + let crate::RawData::U16(d) = img.data else { panic!() }; + let single = decode(strip_of(&arw6_file(&tiles[..1], 64, 48)), 64, 48, crate::Mode::Full).unwrap(); + assert_eq!(&d[..64], &single[..64]); // tile 0's first row lands at (0, 0) + assert_eq!(crate::probe_info(&file).unwrap().width, 128); // header mode: tile tables and headers only + } } diff --git a/crates/raw/src/vendor/arw6_curve.rs b/crates/raw/src/vendor/arw6_curve.rs new file mode 100644 index 00000000..1807195b --- /dev/null +++ b/crates/raw/src/vendor/arw6_curve.rs @@ -0,0 +1,176 @@ +//! The ARW6 companding table: 12-bit tile code to output value. + +/// First code the table covers; below it the curve is the identity. +pub(crate) const CURVE_KNEE: usize = 1428; + +/// code → 2 × 14-bit DN; identity below the knee; derived in Phase 0 from the black-box oracle's output over 8 files (0 disagreements), see docs/arw6-compression.md. +#[rustfmt::skip] +pub(crate) const ARW6_CURVE: [u16; 2668] = [ + 1429,1430,1431,1432,1433,1434,1435,1436,1438,1439,1440,1441,1442,1443,1444,1445, + 1446,1447,1448,1449,1450,1451,1452,1453,1455,1456,1457,1458,1459,1460,1461,1462, + 1463,1464,1465,1466,1467,1468,1469,1470,1471,1472,1473,1474,1475,1476,1477,1478, + 1480,1481,1482,1483,1484,1485,1486,1487,1489,1490,1491,1492,1493,1494,1495,1496, + 1497,1498,1499,1500,1501,1502,1503,1504,1505,1506,1507,1508,1509,1510,1511,1512, + 1513,1514,1515,1516,1517,1518,1519,1520,1522,1523,1524,1525,1526,1527,1529,1530, + 1531,1532,1534,1535,1536,1537,1538,1539,1541,1542,1543,1544,1545,1546,1548,1549, + 1550,1551,1553,1554,1555,1556,1558,1559,1561,1562,1563,1565,1566,1567,1568,1569, + 1571,1572,1573,1574,1575,1576,1578,1579,1580,1581,1583,1584,1585,1586,1588,1589, + 1590,1591,1593,1594,1595,1596,1598,1599,1601,1602,1603,1605,1606,1607,1608,1609, + 1611,1612,1613,1614,1615,1616,1618,1619,1621,1622,1623,1625,1626,1627,1629,1630, + 1631,1632,1634,1635,1636,1637,1639,1640,1641,1642,1644,1645,1646,1647,1649,1650, + 1651,1652,1654,1655,1656,1657,1659,1660,1662,1663,1664,1666,1667,1668,1670,1671, + 1673,1674,1675,1677,1678,1680,1681,1683,1685,1686,1688,1689,1691,1692,1694,1695, + 1697,1698,1699,1701,1702,1704,1705,1707,1709,1710,1712,1713,1715,1716,1718,1719, + 1720,1721,1723,1724,1725,1727,1728,1730,1731,1733,1734,1736,1737,1739,1740,1742, + 1743,1745,1746,1748,1749,1750,1752,1753,1755,1756,1757,1759,1760,1762,1763,1765, + 1767,1768,1770,1771,1773,1774,1776,1777,1779,1780,1781,1783,1784,1786,1787,1789, + 1791,1792,1794,1795,1797,1799,1801,1802,1804,1806,1808,1809,1811,1813,1814,1816, + 1818,1819,1821,1822,1824,1826,1827,1829,1831,1832,1834,1835,1837,1839,1841,1842, + 1844,1846,1848,1849,1851,1853,1854,1856,1858,1859,1861,1862,1864,1866,1868,1869, + 1871,1873,1875,1876,1878,1880,1881,1883,1885,1886,1888,1889,1891,1893,1894,1896, + 1898,1899,1901,1902,1904,1906,1908,1909,1911,1913,1915,1916,1918,1920,1922,1924, + 1926,1927,1929,1931,1933,1935,1937,1938,1940,1942,1944,1945,1947,1949,1951,1953, + 1955,1957,1959,1961,1963,1965,1967,1968,1970,1972,1974,1975,1977,1979,1981,1983, + 1985,1986,1988,1990,1992,1994,1996,1998,2000,2001,2003,2005,2007,2009,2011,2013, + 2015,2016,2018,2020,2022,2024,2026,2027,2029,2031,2033,2034,2036,2038,2040,2042, + 2044,2046,2048,2050,2052,2054,2056,2058,2060,2062,2064,2066,2068,2070,2072,2074, + 2076,2078,2080,2082,2084,2086,2088,2090,2092,2094,2096,2098,2100,2102,2104,2106, + 2109,2111,2113,2115,2117,2119,2121,2123,2125,2127,2129,2131,2133,2135,2137,2139, + 2141,2143,2145,2147,2149,2151,2153,2155,2157,2159,2161,2163,2165,2167,2170,2172, + 2175,2177,2179,2182,2184,2186,2188,2190,2193,2195,2197,2199,2201,2203,2206,2208, + 2210,2212,2215,2217,2219,2221,2224,2226,2228,2230,2233,2235,2237,2239,2242,2244, + 2247,2249,2251,2254,2256,2258,2261,2263,2265,2267,2270,2272,2274,2276,2279,2281, + 2283,2285,2288,2290,2292,2294,2297,2299,2302,2304,2306,2309,2311,2314,2316,2319, + 2321,2324,2326,2329,2331,2333,2336,2338,2340,2342,2345,2347,2349,2352,2354,2357, + 2359,2362,2364,2367,2369,2371,2374,2376,2379,2381,2383,2386,2388,2390,2393,2395, + 2398,2400,2402,2405,2407,2410,2412,2415,2417,2420,2422,2425,2427,2430,2432,2435, + 2438,2440,2443,2445,2448,2451,2453,2456,2459,2461,2464,2466,2469,2472,2475,2477, + 2480,2483,2486,2488,2491,2494,2496,2499,2501,2504,2506,2509,2511,2514,2517,2519, + 2522,2525,2528,2530,2533,2536,2538,2541,2543,2546,2548,2551,2553,2556,2559,2561, + 2564,2567,2570,2572,2575,2578,2581,2584,2587,2589,2592,2595,2598,2601,2604,2606, + 2609,2612,2615,2617,2620,2623,2626,2629,2632,2634,2637,2640,2643,2646,2649,2652, + 2655,2657,2660,2663,2666,2669,2672,2675,2678,2680,2683,2686,2689,2692,2695,2698, + 2701,2704,2707,2710,2713,2716,2719,2722,2725,2727,2730,2733,2736,2739,2742,2745, + 2749,2752,2755,2758,2761,2764,2767,2770,2773,2776,2779,2782,2785,2788,2791,2794, + 2798,2801,2804,2807,2810,2813,2816,2819,2823,2826,2829,2832,2835,2838,2841,2844, + 2848,2851,2854,2857,2860,2863,2867,2870,2873,2876,2880,2883,2886,2889,2893,2896, + 2899,2902,2906,2909,2912,2915,2919,2922,2925,2928,2932,2935,2938,2941,2945,2948, + 2952,2955,2958,2962,2965,2968,2972,2975,2979,2982,2985,2989,2992,2995,2999,3002, + 3006,3009,3012,3016,3019,3023,3026,3030,3033,3037,3040,3044,3047,3051,3054,3058, + 3061,3065,3068,3072,3075,3079,3082,3086,3089,3093,3096,3100,3103,3107,3110,3114, + 3118,3121,3125,3128,3132,3136,3139,3143,3146,3150,3153,3157,3160,3164,3168,3171, + 3175,3179,3183,3186,3190,3194,3197,3201,3205,3208,3212,3215,3219,3223,3227,3231, + 3235,3238,3242,3246,3250,3254,3258,3261,3265,3269,3273,3276,3280,3284,3288,3292, + 3296,3299,3303,3307,3311,3315,3319,3323,3327,3331,3335,3339,3343,3347,3351,3354, + 3358,3362,3366,3369,3373,3377,3381,3385,3389,3393,3397,3401,3405,3409,3413,3417, + 3422,3426,3430,3434,3438,3442,3446,3450,3455,3459,3463,3467,3471,3475,3479,3483, + 3487,3491,3495,3499,3503,3507,3512,3516,3520,3524,3529,3533,3537,3541,3546,3550, + 3554,3558,3563,3567,3571,3575,3580,3584,3589,3593,3597,3602,3606,3610,3615,3619, + 3624,3628,3632,3637,3641,3645,3650,3654,3658,3662,3667,3671,3675,3680,3684,3689, + 3693,3698,3702,3707,3711,3716,3720,3725,3729,3734,3738,3743,3747,3752,3756,3761, + 3766,3770,3775,3779,3784,3789,3793,3798,3802,3807,3811,3816,3820,3825,3830,3834, + 3839,3844,3849,3853,3858,3863,3868,3872,3877,3882,3887,3891,3896,3901,3906,3910, + 3915,3920,3925,3929,3934,3939,3944,3949,3954,3958,3963,3968,3973,3978,3983,3988, + 3993,3997,4002,4007,4012,4017,4022,4027,4032,4037,4042,4047,4052,4057,4062,4067, + 4072,4077,4082,4087,4092,4097,4102,4107,4113,4118,4123,4128,4133,4138,4143,4148, + 4154,4159,4164,4169,4174,4179,4185,4190,4195,4200,4206,4211,4216,4221,4227,4232, + 4237,4242,4248,4253,4258,4263,4269,4274,4280,4285,4290,4296,4301,4306,4312,4317, + 4323,4328,4333,4339,4344,4350,4355,4361,4366,4372,4377,4383,4388,4394,4399,4405, + 4410,4416,4421,4427,4432,4438,4444,4449,4455,4461,4467,4472,4478,4484,4489,4495, + 4500,4506,4511,4517,4522,4528,4534,4540,4546,4551,4557,4563,4569,4575,4581,4586, + 4592,4598,4604,4609,4615,4621,4627,4633,4639,4644,4650,4656,4662,4668,4674,4680, + 4686,4692,4698,4704,4710,4716,4722,4728,4734,4740,4746,4752,4758,4764,4771,4777, + 4783,4789,4796,4802,4808,4814,4820,4826,4832,4838,4844,4850,4856,4862,4869,4875, + 4882,4888,4894,4901,4907,4913,4920,4926,4933,4939,4945,4952,4958,4964,4971,4977, + 4983,4989,4996,5002,5008,5015,5021,5028,5034,5041,5047,5054,5060,5067,5073,5080, + 5087,5093,5100,5106,5113,5120,5126,5133,5140,5146,5153,5159,5166,5173,5180,5186, + 5193,5200,5207,5213,5220,5227,5234,5240,5247,5254,5261,5267,5274,5281,5288,5295, + 5302,5309,5316,5323,5330,5337,5344,5351,5358,5365,5372,5379,5386,5393,5400,5407, + 5414,5421,5428,5435,5442,5449,5456,5463,5471,5478,5485,5492,5499,5506,5514,5521, + 5528,5535,5543,5550,5557,5564,5572,5579,5587,5594,5601,5609,5616,5623,5631,5638, + 5646,5653,5660,5668,5675,5683,5690,5698,5705,5713,5720,5728,5735,5743,5751,5758, + 5766,5774,5782,5789,5797,5805,5812,5820,5828,5835,5843,5850,5858,5866,5874,5881, + 5889,5897,5905,5912,5920,5928,5936,5944,5952,5959,5967,5975,5983,5991,5999,6007, + 6015,6023,6031,6039,6047,6055,6063,6071,6079,6087,6095,6103,6111,6119,6128,6136, + 6144,6152,6161,6169,6177,6185,6194,6202,6210,6218,6227,6235,6243,6251,6260,6268, + 6277,6285,6293,6302,6310,6319,6327,6336,6344,6353,6361,6370,6378,6387,6395,6404, + 6412,6421,6429,6438,6446,6455,6464,6472,6481,6490,6499,6507,6516,6525,6534,6543, + 6552,6560,6569,6578,6587,6596,6605,6613,6622,6631,6640,6648,6657,6666,6675,6684, + 6694,6703,6712,6721,6730,6739,6748,6757,6767,6776,6785,6794,6803,6812,6822,6831, + 6840,6849,6859,6868,6877,6886,6896,6905,6914,6923,6933,6942,6951,6961,6970,6980, + 6989,6999,7008,7018,7027,7037,7046,7056,7065,7075,7084,7094,7103,7113,7123,7132, + 7142,7152,7162,7171,7181,7191,7201,7210,7220,7230,7240,7249,7259,7269,7279,7289, + 7299,7309,7319,7329,7339,7349,7359,7369,7379,7389,7399,7409,7419,7429,7440,7450, + 7460,7470,7481,7491,7501,7511,7522,7532,7543,7553,7563,7574,7584,7594,7605,7615, + 7626,7636,7646,7657,7667,7678,7688,7699,7709,7720,7730,7741,7751,7762,7772,7783, + 7794,7804,7815,7825,7836,7847,7858,7869,7880,7890,7901,7912,7923,7934,7945,7956, + 7967,7977,7988,7999,8010,8021,8032,8043,8055,8066,8077,8088,8099,8110,8122,8133, + 8144,8155,8167,8178,8189,8200,8212,8223,8234,8245,8257,8268,8279,8291,8302,8314, + 8326,8337,8349,8360,8372,8384,8395,8407,8418,8430,8441,8453,8464,8476,8488,8500, + 8512,8523,8535,8547,8559,8571,8583,8595,8607,8618,8630,8642,8654,8666,8678,8690, + 8702,8714,8726,8738,8750,8762,8775,8787,8799,8811,8824,8836,8848,8860,8873,8885, + 8898,8910,8922,8935,8947,8960,8972,8985,8997,9010,9022,9035,9047,9060,9072,9085, + 9098,9110,9123,9135,9148,9161,9174,9187,9200,9212,9225,9238,9251,9264,9277,9290, + 9303,9316,9329,9342,9355,9368,9381,9394,9408,9421,9434,9447,9460,9473,9487,9500, + 9513,9526,9540,9553,9566,9580,9593,9607,9620,9634,9647,9661,9674,9688,9701,9715, + 9728,9742,9755,9769,9782,9796,9810,9824,9838,9851,9865,9879,9893,9907,9921,9935, + 9949,9963,9977,9991,10005,10019,10033,10047,10061,10075,10089,10103,10117,10131,10146,10160, + 10175,10189,10203,10218,10232,10247,10261,10276,10290,10305,10319,10334,10348,10363,10377,10392, + 10407,10421,10436,10450,10465,10480,10495,10509,10524,10539,10554,10568,10583,10598,10613,10628, + 10643,10658,10673,10688,10703,10718,10734,10749,10764,10779,10795,10810,10825,10840,10856,10871, + 10887,10902,10917,10933,10948,10964,10979,10995,11010,11026,11041,11057,11072,11088,11104,11120, + 11136,11151,11167,11183,11199,11215,11231,11247,11263,11278,11294,11310,11326,11342,11358,11374, + 11391,11407,11423,11439,11455,11471,11488,11504,11521,11537,11553,11570,11586,11603,11619,11636, + 11652,11669,11685,11702,11718,11735,11752,11768,11785,11802,11819,11835,11852,11869,11886,11903, + 11920,11937,11954,11971,11988,12005,12022,12039,12057,12074,12091,12108,12125,12142,12160,12177, + 12195,12212,12229,12247,12264,12282,12299,12317,12335,12352,12370,12387,12405,12423,12441,12458, + 12476,12494,12512,12529,12547,12565,12583,12601,12619,12637,12655,12673,12691,12709,12728,12746, + 12764,12782,12801,12819,12837,12855,12874,12892,12911,12929,12947,12966,12984,13003,13022,13040, + 13059,13078,13097,13115,13134,13153,13172,13191,13210,13228,13247,13266,13285,13304,13323,13342, + 13362,13381,13400,13419,13438,13457,13477,13496,13516,13535,13554,13574,13593,13613,13632,13652, + 13672,13691,13711,13730,13750,13770,13790,13810,13830,13849,13869,13889,13909,13929,13949,13969, + 13990,14010,14030,14050,14070,14090,14111,14131,14151,14171,14192,14212,14232,14253,14273,14294, + 14315,14335,14356,14376,14397,14418,14439,14460,14481,14501,14522,14543,14564,14585,14606,14627, + 14648,14669,14690,14711,14732,14753,14775,14796,14818,14839,14860,14882,14903,14925,14946,14968, + 14990,15011,15033,15054,15076,15098,15120,15142,15164,15185,15207,15229,15251,15273,15295,15317, + 15340,15362,15384,15406,15428,15450,15473,15495,15518,15540,15562,15585,15607,15630,15653,15675, + 15698,15721,15744,15766,15789,15812,15835,15858,15881,15903,15926,15949,15972,15995,16019,16042, + 16065,16088,16112,16135,16158,16182,16205,16229,16253,16276,16300,16323,16347,16371,16395,16418, + 16442,16466,16490,16513,16537,16561,16585,16609,16634,16658,16682,16706,16730,16754,16779,16803, + 16828,16852,16876,16901,16925,16950,16975,16999,17024,17049,17074,17098,17123,17148,17173,17198, + 17223,17248,17273,17298,17323,17348,17374,17399,17424,17449,17475,17500,17525,17551,17576,17602, + 17628,17653,17679,17704,17730,17756,17782,17808,17834,17860,17886,17912,17938,17964,17991,18017, + 18043,18069,18096,18122,18148,18175,18201,18228,18254,18281,18307,18334,18360,18387,18414,18441, + 18468,18494,18521,18548,18575,18602,18630,18657,18684,18711,18739,18766,18793,18821,18848,18876, + 18904,18931,18959,18986,19014,19042,19070,19097,19125,19153,19181,19208,19236,19264,19293,19321, + 19349,19377,19406,19434,19462,19491,19519,19548,19577,19605,19634,19662,19691,19720,19749,19778, + 19807,19835,19864,19893,19922,19951,19981,20010,20040,20069,20098,20128,20157,20187,20216,20246, + 20276,20305,20335,20364,20394,20424,20454,20484,20514,20544,20574,20604,20634,20664,20695,20725, + 20756,20786,20816,20847,20877,20908,20939,20969,21000,21031,21062,21092,21123,21154,21185,21216, + 21247,21278,21309,21340,21371,21403,21434,21466,21497,21529,21560,21592,21623,21655,21687,21719, + 21751,21782,21814,21846,21878,21910,21943,21975,22007,22039,22072,22104,22136,22169,22202,22234, + 22267,22300,22333,22365,22398,22431,22464,22497,22530,22563,22596,22629,22662,22696,22729,22763, + 22796,22830,22863,22897,22930,22964,22998,23032,23066,23099,23133,23167,23201,23235,23270,23304, + 23338,23372,23407,23441,23475,23510,23545,23579,23614,23649,23684,23718,23753,23788,23823,23858, + 23894,23929,23964,23999,24034,24070,24105,24141,24176,24212,24247,24283,24318,24354,24390,24426, + 24462,24498,24534,24570,24606,24643,24679,24716,24752,24789,24825,24862,24898,24935,24972,25009, + 25046,25082,25119,25156,25193,25230,25268,25305,25342,25379,25417,25454,25491,25529,25567,25605, + 25643,25680,25718,25756,25794,25832,25871,25909,25947,25985,26024,26062,26100,26139,26178,26216, + 26255,26294,26333,26371,26410,26449,26488,26527,26567,26606,26645,26684,26723,26763,26802,26842, + 26882,26921,26961,27000,27040,27080,27121,27161,27201,27241,27282,27322,27362,27403,27443,27484, + 27525,27565,27606,27646,27687,27728,27769,27810,27852,27893,27934,27975,28016,28058,28099,28141, + 28183,28224,28266,28307,28349,28391,28433,28475,28518,28560,28602,28644,28686,28729,28772,28814, + 28857,28900,28943,28985,29028,29071,29114,29157,29201,29244,29287,29330,29373,29417,29461,29504, + 29548,29592,29636,29679,29723,29767,29812,29856,29900,29944,29989,30033,30077,30122,30167,30211, + 30256,30301,30346,30390,30435,30480,30526,30571,30617,30662,30707,30753,30798,30844,30890,30936, + 30982,31027,31073,31119,31165,31212,31258,31305,31351,31398,31444,31491,31537,31584,31631,31678, + 31725,31772,31819,31866,31913,31961,32008,32056,32104,32151,32199,32246,32294,32342,32390,32438, + 32487,32535,32583,32631,32679,32766,32777,32825,32874,32923,32972,33020,33069,33118,33168,33217, + 33267,33316,33365,33415,33464,33514,33564,33614,33664,33714,33764,33814,33864,33915,33965,34016, + 34067,34117,34168,34218,34269,34320,34371,34422,34474,34525,34576,34627,34678,34730,34782,34834, + 34886,34937,34989,35041,35093,35146,35198,35251,35303,35356,35408,35461,35513,35566,35619,35672, + 35725,35778,35831,35884,35937,35991,36045,36098,36152,36206,36260,36313,36367,36422,36476,36531, + 36585,36640,36694,36749,36803,36858,36913,36968,37023,37078,37133,37188,37243,37299,37355,37410, + 37466,37522,37578,37633,37689,37746,37802,37859,37915,37972,38028,38085,38141,38198,38255,38312, + 38369,38426,38483,38540,38597,38655,38713,38771,38829,38886,38944,39002, +]; diff --git a/crates/raw/src/vendor/mod.rs b/crates/raw/src/vendor/mod.rs index 0e4ca414..492e396b 100644 --- a/crates/raw/src/vendor/mod.rs +++ b/crates/raw/src/vendor/mod.rs @@ -2,6 +2,7 @@ pub mod arw; pub mod arw6; +mod arw6_curve; #[cfg(test)] pub(crate) mod arw6_testenc; mod arw_lens; diff --git a/crates/raw/tests/vendor_robust.rs b/crates/raw/tests/vendor_robust.rs index 81a751c8..cb79c87d 100644 --- a/crates/raw/tests/vendor_robust.rs +++ b/crates/raw/tests/vendor_robust.rs @@ -232,6 +232,7 @@ fn samples() -> Vec> { cfa_tiff("NIKON CORPORATION", 34713, 14, ByteOrder::Big), cfa_tiff("SONY", 32767, 12, ByteOrder::Little), cfa_tiff("SONY", 1, 14, ByteOrder::Little), + cfa_tiff("SONY", 32766, 14, ByteOrder::Little), pef(1), pef(65535), cfa_tiff("SAMSUNG", 1, 12, ByteOrder::Little), @@ -282,7 +283,7 @@ proptest! { #![proptest_config(ProptestConfig { cases: 2000, .. ProptestConfig::default() })] #[test] - fn mutated_vendor_files_never_panic(kind in 0usize..17, flips in proptest::collection::vec((any::(), any::()), 1..16), cut in any::()) { + fn mutated_vendor_files_never_panic(kind in 0usize..18, flips in proptest::collection::vec((any::(), any::()), 1..16), cut in any::()) { let mut data = samples().swap_remove(kind); let n = data.len(); for (i, v) in flips { From 1bbb57650c802999ded266ac8446999a53ec5ec5 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 00:26:38 +0200 Subject: [PATCH 09/21] LR-IMP-FORMATS: ARW6 halves must end within their last byte --- crates/raw/src/vendor/arw6.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index 4d9cf165..50ea2034 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -336,13 +336,19 @@ fn decode_stream(tile: &[u8], st: &StreamRef, ntu: usize, w2: usize, layouts: &[ let total = bytes.len() * 8; let mut bits = Bits::new(bytes); let mut lines = Vec::with_capacity(line_count(st.group, rows)); - for _ in 0..line_count(st.group, rows) { + let n = line_count(st.group, rows); + for _ in 0..n { lines.push(vld_decode_line(&mut bits, total, width)?); if bits.consumed_bits() > total { return Err(corrupt("line runs past its half")); } } - Ok((half, lines)) // bytes beyond the last line are ignored + // Phase 0 measurement: in all 3562 halves of the 8 real files the lines end within the half's last + // byte (`len*8 - 8 < consumed <= len*8`); garbage that decodes to fewer bits is corruption. + if n > 0 && bits.consumed_bits() <= total.saturating_sub(8) { + return Err(corrupt("half ends early")); + } + Ok((half, lines)) }) .collect() } @@ -879,6 +885,20 @@ mod tests { } } + #[test] + fn garbage_streams_import_then_fail() { + let (mut tile, _) = one_tile(64, 48, 0, Qis::REAL); + let h = parse_tile_header(&tile, 64, 48).unwrap(); + let st = &h.streams[9]; // g3 c0 + let start = (st.word + 1 + st.index_words) * 16; + for (i, b) in tile[start..start + st.data_words * 16].iter_mut().enumerate() { + *b = (i as u8).wrapping_mul(97) ^ 0xa5; + } + let strip = strip_of(&arw6_file(&[(0, 0, 64, 48, tile)], 64, 48)).to_vec(); + assert!(decode(&strip, 64, 48, crate::Mode::Header).is_ok()); + assert!(matches!(decode(&strip, 64, 48, crate::Mode::Full), Err(RawError::Corrupt(_)))); + } + #[test] fn corrupt_streams_import_then_fail() { // Garbage VLD data is self-delimiting and decodes to *something*; what is detectable is a half whose index From 1a146c12b007383d4d0cd3eb2077f5e9c97e3b1c Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 00:35:39 +0200 Subject: [PATCH 10/21] LR-IMP-FORMATS: ARW6 chroma planes are base-free; white fallback not doubled --- crates/raw/src/vendor/arw.rs | 7 +++-- crates/raw/src/vendor/arw6.rs | 38 +++++++++++++++++++++++++-- crates/raw/src/vendor/arw6_testenc.rs | 27 +++++++++++++++---- 3 files changed, 61 insertions(+), 11 deletions(-) diff --git a/crates/raw/src/vendor/arw.rs b/crates/raw/src/vendor/arw.rs index f7dc1831..72eee061 100644 --- a/crates/raw/src/vendor/arw.rs +++ b/crates/raw/src/vendor/arw.rs @@ -654,15 +654,14 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { _ if linear_rgb => BlackLevel::uniform(default_black + YCBCR_OFFSET), _ => BlackLevel::uniform((scale_bits >= 14).then(|| sr2().and_then(sr2_black)).flatten().unwrap_or(default_black)), }; + // ARW6 samples are in 2 x 14-bit units, so the file's 14-bit levels double (a data-derived white is already in them) + let unit = if info.compression == 32766 { 2.0 } else { 1.0 }; let white = if linear_rgb { YCBCR_WHITE + YCBCR_OFFSET } else { - raw.f64(t::WHITE_LEVEL).map(|v| v as f32).filter(|v| *v > 0.0).unwrap_or_else(|| super::white_from_data(samples, scale_bits)) + raw.f64(t::WHITE_LEVEL).map(|v| v as f32 * unit).filter(|v| *v > 0.0).unwrap_or_else(|| super::white_from_data(samples, scale_bits)) }; - // ARW6 samples are in 2 x 14-bit units, so the file's 14-bit levels double - let unit = if info.compression == 32766 { 2.0 } else { 1.0 }; let black = BlackLevel { values: black.values.iter().map(|v| v * unit).collect(), ..black }; - let white = white * unit; let model = ifd0.string(t::MODEL).unwrap_or_default(); let mn = tiff .exif() diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index 50ea2034..d3eab0bd 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -396,12 +396,12 @@ fn component(c: usize, streams: &[Vec], layouts: &[HalfRows], vs: usi let grp = |g: usize, n: usize| streams.get(3 * g + c).and_then(|s| s.get(n)).ok_or_else(|| corrupt("missing half")); for (n, r) in layouts.iter().enumerate() { let (h0, l0) = grp(0, n)?; - // LL3: the nibble must be 0 (Phase 0: never seen otherwise); lines are DPCM from 2048 (spec *Container*). + // LL3: the nibble must be 0 (Phase 0: never seen otherwise); lines are DPCM from 2048 for the green mean (c = 0) and from 0 for the base-free chroma planes (spec *Container*). if h0.qi[0] != 0 { return Err(unsupported("LL3 quantiser index")); } for (&row, line) in r.l3.iter().zip(l0) { - let mut acc = 2048i32; + let mut acc = if c == 0 { 2048i32 } else { 0 }; put(&mut b.ll3, row, line, |d| { acc = acc.saturating_add(d); acc @@ -899,6 +899,40 @@ mod tests { assert!(matches!(decode(&strip, 64, 48, crate::Mode::Full), Err(RawError::Corrupt(_)))); } + #[test] + fn chroma_planes_are_base_free() { + let (w2, h2) = (32, 24); + let flat = |v: i32| Plane { width: w2, height: h2, data: vec![v; w2 * h2] }; + let (m, _, _, res) = planes(w2, h2, 7); + for (c1, c2) in [(0, 0), (5, -3)] { + let t = TileSpec { s: 0, qi: Qis::ZERO, m: m.clone(), c1: flat(c1), c2: flat(c2), res: res.clone() }; + let tile = encode_tile(&t); + let p = decode_tile_planes(&tile, 64, 48).unwrap(); + assert!(p.c1.data.iter().all(|&v| v == c1) && p.c2.data.iter().all(|&v| v == c2)); + if c1 == 0 { + // zero chroma: R = B = (G1 + G2) >> 1 at every cell (no 2048 base, no saturation) + let out = decode_tile(&tile, 64, 48).unwrap(); + for j in 0..h2 { + for x in 0..w2 { + let at = |dy: usize, dx: usize| out[(2 * j + dy) * 64 + 2 * x + dx]; + assert_eq!(at(0, 0), at(1, 1), "R == B at ({x},{j})"); + assert!(at(0, 0) < 39002); + } + } + } + } + } + + #[test] + fn data_derived_white_is_not_doubled() { + let (tile, _) = one_tile(64, 48, 0, Qis::ZERO); + let file = arw6_file_no_white(&[(0, 0, 64, 48, tile)], 64, 48); + let img = crate::decode(&file).unwrap(); + let crate::RawData::U16(ref d) = img.data else { panic!() }; + assert_eq!(img.white, vec![super::super::white_from_data(d, 16)]); + assert!(img.white[0] <= 65535.0); + } + #[test] fn corrupt_streams_import_then_fail() { // Garbage VLD data is self-delimiting and decodes to *something*; what is detectable is a half whose index diff --git a/crates/raw/src/vendor/arw6_testenc.rs b/crates/raw/src/vendor/arw6_testenc.rs index ba7e30af..dd364caf 100644 --- a/crates/raw/src/vendor/arw6_testenc.rs +++ b/crates/raw/src/vendor/arw6_testenc.rs @@ -312,7 +312,7 @@ pub(crate) fn encode_tile(t: &TileSpec) -> Vec { let dpcm = { let mut ll = quantised_rows(&b.ll3, &low3, 0); for l in &mut ll { - let mut prev = 2048; + let mut prev = if c == 0 { 2048 } else { 0 }; for v in l.iter_mut() { (*v, prev) = (*v - prev, *v); } @@ -378,6 +378,15 @@ pub(crate) fn encode_tile(t: &TileSpec) -> Vec { /// A little-endian ARW6 TIFF: IFD0 (Sony, ILCE-7RM6) + a SubIFD with the strip = tile table, zero padding to 512, /// then the tiles `(x, y, w, h, bytes)` back to back. pub(crate) fn arw6_file(tiles: &[(usize, usize, usize, usize, Vec)], width: usize, height: usize) -> Vec { + arw6_file_with(tiles, width, height, true) +} + +/// [`arw6_file`] without the WhiteLevel tag. +pub(crate) fn arw6_file_no_white(tiles: &[(usize, usize, usize, usize, Vec)], width: usize, height: usize) -> Vec { + arw6_file_with(tiles, width, height, false) +} + +fn arw6_file_with(tiles: &[(usize, usize, usize, usize, Vec)], width: usize, height: usize, white: bool) -> Vec { let mut strip = (tiles.len() as u32).to_le_bytes().to_vec(); strip.extend([0; 4]); let mut offset = 512u64; @@ -402,7 +411,9 @@ pub(crate) fn arw6_file(tiles: &[(usize, usize, usize, usize, Vec)], width: raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); raw.set(0x7310, Value::Short(vec![512; 4])); - raw.set(t::WHITE_LEVEL, Value::Long(vec![15360])); + if white { + raw.set(t::WHITE_LEVEL, Value::Long(vec![15360])); + } raw.set_image(ImageData::Strips { rows_per_strip: height as u32, strips: vec![strip] }); let mut ifd0 = IfdBuilder::new(); ifd0.set(t::MAKE, Value::Ascii("SONY".into())); @@ -413,7 +424,7 @@ pub(crate) fn arw6_file(tiles: &[(usize, usize, usize, usize, Vec)], width: } /// A tile whose bands are random quantised integers `q` (level 1 wider), `v = dequant(q, qi)`, planes by -/// `reconstruct3` (so `quantize` in the encoder is exact on them); LL3 is random around 2048, the residual +/// `reconstruct3` (so `quantize` in the encoder is exact on them); LL3 is random around 2048 (green mean) or 0 (chroma), the residual /// `dequant(q, qi.res)`. pub(crate) fn one_tile_quantised(w: usize, h: usize, s: u8, qi: Qis) -> (Vec, TileSpec) { use crate::llvc::{dequant, reconstruct3}; @@ -425,7 +436,13 @@ pub(crate) fn one_tile_quantised(w: usize, h: usize, s: u8, qi: Qis) -> (Vec x ^= x >> 7; x ^= x << 17; let v = (x % (2 * span as u64 + 1)) as i32 - span; - if centre == 0 { dequant(v, q) } else { centre + v } + if centre == i32::MIN { + v + } else if centre == 0 { + dequant(v, q) + } else { + centre + v + } }; let mut plane = |wd: usize, ht: usize, span: i32, centre: i32, q: u32| Plane { width: wd, @@ -440,7 +457,7 @@ pub(crate) fn one_tile_quantised(w: usize, h: usize, s: u8, qi: Qis) -> (Vec let (w1, w2b, w3) = (w2 / 2, w2 / 4, w2 / 8); let (a, b, d) = (qi.l1[c], qi.l2[c], qi.l3[c]); let bands = Bands3 { - ll3: plane(w3, n3l, 60, 2048, 0), + ll3: plane(w3, n3l, 60, if c == 0 { 2048 } else { i32::MIN }, 0), hl3: plane(w3, n3l, 7, 0, d[0]), lh3: plane(w3, n3h, 7, 0, d[1]), hh3: plane(w3, n3h, 7, 0, d[2]), From 7b4bdfa68b64d00bd61aa3145852687bb54b9cdf Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 00:37:48 +0200 Subject: [PATCH 11/21] LR-IMP-FORMATS: ARW6 four-tile placement test checks every tile --- crates/raw/src/vendor/arw6.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index d3eab0bd..103a2c10 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -565,7 +565,11 @@ mod tests { } fn one_tile(w: usize, h: usize, s: u8, qi: Qis) -> (Vec, TileSpec) { - let (m, c1, c2, res) = planes(w / 2, h / 2, 7); + seeded_tile(w, h, s, qi, 7) + } + + fn seeded_tile(w: usize, h: usize, s: u8, qi: Qis, seed: u64) -> (Vec, TileSpec) { + let (m, c1, c2, res) = planes(w / 2, h / 2, seed); let t = TileSpec { s, qi, m, c1, c2, res }; (encode_tile(&t), t) } @@ -951,8 +955,9 @@ mod tests { fn four_tiles_place_correctly_and_arw_reports_doubled_levels() { let tiles: Vec<_> = [(0, 0), (64, 0), (0, 48), (64, 48)] .iter() - .map(|&(x, y)| { - let (t, _) = one_tile(64, 48, 0, Qis::ZERO); + .enumerate() + .map(|(i, &(x, y))| { + let (t, _) = seeded_tile(64, 48, 0, Qis::ZERO, 11 + i as u64 * 17); // a different image per tile (x, y, 64, 48, t) }) .collect(); @@ -963,8 +968,12 @@ mod tests { assert_eq!(img.white, vec![30720.0]); assert_eq!(img.cfa.as_ref().map(|c| c.pattern.clone()), Some(vec![0, 1, 1, 2])); let crate::RawData::U16(d) = img.data else { panic!() }; - let single = decode(strip_of(&arw6_file(&tiles[..1], 64, 48)), 64, 48, crate::Mode::Full).unwrap(); - assert_eq!(&d[..64], &single[..64]); // tile 0's first row lands at (0, 0) + for (x, y, w, h, bytes) in &tiles { + let want = decode_tile(bytes, *w, *h).unwrap(); + for r in 0..*h { + assert_eq!(&d[(y + r) * 128 + x..(y + r) * 128 + x + w], &want[r * w..(r + 1) * w], "tile at ({x},{y}) row {r}"); + } + } assert_eq!(crate::probe_info(&file).unwrap().width, 128); // header mode: tile tables and headers only } } From 458b9382486d1456fa7cb3ec1df57a212e4d0cb8 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 00:58:31 +0200 Subject: [PATCH 12/21] LR-IMP-FORMATS: ARW6 corpus verification, docs and tracker --- crates/raw/src/vendor/arw6.rs | 2 +- crates/raw/src/vendor/arw6_testenc.rs | 4 +- crates/raw/tests/corpus.rs | 57 ++++++++++++++ docs/arw6-compression.md | 107 ++++++++++++++++++++++++++ docs/arw6-corpus.sha256 | 14 ++++ docs/parity-checklist.md | 4 +- docs/raw-parity.md | 1 + xtask/src/main.rs | 61 +++++++++++++++ 8 files changed, 245 insertions(+), 5 deletions(-) create mode 100644 docs/arw6-compression.md create mode 100644 docs/arw6-corpus.sha256 diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index 103a2c10..5c060227 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -227,7 +227,7 @@ pub(crate) fn tu_count(vs: usize, s: u8) -> usize { halves.div_ceil(2) } -/// Lifting phases of levels 1..=3 for anchor offset `s` (`plan/arw6/scratch/assemble.py::geometry`): +/// Lifting phases of levels 1..=3 for anchor offset `s` (the Phase 0 reference model, local and not in the repo; see `docs/arw6-compression.md`): /// FF (s = 0) gives [0, 1, 1], the APS-C crop (s = 3) [1, 0, 0]. pub(crate) fn phases(s: u8) -> [u8; 3] { let s = i32::from(s); diff --git a/crates/raw/src/vendor/arw6_testenc.rs b/crates/raw/src/vendor/arw6_testenc.rs index dd364caf..d7f51d2f 100644 --- a/crates/raw/src/vendor/arw6_testenc.rs +++ b/crates/raw/src/vendor/arw6_testenc.rs @@ -13,7 +13,7 @@ fn at(v: &[i32], i: isize) -> i32 { if v.is_empty() { 0 } else { v[i.clamp(0, v.len() as isize - 1) as usize] } } -/// Forward 1-D 5/3 with whole-sample symmetric extension (`plan/arw6/scratch/fwd.py::fwd1d`). +/// Forward 1-D 5/3 with whole-sample symmetric extension (port of the Phase 0 reference model, local and not in the repo). fn forward_1d(x: &[i32], phase: u8) -> (Vec, Vec) { let n = x.len() as isize; let p = isize::from(phase); @@ -80,7 +80,7 @@ pub(crate) fn forward3(x: &Plane, phases: [u8; 3]) -> Bands3 { Bands3 { ll3, hl3, lh3, hh3, hl2, lh2, hh2, hl1, lh1, hh1 } } -// ---- RDD 34 line encoder (mirror of `llvc::vld_decode_line`; `plan/arw6/scratch/tilewrite.py::vld_encode`) ---- +// ---- RDD 34 line encoder (mirror of `llvc::vld_decode_line`; port of the Phase 0 reference model's encoder) ---- /// MSB-first bit sink; one `0`/`1` per element until `finish`. #[derive(Default)] diff --git a/crates/raw/tests/corpus.rs b/crates/raw/tests/corpus.rs index 8649dd70..edfd1239 100644 --- a/crates/raw/tests/corpus.rs +++ b/crates/raw/tests/corpus.rs @@ -861,6 +861,63 @@ fn corpus_fujifilm_compressed_samples() { eprintln!("verified {seen} Fujifilm compressed sensor arrays"); } +/// Checks each available `(name, width, height, sum, weighted)` case against the pinned SHA-256 in `checksums` +/// and the decoder's sensor array; absent corpus files are skipped. Returns how many were verified. +fn verify_sensor_arrays(checksums: &str, cases: &[(&str, usize, usize, u64, u64)]) -> usize { + use sha2::{Digest, Sha256}; + let dir = corpus_root().join("raw"); + let mut seen = 0; + for &(name, width, height, sum, weighted) in cases { + let path = format!("corpus/raw/{name}"); + let checksum = checksums.lines().filter_map(|s| s.split_once(" ")).find(|(_, p)| *p == path).unwrap().0; + assert_eq!(checksum.len(), 64, "{name}: missing published SHA-256"); + let Ok(bytes) = std::fs::read(dir.join(name)) else { continue }; + let actual_sha: String = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!(actual_sha, checksum, "{name}: corpus file differs from its pinned identity"); + let img = decode(&bytes).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!((img.width, img.height), (width, height), "{name}"); + let lightcraft_raw::RawData::U16(data) = img.data else { panic!("{name}: float data") }; + let actual = data + .iter() + .enumerate() + .fold((0u64, 0u64), |(s, w), (i, &v)| (s.wrapping_add(u64::from(v)), w.wrapping_add((i as u64 + 1).wrapping_mul(u64::from(v))))); + assert_eq!(actual, (sum, weighted), "{name}: sensor samples differ from reference"); + seen += 1; + } + seen +} + +/// Reference sums from the oracle-verified Phase 0 model (docs/arw6-compression.md); the files are CC0 from RawDB. +#[test] +fn corpus_sony_arw6_samples() { + let cases: &[(&str, usize, usize, u64, u64)] = &[ + ("arw6-sony-ilce7rm6-apsc-land-hq.arw", 6592, 4372, 85834467900, 1323814215465139776), + ("arw6-sony-ilce7rm6-apsc-land-c.arw", 6592, 4372, 100710478599, 1516298925086164077), + ("arw6-sony-ilce7rm6-ff-land-hq.arw", 10016, 6672, 258417758289, 9667602918876623332), + ("arw6-sony-ilce7rm6-ff-land-c.arw", 10016, 6672, 258558260019, 9665041696390559268), + ("arw6-sony-ilce7rm6-apsc-port-hq.arw", 6592, 4372, 126965386051, 1647947621898118992), + ("arw6-sony-ilce7rm6-apsc-port-c.arw", 6592, 4372, 122629012213, 1601616875702755341), + ("arw6-sony-ilce7rm6-ff-port-hq.arw", 10016, 6672, 242772794178, 8043470668590476975), + ("arw6-sony-ilce7rm6-ff-port-c.arw", 10016, 6672, 241868995482, 8014659803009871380), + ]; + let seen = verify_sensor_arrays(include_str!("../../../docs/arw6-corpus.sha256"), cases); + eprintln!("verified {seen} Sony ARW6 sensor arrays"); +} + +/// The lossless siblings keep decoding through the LJ92 quad-tile path. Regression values from LightCraft's own +/// LJ92 path, 2026-10-10 (no independent reference). +#[test] +fn corpus_sony_ilce7rm6_lossless_samples() { + let cases: &[(&str, usize, usize, u64, u64)] = &[ + ("arw-sony-ilce7rm6-apsc-land-lossless.arw", 6656, 4608, 42685586690, 664300694689609738), + ("arw-sony-ilce7rm6-apsc-port-lossless.arw", 6656, 4608, 62443944469, 818441184988649303), + ("arw-sony-ilce7rm6-ff-land-lossless.arw", 10240, 7168, 128728791716, 4922490451480041632), + ("arw-sony-ilce7rm6-ff-port-lossless.arw", 10240, 7168, 120718314835, 4098302368966213583), + ]; + let seen = verify_sensor_arrays(include_str!("../../../docs/arw6-corpus.sha256"), cases); + eprintln!("verified {seen} Sony ILCE-7RM6 lossless sensor arrays"); +} + /// The container rule for TIFF "shells" (a small IFD0 next to a private raw block) must not touch real /// raws: every corpus file keeps the format its maker implies, and none is described as a private block. #[test] diff --git a/docs/arw6-compression.md b/docs/arw6-compression.md new file mode 100644 index 00000000..fef97c9d --- /dev/null +++ b/docs/arw6-compression.md @@ -0,0 +1,107 @@ +# Sony ARW6 (Compressed RAW 2) + +LightCraft decodes the raw sensor data of Sony's *Compressed* and *Compressed (HQ)* ARW files (TIFF Compression 32766, SonyRawFileType 6, "ARW 6.0") written by the A7R VI (ILCE-7RM6) in pure Rust. The shared RAW decoder serves import, desktop previews, editing, CLI rendering, web and export. Before this decoder these files failed the full decode and silently rendered from their embedded JPEG. The ILCE-7M5 (A7 V) writes the same codec; no sample of it was available, so it is unverified. + +Decode timings: see the end of this document (measured in the performance pass). + +## Format and implementation + +The codec is Sony's use of SMPTE RDD 34 (LLVC, Low Latency Video Codec). `crates/raw/src/llvc.rs` is the codec core (bit reader, variable-length decoder, dequantiser, inverse 5/3 wavelet); `crates/raw/src/vendor/arw6.rs` is the Sony container, geometry and colour reconstruction; `crates/raw/src/vendor/arw6_curve.rs` is the companding table; `arw.rs` dispatches Compression 32766 to it. A test-only encoder (`arw6_testenc.rs`) builds synthetic tiles for round-trip tests. + +### Container + +- Raw SubIFD: Compression 32766, 14 bits per sample, BlackLevel 512 x4 (`0x7310`), WB `0x7313`, crop `0x74c7/0x74c8` (full frame: origin 12,8, size 9984x6656; APS-C: origin 16,10, size 6528x4352), CFA RGGB. The Sony tag-based white level (15360) is not read; the DNG `WhiteLevel` is (16383). +- The single strip starts with a tile table: `u32` count, `u32` 0, then per tile a `u64` offset (relative to the strip) and `u32` x, y, width, height. Seen: full frame 4 tiles of 5008x3336 (HQ) or 5024 / 4992 wide (Compressed); APS-C (6592x4372) one tile. A 480-byte block follows the table (not interpreted, not needed). +- A tile is a sequence of 16-byte words. Word 0 is RDD 34 `Picture_info` (HS = tile width, VS = tile height / 2, BBD = 16, NC = 3, NW = 3). Word 1 holds five `u24` group byte-sums, word 2 is zero, words 3-7 describe the groups (a count byte, then `u24` stream sizes in words). Groups: g0 = LL3 (3 streams, one per component), g1 / g2 / g3 = level-3 / 2 / 1 bands (3 streams each), g4 = green residual (1 stream). Streams follow in that order from word 8. +- A stream is a header word, an index table and data, each padded to a word. The index has one entry per transform unit (TU): `A(16) X B(16) X`, where A and B are the byte lengths of the TU's two halves and X are quantiser-index (QI) nibbles (one for g0 and g4, three for g1-g3: HL, LH, HH). Halves per tile = ceil((VS - 2 - s) / 8) + 1 with s the first-half shift (below), TUs = ceil(halves / 2): 105 and 137 for the sample sizes. Halves are numbered n = 2 * TU + h; each is byte-aligned and consecutive halves are contiguous. +- QI values seen, identical in Compressed and HQ files: level 1 component 0 (1,1,2), components 1-2 (2,2,3); level 2 (0,0,1); level 3 (0,0,0); LL3 0; residual 2. Compressed and HQ differ only in the coefficient data. + +### Entropy coding and dequantisation + +- Each line of a band is an RDD 34 section 6.3 coefficient-set stream: ceil(width / 4) sets of four coefficients driven by the DPT / ABS / SGN state machine, with zero runs and the "0^lim" end code. Values past the width are discarded. Lines of a half follow one another bit-contiguously; the state resets per line. +- Two deviations from the RDD 34 text were established by black-box comparison: in state DPTs = 0 with DPT = 0, a "0" code is a zero set that also enters DPTs = 1; and a run code of value V means V - 1 further zero sets before the post-run "0^n 1" depth code. +- Dequantisation is `recon(q) = sign(q) * (((2|q| + 1) << (QI - 1)) - (|q| & 1))`, `recon(0) = 0`, and QI = 0 leaves q unchanged. This replaces RDD 34's plain shift. +- LL3 lines are DPCM: a running sum along the line. The 2048 base (codes are unsigned 12-bit) applies to component 0 (the green mean) only; the chroma planes start at 0. +- Check: every half's lines end inside its last byte. The Phase 0 measurement found budget - 8 < consumed <= budget on every half of all 8 files; the decoder rejects a half that does not. + +### Frame geometry + +- Each tile holds three W/2 x H/2 planes (W, H = tile size): component 0 = M, the green mean; components 1-2 = chroma c1, c2; plus a W/2 x H/2 residual plane from g4. A three-level 5/3 wavelet is inverted (vertical, then horizontal) with whole-sample symmetric extension at every edge and integer arithmetic. Tiles are independent. +- The TU grid and the lifting phases are anchored to the full sensor, not to the tile. Let s = (lines in g4's first half) - 2, read from the stream: 0 on full frame, 3 on the APS-C crop (the crop's sensor-row offset 573 is 5 mod 8). Half n then covers plane rows 8n - 6 + s .. 8n + 1 + s, clipped to the frame. The lifting phases follow from s: full frame (0,1,1), APS-C (1,0,0). Each half holds, in clipped natural order, its rows of HL1, LH1, HH1, HL2, LH2, HH2, LL3, HL3, LH3, HH3 and, in g4, 8 residual rows; edge halves are shorter. With the right s every line of every file is used. + +### Colour reconstruction + +With plane row j, column x (x +- 1 clamped at the edges), in 12-bit code units: + +- `G1[j][x] = M[j][x] - ((res[j-1][x] + res[j-1][x+1] + res[j][x] + res[j][x+1] + 4) >> 3)`, with `res[-1] := res[0]`. +- `G2[j][x] = ((G1[j][x-1] + G1[j][x] + G1[j+1][x-1] + G1[j+1][x]) >> 2) + res[j][x]` (unclipped G1; the last row uses G1[j] for G1[j+1]). +- `R = 2*c1 + ((min(G1, 4095) + min(G2, 4095)) >> 1)`, `B = 2*c2 + (same)`. +- Every code is clipped to 0..4095. Per 2x2 cell: R (0,0), G1 (0,1), G2 (1,0), B (1,1). + +### Output range (companding table) + +- Codes map through one monotone table shared by all files: identity up to code 1427, then a smooth curve reaching 39002 at code 4095 (steps grow from 1 to 58). No closed form fits within +-22, so `arw6_curve.rs` embeds the table (2668 `u16` values from code 1428). It is not stored in the file. +- Provenance: the table was read off the black-box oracle's (LibRaw, below) output over the 8 Compressed / HQ files; every code from 1027 to 4095 occurred and no two files disagreed. It is therefore a measurement of that program's output, not an independent derivation. +- Unit: 2 x 14-bit DN. The decoder reports black = 2 x 512 = 1024 and white = 2 x the file's DNG `WhiteLevel` (16383), i.e. 32766; saturated highlights sit at code 4095 = 39002, above white, and clip as usual. If a file carries no usable white level, a data-derived fallback already in output units is used. +- The table has one knot: at code 3977 it runs 32679 -> 32766 -> 32777 (steps +87 then +11), the same in every file. 32766 = 2 x 16383 is exactly the reported white level, so the knot is the white point of the measured curve (inferred from the arithmetic, not from any documentation): codes 3978..4095 sit above white and clip. + +## Verification + +Method: LibRaw master (commit `d1f0dd95`, 2026-10-08, run as `unprocessed_raw`, 16-bit output before any processing) was used only as a black-box oracle: it was built and run, and its source was never read. A Python reference model of the format (the Phase 0 reference model, local, not in the repo) was written from RDD 34 and from the oracle's behaviour on real and synthetic input, then reproduced the oracle exactly on every tile of the 8 Compressed / HQ files below. A test-only encoder, validated byte for byte against real tiles, probed the oracle with synthetic coefficients (dequantiser, phases, edge mapping). The Rust decoder reproduces the Phase 0 reference sums on all 8 files. + +Geometry was checked against each file's embedded full-resolution JPEG at the DefaultCropOrigin: our output aligns at offset 0 on full frame and APS-C. + +### LibRaw's APS-C bug + +LibRaw assumes the full-frame grid (s = 0) for every tile. On the APS-C crop that drops the first three plane rows, leaves the last three unfed, and shifts its whole output up by 6 sensor rows; its first rows and last rows are also wrong. Our decoder differs from LibRaw there on purpose. To compare against LibRaw on APS-C files, shift its output by 6 rows and skip its first 16 and last 20 rows; on full frame compare directly. + +### Corpus + +| File | Source path (RawDB, ILCE-7RM6) | Size (bytes) | SHA-256 | +|---|---|---|---| +| `arw6-sony-ilce7rm6-apsc-land-hq.arw` | `arw6/ILCE-7RM6_APSC_land_RAW-C-HD.ARW` | 29 720 576 | `b60a7e752d2a8102ccbe6eebcfdbf533c6b0f2545739090873e9e8eb32cc0637` | +| `arw6-sony-ilce7rm6-apsc-land-c.arw` | `arw6/ILCE-7RM6_APSC_land_RAW-C.ARW` | 30 900 224 | `1c803304e63ec508b2b5f9d59d4a7e30ed279315b35fa4c5d75f959bed62198b` | +| `arw6-sony-ilce7rm6-apsc-port-hq.arw` | `arw6/ILCE-7RM6_APSC_port_RAW-C-HD.ARW` | 28 758 016 | `0b6d782571e86868670f613de9fa1f1364623b24fbfd21b704b2c516d7a1c1cb` | +| `arw6-sony-ilce7rm6-apsc-port-c.arw` | `arw6/ILCE-7RM6_APSC_port_RAW-C.ARW` | 29 044 736 | `c41674a485ffcf6d873e20e545ae62936192d94e95be3d53548e93bc543ecfd4` | +| `arw6-sony-ilce7rm6-ff-land-hq.arw` | `arw6/ILCE-7RM6_FF_land_RAW-C-HD.ARW` | 63 451 136 | `559fa26501d7813e56afecde2aea3d9965a99228162b194752d986193abb172c` | +| `arw6-sony-ilce7rm6-ff-land-c.arw` | `arw6/ILCE-7RM6_FF_land_RAW-C.ARW` | 63 844 352 | `d900d6cbe838be864269ad54de4a33fcac7eb3a3d4f91009739f770b8f85a23b` | +| `arw6-sony-ilce7rm6-ff-port-hq.arw` | `arw6/ILCE-7RM6_FF_port_RAW-C-HD.ARW` | 62 640 128 | `81c709633cb8f6340e612c3f53bb6ec6b0cccfe5b713c67efb1e977ece9e266d` | +| `arw6-sony-ilce7rm6-ff-port-c.arw` | `arw6/ILCE-7RM6_FF_port_RAW-C.ARW` | 63 168 512 | `f4448485629c3f82ff1955fd046404350e9a1f09b346038574b89c074d7c50fd` | +| `arw-sony-ilce7rm6-apsc-land-lossless.arw` | `raw_modes/ILCE-7RM6_APSC_land_RAW.ARW` | 44 167 168 | `7aaf0b3941509d7364a6f03844783155ebc912d246d1c456e5cdb4693ec09fbc` | +| `arw-sony-ilce7rm6-apsc-port-lossless.arw` | `raw_modes/ILCE-7RM6_APSC_port_RAW.ARW` | 43 692 032 | `0f011933ee96525a39710daa50b59d39702b4ec5934fa0206742e2128c55f366` | +| `arw-sony-ilce7rm6-ff-land-lossless.arw` | `raw_modes/ILCE-7RM6_FF_land_RAW.ARW` | 100 851 712 | `5cb3c870bc961cf6b079d56c860d0cdf11acd1afd04e5fb8dbe041bcfd2d6201` | +| `arw-sony-ilce7rm6-ff-port-lossless.arw` | `raw_modes/ILCE-7RM6_FF_port_RAW.ARW` | 100 884 480 | `b1a4026aa6adbaa27973b8b3426d8b4aa0c1cae1845cf5102359327d3b069691` | + +These 12 files are CC0 1.0 per the RawDB record of the set (uploaded by abbradar; ); the server answers 303 to a signed object URL, so fetch with `curl -L` from `https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/`. They live in the gitignored corpus; `cargo xtask corpus --download` fetches them and [arw6-corpus.sha256](arw6-corpus.sha256) pins their identities. `cargo test -p lightcraft-raw corpus_sony -- --nocapture` verifies each available file's checksum, then the decoder's sensor sum and position-weighted sum. The first 8 rows (ARW6) are checked against the Phase 0 reference sums; the 4 lossless siblings go through the existing LJ92 path and their sums are regression values from LightCraft's own decoder. The test skips absent files. + +Nine further full-frame HQ photos from the maintainer's A7R VI were compared with the oracle locally; they are private and never committed or published. + +Unconditional synthetic tests (encode -> decode round trips for both geometries, the RDD 34 worked example, the dequantiser, hostile and truncated input) run without the corpus. + +## Coverage + +| Coverage | Status | +|---|---| +| ILCE-7RM6 Compressed and HQ, full frame, landscape and portrait | 4 files, exact against the reference sums | +| ILCE-7RM6 Compressed and HQ, APS-C crop, landscape and portrait | 4 files, exact (with LibRaw only after the 6-row shift) | +| ILCE-7RM6 lossless (existing LJ92 path) | 4 files, regression values | +| Private A7R VI HQ photos | 9 files, compared locally | + +## Not covered + +- The 12-bit Compressed mode (electronic shutter with continuous drive): no sample exists, so it returns `Unsupported` unless its headers prove identical. +- The ILCE-7M5: same codec, no sample; unverified. +- The x2 scale is an assumption backed by shadow-floor evidence (the darkest pixels of all eight ISO 100 files sit at 1037..1059, just above 2 x 512, and the lossless sibling's shadows match at x2; x2.38 would put them 76 DN below black). A tripod-matched lossless / compressed pair would confirm it. If wrong, only the reported black and white levels change. +- Tiles whose plane width is not a multiple of 8. +- Colour: the ILCE-7RM6 bundled colour profile and Sony's embedded lens corrections are separate work. + +## Sources + +- SMPTE RDD 34:2015 "LLVC (Low Latency Video Codec) for Network Transfer", (accessed 2026-10-09): picture / TU structure, VLD, inverse quantisation, 5/3 lifting with symmetric extension. +- LibRaw master `d1f0dd95`, run only as a black-box oracle (not a product, test or build dependency). +- The embedded JPEG of each file, for the geometry check. +- Not read, by licence: LibRaw, rawspeed, dnglab, RawTherapee and other ARW6 decoder sources. Exact byte layouts, deviations, geometry and the table were established through sample analysis and black-box comparison. + +## Timings + +pending diff --git a/docs/arw6-corpus.sha256 b/docs/arw6-corpus.sha256 new file mode 100644 index 00000000..30e80de0 --- /dev/null +++ b/docs/arw6-corpus.sha256 @@ -0,0 +1,14 @@ +# Sony ILCE-7RM6 ARW files (ARW6 Compressed / HQ and lossless siblings); CC0 1.0, RawDB (rawdb.dnglab.org), uploaded by abbradar. +# SHA-256 values verified 2026-10-09; see docs/arw6-compression.md. +b60a7e752d2a8102ccbe6eebcfdbf533c6b0f2545739090873e9e8eb32cc0637 corpus/raw/arw6-sony-ilce7rm6-apsc-land-hq.arw +1c803304e63ec508b2b5f9d59d4a7e30ed279315b35fa4c5d75f959bed62198b corpus/raw/arw6-sony-ilce7rm6-apsc-land-c.arw +0b6d782571e86868670f613de9fa1f1364623b24fbfd21b704b2c516d7a1c1cb corpus/raw/arw6-sony-ilce7rm6-apsc-port-hq.arw +c41674a485ffcf6d873e20e545ae62936192d94e95be3d53548e93bc543ecfd4 corpus/raw/arw6-sony-ilce7rm6-apsc-port-c.arw +559fa26501d7813e56afecde2aea3d9965a99228162b194752d986193abb172c corpus/raw/arw6-sony-ilce7rm6-ff-land-hq.arw +d900d6cbe838be864269ad54de4a33fcac7eb3a3d4f91009739f770b8f85a23b corpus/raw/arw6-sony-ilce7rm6-ff-land-c.arw +81c709633cb8f6340e612c3f53bb6ec6b0cccfe5b713c67efb1e977ece9e266d corpus/raw/arw6-sony-ilce7rm6-ff-port-hq.arw +f4448485629c3f82ff1955fd046404350e9a1f09b346038574b89c074d7c50fd corpus/raw/arw6-sony-ilce7rm6-ff-port-c.arw +7aaf0b3941509d7364a6f03844783155ebc912d246d1c456e5cdb4693ec09fbc corpus/raw/arw-sony-ilce7rm6-apsc-land-lossless.arw +0f011933ee96525a39710daa50b59d39702b4ec5934fa0206742e2128c55f366 corpus/raw/arw-sony-ilce7rm6-apsc-port-lossless.arw +5cb3c870bc961cf6b079d56c860d0cdf11acd1afd04e5fb8dbe041bcfd2d6201 corpus/raw/arw-sony-ilce7rm6-ff-land-lossless.arw +b1a4026aa6adbaa27973b8b3426d8b4aa0c1cae1845cf5102359327d3b069691 corpus/raw/arw-sony-ilce7rm6-ff-port-lossless.arw diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 09941108..17d2b0c2 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -80,8 +80,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate, photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop; masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs; Adobe profile formats deliberately unsupported | | LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); browsed photos stay out of All Photos, albums and counts; folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back; a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | -| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG, PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP; DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared linear primaries without clipping or gamut mapping, checked on one real file with 108 lossy tiles, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth but CFA and black unverified), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8 (`crates/raw/tests/cr3_corpus.rs`, `docs/cr3.md`). Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), NEFs labelled compressed (34713) but stored uncompressed without a `0x0096` table (Z 6 packed 14-bit, D850 12-bit uncompressed), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and Kodak DCS TIFFs: IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Canon CRW, Minolta MRW and Sigma X3F (containers recognised by magic, preview found by a structural JPEG scan), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan), and any decode failure of a recognised raw, not only an unsupported variant; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate) | -| LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/corpus.rs`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535; pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; private Z 8 crop verified. | +| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG, PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP; DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared linear primaries without clipping or gamut mapping, checked on one real file with 108 lossy tiles, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`, 8 CC0 files bit-exact against a black-box oracle and against the Phase 0 reference sums, geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth but CFA and black unverified), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8 (`crates/raw/tests/cr3_corpus.rs`, `docs/cr3.md`). Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), NEFs labelled compressed (34713) but stored uncompressed without a `0x0096` table (Z 6 packed 14-bit, D850 12-bit uncompressed), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and Kodak DCS TIFFs: IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Canon CRW, Minolta MRW and Sigma X3F (containers recognised by magic, preview found by a structural JPEG scan), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan), and any decode failure of a recognised raw, not only an unsupported variant; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate) | +| LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/corpus.rs`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535; pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 sensor arrays verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; private Z 8 crop verified. | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | | LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests_import_move.rs`, `crates/ui-egui/src/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving | | LR-IMP-DNG-CONVERT | Convert to DNG on import [Classic] | P2 | ✅ | `cmd:library.import` (`dng`), `crates/ui-egui/src/import.rs` | copy imports: Raw files ▸ Copy as DNG (lossless; the card is untouched); the raw copy is removed only once its DNG is verified and on disk (issue #106) | diff --git a/docs/raw-parity.md b/docs/raw-parity.md index ca5cbcfd..d5a4e027 100644 --- a/docs/raw-parity.md +++ b/docs/raw-parity.md @@ -122,6 +122,7 @@ checked, and Canon, the largest bucket, is the weakest of the big four. | NEF | High Efficiency / HE★ (JPEG XS) | ⬜ | named, preview (#193); needs a JPEG XS decoder | | ARW | uncompressed, cRAW (ARW2), lossless LJ92 (L / M / S) | ✅ | 86 bodies (#535); M/S black level 1024 | | ARW | packed 12-bit (A900) | ✅ | one CC0 file; A850 unmeasured | +| ARW | ARW6 Compressed / HQ (compression 32766; ILCE-7RM6) | ✅ | 8 CC0 files; 12-bit mode unsupported; `docs/arw6-compression.md` | | ARW | 12-bit compressed of DSLR-A200…A390 | ⬜ | preview (#535) | | ARW | A100 ARW; SRF (F828, V3) | ⬜ | refused (#702); SRF not imported | | ARW | ARQ pixel shift | ⬜ | no code | diff --git a/xtask/src/main.rs b/xtask/src/main.rs index cd226d6f..91063e74 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -775,6 +775,67 @@ const RAW_SAMPLES: &[(&str, &str, &str)] = &[ "https://raw.pixls.us/getfile.php/7807/nice/Fujifilm%20-%20X-T50%20-%2014bit%20compressed%20%283:2%29.RAF", "3a8a9ac6d92274969aaa1f55ea669191b98bb8f588d00ec8ec17afd8b3963dea", ), + // Sony ILCE-7RM6: ARW6 Compressed (RAW-C) / Compressed HQ (RAW-C-HD) and the lossless siblings; CC0 1.0, RawDB. + ( + "arw6-sony-ilce7rm6-apsc-land-hq.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_APSC_land_RAW-C-HD.ARW", + "b60a7e752d2a8102ccbe6eebcfdbf533c6b0f2545739090873e9e8eb32cc0637", + ), + ( + "arw6-sony-ilce7rm6-apsc-land-c.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_APSC_land_RAW-C.ARW", + "1c803304e63ec508b2b5f9d59d4a7e30ed279315b35fa4c5d75f959bed62198b", + ), + ( + "arw6-sony-ilce7rm6-apsc-port-hq.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_APSC_port_RAW-C-HD.ARW", + "0b6d782571e86868670f613de9fa1f1364623b24fbfd21b704b2c516d7a1c1cb", + ), + ( + "arw6-sony-ilce7rm6-apsc-port-c.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_APSC_port_RAW-C.ARW", + "c41674a485ffcf6d873e20e545ae62936192d94e95be3d53548e93bc543ecfd4", + ), + ( + "arw6-sony-ilce7rm6-ff-land-hq.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_FF_land_RAW-C-HD.ARW", + "559fa26501d7813e56afecde2aea3d9965a99228162b194752d986193abb172c", + ), + ( + "arw6-sony-ilce7rm6-ff-land-c.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_FF_land_RAW-C.ARW", + "d900d6cbe838be864269ad54de4a33fcac7eb3a3d4f91009739f770b8f85a23b", + ), + ( + "arw6-sony-ilce7rm6-ff-port-hq.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_FF_port_RAW-C-HD.ARW", + "81c709633cb8f6340e612c3f53bb6ec6b0cccfe5b713c67efb1e977ece9e266d", + ), + ( + "arw6-sony-ilce7rm6-ff-port-c.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_FF_port_RAW-C.ARW", + "f4448485629c3f82ff1955fd046404350e9a1f09b346038574b89c074d7c50fd", + ), + ( + "arw-sony-ilce7rm6-apsc-land-lossless.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/raw_modes/ILCE-7RM6_APSC_land_RAW.ARW", + "7aaf0b3941509d7364a6f03844783155ebc912d246d1c456e5cdb4693ec09fbc", + ), + ( + "arw-sony-ilce7rm6-apsc-port-lossless.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/raw_modes/ILCE-7RM6_APSC_port_RAW.ARW", + "0f011933ee96525a39710daa50b59d39702b4ec5934fa0206742e2128c55f366", + ), + ( + "arw-sony-ilce7rm6-ff-land-lossless.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/raw_modes/ILCE-7RM6_FF_land_RAW.ARW", + "5cb3c870bc961cf6b079d56c860d0cdf11acd1afd04e5fb8dbe041bcfd2d6201", + ), + ( + "arw-sony-ilce7rm6-ff-port-lossless.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/raw_modes/ILCE-7RM6_FF_port_RAW.ARW", + "b1a4026aa6adbaa27973b8b3426d8b4aa0c1cae1845cf5102359327d3b069691", + ), ( "rw2-panasonic-g9-b.rw2", "https://raw.pixls.us/getfile.php/2348/nice/Panasonic%20-%20DC-G9%20-%204:3.RW2", From 9aa9bcb54ed6ab6bc65af36bd84ca4b5a52e93ee Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 01:29:04 +0200 Subject: [PATCH 13/21] LR-IMP-FORMATS: ARW6 decode timings Co-Authored-By: Claude --- docs/arw6-compression.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/arw6-compression.md b/docs/arw6-compression.md index fef97c9d..12cb54a8 100644 --- a/docs/arw6-compression.md +++ b/docs/arw6-compression.md @@ -104,4 +104,13 @@ Unconditional synthetic tests (encode -> decode round trips for both geometries, ## Timings -pending +Raw decode only (`lightcraft_raw::decode`, release build, 4 CPUs, best of 3 wall-clock, 2026-10-10): + +| File | Size | Sensor | Decode | +|---|---|---|---| +| ILCE-7RM6 FF, Compressed (HQ) | 63.5 MB | 10016x6672 | 0.78 s | +| ILCE-7RM6 FF, Compressed | 63.8 MB | 10016x6672 | 0.78 s | +| ILCE-7RM6 APS-C, Compressed (HQ) | 29.7 MB | 6592x4372 | 0.49 s | +| ILCE-7RM6 APS-C, Compressed | 30.9 MB | 6592x4372 | 0.42 s | + +The 1.0 s budget for the full-frame file is met. Parallelised: rayon over the tiles, over the 13 streams of each tile and over its 3 components. From aea5236790bf5ed8c83e4f0d0c73d1d101e8ee2c Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 01:31:32 +0200 Subject: [PATCH 14/21] LR-IMP-FORMATS: ARW6 decode timing method Co-Authored-By: Claude --- docs/arw6-compression.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/arw6-compression.md b/docs/arw6-compression.md index 12cb54a8..968c47b8 100644 --- a/docs/arw6-compression.md +++ b/docs/arw6-compression.md @@ -104,13 +104,13 @@ Unconditional synthetic tests (encode -> decode round trips for both geometries, ## Timings -Raw decode only (`lightcraft_raw::decode`, release build, 4 CPUs, best of 3 wall-clock, 2026-10-10): +Raw decode only, 4 CPUs, release build, best of 3 wall-clock (2026-10-10). Method: a small throwaway Rust program linking `lightcraft-raw` reads the file into memory, then times `lightcraft_raw::decode` alone with `std::time::Instant` (no render, no JPEG encode), three decodes in one process; the best is reported. Files were already in the page cache. | File | Size | Sensor | Decode | |---|---|---|---| -| ILCE-7RM6 FF, Compressed (HQ) | 63.5 MB | 10016x6672 | 0.78 s | -| ILCE-7RM6 FF, Compressed | 63.8 MB | 10016x6672 | 0.78 s | -| ILCE-7RM6 APS-C, Compressed (HQ) | 29.7 MB | 6592x4372 | 0.49 s | -| ILCE-7RM6 APS-C, Compressed | 30.9 MB | 6592x4372 | 0.42 s | +| ILCE-7RM6 FF, Compressed (HQ) | 63.5 MB | 10016x6672 | 0.45 s | +| ILCE-7RM6 FF, Compressed | 63.8 MB | 10016x6672 | 0.51 s | +| ILCE-7RM6 APS-C, Compressed (HQ) | 29.7 MB | 6592x4372 | 0.35 s | +| ILCE-7RM6 APS-C, Compressed | 30.9 MB | 6592x4372 | 0.34 s | The 1.0 s budget for the full-frame file is met. Parallelised: rayon over the tiles, over the 13 streams of each tile and over its 3 components. From 69d3d4cf911b973ef9a06cd6414c888fa2765a9b Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 01:58:36 +0200 Subject: [PATCH 15/21] LR-IMP-FORMATS: ARW6 chroma clamps negative greens; 12-bit guard; fallback white --- crates/raw/src/llvc.rs | 2 +- crates/raw/src/vendor/arw.rs | 15 ++++++-- crates/raw/src/vendor/arw6.rs | 52 ++++++++++++++++++++++----- crates/raw/src/vendor/arw6_testenc.rs | 13 ++++--- 4 files changed, 65 insertions(+), 17 deletions(-) diff --git a/crates/raw/src/llvc.rs b/crates/raw/src/llvc.rs index ef525891..0e2cc39c 100644 --- a/crates/raw/src/llvc.rs +++ b/crates/raw/src/llvc.rs @@ -216,7 +216,7 @@ fn inverse_1d(l: &[i32], h: &[i32], phase: u8) -> Result> { Ok(x) } -/// Gathers the lines of `a` along one axis (columns when `vertical`), applies `f`, and scatters back. +/// Gathers the lines of the `low`/`high` pair along one axis (columns when `vertical`), transforms them, and scatters back. fn lines(low: &Plane, high: &Plane, phase: u8, vertical: bool) -> Result { if !low.ok() || !high.ok() { return Err(RawError::Corrupt("ARW6 wavelet: plane size mismatch".into())); diff --git a/crates/raw/src/vendor/arw.rs b/crates/raw/src/vendor/arw.rs index 72eee061..43153f2c 100644 --- a/crates/raw/src/vendor/arw.rs +++ b/crates/raw/src/vendor/arw.rs @@ -613,10 +613,13 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { } }, 32766 if chunks.len() == 1 => { + if bits != 14 { + return Err(RawError::Unsupported("ARW6 12-bit mode (no sample to verify)".into())); + } let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("raw strip outside file".into()))?; (RawData::U16(arw6::decode(src, w, h, mode)?), 16) } - 32766 => return Err(RawError::Unsupported("ARW6 with more than one strip".into())), + 32766 => return Err(RawError::Unsupported("ARW6 without exactly one strip".into())), 1 => { let word16 = strip_len >= (w * h * 2) as u64; let packing = if word16 { Packing::Word16 } else { Packing::Msb }; @@ -654,12 +657,18 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { _ if linear_rgb => BlackLevel::uniform(default_black + YCBCR_OFFSET), _ => BlackLevel::uniform((scale_bits >= 14).then(|| sr2().and_then(sr2_black)).flatten().unwrap_or(default_black)), }; - // ARW6 samples are in 2 x 14-bit units, so the file's 14-bit levels double (a data-derived white is already in them) + // ARW6 samples are in 2 x 14-bit units, so the file's 14-bit levels double; without the tag the white is the + // companding table's knot, 2 x 16383 let unit = if info.compression == 32766 { 2.0 } else { 1.0 }; let white = if linear_rgb { YCBCR_WHITE + YCBCR_OFFSET } else { - raw.f64(t::WHITE_LEVEL).map(|v| v as f32 * unit).filter(|v| *v > 0.0).unwrap_or_else(|| super::white_from_data(samples, scale_bits)) + let tag = raw.f64(t::WHITE_LEVEL).map(|v| v as f32 * unit).filter(|v| *v > 0.0); + match (tag, info.compression) { + (Some(v), _) => v, + (None, 32766) => 32766.0, + (None, _) => super::white_from_data(samples, scale_bits), + } }; let black = BlackLevel { values: black.values.iter().map(|v| v * unit).collect(), ..black }; let model = ifd0.string(t::MODEL).unwrap_or_default(); diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index 5c060227..26387b41 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -1,4 +1,4 @@ -//! Sony ARW6 ("Compressed RAW 2" / HQ, TIFF Compression 32766): container parsing. +//! Sony ARW6 ("Compressed RAW 2" / HQ, TIFF Compression 32766): container parsing, geometry, colour and decode. //! //! Clean-room. The layout comes from SMPTE RDD 34 (Picture_info in word 0) and from Phase 0 black-box //! inspection of real ILCE-7RM6 files (tile table, group size words, stream headers and index entries), each rule @@ -259,6 +259,8 @@ pub(crate) fn first_half_shift(tile: &[u8], g4: &StreamRef, width2: usize) -> Re vld_decode_line(&mut bits, total, width2)?; lines += 1; } + // The stop rule is sound because a residual line costs at least 8 bits: an all-zero line of width w costs + // 1 + ceil(log2(ceil(w/4) + 1)) bits, >= 8 for w >= 253, and real plane widths are >= 2496. match lines.checked_sub(2) { Some(s @ 0..=5) => Ok(s as u8), _ => Err(unsupported("first-half row count outside 2..=7")), @@ -465,7 +467,7 @@ pub(crate) fn curve(code12: i32) -> u16 { /// Colour reconstruction (spec *Colour reconstruction*, checked against Phase 0 oracle output): the planes give a /// `(2 W2) x (2 H2)` mosaic with R at (0,0), G1 (0,1), G2 (1,0), B (1,1) of every 2x2 cell, each value passed through /// [`curve`]. G1 comes from the green mean minus a residual average, G2 is predicted from the (unclipped) G1 plus the -/// residual, and R/B are chroma plus the mean of the greens clipped to 12 bits. +/// residual, and R/B are chroma plus the mean of the greens clamped to 0..=4095. pub(crate) fn colour(p: &TilePlanes) -> Result> { let (w2, h2) = (p.m.width, p.m.height); let len = w2.checked_mul(h2).ok_or_else(|| corrupt("tile size"))?; @@ -493,7 +495,7 @@ pub(crate) fn colour(p: &TilePlanes) -> Result> { for x in 0..w2 { let xp = x.saturating_sub(1); let g2 = ((g(j, xp) + g(j, x) + g(jn, xp) + g(jn, x)) >> 2) + at(&p.res, j, x); - let mean = (g(j, x).min(4095) + g2.min(4095)) >> 1; + let mean = (g(j, x).clamp(0, 4095) + g2.clamp(0, 4095)) >> 1; let r = 2 * at(&p.c1, j, x) + mean; let b = 2 * at(&p.c2, j, x) + mean; let cells = [(0, r), (1, g(j, x)), (mw, g2), (mw + 1, b)]; @@ -821,8 +823,8 @@ mod tests { let (mut tile, _) = one_tile(64, 48, 3, Qis::REAL); for (i, b) in flips { let i = i % tile.len(); tile[i] ^= b; } let n = cut % (tile.len() + 1); - let _ = decode_tile_planes(&tile[..n], 64, 48); - let _ = decode_tile_planes(&tile, 64, 48); + let _ = decode_tile(&tile[..n], 64, 48); + let _ = decode_tile(&tile, 64, 48); } } @@ -876,6 +878,25 @@ mod tests { assert_eq!(out[2], curve(3304)); // R = 2*(-10) + ((4095 + 2554) >> 1): chroma uses the clipped greens } + #[test] + fn colour_clamps_negative_greens() { + let p = TilePlanes { + m: plane(2, &[10, 2048, 2048, 2048]), + res: plane(2, &[100, 100, 0, 0]), + c1: plane(2, &[7, 0, 0, 0]), + c2: plane(2, &[-3, 0, 0, 0]), + }; + let g1_00 = 10 - ((400 + 4) >> 3); // -40 + let g1_10 = 2048 - ((200 + 4) >> 3); + let g2_00 = ((2 * g1_00 + 2 * g1_10) >> 2) + 100; + assert!(g1_00 < 0); + let mean = g2_00.clamp(0, 4095) >> 1; // G1 contributes 0 + let out = colour(&p).unwrap(); + assert_eq!(out[0], curve(14 + mean)); + assert_eq!(out[1], curve(0)); // G1 itself clamps + assert_eq!(out[2 * 2 + 1], curve(-6 + mean)); // B at (0,0): row 1, col 1 of a 4-wide mosaic + } + #[test] fn decode_header_and_full_and_truncations() { let (tile, _) = one_tile(64, 48, 3, Qis::REAL); @@ -928,13 +949,26 @@ mod tests { } #[test] - fn data_derived_white_is_not_doubled() { + fn arw6_white_without_tag_is_32766() { let (tile, _) = one_tile(64, 48, 0, Qis::ZERO); let file = arw6_file_no_white(&[(0, 0, 64, 48, tile)], 64, 48); let img = crate::decode(&file).unwrap(); - let crate::RawData::U16(ref d) = img.data else { panic!() }; - assert_eq!(img.white, vec![super::super::white_from_data(d, 16)]); - assert!(img.white[0] <= 65535.0); + assert_eq!(img.white, [32766.0]); + } + + #[test] + fn twelve_bit_mode_is_unsupported() { + let (tile, _) = one_tile(64, 48, 0, Qis::ZERO); + let file = arw6_file_bits(&[(0, 0, 64, 48, tile)], 64, 48, 12); + assert!(matches!(crate::decode(&file), Err(RawError::Unsupported(_)))); + } + + #[test] + fn shift_out_of_range_is_unsupported() { + let (w2, h2) = (32, 24); + let (m, c1, c2, res) = planes(w2, h2, 7); + let tile = encode_tile(&TileSpec { s: 6, qi: Qis::ZERO, m, c1, c2, res }); + assert!(matches!(decode_tile_planes(&tile, 64, 48), Err(RawError::Unsupported(_)))); } #[test] diff --git a/crates/raw/src/vendor/arw6_testenc.rs b/crates/raw/src/vendor/arw6_testenc.rs index d7f51d2f..59dfa90a 100644 --- a/crates/raw/src/vendor/arw6_testenc.rs +++ b/crates/raw/src/vendor/arw6_testenc.rs @@ -378,15 +378,20 @@ pub(crate) fn encode_tile(t: &TileSpec) -> Vec { /// A little-endian ARW6 TIFF: IFD0 (Sony, ILCE-7RM6) + a SubIFD with the strip = tile table, zero padding to 512, /// then the tiles `(x, y, w, h, bytes)` back to back. pub(crate) fn arw6_file(tiles: &[(usize, usize, usize, usize, Vec)], width: usize, height: usize) -> Vec { - arw6_file_with(tiles, width, height, true) + arw6_file_with(tiles, width, height, true, 14) +} + +/// [`arw6_file`] with another BitsPerSample. +pub(crate) fn arw6_file_bits(tiles: &[(usize, usize, usize, usize, Vec)], width: usize, height: usize, bits: u16) -> Vec { + arw6_file_with(tiles, width, height, true, bits) } /// [`arw6_file`] without the WhiteLevel tag. pub(crate) fn arw6_file_no_white(tiles: &[(usize, usize, usize, usize, Vec)], width: usize, height: usize) -> Vec { - arw6_file_with(tiles, width, height, false) + arw6_file_with(tiles, width, height, false, 14) } -fn arw6_file_with(tiles: &[(usize, usize, usize, usize, Vec)], width: usize, height: usize, white: bool) -> Vec { +fn arw6_file_with(tiles: &[(usize, usize, usize, usize, Vec)], width: usize, height: usize, white: bool, bits: u16) -> Vec { let mut strip = (tiles.len() as u32).to_le_bytes().to_vec(); strip.extend([0; 4]); let mut offset = 512u64; @@ -405,7 +410,7 @@ fn arw6_file_with(tiles: &[(usize, usize, usize, usize, Vec)], width: usize, raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); raw.set(t::IMAGE_WIDTH, Value::Long(vec![width as u32])); raw.set(t::IMAGE_LENGTH, Value::Long(vec![height as u32])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![14])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![bits])); raw.set(t::COMPRESSION, Value::Short(vec![32766])); raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA])); raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); From fa7f1e8d6c737010521ee3b6e2199d8cd7329915 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 01:58:36 +0200 Subject: [PATCH 16/21] LR-IMP-FORMATS: ARW6 docs after the final review --- docs/arw6-compression.md | 16 +++++++++------- docs/parity-checklist.md | 2 +- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/arw6-compression.md b/docs/arw6-compression.md index 968c47b8..95698799 100644 --- a/docs/arw6-compression.md +++ b/docs/arw6-compression.md @@ -35,14 +35,14 @@ With plane row j, column x (x +- 1 clamped at the edges), in 12-bit code units: - `G1[j][x] = M[j][x] - ((res[j-1][x] + res[j-1][x+1] + res[j][x] + res[j][x+1] + 4) >> 3)`, with `res[-1] := res[0]`. - `G2[j][x] = ((G1[j][x-1] + G1[j][x] + G1[j+1][x-1] + G1[j+1][x]) >> 2) + res[j][x]` (unclipped G1; the last row uses G1[j] for G1[j+1]). -- `R = 2*c1 + ((min(G1, 4095) + min(G2, 4095)) >> 1)`, `B = 2*c2 + (same)`. +- `R = 2*c1 + ((clamp(G1, 0, 4095) + clamp(G2, 0, 4095)) >> 1)`, `B = 2*c2 + (same)` (a negative green, as in deep high-ISO shadows, counts as 0). - Every code is clipped to 0..4095. Per 2x2 cell: R (0,0), G1 (0,1), G2 (1,0), B (1,1). ### Output range (companding table) - Codes map through one monotone table shared by all files: identity up to code 1427, then a smooth curve reaching 39002 at code 4095 (steps grow from 1 to 58). No closed form fits within +-22, so `arw6_curve.rs` embeds the table (2668 `u16` values from code 1428). It is not stored in the file. - Provenance: the table was read off the black-box oracle's (LibRaw, below) output over the 8 Compressed / HQ files; every code from 1027 to 4095 occurred and no two files disagreed. It is therefore a measurement of that program's output, not an independent derivation. -- Unit: 2 x 14-bit DN. The decoder reports black = 2 x 512 = 1024 and white = 2 x the file's DNG `WhiteLevel` (16383), i.e. 32766; saturated highlights sit at code 4095 = 39002, above white, and clip as usual. If a file carries no usable white level, a data-derived fallback already in output units is used. +- Unit: 2 x 14-bit DN. The decoder reports black = 2 x 512 = 1024 and white = 2 x the file's DNG `WhiteLevel` (16383), i.e. 32766; saturated highlights sit at code 4095 = 39002, above white, and clip as usual. If a file carries no usable white level, the white is 32766 (2 x 16383, the table's knot below), not a data-derived value. - The table has one knot: at code 3977 it runs 32679 -> 32766 -> 32777 (steps +87 then +11), the same in every file. 32766 = 2 x 16383 is exactly the reported white level, so the knot is the white point of the measured curve (inferred from the arithmetic, not from any documentation): codes 3978..4095 sit above white and clip. ## Verification @@ -53,7 +53,7 @@ Geometry was checked against each file's embedded full-resolution JPEG at the De ### LibRaw's APS-C bug -LibRaw assumes the full-frame grid (s = 0) for every tile. On the APS-C crop that drops the first three plane rows, leaves the last three unfed, and shifts its whole output up by 6 sensor rows; its first rows and last rows are also wrong. Our decoder differs from LibRaw there on purpose. To compare against LibRaw on APS-C files, shift its output by 6 rows and skip its first 16 and last 20 rows; on full frame compare directly. +LibRaw assumes the full-frame grid (s = 0) for every tile. On the APS-C crop that drops the first three plane rows, leaves the last three unfed, and shifts its whole output up by 6 sensor rows; its first rows and last rows are also wrong. Our decoder differs from LibRaw there on purpose. To compare against LibRaw on APS-C files, our row y+6 equals LibRaw's row y for 12 <= y < h - 24 (LibRaw's rows 0-11 and the last 18 rows of the shifted overlap differ); on full frame compare directly, the whole frame is exact. ### Corpus @@ -72,9 +72,9 @@ LibRaw assumes the full-frame grid (s = 0) for every tile. On the APS-C crop tha | `arw-sony-ilce7rm6-ff-land-lossless.arw` | `raw_modes/ILCE-7RM6_FF_land_RAW.ARW` | 100 851 712 | `5cb3c870bc961cf6b079d56c860d0cdf11acd1afd04e5fb8dbe041bcfd2d6201` | | `arw-sony-ilce7rm6-ff-port-lossless.arw` | `raw_modes/ILCE-7RM6_FF_port_RAW.ARW` | 100 884 480 | `b1a4026aa6adbaa27973b8b3426d8b4aa0c1cae1845cf5102359327d3b069691` | -These 12 files are CC0 1.0 per the RawDB record of the set (uploaded by abbradar; ); the server answers 303 to a signed object URL, so fetch with `curl -L` from `https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/`. They live in the gitignored corpus; `cargo xtask corpus --download` fetches them and [arw6-corpus.sha256](arw6-corpus.sha256) pins their identities. `cargo test -p lightcraft-raw corpus_sony -- --nocapture` verifies each available file's checksum, then the decoder's sensor sum and position-weighted sum. The first 8 rows (ARW6) are checked against the Phase 0 reference sums; the 4 lossless siblings go through the existing LJ92 path and their sums are regression values from LightCraft's own decoder. The test skips absent files. +These 12 files are CC0 1.0 per the RawDB record of the set (uploaded by abbradar; ); the server answers 303 to a signed object URL, so fetch with `curl -L` from `https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/`. They live in the gitignored corpus; `cargo xtask corpus --download` fetches them and [arw6-corpus.sha256](arw6-corpus.sha256) pins their identities. `cargo test -p lightcraft-raw corpus_sony -- --nocapture` verifies each available file's checksum, then the decoder's sensor sum and position-weighted sum. The 8 ARW6 files are checked against the Phase 0 reference sums; the 4 lossless siblings go through the existing LJ92 path and their sums are regression values from LightCraft's own decoder. The test skips absent files. -Nine further full-frame HQ photos from the maintainer's A7R VI were compared with the oracle locally; they are private and never committed or published. +Nine further full-frame HQ photos from the maintainer's A7R VI were compared with the oracle locally; they are private and never committed or published. All 9 private FF photos (ISO 100-12800, incl. two near-black night shots) decode bit-exact over the full frame (0 mismatching pixels of 66.8 MP each). Unconditional synthetic tests (encode -> decode round trips for both geometries, the RDD 34 worked example, the dequantiser, hostile and truncated input) run without the corpus. @@ -83,9 +83,9 @@ Unconditional synthetic tests (encode -> decode round trips for both geometries, | Coverage | Status | |---|---| | ILCE-7RM6 Compressed and HQ, full frame, landscape and portrait | 4 files, exact against the reference sums | -| ILCE-7RM6 Compressed and HQ, APS-C crop, landscape and portrait | 4 files, exact (with LibRaw only after the 6-row shift) | +| ILCE-7RM6 Compressed and HQ, APS-C crop, landscape and portrait | 4 files, exact against the reference sums (interior-exact against LibRaw after the 6-row shift; LibRaw's own edge rows differ) | | ILCE-7RM6 lossless (existing LJ92 path) | 4 files, regression values | -| Private A7R VI HQ photos | 9 files, compared locally | +| Private A7R VI HQ photos | 9 files, bit-exact over the full frame against the oracle (local) | ## Not covered @@ -93,6 +93,8 @@ Unconditional synthetic tests (encode -> decode round trips for both geometries, - The ILCE-7M5: same codec, no sample; unverified. - The x2 scale is an assumption backed by shadow-floor evidence (the darkest pixels of all eight ISO 100 files sit at 1037..1059, just above 2 x 512, and the lossless sibling's shadows match at x2; x2.38 would put them 76 DN below black). A tripod-matched lossless / compressed pair would confirm it. If wrong, only the reported black and white levels change. - Tiles whose plane width is not a multiple of 8. +- First-half shifts other than 0 and 3 (other crops / bodies): the geometry is generic and round-trip tested, but no real sample exists. +- Memory: one FF decode peaks at about 896 MB RSS (about 6.7 x the 134 MB output; the lossless path peaks at 249 MB). Follow-ups: dequantise straight into bands, place tiles as they arrive. - Colour: the ILCE-7RM6 bundled colour profile and Sony's embedded lens corrections are separate work. ## Sources diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 17d2b0c2..46199a90 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -80,7 +80,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate, photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop; masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs; Adobe profile formats deliberately unsupported | | LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); browsed photos stay out of All Photos, albums and counts; folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back; a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | -| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG, PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP; DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared linear primaries without clipping or gamut mapping, checked on one real file with 108 lossy tiles, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`, 8 CC0 files bit-exact against a black-box oracle and against the Phase 0 reference sums, geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth but CFA and black unverified), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8 (`crates/raw/tests/cr3_corpus.rs`, `docs/cr3.md`). Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), NEFs labelled compressed (34713) but stored uncompressed without a `0x0096` table (Z 6 packed 14-bit, D850 12-bit uncompressed), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and Kodak DCS TIFFs: IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Canon CRW, Minolta MRW and Sigma X3F (containers recognised by magic, preview found by a structural JPEG scan), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan), and any decode failure of a recognised raw, not only an unsupported variant; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate) | +| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG, PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP; DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared linear primaries without clipping or gamut mapping, checked on one real file with 108 lossy tiles, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`, FF files bit-exact over the full frame, APS-C files interior-exact (LibRaw's own edge rows differ); 8 CC0 files checked against a black-box oracle and the Phase 0 reference sums, geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth but CFA and black unverified), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8 (`crates/raw/tests/cr3_corpus.rs`, `docs/cr3.md`). Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), NEFs labelled compressed (34713) but stored uncompressed without a `0x0096` table (Z 6 packed 14-bit, D850 12-bit uncompressed), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and Kodak DCS TIFFs: IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Canon CRW, Minolta MRW and Sigma X3F (containers recognised by magic, preview found by a structural JPEG scan), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan), and any decode failure of a recognised raw, not only an unsupported variant; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate) | | LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/corpus.rs`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535; pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 sensor arrays verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; private Z 8 crop verified. | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | | LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests_import_move.rs`, `crates/ui-egui/src/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving | From 1be303ca00459161f3cdca905e0d60cfbb43a197 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 12:54:01 +0200 Subject: [PATCH 17/21] LR-IMP-FORMATS: ARW6 corpus hashes live in RAW_SAMPLES; drop docs/arw6-corpus.sha256 The RawDB entries in xtask carry their SHA-256 as the third field, which `cargo xtask corpus --download` checks; the corpus test keeps only the sensor sum checks. Co-Authored-By: Claude --- crates/raw/tests/corpus.rs | 16 +++++----------- docs/arw6-compression.md | 2 +- docs/arw6-corpus.sha256 | 14 -------------- 3 files changed, 6 insertions(+), 26 deletions(-) delete mode 100644 docs/arw6-corpus.sha256 diff --git a/crates/raw/tests/corpus.rs b/crates/raw/tests/corpus.rs index edfd1239..cb892867 100644 --- a/crates/raw/tests/corpus.rs +++ b/crates/raw/tests/corpus.rs @@ -861,19 +861,13 @@ fn corpus_fujifilm_compressed_samples() { eprintln!("verified {seen} Fujifilm compressed sensor arrays"); } -/// Checks each available `(name, width, height, sum, weighted)` case against the pinned SHA-256 in `checksums` -/// and the decoder's sensor array; absent corpus files are skipped. Returns how many were verified. -fn verify_sensor_arrays(checksums: &str, cases: &[(&str, usize, usize, u64, u64)]) -> usize { - use sha2::{Digest, Sha256}; +/// Checks each available `(name, width, height, sum, weighted)` case against the decoder's sensor array (the file's +/// identity is checked by `cargo xtask corpus --download`); absent corpus files are skipped. Returns how many were verified. +fn verify_sensor_arrays(cases: &[(&str, usize, usize, u64, u64)]) -> usize { let dir = corpus_root().join("raw"); let mut seen = 0; for &(name, width, height, sum, weighted) in cases { - let path = format!("corpus/raw/{name}"); - let checksum = checksums.lines().filter_map(|s| s.split_once(" ")).find(|(_, p)| *p == path).unwrap().0; - assert_eq!(checksum.len(), 64, "{name}: missing published SHA-256"); let Ok(bytes) = std::fs::read(dir.join(name)) else { continue }; - let actual_sha: String = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect(); - assert_eq!(actual_sha, checksum, "{name}: corpus file differs from its pinned identity"); let img = decode(&bytes).unwrap_or_else(|e| panic!("{name}: {e}")); assert_eq!((img.width, img.height), (width, height), "{name}"); let lightcraft_raw::RawData::U16(data) = img.data else { panic!("{name}: float data") }; @@ -900,7 +894,7 @@ fn corpus_sony_arw6_samples() { ("arw6-sony-ilce7rm6-ff-port-hq.arw", 10016, 6672, 242772794178, 8043470668590476975), ("arw6-sony-ilce7rm6-ff-port-c.arw", 10016, 6672, 241868995482, 8014659803009871380), ]; - let seen = verify_sensor_arrays(include_str!("../../../docs/arw6-corpus.sha256"), cases); + let seen = verify_sensor_arrays(cases); eprintln!("verified {seen} Sony ARW6 sensor arrays"); } @@ -914,7 +908,7 @@ fn corpus_sony_ilce7rm6_lossless_samples() { ("arw-sony-ilce7rm6-ff-land-lossless.arw", 10240, 7168, 128728791716, 4922490451480041632), ("arw-sony-ilce7rm6-ff-port-lossless.arw", 10240, 7168, 120718314835, 4098302368966213583), ]; - let seen = verify_sensor_arrays(include_str!("../../../docs/arw6-corpus.sha256"), cases); + let seen = verify_sensor_arrays(cases); eprintln!("verified {seen} Sony ILCE-7RM6 lossless sensor arrays"); } diff --git a/docs/arw6-compression.md b/docs/arw6-compression.md index 95698799..9f263051 100644 --- a/docs/arw6-compression.md +++ b/docs/arw6-compression.md @@ -72,7 +72,7 @@ LibRaw assumes the full-frame grid (s = 0) for every tile. On the APS-C crop tha | `arw-sony-ilce7rm6-ff-land-lossless.arw` | `raw_modes/ILCE-7RM6_FF_land_RAW.ARW` | 100 851 712 | `5cb3c870bc961cf6b079d56c860d0cdf11acd1afd04e5fb8dbe041bcfd2d6201` | | `arw-sony-ilce7rm6-ff-port-lossless.arw` | `raw_modes/ILCE-7RM6_FF_port_RAW.ARW` | 100 884 480 | `b1a4026aa6adbaa27973b8b3426d8b4aa0c1cae1845cf5102359327d3b069691` | -These 12 files are CC0 1.0 per the RawDB record of the set (uploaded by abbradar; ); the server answers 303 to a signed object URL, so fetch with `curl -L` from `https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/`. They live in the gitignored corpus; `cargo xtask corpus --download` fetches them and [arw6-corpus.sha256](arw6-corpus.sha256) pins their identities. `cargo test -p lightcraft-raw corpus_sony -- --nocapture` verifies each available file's checksum, then the decoder's sensor sum and position-weighted sum. The 8 ARW6 files are checked against the Phase 0 reference sums; the 4 lossless siblings go through the existing LJ92 path and their sums are regression values from LightCraft's own decoder. The test skips absent files. +These 12 files are CC0 1.0 per the RawDB record of the set (uploaded by abbradar; ); the server answers 303 to a signed object URL, so fetch with `curl -L` from `https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/`. They live in the gitignored corpus; `cargo xtask corpus --download` fetches them and checks each against its SHA-256, pinned in `RAW_SAMPLES` (`xtask/src/main.rs`). `cargo test -p lightcraft-raw corpus_sony -- --nocapture` verifies the decoder's sensor sum and position-weighted sum of each available file. The 8 ARW6 files are checked against the Phase 0 reference sums; the 4 lossless siblings go through the existing LJ92 path and their sums are regression values from LightCraft's own decoder. The test skips absent files. Nine further full-frame HQ photos from the maintainer's A7R VI were compared with the oracle locally; they are private and never committed or published. All 9 private FF photos (ISO 100-12800, incl. two near-black night shots) decode bit-exact over the full frame (0 mismatching pixels of 66.8 MP each). diff --git a/docs/arw6-corpus.sha256 b/docs/arw6-corpus.sha256 deleted file mode 100644 index 30e80de0..00000000 --- a/docs/arw6-corpus.sha256 +++ /dev/null @@ -1,14 +0,0 @@ -# Sony ILCE-7RM6 ARW files (ARW6 Compressed / HQ and lossless siblings); CC0 1.0, RawDB (rawdb.dnglab.org), uploaded by abbradar. -# SHA-256 values verified 2026-10-09; see docs/arw6-compression.md. -b60a7e752d2a8102ccbe6eebcfdbf533c6b0f2545739090873e9e8eb32cc0637 corpus/raw/arw6-sony-ilce7rm6-apsc-land-hq.arw -1c803304e63ec508b2b5f9d59d4a7e30ed279315b35fa4c5d75f959bed62198b corpus/raw/arw6-sony-ilce7rm6-apsc-land-c.arw -0b6d782571e86868670f613de9fa1f1364623b24fbfd21b704b2c516d7a1c1cb corpus/raw/arw6-sony-ilce7rm6-apsc-port-hq.arw -c41674a485ffcf6d873e20e545ae62936192d94e95be3d53548e93bc543ecfd4 corpus/raw/arw6-sony-ilce7rm6-apsc-port-c.arw -559fa26501d7813e56afecde2aea3d9965a99228162b194752d986193abb172c corpus/raw/arw6-sony-ilce7rm6-ff-land-hq.arw -d900d6cbe838be864269ad54de4a33fcac7eb3a3d4f91009739f770b8f85a23b corpus/raw/arw6-sony-ilce7rm6-ff-land-c.arw -81c709633cb8f6340e612c3f53bb6ec6b0cccfe5b713c67efb1e977ece9e266d corpus/raw/arw6-sony-ilce7rm6-ff-port-hq.arw -f4448485629c3f82ff1955fd046404350e9a1f09b346038574b89c074d7c50fd corpus/raw/arw6-sony-ilce7rm6-ff-port-c.arw -7aaf0b3941509d7364a6f03844783155ebc912d246d1c456e5cdb4693ec09fbc corpus/raw/arw-sony-ilce7rm6-apsc-land-lossless.arw -0f011933ee96525a39710daa50b59d39702b4ec5934fa0206742e2128c55f366 corpus/raw/arw-sony-ilce7rm6-apsc-port-lossless.arw -5cb3c870bc961cf6b079d56c860d0cdf11acd1afd04e5fb8dbe041bcfd2d6201 corpus/raw/arw-sony-ilce7rm6-ff-land-lossless.arw -b1a4026aa6adbaa27973b8b3426d8b4aa0c1cae1845cf5102359327d3b069691 corpus/raw/arw-sony-ilce7rm6-ff-port-lossless.arw From 2f75b21ac3c0ac66d43e9e0a98dd5bdaaacb7486 Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 13:05:06 +0200 Subject: [PATCH 18/21] LR-IMP-FORMATS: ARW6 corpus pins two files (FF Compressed, APS-C HQ) `cargo xtask corpus --download` now fetches one full-frame Compressed and one APS-C Compressed HQ file (about 94 MB) instead of all 12 (about 630 MB); the corpus test checks those two and the lossless-sibling regression test is gone, since nothing would download those files. docs/arw6-compression.md keeps the full table with source paths and SHA-256, says which two xtask fetches and how to fetch the rest with `curl -L`, and records the CC0 1.0 statement of RawDB's set record (accessed 2026-10-10). Co-Authored-By: Claude --- crates/raw/tests/corpus.rs | 23 ++--------------- docs/arw6-compression.md | 34 ++++++++++++------------ xtask/src/main.rs | 53 ++------------------------------------ 3 files changed, 22 insertions(+), 88 deletions(-) diff --git a/crates/raw/tests/corpus.rs b/crates/raw/tests/corpus.rs index cb892867..3170742a 100644 --- a/crates/raw/tests/corpus.rs +++ b/crates/raw/tests/corpus.rs @@ -881,37 +881,18 @@ fn verify_sensor_arrays(cases: &[(&str, usize, usize, u64, u64)]) -> usize { seen } -/// Reference sums from the oracle-verified Phase 0 model (docs/arw6-compression.md); the files are CC0 from RawDB. +/// Reference sums from the oracle-verified Phase 0 model (docs/arw6-compression.md); the files are CC0 from RawDB, +/// one per geometry and compression mode. #[test] fn corpus_sony_arw6_samples() { let cases: &[(&str, usize, usize, u64, u64)] = &[ ("arw6-sony-ilce7rm6-apsc-land-hq.arw", 6592, 4372, 85834467900, 1323814215465139776), - ("arw6-sony-ilce7rm6-apsc-land-c.arw", 6592, 4372, 100710478599, 1516298925086164077), - ("arw6-sony-ilce7rm6-ff-land-hq.arw", 10016, 6672, 258417758289, 9667602918876623332), ("arw6-sony-ilce7rm6-ff-land-c.arw", 10016, 6672, 258558260019, 9665041696390559268), - ("arw6-sony-ilce7rm6-apsc-port-hq.arw", 6592, 4372, 126965386051, 1647947621898118992), - ("arw6-sony-ilce7rm6-apsc-port-c.arw", 6592, 4372, 122629012213, 1601616875702755341), - ("arw6-sony-ilce7rm6-ff-port-hq.arw", 10016, 6672, 242772794178, 8043470668590476975), - ("arw6-sony-ilce7rm6-ff-port-c.arw", 10016, 6672, 241868995482, 8014659803009871380), ]; let seen = verify_sensor_arrays(cases); eprintln!("verified {seen} Sony ARW6 sensor arrays"); } -/// The lossless siblings keep decoding through the LJ92 quad-tile path. Regression values from LightCraft's own -/// LJ92 path, 2026-10-10 (no independent reference). -#[test] -fn corpus_sony_ilce7rm6_lossless_samples() { - let cases: &[(&str, usize, usize, u64, u64)] = &[ - ("arw-sony-ilce7rm6-apsc-land-lossless.arw", 6656, 4608, 42685586690, 664300694689609738), - ("arw-sony-ilce7rm6-apsc-port-lossless.arw", 6656, 4608, 62443944469, 818441184988649303), - ("arw-sony-ilce7rm6-ff-land-lossless.arw", 10240, 7168, 128728791716, 4922490451480041632), - ("arw-sony-ilce7rm6-ff-port-lossless.arw", 10240, 7168, 120718314835, 4098302368966213583), - ]; - let seen = verify_sensor_arrays(cases); - eprintln!("verified {seen} Sony ILCE-7RM6 lossless sensor arrays"); -} - /// The container rule for TIFF "shells" (a small IFD0 next to a private raw block) must not touch real /// raws: every corpus file keeps the format its maker implies, and none is described as a private block. #[test] diff --git a/docs/arw6-compression.md b/docs/arw6-compression.md index 9f263051..793991a2 100644 --- a/docs/arw6-compression.md +++ b/docs/arw6-compression.md @@ -57,22 +57,24 @@ LibRaw assumes the full-frame grid (s = 0) for every tile. On the APS-C crop tha ### Corpus -| File | Source path (RawDB, ILCE-7RM6) | Size (bytes) | SHA-256 | -|---|---|---|---| -| `arw6-sony-ilce7rm6-apsc-land-hq.arw` | `arw6/ILCE-7RM6_APSC_land_RAW-C-HD.ARW` | 29 720 576 | `b60a7e752d2a8102ccbe6eebcfdbf533c6b0f2545739090873e9e8eb32cc0637` | -| `arw6-sony-ilce7rm6-apsc-land-c.arw` | `arw6/ILCE-7RM6_APSC_land_RAW-C.ARW` | 30 900 224 | `1c803304e63ec508b2b5f9d59d4a7e30ed279315b35fa4c5d75f959bed62198b` | -| `arw6-sony-ilce7rm6-apsc-port-hq.arw` | `arw6/ILCE-7RM6_APSC_port_RAW-C-HD.ARW` | 28 758 016 | `0b6d782571e86868670f613de9fa1f1364623b24fbfd21b704b2c516d7a1c1cb` | -| `arw6-sony-ilce7rm6-apsc-port-c.arw` | `arw6/ILCE-7RM6_APSC_port_RAW-C.ARW` | 29 044 736 | `c41674a485ffcf6d873e20e545ae62936192d94e95be3d53548e93bc543ecfd4` | -| `arw6-sony-ilce7rm6-ff-land-hq.arw` | `arw6/ILCE-7RM6_FF_land_RAW-C-HD.ARW` | 63 451 136 | `559fa26501d7813e56afecde2aea3d9965a99228162b194752d986193abb172c` | -| `arw6-sony-ilce7rm6-ff-land-c.arw` | `arw6/ILCE-7RM6_FF_land_RAW-C.ARW` | 63 844 352 | `d900d6cbe838be864269ad54de4a33fcac7eb3a3d4f91009739f770b8f85a23b` | -| `arw6-sony-ilce7rm6-ff-port-hq.arw` | `arw6/ILCE-7RM6_FF_port_RAW-C-HD.ARW` | 62 640 128 | `81c709633cb8f6340e612c3f53bb6ec6b0cccfe5b713c67efb1e977ece9e266d` | -| `arw6-sony-ilce7rm6-ff-port-c.arw` | `arw6/ILCE-7RM6_FF_port_RAW-C.ARW` | 63 168 512 | `f4448485629c3f82ff1955fd046404350e9a1f09b346038574b89c074d7c50fd` | -| `arw-sony-ilce7rm6-apsc-land-lossless.arw` | `raw_modes/ILCE-7RM6_APSC_land_RAW.ARW` | 44 167 168 | `7aaf0b3941509d7364a6f03844783155ebc912d246d1c456e5cdb4693ec09fbc` | -| `arw-sony-ilce7rm6-apsc-port-lossless.arw` | `raw_modes/ILCE-7RM6_APSC_port_RAW.ARW` | 43 692 032 | `0f011933ee96525a39710daa50b59d39702b4ec5934fa0206742e2128c55f366` | -| `arw-sony-ilce7rm6-ff-land-lossless.arw` | `raw_modes/ILCE-7RM6_FF_land_RAW.ARW` | 100 851 712 | `5cb3c870bc961cf6b079d56c860d0cdf11acd1afd04e5fb8dbe041bcfd2d6201` | -| `arw-sony-ilce7rm6-ff-port-lossless.arw` | `raw_modes/ILCE-7RM6_FF_port_RAW.ARW` | 100 884 480 | `b1a4026aa6adbaa27973b8b3426d8b4aa0c1cae1845cf5102359327d3b069691` | +| File | Source path (RawDB, ILCE-7RM6) | Size (bytes) | SHA-256 | Fetched by | +|---|---|---|---|---| +| `arw6-sony-ilce7rm6-apsc-land-hq.arw` | `arw6/ILCE-7RM6_APSC_land_RAW-C-HD.ARW` | 29 720 576 | `b60a7e752d2a8102ccbe6eebcfdbf533c6b0f2545739090873e9e8eb32cc0637` | `cargo xtask corpus --download` | +| `arw6-sony-ilce7rm6-apsc-land-c.arw` | `arw6/ILCE-7RM6_APSC_land_RAW-C.ARW` | 30 900 224 | `1c803304e63ec508b2b5f9d59d4a7e30ed279315b35fa4c5d75f959bed62198b` | `curl -L` | +| `arw6-sony-ilce7rm6-apsc-port-hq.arw` | `arw6/ILCE-7RM6_APSC_port_RAW-C-HD.ARW` | 28 758 016 | `0b6d782571e86868670f613de9fa1f1364623b24fbfd21b704b2c516d7a1c1cb` | `curl -L` | +| `arw6-sony-ilce7rm6-apsc-port-c.arw` | `arw6/ILCE-7RM6_APSC_port_RAW-C.ARW` | 29 044 736 | `c41674a485ffcf6d873e20e545ae62936192d94e95be3d53548e93bc543ecfd4` | `curl -L` | +| `arw6-sony-ilce7rm6-ff-land-hq.arw` | `arw6/ILCE-7RM6_FF_land_RAW-C-HD.ARW` | 63 451 136 | `559fa26501d7813e56afecde2aea3d9965a99228162b194752d986193abb172c` | `curl -L` | +| `arw6-sony-ilce7rm6-ff-land-c.arw` | `arw6/ILCE-7RM6_FF_land_RAW-C.ARW` | 63 844 352 | `d900d6cbe838be864269ad54de4a33fcac7eb3a3d4f91009739f770b8f85a23b` | `cargo xtask corpus --download` | +| `arw6-sony-ilce7rm6-ff-port-hq.arw` | `arw6/ILCE-7RM6_FF_port_RAW-C-HD.ARW` | 62 640 128 | `81c709633cb8f6340e612c3f53bb6ec6b0cccfe5b713c67efb1e977ece9e266d` | `curl -L` | +| `arw6-sony-ilce7rm6-ff-port-c.arw` | `arw6/ILCE-7RM6_FF_port_RAW-C.ARW` | 63 168 512 | `f4448485629c3f82ff1955fd046404350e9a1f09b346038574b89c074d7c50fd` | `curl -L` | +| `arw-sony-ilce7rm6-apsc-land-lossless.arw` | `raw_modes/ILCE-7RM6_APSC_land_RAW.ARW` | 44 167 168 | `7aaf0b3941509d7364a6f03844783155ebc912d246d1c456e5cdb4693ec09fbc` | `curl -L` | +| `arw-sony-ilce7rm6-apsc-port-lossless.arw` | `raw_modes/ILCE-7RM6_APSC_port_RAW.ARW` | 43 692 032 | `0f011933ee96525a39710daa50b59d39702b4ec5934fa0206742e2128c55f366` | `curl -L` | +| `arw-sony-ilce7rm6-ff-land-lossless.arw` | `raw_modes/ILCE-7RM6_FF_land_RAW.ARW` | 100 851 712 | `5cb3c870bc961cf6b079d56c860d0cdf11acd1afd04e5fb8dbe041bcfd2d6201` | `curl -L` | +| `arw-sony-ilce7rm6-ff-port-lossless.arw` | `raw_modes/ILCE-7RM6_FF_port_RAW.ARW` | 100 884 480 | `b1a4026aa6adbaa27973b8b3426d8b4aa0c1cae1845cf5102359327d3b069691` | `curl -L` | -These 12 files are CC0 1.0 per the RawDB record of the set (uploaded by abbradar; ); the server answers 303 to a signed object URL, so fetch with `curl -L` from `https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/`. They live in the gitignored corpus; `cargo xtask corpus --download` fetches them and checks each against its SHA-256, pinned in `RAW_SAMPLES` (`xtask/src/main.rs`). `cargo test -p lightcraft-raw corpus_sony -- --nocapture` verifies the decoder's sensor sum and position-weighted sum of each available file. The 8 ARW6 files are checked against the Phase 0 reference sums; the 4 lossless siblings go through the existing LJ92 path and their sums are regression values from LightCraft's own decoder. The test skips absent files. +These 12 files are CC0 1.0. RawDB's record of the set, (the data behind , accessed 2026-10-10), says `"license":"CC0 1.0"` for the set (uploaded by abbradar, 2026-08-29) and again for each of the 12 files, next to the SHA-256 values in the table. + +They live in the gitignored corpus. `cargo xtask corpus --download` fetches two of them, one per geometry and compression mode (full frame Compressed, APS-C HQ), and checks each against its SHA-256, pinned in `RAW_SAMPLES` (`xtask/src/main.rs`). Fetch the other ten by hand: the server answers 303 to a signed object URL, so `curl -L -o corpus/raw/ https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/`, then compare with the SHA-256 above. `cargo test -p lightcraft-raw corpus_sony -- --nocapture` checks the decoder's sensor sum and position-weighted sum of the two pinned files against the Phase 0 reference sums and skips absent files. Nine further full-frame HQ photos from the maintainer's A7R VI were compared with the oracle locally; they are private and never committed or published. All 9 private FF photos (ISO 100-12800, incl. two near-black night shots) decode bit-exact over the full frame (0 mismatching pixels of 66.8 MP each). @@ -84,7 +86,7 @@ Unconditional synthetic tests (encode -> decode round trips for both geometries, |---|---| | ILCE-7RM6 Compressed and HQ, full frame, landscape and portrait | 4 files, exact against the reference sums | | ILCE-7RM6 Compressed and HQ, APS-C crop, landscape and portrait | 4 files, exact against the reference sums (interior-exact against LibRaw after the 6-row shift; LibRaw's own edge rows differ) | -| ILCE-7RM6 lossless (existing LJ92 path) | 4 files, regression values | +| ILCE-7RM6 lossless (existing LJ92 path) | 4 files decode; not in the corpus test | | Private A7R VI HQ photos | 9 files, bit-exact over the full frame against the oracle (local) | ## Not covered diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 91063e74..14b71d4d 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -775,67 +775,18 @@ const RAW_SAMPLES: &[(&str, &str, &str)] = &[ "https://raw.pixls.us/getfile.php/7807/nice/Fujifilm%20-%20X-T50%20-%2014bit%20compressed%20%283:2%29.RAF", "3a8a9ac6d92274969aaa1f55ea669191b98bb8f588d00ec8ec17afd8b3963dea", ), - // Sony ILCE-7RM6: ARW6 Compressed (RAW-C) / Compressed HQ (RAW-C-HD) and the lossless siblings; CC0 1.0, RawDB. + // Sony ILCE-7RM6 ARW6, CC0 1.0 (RawDB): one full-frame Compressed (RAW-C) and one APS-C Compressed HQ (RAW-C-HD) file; + // docs/arw6-compression.md lists the rest of the set. ( "arw6-sony-ilce7rm6-apsc-land-hq.arw", "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_APSC_land_RAW-C-HD.ARW", "b60a7e752d2a8102ccbe6eebcfdbf533c6b0f2545739090873e9e8eb32cc0637", ), - ( - "arw6-sony-ilce7rm6-apsc-land-c.arw", - "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_APSC_land_RAW-C.ARW", - "1c803304e63ec508b2b5f9d59d4a7e30ed279315b35fa4c5d75f959bed62198b", - ), - ( - "arw6-sony-ilce7rm6-apsc-port-hq.arw", - "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_APSC_port_RAW-C-HD.ARW", - "0b6d782571e86868670f613de9fa1f1364623b24fbfd21b704b2c516d7a1c1cb", - ), - ( - "arw6-sony-ilce7rm6-apsc-port-c.arw", - "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_APSC_port_RAW-C.ARW", - "c41674a485ffcf6d873e20e545ae62936192d94e95be3d53548e93bc543ecfd4", - ), - ( - "arw6-sony-ilce7rm6-ff-land-hq.arw", - "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_FF_land_RAW-C-HD.ARW", - "559fa26501d7813e56afecde2aea3d9965a99228162b194752d986193abb172c", - ), ( "arw6-sony-ilce7rm6-ff-land-c.arw", "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_FF_land_RAW-C.ARW", "d900d6cbe838be864269ad54de4a33fcac7eb3a3d4f91009739f770b8f85a23b", ), - ( - "arw6-sony-ilce7rm6-ff-port-hq.arw", - "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_FF_port_RAW-C-HD.ARW", - "81c709633cb8f6340e612c3f53bb6ec6b0cccfe5b713c67efb1e977ece9e266d", - ), - ( - "arw6-sony-ilce7rm6-ff-port-c.arw", - "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_FF_port_RAW-C.ARW", - "f4448485629c3f82ff1955fd046404350e9a1f09b346038574b89c074d7c50fd", - ), - ( - "arw-sony-ilce7rm6-apsc-land-lossless.arw", - "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/raw_modes/ILCE-7RM6_APSC_land_RAW.ARW", - "7aaf0b3941509d7364a6f03844783155ebc912d246d1c456e5cdb4693ec09fbc", - ), - ( - "arw-sony-ilce7rm6-apsc-port-lossless.arw", - "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/raw_modes/ILCE-7RM6_APSC_port_RAW.ARW", - "0f011933ee96525a39710daa50b59d39702b4ec5934fa0206742e2128c55f366", - ), - ( - "arw-sony-ilce7rm6-ff-land-lossless.arw", - "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/raw_modes/ILCE-7RM6_FF_land_RAW.ARW", - "5cb3c870bc961cf6b079d56c860d0cdf11acd1afd04e5fb8dbe041bcfd2d6201", - ), - ( - "arw-sony-ilce7rm6-ff-port-lossless.arw", - "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/raw_modes/ILCE-7RM6_FF_port_RAW.ARW", - "b1a4026aa6adbaa27973b8b3426d8b4aa0c1cae1845cf5102359327d3b069691", - ), ( "rw2-panasonic-g9-b.rw2", "https://raw.pixls.us/getfile.php/2348/nice/Panasonic%20-%20DC-G9%20-%204:3.RW2", From 2218a53f2bb611d30c81d9ef4e183a0e629e5fba Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 13:13:03 +0200 Subject: [PATCH 19/21] LR-IMP-FORMATS: ARW6 module docs cite docs/arw6-compression.md docs/superpowers/ held the working spec and plan, which pointed at the local plan/ folder. The ARW6 module docs now cite the sections of docs/arw6-compression.md, which gains the facts they relied on from the spec: the NP field of word 0, the stream header word layout and how the first half's residual lines are counted. Co-Authored-By: Claude --- crates/raw/src/vendor/arw6.rs | 21 +++++++++++---------- crates/raw/src/vendor/arw6_testenc.rs | 7 ++++--- docs/arw6-compression.md | 6 +++--- 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index 26387b41..e583a676 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -2,8 +2,8 @@ //! //! Clean-room. The layout comes from SMPTE RDD 34 (Picture_info in word 0) and from Phase 0 black-box //! inspection of real ILCE-7RM6 files (tile table, group size words, stream headers and index entries), each rule -//! checked by re-serialising parsed tiles byte-for-byte; see `docs/superpowers/specs/2026-10-09-sony-arw6-decoder-design.md` -//! (*Container (Sony)*). No other raw decoder's source was consulted. +//! checked by re-serialising parsed tiles byte-for-byte. The format is described in `docs/arw6-compression.md`; section +//! names in italics below refer to it. No other raw decoder's source was consulted. use crate::llvc::{Bands3, Plane, band_rows, dequant, reconstruct3, vld_decode_line}; use crate::vendor::arw6_curve::{ARW6_CURVE, CURVE_KNEE}; @@ -48,7 +48,7 @@ pub(crate) struct TileEntry { /// Most tiles a strip may hold (real files have 1 or 4). const MAX_TILES: usize = 16; -/// Parse the tile table at the start of the strip (file structure, spec *Container*): `u32` count, `u32` 0, then +/// Parse the tile table at the start of the strip (file structure, *Container*): `u32` count, `u32` 0, then /// 24-byte entries `u64` offset (relative to the strip), `u32` x, y, width, height, all little-endian. pub(crate) fn parse_tile_table(strip: &[u8], width: usize, height: usize) -> Result> { let count = u32_le(strip, 0).ok_or_else(|| corrupt("truncated tile table"))?; @@ -136,7 +136,7 @@ fn field(w: &[u8], pos: usize, n: usize) -> Option { const GROUP_STREAMS: [usize; 5] = [3, 3, 3, 3, 1]; /// Parse word 0 (RDD 34 `Picture_info`; every real file has HS = tile width, VS = tile height / 2, BBD 16, NC 3, NW 3, -/// NP 1000000000b), the group size words 3..=7 and each stream's header word (spec *Container*, Phase 0). +/// NP 1000000000b), the group size words 3..=7 and each stream's header word (*Container*, Phase 0). pub(crate) fn parse_tile_header(tile: &[u8], tw: usize, th: usize) -> Result { let w0 = tile.get(..16).ok_or_else(|| corrupt("tile shorter than its picture header"))?; let f = |pos, n| field(w0, pos, n).map(|v| v as usize); @@ -218,10 +218,10 @@ pub(crate) fn stream_halves(tile: &[u8], s: &StreamRef, ntu: usize) -> Result usize { let halves = vs.saturating_sub(2usize.saturating_add(usize::from(s))).div_ceil(8).saturating_add(1); halves.div_ceil(2) @@ -246,7 +246,7 @@ pub(crate) fn half_rows(n: usize, s: u8, rows: usize) -> Range { /// First half's frame rows `lines - 2`, read before the TU count is known from g4's first index entry alone /// (index table at word `g4.word + 1`, entry 0's `A` = big-endian u16; its bytes start after the index table). -/// Residual lines are decoded while at least 8 bits remain and fewer than 8 lines were read (spec *Frame geometry*). +/// Residual lines are decoded while at least 8 bits remain and fewer than 8 lines were read (*Frame geometry*). pub(crate) fn first_half_shift(tile: &[u8], g4: &StreamRef, width2: usize) -> Result { let idx = g4.word.checked_add(1).and_then(|w| w.checked_mul(16)).ok_or_else(|| corrupt("stream position"))?; let data = g4.index_words.checked_mul(16).and_then(|l| l.checked_add(idx)).ok_or_else(|| corrupt("stream position"))?; @@ -365,7 +365,7 @@ fn put(plane: &mut Plane, row: usize, line: &[i32], mut f: impl FnMut(i32) -> i3 Ok(()) } -/// Lay a half's lines into (band, rows, QI) in order: the natural clipped assignment of spec *Frame geometry*. +/// Lay a half's lines into (band, rows, QI) in order: the natural clipped assignment of *Frame geometry*. fn fill(set: [(&mut Plane, &[usize], u32); 3], lines: &[Vec]) -> Result<()> { let mut it = lines.iter(); for (plane, rows, qi) in set { @@ -398,7 +398,8 @@ fn component(c: usize, streams: &[Vec], layouts: &[HalfRows], vs: usi let grp = |g: usize, n: usize| streams.get(3 * g + c).and_then(|s| s.get(n)).ok_or_else(|| corrupt("missing half")); for (n, r) in layouts.iter().enumerate() { let (h0, l0) = grp(0, n)?; - // LL3: the nibble must be 0 (Phase 0: never seen otherwise); lines are DPCM from 2048 for the green mean (c = 0) and from 0 for the base-free chroma planes (spec *Container*). + // LL3: the nibble must be 0 (Phase 0: never seen otherwise); lines are DPCM from 2048 for the green mean (c = 0) and + // from 0 for the base-free chroma planes (*Entropy coding and dequantisation*). if h0.qi[0] != 0 { return Err(unsupported("LL3 quantiser index")); } @@ -464,7 +465,7 @@ pub(crate) fn curve(code12: i32) -> u16 { } } -/// Colour reconstruction (spec *Colour reconstruction*, checked against Phase 0 oracle output): the planes give a +/// Colour reconstruction (*Colour reconstruction*, checked against Phase 0 oracle output): the planes give a /// `(2 W2) x (2 H2)` mosaic with R at (0,0), G1 (0,1), G2 (1,0), B (1,1) of every 2x2 cell, each value passed through /// [`curve`]. G1 comes from the green mean minus a residual average, G2 is predicted from the (unclipped) G1 plus the /// residual, and R/B are chroma plus the mean of the greens clamped to 0..=4095. diff --git a/crates/raw/src/vendor/arw6_testenc.rs b/crates/raw/src/vendor/arw6_testenc.rs index 59dfa90a..54933112 100644 --- a/crates/raw/src/vendor/arw6_testenc.rs +++ b/crates/raw/src/vendor/arw6_testenc.rs @@ -1,4 +1,5 @@ //! Test-only ARW6 synthetic encoder pieces: forward 5/3 transforms (exact inverse of `llvc::inverse_*`) and `quantize`. +//! Section names in italics refer to `docs/arw6-compression.md`. use crate::llvc::{Bands3, Plane, band_rows}; use lightcraft_tiff::tags as t; @@ -217,11 +218,11 @@ pub(crate) struct Qis { impl Qis { pub(crate) const ZERO: Qis = Qis { l1: [[0; 3]; 3], l2: [[0; 3]; 3], l3: [[0; 3]; 3], res: 0 }; - /// The values seen in every real file (spec *Container*). + /// The values seen in every real file (*Container*). pub(crate) const REAL: Qis = Qis { l1: [[1, 1, 2], [2, 2, 3], [2, 2, 3]], l2: [[0, 0, 1]; 3], l3: [[0; 3]; 3], res: 2 }; } -/// One tile to encode: `s` is the anchor offset (spec *Frame geometry*), planes are W/2 x H/2. +/// One tile to encode: `s` is the anchor offset (*Frame geometry*), planes are W/2 x H/2. pub(crate) struct TileSpec { pub s: u8, pub qi: Qis, @@ -287,7 +288,7 @@ fn build_stream(halves: &[(Vec, Vec)]) -> Vec { } /// Encode one tile: forward 3-level 5/3 per component with the phases of `s`, quantise, pack every half in natural -/// clipped order (spec *Frame geometry*), then add index tables, stream headers and the tile header. +/// clipped order (*Frame geometry*), then add index tables, stream headers and the tile header. pub(crate) fn encode_tile(t: &TileSpec) -> Vec { let (vs, s) = (t.m.height, i32::from(t.s)); let ntu = crate::vendor::arw6::tu_count(vs, t.s); diff --git a/docs/arw6-compression.md b/docs/arw6-compression.md index 793991a2..80c21f8d 100644 --- a/docs/arw6-compression.md +++ b/docs/arw6-compression.md @@ -12,8 +12,8 @@ The codec is Sony's use of SMPTE RDD 34 (LLVC, Low Latency Video Codec). `crates - Raw SubIFD: Compression 32766, 14 bits per sample, BlackLevel 512 x4 (`0x7310`), WB `0x7313`, crop `0x74c7/0x74c8` (full frame: origin 12,8, size 9984x6656; APS-C: origin 16,10, size 6528x4352), CFA RGGB. The Sony tag-based white level (15360) is not read; the DNG `WhiteLevel` is (16383). - The single strip starts with a tile table: `u32` count, `u32` 0, then per tile a `u64` offset (relative to the strip) and `u32` x, y, width, height. Seen: full frame 4 tiles of 5008x3336 (HQ) or 5024 / 4992 wide (Compressed); APS-C (6592x4372) one tile. A 480-byte block follows the table (not interpreted, not needed). -- A tile is a sequence of 16-byte words. Word 0 is RDD 34 `Picture_info` (HS = tile width, VS = tile height / 2, BBD = 16, NC = 3, NW = 3). Word 1 holds five `u24` group byte-sums, word 2 is zero, words 3-7 describe the groups (a count byte, then `u24` stream sizes in words). Groups: g0 = LL3 (3 streams, one per component), g1 / g2 / g3 = level-3 / 2 / 1 bands (3 streams each), g4 = green residual (1 stream). Streams follow in that order from word 8. -- A stream is a header word, an index table and data, each padded to a word. The index has one entry per transform unit (TU): `A(16) X B(16) X`, where A and B are the byte lengths of the TU's two halves and X are quantiser-index (QI) nibbles (one for g0 and g4, three for g1-g3: HL, LH, HH). Halves per tile = ceil((VS - 2 - s) / 8) + 1 with s the first-half shift (below), TUs = ceil(halves / 2): 105 and 137 for the sample sizes. Halves are numbered n = 2 * TU + h; each is byte-aligned and consecutive halves are contiguous. +- A tile is a sequence of 16-byte words. Word 0 is RDD 34 `Picture_info` (HS = tile width, VS = tile height / 2, BBD = 16, NC = 3, NW = 3, NP = `1000000000b`; other values are refused as unsupported). Word 1 holds five `u24` group byte-sums, word 2 is zero, words 3-7 describe the groups (a count byte, then `u24` stream sizes in words). Groups: g0 = LL3 (3 streams, one per component), g1 / g2 / g3 = level-3 / 2 / 1 bands (3 streams each), g4 = green residual (1 stream). Streams follow in that order from word 8. +- A stream is a header word (a `u16` count of index words, a `u24` count of data words, then 11 bytes that are not interpreted), an index table and data, each padded to a word. The index has one entry per transform unit (TU): `A(16) X B(16) X`, where A and B are the byte lengths of the TU's two halves and X are quantiser-index (QI) nibbles (one for g0 and g4, three for g1-g3: HL, LH, HH). Halves per tile = ceil((VS - 2 - s) / 8) + 1 with s the first-half shift (below), TUs = ceil(halves / 2): 105 and 137 for the sample sizes. Halves are numbered n = 2 * TU + h; each is byte-aligned and consecutive halves are contiguous. - QI values seen, identical in Compressed and HQ files: level 1 component 0 (1,1,2), components 1-2 (2,2,3); level 2 (0,0,1); level 3 (0,0,0); LL3 0; residual 2. Compressed and HQ differ only in the coefficient data. ### Entropy coding and dequantisation @@ -27,7 +27,7 @@ The codec is Sony's use of SMPTE RDD 34 (LLVC, Low Latency Video Codec). `crates ### Frame geometry - Each tile holds three W/2 x H/2 planes (W, H = tile size): component 0 = M, the green mean; components 1-2 = chroma c1, c2; plus a W/2 x H/2 residual plane from g4. A three-level 5/3 wavelet is inverted (vertical, then horizontal) with whole-sample symmetric extension at every edge and integer arithmetic. Tiles are independent. -- The TU grid and the lifting phases are anchored to the full sensor, not to the tile. Let s = (lines in g4's first half) - 2, read from the stream: 0 on full frame, 3 on the APS-C crop (the crop's sensor-row offset 573 is 5 mod 8). Half n then covers plane rows 8n - 6 + s .. 8n + 1 + s, clipped to the frame. The lifting phases follow from s: full frame (0,1,1), APS-C (1,0,0). Each half holds, in clipped natural order, its rows of HL1, LH1, HH1, HL2, LH2, HH2, LL3, HL3, LH3, HH3 and, in g4, 8 residual rows; edge halves are shorter. With the right s every line of every file is used. +- The TU grid and the lifting phases are anchored to the full sensor, not to the tile. Let s = (lines in g4's first half) - 2, read from the stream (residual lines are decoded while at least 8 bits of the half remain, at most 8): 0 on full frame, 3 on the APS-C crop (the crop's sensor-row offset 573 is 5 mod 8). Half n then covers plane rows 8n - 6 + s .. 8n + 1 + s, clipped to the frame. The lifting phases follow from s: full frame (0,1,1), APS-C (1,0,0). Each half holds, in clipped natural order, its rows of HL1, LH1, HH1, HL2, LH2, HH2, LL3, HL3, LH3, HH3 and, in g4, 8 residual rows; edge halves are shorter. With the right s every line of every file is used. ### Colour reconstruction From 4d26a4d7b445c1f2e756696cddee0f8de09e869e Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 20:03:41 +0200 Subject: [PATCH 20/21] LR-IMP-FORMATS: render cache version 43 (ARW6 decodes instead of falling back to the embedded JPEG) Co-Authored-By: Claude --- crates/engine/src/media.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 6d5b548f..d863060e 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -62,7 +62,7 @@ impl SettingsHashes { } /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 42; +pub const RENDER_CACHE_VERSION: u64 = 43; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; From 4860f5e8d4fdafb033f9af22fdfde096b40e3c1a Mon Sep 17 00:00:00 2001 From: dev-null-undefined Date: Sat, 10 Oct 2026 19:58:36 +0200 Subject: [PATCH 21/21] LR-IMP-FORMATS: ARW6 companding curve derived clean-room from CC0 lossless pairs The 2668-entry table read off the black-box oracle's output is gone. arw6_curve.rs now builds the 4096-entry table at first use from our own measurement: piecewise linear through knots u_k = 128 k, c_k = u_k for k <= 11 and 356.89 + 655.646 ln(k - 6) above, rounded half up, fitted to the 7 same-exposure lossless (LJ92) / ARW6 pairs of the CC0 ILCE-7RM6 set. A unit test pins the whole table (sum 27776336, weighted 92792980288), its anchors, the identity through 1408 and strict monotonicity. The corpus sums become regression values of the new output; the 12-bit codes before the curve stay verified against the oracle (Phase 0). docs/arw6-compression.md describes the curve, how it was measured, its uncertainty, the structure and x2-scale evidence, why it is not in the file, and the after-the-fact comparison with the oracle's curve; the tracker and docs no longer call the output bit-exact against LibRaw. Co-Authored-By: Claude --- crates/raw/src/vendor/arw.rs | 2 +- crates/raw/src/vendor/arw6.rs | 26 +--- crates/raw/src/vendor/arw6_curve.rs | 227 +++++++--------------------- crates/raw/tests/corpus.rs | 9 +- docs/arw6-compression.md | 88 ++++++++--- docs/parity-checklist.md | 4 +- 6 files changed, 135 insertions(+), 221 deletions(-) diff --git a/crates/raw/src/vendor/arw.rs b/crates/raw/src/vendor/arw.rs index 43153f2c..8ac90f54 100644 --- a/crates/raw/src/vendor/arw.rs +++ b/crates/raw/src/vendor/arw.rs @@ -658,7 +658,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { _ => BlackLevel::uniform((scale_bits >= 14).then(|| sr2().and_then(sr2_black)).flatten().unwrap_or(default_black)), }; // ARW6 samples are in 2 x 14-bit units, so the file's 14-bit levels double; without the tag the white is the - // companding table's knot, 2 x 16383 + // 14-bit white in those units, 2 x 16383 let unit = if info.compression == 32766 { 2.0 } else { 1.0 }; let white = if linear_rgb { YCBCR_WHITE + YCBCR_OFFSET diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index e583a676..f6f535bd 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -6,7 +6,7 @@ //! names in italics below refer to it. No other raw decoder's source was consulted. use crate::llvc::{Bands3, Plane, band_rows, dequant, reconstruct3, vld_decode_line}; -use crate::vendor::arw6_curve::{ARW6_CURVE, CURVE_KNEE}; +use crate::vendor::arw6_curve::curve; use crate::vendor::pef::Bits; use crate::{RawError, Result}; use rayon::prelude::*; @@ -456,15 +456,6 @@ pub(crate) fn decode_tile_planes(tile: &[u8], tw: usize, th: usize) -> Result u16 { - let c = code12.clamp(0, 4095) as usize; - match c.checked_sub(CURVE_KNEE) { - None => c as u16, - Some(i) => ARW6_CURVE.get(i).copied().unwrap_or(39002), - } -} - /// Colour reconstruction (*Colour reconstruction*, checked against Phase 0 oracle output): the planes give a /// `(2 W2) x (2 H2)` mosaic with R at (0,0), G1 (0,1), G2 (1,0), B (1,1) of every 2x2 cell, each value passed through /// [`curve`]. G1 comes from the green mean minus a residual average, G2 is predicted from the (unclipped) G1 plus the @@ -829,17 +820,6 @@ mod tests { } } - #[test] - fn curve_anchors() { - assert_eq!(ARW6_CURVE.len(), 2668); - for (c, v) in [(0, 0), (1427, 1427), (1428, 1429), (1436, 1438), (2048, 2469), (3000, 8010), (4094, 38944), (4095, 39002)] { - assert_eq!(curve(c), v, "code {c}"); - } - assert_eq!(curve(-5), 0); - assert_eq!(curve(5000), 39002); - assert!(ARW6_CURVE.windows(2).all(|w| w[0] < w[1])); - } - fn plane(w: usize, v: &[i32]) -> Plane { Plane { width: w, height: v.len() / w, data: v.to_vec() } } @@ -874,7 +854,7 @@ mod tests { let mut p = example(); p.m.data[1] = 4100; let out = colour(&p).unwrap(); - assert_eq!(out[3], 39002); // G1 = 4101 -> clipped output + assert_eq!(out[3], curve(4095)); // G1 = 4101 -> clipped output assert_eq!(out[6 + 2], curve(2554)); // G2 predicted from the unclipped G1 assert_eq!(out[2], curve(3304)); // R = 2*(-10) + ((4095 + 2554) >> 1): chroma uses the clipped greens } @@ -942,7 +922,7 @@ mod tests { for x in 0..w2 { let at = |dy: usize, dx: usize| out[(2 * j + dy) * 64 + 2 * x + dx]; assert_eq!(at(0, 0), at(1, 1), "R == B at ({x},{j})"); - assert!(at(0, 0) < 39002); + assert!(at(0, 0) < curve(4095)); } } } diff --git a/crates/raw/src/vendor/arw6_curve.rs b/crates/raw/src/vendor/arw6_curve.rs index 1807195b..f7c748a1 100644 --- a/crates/raw/src/vendor/arw6_curve.rs +++ b/crates/raw/src/vendor/arw6_curve.rs @@ -1,176 +1,55 @@ -//! The ARW6 companding table: 12-bit tile code to output value. +//! The ARW6 companding curve: 12-bit tile code to output value in 2 × 14-bit DN (black 1024, white 32766). +//! +//! Piecewise linear through knots (c_k, 128 k): c_k = 128 k for k <= 11, else 356.89 + 655.646 ln(k - 6); each code's +//! value is the interpolation rounded half up. Our own measurement from the CC0 lossless / ARW6 pairs of the ILCE-7RM6, +//! not stored in the file; see docs/arw6-compression.md (*Output range*). -/// First code the table covers; below it the curve is the identity. -pub(crate) const CURVE_KNEE: usize = 1428; +use std::sync::OnceLock; -/// code → 2 × 14-bit DN; identity below the knee; derived in Phase 0 from the black-box oracle's output over 8 files (0 disagreements), see docs/arw6-compression.md. -#[rustfmt::skip] -pub(crate) const ARW6_CURVE: [u16; 2668] = [ - 1429,1430,1431,1432,1433,1434,1435,1436,1438,1439,1440,1441,1442,1443,1444,1445, - 1446,1447,1448,1449,1450,1451,1452,1453,1455,1456,1457,1458,1459,1460,1461,1462, - 1463,1464,1465,1466,1467,1468,1469,1470,1471,1472,1473,1474,1475,1476,1477,1478, - 1480,1481,1482,1483,1484,1485,1486,1487,1489,1490,1491,1492,1493,1494,1495,1496, - 1497,1498,1499,1500,1501,1502,1503,1504,1505,1506,1507,1508,1509,1510,1511,1512, - 1513,1514,1515,1516,1517,1518,1519,1520,1522,1523,1524,1525,1526,1527,1529,1530, - 1531,1532,1534,1535,1536,1537,1538,1539,1541,1542,1543,1544,1545,1546,1548,1549, - 1550,1551,1553,1554,1555,1556,1558,1559,1561,1562,1563,1565,1566,1567,1568,1569, - 1571,1572,1573,1574,1575,1576,1578,1579,1580,1581,1583,1584,1585,1586,1588,1589, - 1590,1591,1593,1594,1595,1596,1598,1599,1601,1602,1603,1605,1606,1607,1608,1609, - 1611,1612,1613,1614,1615,1616,1618,1619,1621,1622,1623,1625,1626,1627,1629,1630, - 1631,1632,1634,1635,1636,1637,1639,1640,1641,1642,1644,1645,1646,1647,1649,1650, - 1651,1652,1654,1655,1656,1657,1659,1660,1662,1663,1664,1666,1667,1668,1670,1671, - 1673,1674,1675,1677,1678,1680,1681,1683,1685,1686,1688,1689,1691,1692,1694,1695, - 1697,1698,1699,1701,1702,1704,1705,1707,1709,1710,1712,1713,1715,1716,1718,1719, - 1720,1721,1723,1724,1725,1727,1728,1730,1731,1733,1734,1736,1737,1739,1740,1742, - 1743,1745,1746,1748,1749,1750,1752,1753,1755,1756,1757,1759,1760,1762,1763,1765, - 1767,1768,1770,1771,1773,1774,1776,1777,1779,1780,1781,1783,1784,1786,1787,1789, - 1791,1792,1794,1795,1797,1799,1801,1802,1804,1806,1808,1809,1811,1813,1814,1816, - 1818,1819,1821,1822,1824,1826,1827,1829,1831,1832,1834,1835,1837,1839,1841,1842, - 1844,1846,1848,1849,1851,1853,1854,1856,1858,1859,1861,1862,1864,1866,1868,1869, - 1871,1873,1875,1876,1878,1880,1881,1883,1885,1886,1888,1889,1891,1893,1894,1896, - 1898,1899,1901,1902,1904,1906,1908,1909,1911,1913,1915,1916,1918,1920,1922,1924, - 1926,1927,1929,1931,1933,1935,1937,1938,1940,1942,1944,1945,1947,1949,1951,1953, - 1955,1957,1959,1961,1963,1965,1967,1968,1970,1972,1974,1975,1977,1979,1981,1983, - 1985,1986,1988,1990,1992,1994,1996,1998,2000,2001,2003,2005,2007,2009,2011,2013, - 2015,2016,2018,2020,2022,2024,2026,2027,2029,2031,2033,2034,2036,2038,2040,2042, - 2044,2046,2048,2050,2052,2054,2056,2058,2060,2062,2064,2066,2068,2070,2072,2074, - 2076,2078,2080,2082,2084,2086,2088,2090,2092,2094,2096,2098,2100,2102,2104,2106, - 2109,2111,2113,2115,2117,2119,2121,2123,2125,2127,2129,2131,2133,2135,2137,2139, - 2141,2143,2145,2147,2149,2151,2153,2155,2157,2159,2161,2163,2165,2167,2170,2172, - 2175,2177,2179,2182,2184,2186,2188,2190,2193,2195,2197,2199,2201,2203,2206,2208, - 2210,2212,2215,2217,2219,2221,2224,2226,2228,2230,2233,2235,2237,2239,2242,2244, - 2247,2249,2251,2254,2256,2258,2261,2263,2265,2267,2270,2272,2274,2276,2279,2281, - 2283,2285,2288,2290,2292,2294,2297,2299,2302,2304,2306,2309,2311,2314,2316,2319, - 2321,2324,2326,2329,2331,2333,2336,2338,2340,2342,2345,2347,2349,2352,2354,2357, - 2359,2362,2364,2367,2369,2371,2374,2376,2379,2381,2383,2386,2388,2390,2393,2395, - 2398,2400,2402,2405,2407,2410,2412,2415,2417,2420,2422,2425,2427,2430,2432,2435, - 2438,2440,2443,2445,2448,2451,2453,2456,2459,2461,2464,2466,2469,2472,2475,2477, - 2480,2483,2486,2488,2491,2494,2496,2499,2501,2504,2506,2509,2511,2514,2517,2519, - 2522,2525,2528,2530,2533,2536,2538,2541,2543,2546,2548,2551,2553,2556,2559,2561, - 2564,2567,2570,2572,2575,2578,2581,2584,2587,2589,2592,2595,2598,2601,2604,2606, - 2609,2612,2615,2617,2620,2623,2626,2629,2632,2634,2637,2640,2643,2646,2649,2652, - 2655,2657,2660,2663,2666,2669,2672,2675,2678,2680,2683,2686,2689,2692,2695,2698, - 2701,2704,2707,2710,2713,2716,2719,2722,2725,2727,2730,2733,2736,2739,2742,2745, - 2749,2752,2755,2758,2761,2764,2767,2770,2773,2776,2779,2782,2785,2788,2791,2794, - 2798,2801,2804,2807,2810,2813,2816,2819,2823,2826,2829,2832,2835,2838,2841,2844, - 2848,2851,2854,2857,2860,2863,2867,2870,2873,2876,2880,2883,2886,2889,2893,2896, - 2899,2902,2906,2909,2912,2915,2919,2922,2925,2928,2932,2935,2938,2941,2945,2948, - 2952,2955,2958,2962,2965,2968,2972,2975,2979,2982,2985,2989,2992,2995,2999,3002, - 3006,3009,3012,3016,3019,3023,3026,3030,3033,3037,3040,3044,3047,3051,3054,3058, - 3061,3065,3068,3072,3075,3079,3082,3086,3089,3093,3096,3100,3103,3107,3110,3114, - 3118,3121,3125,3128,3132,3136,3139,3143,3146,3150,3153,3157,3160,3164,3168,3171, - 3175,3179,3183,3186,3190,3194,3197,3201,3205,3208,3212,3215,3219,3223,3227,3231, - 3235,3238,3242,3246,3250,3254,3258,3261,3265,3269,3273,3276,3280,3284,3288,3292, - 3296,3299,3303,3307,3311,3315,3319,3323,3327,3331,3335,3339,3343,3347,3351,3354, - 3358,3362,3366,3369,3373,3377,3381,3385,3389,3393,3397,3401,3405,3409,3413,3417, - 3422,3426,3430,3434,3438,3442,3446,3450,3455,3459,3463,3467,3471,3475,3479,3483, - 3487,3491,3495,3499,3503,3507,3512,3516,3520,3524,3529,3533,3537,3541,3546,3550, - 3554,3558,3563,3567,3571,3575,3580,3584,3589,3593,3597,3602,3606,3610,3615,3619, - 3624,3628,3632,3637,3641,3645,3650,3654,3658,3662,3667,3671,3675,3680,3684,3689, - 3693,3698,3702,3707,3711,3716,3720,3725,3729,3734,3738,3743,3747,3752,3756,3761, - 3766,3770,3775,3779,3784,3789,3793,3798,3802,3807,3811,3816,3820,3825,3830,3834, - 3839,3844,3849,3853,3858,3863,3868,3872,3877,3882,3887,3891,3896,3901,3906,3910, - 3915,3920,3925,3929,3934,3939,3944,3949,3954,3958,3963,3968,3973,3978,3983,3988, - 3993,3997,4002,4007,4012,4017,4022,4027,4032,4037,4042,4047,4052,4057,4062,4067, - 4072,4077,4082,4087,4092,4097,4102,4107,4113,4118,4123,4128,4133,4138,4143,4148, - 4154,4159,4164,4169,4174,4179,4185,4190,4195,4200,4206,4211,4216,4221,4227,4232, - 4237,4242,4248,4253,4258,4263,4269,4274,4280,4285,4290,4296,4301,4306,4312,4317, - 4323,4328,4333,4339,4344,4350,4355,4361,4366,4372,4377,4383,4388,4394,4399,4405, - 4410,4416,4421,4427,4432,4438,4444,4449,4455,4461,4467,4472,4478,4484,4489,4495, - 4500,4506,4511,4517,4522,4528,4534,4540,4546,4551,4557,4563,4569,4575,4581,4586, - 4592,4598,4604,4609,4615,4621,4627,4633,4639,4644,4650,4656,4662,4668,4674,4680, - 4686,4692,4698,4704,4710,4716,4722,4728,4734,4740,4746,4752,4758,4764,4771,4777, - 4783,4789,4796,4802,4808,4814,4820,4826,4832,4838,4844,4850,4856,4862,4869,4875, - 4882,4888,4894,4901,4907,4913,4920,4926,4933,4939,4945,4952,4958,4964,4971,4977, - 4983,4989,4996,5002,5008,5015,5021,5028,5034,5041,5047,5054,5060,5067,5073,5080, - 5087,5093,5100,5106,5113,5120,5126,5133,5140,5146,5153,5159,5166,5173,5180,5186, - 5193,5200,5207,5213,5220,5227,5234,5240,5247,5254,5261,5267,5274,5281,5288,5295, - 5302,5309,5316,5323,5330,5337,5344,5351,5358,5365,5372,5379,5386,5393,5400,5407, - 5414,5421,5428,5435,5442,5449,5456,5463,5471,5478,5485,5492,5499,5506,5514,5521, - 5528,5535,5543,5550,5557,5564,5572,5579,5587,5594,5601,5609,5616,5623,5631,5638, - 5646,5653,5660,5668,5675,5683,5690,5698,5705,5713,5720,5728,5735,5743,5751,5758, - 5766,5774,5782,5789,5797,5805,5812,5820,5828,5835,5843,5850,5858,5866,5874,5881, - 5889,5897,5905,5912,5920,5928,5936,5944,5952,5959,5967,5975,5983,5991,5999,6007, - 6015,6023,6031,6039,6047,6055,6063,6071,6079,6087,6095,6103,6111,6119,6128,6136, - 6144,6152,6161,6169,6177,6185,6194,6202,6210,6218,6227,6235,6243,6251,6260,6268, - 6277,6285,6293,6302,6310,6319,6327,6336,6344,6353,6361,6370,6378,6387,6395,6404, - 6412,6421,6429,6438,6446,6455,6464,6472,6481,6490,6499,6507,6516,6525,6534,6543, - 6552,6560,6569,6578,6587,6596,6605,6613,6622,6631,6640,6648,6657,6666,6675,6684, - 6694,6703,6712,6721,6730,6739,6748,6757,6767,6776,6785,6794,6803,6812,6822,6831, - 6840,6849,6859,6868,6877,6886,6896,6905,6914,6923,6933,6942,6951,6961,6970,6980, - 6989,6999,7008,7018,7027,7037,7046,7056,7065,7075,7084,7094,7103,7113,7123,7132, - 7142,7152,7162,7171,7181,7191,7201,7210,7220,7230,7240,7249,7259,7269,7279,7289, - 7299,7309,7319,7329,7339,7349,7359,7369,7379,7389,7399,7409,7419,7429,7440,7450, - 7460,7470,7481,7491,7501,7511,7522,7532,7543,7553,7563,7574,7584,7594,7605,7615, - 7626,7636,7646,7657,7667,7678,7688,7699,7709,7720,7730,7741,7751,7762,7772,7783, - 7794,7804,7815,7825,7836,7847,7858,7869,7880,7890,7901,7912,7923,7934,7945,7956, - 7967,7977,7988,7999,8010,8021,8032,8043,8055,8066,8077,8088,8099,8110,8122,8133, - 8144,8155,8167,8178,8189,8200,8212,8223,8234,8245,8257,8268,8279,8291,8302,8314, - 8326,8337,8349,8360,8372,8384,8395,8407,8418,8430,8441,8453,8464,8476,8488,8500, - 8512,8523,8535,8547,8559,8571,8583,8595,8607,8618,8630,8642,8654,8666,8678,8690, - 8702,8714,8726,8738,8750,8762,8775,8787,8799,8811,8824,8836,8848,8860,8873,8885, - 8898,8910,8922,8935,8947,8960,8972,8985,8997,9010,9022,9035,9047,9060,9072,9085, - 9098,9110,9123,9135,9148,9161,9174,9187,9200,9212,9225,9238,9251,9264,9277,9290, - 9303,9316,9329,9342,9355,9368,9381,9394,9408,9421,9434,9447,9460,9473,9487,9500, - 9513,9526,9540,9553,9566,9580,9593,9607,9620,9634,9647,9661,9674,9688,9701,9715, - 9728,9742,9755,9769,9782,9796,9810,9824,9838,9851,9865,9879,9893,9907,9921,9935, - 9949,9963,9977,9991,10005,10019,10033,10047,10061,10075,10089,10103,10117,10131,10146,10160, - 10175,10189,10203,10218,10232,10247,10261,10276,10290,10305,10319,10334,10348,10363,10377,10392, - 10407,10421,10436,10450,10465,10480,10495,10509,10524,10539,10554,10568,10583,10598,10613,10628, - 10643,10658,10673,10688,10703,10718,10734,10749,10764,10779,10795,10810,10825,10840,10856,10871, - 10887,10902,10917,10933,10948,10964,10979,10995,11010,11026,11041,11057,11072,11088,11104,11120, - 11136,11151,11167,11183,11199,11215,11231,11247,11263,11278,11294,11310,11326,11342,11358,11374, - 11391,11407,11423,11439,11455,11471,11488,11504,11521,11537,11553,11570,11586,11603,11619,11636, - 11652,11669,11685,11702,11718,11735,11752,11768,11785,11802,11819,11835,11852,11869,11886,11903, - 11920,11937,11954,11971,11988,12005,12022,12039,12057,12074,12091,12108,12125,12142,12160,12177, - 12195,12212,12229,12247,12264,12282,12299,12317,12335,12352,12370,12387,12405,12423,12441,12458, - 12476,12494,12512,12529,12547,12565,12583,12601,12619,12637,12655,12673,12691,12709,12728,12746, - 12764,12782,12801,12819,12837,12855,12874,12892,12911,12929,12947,12966,12984,13003,13022,13040, - 13059,13078,13097,13115,13134,13153,13172,13191,13210,13228,13247,13266,13285,13304,13323,13342, - 13362,13381,13400,13419,13438,13457,13477,13496,13516,13535,13554,13574,13593,13613,13632,13652, - 13672,13691,13711,13730,13750,13770,13790,13810,13830,13849,13869,13889,13909,13929,13949,13969, - 13990,14010,14030,14050,14070,14090,14111,14131,14151,14171,14192,14212,14232,14253,14273,14294, - 14315,14335,14356,14376,14397,14418,14439,14460,14481,14501,14522,14543,14564,14585,14606,14627, - 14648,14669,14690,14711,14732,14753,14775,14796,14818,14839,14860,14882,14903,14925,14946,14968, - 14990,15011,15033,15054,15076,15098,15120,15142,15164,15185,15207,15229,15251,15273,15295,15317, - 15340,15362,15384,15406,15428,15450,15473,15495,15518,15540,15562,15585,15607,15630,15653,15675, - 15698,15721,15744,15766,15789,15812,15835,15858,15881,15903,15926,15949,15972,15995,16019,16042, - 16065,16088,16112,16135,16158,16182,16205,16229,16253,16276,16300,16323,16347,16371,16395,16418, - 16442,16466,16490,16513,16537,16561,16585,16609,16634,16658,16682,16706,16730,16754,16779,16803, - 16828,16852,16876,16901,16925,16950,16975,16999,17024,17049,17074,17098,17123,17148,17173,17198, - 17223,17248,17273,17298,17323,17348,17374,17399,17424,17449,17475,17500,17525,17551,17576,17602, - 17628,17653,17679,17704,17730,17756,17782,17808,17834,17860,17886,17912,17938,17964,17991,18017, - 18043,18069,18096,18122,18148,18175,18201,18228,18254,18281,18307,18334,18360,18387,18414,18441, - 18468,18494,18521,18548,18575,18602,18630,18657,18684,18711,18739,18766,18793,18821,18848,18876, - 18904,18931,18959,18986,19014,19042,19070,19097,19125,19153,19181,19208,19236,19264,19293,19321, - 19349,19377,19406,19434,19462,19491,19519,19548,19577,19605,19634,19662,19691,19720,19749,19778, - 19807,19835,19864,19893,19922,19951,19981,20010,20040,20069,20098,20128,20157,20187,20216,20246, - 20276,20305,20335,20364,20394,20424,20454,20484,20514,20544,20574,20604,20634,20664,20695,20725, - 20756,20786,20816,20847,20877,20908,20939,20969,21000,21031,21062,21092,21123,21154,21185,21216, - 21247,21278,21309,21340,21371,21403,21434,21466,21497,21529,21560,21592,21623,21655,21687,21719, - 21751,21782,21814,21846,21878,21910,21943,21975,22007,22039,22072,22104,22136,22169,22202,22234, - 22267,22300,22333,22365,22398,22431,22464,22497,22530,22563,22596,22629,22662,22696,22729,22763, - 22796,22830,22863,22897,22930,22964,22998,23032,23066,23099,23133,23167,23201,23235,23270,23304, - 23338,23372,23407,23441,23475,23510,23545,23579,23614,23649,23684,23718,23753,23788,23823,23858, - 23894,23929,23964,23999,24034,24070,24105,24141,24176,24212,24247,24283,24318,24354,24390,24426, - 24462,24498,24534,24570,24606,24643,24679,24716,24752,24789,24825,24862,24898,24935,24972,25009, - 25046,25082,25119,25156,25193,25230,25268,25305,25342,25379,25417,25454,25491,25529,25567,25605, - 25643,25680,25718,25756,25794,25832,25871,25909,25947,25985,26024,26062,26100,26139,26178,26216, - 26255,26294,26333,26371,26410,26449,26488,26527,26567,26606,26645,26684,26723,26763,26802,26842, - 26882,26921,26961,27000,27040,27080,27121,27161,27201,27241,27282,27322,27362,27403,27443,27484, - 27525,27565,27606,27646,27687,27728,27769,27810,27852,27893,27934,27975,28016,28058,28099,28141, - 28183,28224,28266,28307,28349,28391,28433,28475,28518,28560,28602,28644,28686,28729,28772,28814, - 28857,28900,28943,28985,29028,29071,29114,29157,29201,29244,29287,29330,29373,29417,29461,29504, - 29548,29592,29636,29679,29723,29767,29812,29856,29900,29944,29989,30033,30077,30122,30167,30211, - 30256,30301,30346,30390,30435,30480,30526,30571,30617,30662,30707,30753,30798,30844,30890,30936, - 30982,31027,31073,31119,31165,31212,31258,31305,31351,31398,31444,31491,31537,31584,31631,31678, - 31725,31772,31819,31866,31913,31961,32008,32056,32104,32151,32199,32246,32294,32342,32390,32438, - 32487,32535,32583,32631,32679,32766,32777,32825,32874,32923,32972,33020,33069,33118,33168,33217, - 33267,33316,33365,33415,33464,33514,33564,33614,33664,33714,33764,33814,33864,33915,33965,34016, - 34067,34117,34168,34218,34269,34320,34371,34422,34474,34525,34576,34627,34678,34730,34782,34834, - 34886,34937,34989,35041,35093,35146,35198,35251,35303,35356,35408,35461,35513,35566,35619,35672, - 35725,35778,35831,35884,35937,35991,36045,36098,36152,36206,36260,36313,36367,36422,36476,36531, - 36585,36640,36694,36749,36803,36858,36913,36968,37023,37078,37133,37188,37243,37299,37355,37410, - 37466,37522,37578,37633,37689,37746,37802,37859,37915,37972,38028,38085,38141,38198,38255,38312, - 38369,38426,38483,38540,38597,38655,38713,38771,38829,38886,38944,39002, -]; +/// Code of knot `k`, whose output value is 128 k. +fn knot(k: u32) -> f64 { + if k <= 11 { f64::from(128 * k) } else { 356.89 + 655.646 * f64::from(k - 6).ln() } +} + +fn table() -> &'static [u16; 4096] { + static TABLE: OnceLock<[u16; 4096]> = OnceLock::new(); + TABLE.get_or_init(|| { + let mut t = [0u16; 4096]; + let mut k = 0u32; + for (code, v) in t.iter_mut().enumerate() { + let c = code as f64; + while knot(k + 1) < c { + k += 1; + } + let (c0, c1, u0) = (knot(k), knot(k + 1), f64::from(128 * k)); + *v = (u0 + 128.0 * (c - c0) / (c1 - c0) + 0.5).floor() as u16; + } + t + }) +} + +/// Companding curve: 12-bit code (clamped to 0..=4095) to output value. +pub(crate) fn curve(code12: i32) -> u16 { + table().get(code12.clamp(0, 4095) as usize).copied().unwrap_or(u16::MAX) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Pins the whole generated table (sum and position-weighted sum of all 4096 values, from the derivation's own + /// table), so a platform whose `ln` rounds differently fails here. + #[test] + fn table_is_pinned() { + let t = table(); + let sum: u64 = t.iter().map(|&v| u64::from(v)).sum(); + let weighted: u64 = t.iter().enumerate().map(|(i, &v)| (i as u64 + 1) * u64::from(v)).sum(); + assert_eq!((sum, weighted), (27776336, 92792980288)); + for (c, v) in [(0, 0), (1408, 1408), (1536, 1542), (2048, 2457), (3000, 7979), (3500, 16227), (3977, 32767), (4095, 39077)] { + assert_eq!(curve(c), v, "code {c}"); + } + assert!((0..=1408).all(|c| curve(c) == c as u16), "identity through 1408"); + assert!(t.windows(2).all(|w| w[0] < w[1]), "strictly increasing"); + assert_eq!((curve(-5), curve(5000)), (0, 39077)); + } +} diff --git a/crates/raw/tests/corpus.rs b/crates/raw/tests/corpus.rs index 3170742a..a367c514 100644 --- a/crates/raw/tests/corpus.rs +++ b/crates/raw/tests/corpus.rs @@ -881,13 +881,14 @@ fn verify_sensor_arrays(cases: &[(&str, usize, usize, u64, u64)]) -> usize { seen } -/// Reference sums from the oracle-verified Phase 0 model (docs/arw6-compression.md); the files are CC0 from RawDB, -/// one per geometry and compression mode. +/// Regression values from LightCraft's decoder with the derived companding curve; the 12-bit codes before the curve +/// were verified against the black-box oracle in Phase 0 (docs/arw6-compression.md). The files are CC0 from RawDB, one +/// per geometry and compression mode. #[test] fn corpus_sony_arw6_samples() { let cases: &[(&str, usize, usize, u64, u64)] = &[ - ("arw6-sony-ilce7rm6-apsc-land-hq.arw", 6592, 4372, 85834467900, 1323814215465139776), - ("arw6-sony-ilce7rm6-ff-land-c.arw", 10016, 6672, 258558260019, 9665041696390559268), + ("arw6-sony-ilce7rm6-apsc-land-hq.arw", 6592, 4372, 85546367117, 1319631546150087499), + ("arw6-sony-ilce7rm6-ff-land-c.arw", 10016, 6672, 257718215153, 9636375794063042132), ]; let seen = verify_sensor_arrays(cases); eprintln!("verified {seen} Sony ARW6 sensor arrays"); diff --git a/docs/arw6-compression.md b/docs/arw6-compression.md index 80c21f8d..3b65c1d3 100644 --- a/docs/arw6-compression.md +++ b/docs/arw6-compression.md @@ -6,12 +6,12 @@ Decode timings: see the end of this document (measured in the performance pass). ## Format and implementation -The codec is Sony's use of SMPTE RDD 34 (LLVC, Low Latency Video Codec). `crates/raw/src/llvc.rs` is the codec core (bit reader, variable-length decoder, dequantiser, inverse 5/3 wavelet); `crates/raw/src/vendor/arw6.rs` is the Sony container, geometry and colour reconstruction; `crates/raw/src/vendor/arw6_curve.rs` is the companding table; `arw.rs` dispatches Compression 32766 to it. A test-only encoder (`arw6_testenc.rs`) builds synthetic tiles for round-trip tests. +The codec is Sony's use of SMPTE RDD 34 (LLVC, Low Latency Video Codec). `crates/raw/src/llvc.rs` is the codec core (bit reader, variable-length decoder, dequantiser, inverse 5/3 wavelet); `crates/raw/src/vendor/arw6.rs` is the Sony container, geometry and colour reconstruction; `crates/raw/src/vendor/arw6_curve.rs` is the companding curve; `arw.rs` dispatches Compression 32766 to it. A test-only encoder (`arw6_testenc.rs`) builds synthetic tiles for round-trip tests. ### Container - Raw SubIFD: Compression 32766, 14 bits per sample, BlackLevel 512 x4 (`0x7310`), WB `0x7313`, crop `0x74c7/0x74c8` (full frame: origin 12,8, size 9984x6656; APS-C: origin 16,10, size 6528x4352), CFA RGGB. The Sony tag-based white level (15360) is not read; the DNG `WhiteLevel` is (16383). -- The single strip starts with a tile table: `u32` count, `u32` 0, then per tile a `u64` offset (relative to the strip) and `u32` x, y, width, height. Seen: full frame 4 tiles of 5008x3336 (HQ) or 5024 / 4992 wide (Compressed); APS-C (6592x4372) one tile. A 480-byte block follows the table (not interpreted, not needed). +- The single strip starts with a tile table: `u32` count, `u32` 0, then per tile a `u64` offset (relative to the strip) and `u32` x, y, width, height. Seen: full frame 4 tiles of 5008x3336 (HQ) or 5024 / 4992 wide (Compressed); APS-C (6592x4372) one tile. Bytes up to offset 512 follow the table (480 on APS-C, 408 on full frame; not interpreted, not needed). - A tile is a sequence of 16-byte words. Word 0 is RDD 34 `Picture_info` (HS = tile width, VS = tile height / 2, BBD = 16, NC = 3, NW = 3, NP = `1000000000b`; other values are refused as unsupported). Word 1 holds five `u24` group byte-sums, word 2 is zero, words 3-7 describe the groups (a count byte, then `u24` stream sizes in words). Groups: g0 = LL3 (3 streams, one per component), g1 / g2 / g3 = level-3 / 2 / 1 bands (3 streams each), g4 = green residual (1 stream). Streams follow in that order from word 8. - A stream is a header word (a `u16` count of index words, a `u24` count of data words, then 11 bytes that are not interpreted), an index table and data, each padded to a word. The index has one entry per transform unit (TU): `A(16) X B(16) X`, where A and B are the byte lengths of the TU's two halves and X are quantiser-index (QI) nibbles (one for g0 and g4, three for g1-g3: HL, LH, HH). Halves per tile = ceil((VS - 2 - s) / 8) + 1 with s the first-half shift (below), TUs = ceil(halves / 2): 105 and 137 for the sample sizes. Halves are numbered n = 2 * TU + h; each is byte-aligned and consecutive halves are contiguous. - QI values seen, identical in Compressed and HQ files: level 1 component 0 (1,1,2), components 1-2 (2,2,3); level 2 (0,0,1); level 3 (0,0,0); LL3 0; residual 2. Compressed and HQ differ only in the coefficient data. @@ -38,22 +38,77 @@ With plane row j, column x (x +- 1 clamped at the edges), in 12-bit code units: - `R = 2*c1 + ((clamp(G1, 0, 4095) + clamp(G2, 0, 4095)) >> 1)`, `B = 2*c2 + (same)` (a negative green, as in deep high-ISO shadows, counts as 0). - Every code is clipped to 0..4095. Per 2x2 cell: R (0,0), G1 (0,1), G2 (1,0), B (1,1). -### Output range (companding table) +### Output range (companding curve) -- Codes map through one monotone table shared by all files: identity up to code 1427, then a smooth curve reaching 39002 at code 4095 (steps grow from 1 to 58). No closed form fits within +-22, so `arw6_curve.rs` embeds the table (2668 `u16` values from code 1428). It is not stored in the file. -- Provenance: the table was read off the black-box oracle's (LibRaw, below) output over the 8 Compressed / HQ files; every code from 1027 to 4095 occurred and no two files disagreed. It is therefore a measurement of that program's output, not an independent derivation. -- Unit: 2 x 14-bit DN. The decoder reports black = 2 x 512 = 1024 and white = 2 x the file's DNG `WhiteLevel` (16383), i.e. 32766; saturated highlights sit at code 4095 = 39002, above white, and clip as usual. If a file carries no usable white level, the white is 32766 (2 x 16383, the table's knot below), not a data-derived value. -- The table has one knot: at code 3977 it runs 32679 -> 32766 -> 32777 (steps +87 then +11), the same in every file. 32766 = 2 x 16383 is exactly the reported white level, so the knot is the white point of the measured curve (inferred from the arithmetic, not from any documentation): codes 3978..4095 sit above white and clip. +Codes map through one monotone curve, the same for every file and both modes. It is not stored in the file (below); it is our own measurement. Output values are in 2 x 14-bit DN: black 2 x 512 = 1024, the 14-bit white 16383 maps to 32766. + +- The curve is piecewise linear through knots (c_k, u_k), k = 0..306: u_k = 128 k (one knot per 64 DN of the 14-bit scale); c_k = u_k for k <= 11 (the identity through code 1408); c_k = 356.89 + 655.646 ln(k - 6) for k >= 12 (that is, c = -2824.32 + 655.646 ln(u - 768)). F(code) is the linear interpolation of u over c, rounded half up (floor(x + 0.5)). Values: F(1408) = 1408, F(1536) = 1542, F(2048) = 2457, F(3000) = 7979, F(3500) = 16227, F(3977) = 32767, F(4095) = 39077. +- `arw6_curve.rs` builds the 4096-entry table from the formula at first use; a unit test pins the whole table (its sum and position-weighted sum), so a platform whose `ln` rounds differently fails it. +- The decoder reports black 1024 and white = 2 x the file's DNG `WhiteLevel` (16383), i.e. 32766; a file without a usable white level gets 32766 too (2 x 16383), not a data-derived value. Codes above 3977 sit above white and clip as usual. + +#### How it was measured + +Each of the four scenes of the CC0 set (APS-C and full frame, landscape and portrait) has a lossless (LJ92) file and a Compressed and an HQ file, shot handheld one after another. Seven Compressed / HQ files share shutter, aperture and ISO with their lossless sibling. The eighth, APSC_land RAW-C (1/500 s against 1/1000 s), was left out: its brightness ratio to the lossless file is 1.37 rather than 2 and drifts with level, so the light changed between the shots. + +- Data: the ARW6 12-bit codes from LightCraft's decoder with the curve replaced by the identity, and the lossless 14-bit DN from LightCraft's LJ92 path. Both modes share the sensor origin (their crop tags are equal); the lossless frame is the ARW6 frame padded with zeros at the right and bottom. +- Registration: the handheld shifts are large (median 3 to 102 green cells). Patches were registered locally on the green planes with a curve-independent rank transform, normalised cross-correlation and a neighbour-consistency filter. +- Two estimators per pair and CFA channel, each capture with its own gain and offset (the gains' geometric mean fixed to 1, the offsets' mean to 0): + - quantile (CDF) matching over all overlapping pixels: for each code, the mean lossless value over the slice of the distribution the code occupies (precise, slightly smoothed by compression noise); + - block pairs: smooth 8 x 8-cell blocks (16 x 16 sensor pixels) away from clipping, a model linear in F, fitted robustly (unbiased). +- Fitting c = C + A ln(u - B) through the knots gives A 655.88, B 766.9, C -2826.5 on the blocks and A 653.47, B 770.1 on the quantile curves. Holding B at 768 changes the curve by at most 0.08 %; the formula above (A 655.646, C -2824.32) uses it. + +Uncertainty: 95 % intervals of a cluster bootstrap over the 7 captures (40 replicates), as a share of F - 1024 and in codes, and the largest deviation of any subset or method fit (Compressed only, HQ only, greens, red + blue, APS-C, full frame, quantile method): + +| Codes | Bootstrap 95 % | In codes | Largest subset / method deviation | +|---|---|---|---| +| 1408-1536 | -0.42..+0.35 % | -1.6..+2.0 | 0.75 % | +| 1536-2048 | -0.65..+0.58 % | -3.0..+2.8 | 0.80 % | +| 2048-2560 | -0.55..+0.57 % | -3.1..+3.3 | 0.78 % | +| 2560-3072 | -0.59..+0.50 % | -3.1..+3.7 | 0.64 % | +| 3072-3584 | -0.76..+0.54 % | -3.5..+4.9 | 0.77 % (quantile) | +| 3584-3840 | -0.84..+0.57 % | -3.7..+5.5 | 0.90 % (quantile) | +| 3840-3977 | -0.88..+0.59 % | -3.8..+5.8 | 0.97 % (quantile) | +| 3977-4095 | -0.91..+0.62 % | -4.0..+5.9 | 1.03 %, extrapolated | + +The lossless files clip at the 14-bit white, so codes above about 3977 rest on the formula alone. The camera's exact integer table can't be recovered: integer knot codes, the encoder's rounding and a few codes around the knee are below the measurement's resolution. + +#### Evidence for the structure + +- Knots every 128 u: the measured slope dF/dc is flat within segments and jumps at codes 1531, 1632, 1719, 1796, 1865, 1928, 1984, 2037, 2085…, where u = 1536, 1664, 1792…. On codes 1380-2200 a spacing of 128 leaves 0.021 RMS relative slope error; the next best, 126, 64 and a smooth log, leave 0.037, 0.041 and 0.068. Above code 2200 the segments are too short to resolve, but there the piecewise-linear and smooth forms differ by less than 1. +- Log spacing: the measured knot codes follow c = C + A ln(u - B) with chi-squared per degree of freedom 0.90 (bootstrap 95 %: A 654.3-658.2, B 762.8-771.1). +- The knee: the log branch at u = 1408 gives code 1413 (95 % 1410-1415), so the identity runs through knot 11 and the log knots start at k = 12 (segment slope 1.035 between them). Starting them at k = 11 fits as well but would need a slope below 1 right after the identity; a smooth log leaving the identity near code 1340 fits the blocks clearly worse (cost 25.4 against 22.9). +- One curve for everything: Compressed and HQ, all four CFA channels, APS-C and full frame agree within 0.8 %, and the ratio is flat with frame radius to +-0.5 % (no gain map). + +#### Scale + +The x2 unit is measured, not assumed: + +- Below the knee F(c) = c: the measured slope is 1.000 +- 0.01 for codes 1150-1408, with offsets within +-2. +- The overall level is fixed by the captures' average exposure to +-0.4 % (per-capture gains 0.99-1.02). Independently, flat clipped areas of the Compressed files sit at code 3977 +- 1 in all four scenes, and the formula, not fitted to that, puts the 14-bit white (32766) at code 3977.0 (bootstrap 95 % 3973-3983). +- HQ files carry data above the 14-bit clip: their clipped highlights sit at codes 3996-4095 depending on the scene (about 16.8k-19.5k DN), so the curve keeps its values above 32766. The reported white level is unaffected. + +#### Not stored in the file + +Every IFD of all 12 files was dumped and compared across modes: + +- Raw SubIFD: `0x7010` (SonyToneCurve) and `0x7011` are zero. The monotone arrays `0x7032`, `0x7035` and `0x7037` are lens corrections, the same in every mode. The only mode-dependent tag is `0x7000` SonyRawFileType (4 against 6). +- Maker note (`0x9050`, `0x94xx`, deciphered): the Compressed and HQ bytes differ from the lossless ones only in 1-2 bytes (the quality setting), and hold no curve-shaped monotone run. +- SR2SubIFD (encrypted, 42478 bytes): every file uses the same keystream, so XOR-ing two files compares their plaintexts. The lossless and HQ files of a scene differ in only 34 bytes, so there is no ARW6-only region. A curve stored identically in every mode can't be ruled out, but none is known there. `0x7250` likewise has no mode-specific region. +- The bytes after the tile table (480 on APS-C, 408 on full frame; the last 120 high-entropy) are identical in the Compressed and HQ files of a scene, even at different exposure, and differ between scenes: not a curve. + +#### Verification against the oracle + +After the derivation was frozen, the derived table was compared with the black-box oracle's output curve (below), as a check only, with no tuning. They are identical through code 1422 (both are the identity through 1408), then within -1.0 % to +0.25 % of (value - black); the largest difference is 75 (0.2 %) at code 4093. Ours minus the oracle's: -5..+1 for codes 1408-1536, -13..-2 for 1536-2048, -33..-12 for 2048-3072, -34..+40 for 3072-3977, +1..+75 for 3977-4095. ## Verification -Method: LibRaw master (commit `d1f0dd95`, 2026-10-08, run as `unprocessed_raw`, 16-bit output before any processing) was used only as a black-box oracle: it was built and run, and its source was never read. A Python reference model of the format (the Phase 0 reference model, local, not in the repo) was written from RDD 34 and from the oracle's behaviour on real and synthetic input, then reproduced the oracle exactly on every tile of the 8 Compressed / HQ files below. A test-only encoder, validated byte for byte against real tiles, probed the oracle with synthetic coefficients (dequantiser, phases, edge mapping). The Rust decoder reproduces the Phase 0 reference sums on all 8 files. +Method: LibRaw master (commit `d1f0dd95`, 2026-10-08, run as `unprocessed_raw`, 16-bit output before any processing) was used only as a black-box oracle: it was built and run, and its source was never read. A Python reference model of the format (the Phase 0 reference model, local, not in the repo) was written from RDD 34 and from the oracle's behaviour on real and synthetic input, then reproduced the oracle exactly on every tile of the 8 Compressed / HQ files below. A test-only encoder, validated byte for byte against real tiles, probed the oracle with synthetic coefficients (dequantiser, phases, edge mapping). The Rust decoder reproduced the Phase 0 reference sums on all 8 files. Its output then went through a table read off the oracle's output; that table was strictly increasing, so these exact matches prove the 12-bit codes before the curve identical to the oracle's. The table has since been replaced by our own measured curve (*Output range*), so the output values now differ from the oracle's by the amounts in *Verification against the oracle*. Geometry was checked against each file's embedded full-resolution JPEG at the DefaultCropOrigin: our output aligns at offset 0 on full frame and APS-C. ### LibRaw's APS-C bug -LibRaw assumes the full-frame grid (s = 0) for every tile. On the APS-C crop that drops the first three plane rows, leaves the last three unfed, and shifts its whole output up by 6 sensor rows; its first rows and last rows are also wrong. Our decoder differs from LibRaw there on purpose. To compare against LibRaw on APS-C files, our row y+6 equals LibRaw's row y for 12 <= y < h - 24 (LibRaw's rows 0-11 and the last 18 rows of the shifted overlap differ); on full frame compare directly, the whole frame is exact. +LibRaw assumes the full-frame grid (s = 0) for every tile. On the APS-C crop that drops the first three plane rows, leaves the last three unfed, and shifts its whole output up by 6 sensor rows; its first rows and last rows are also wrong. Our decoder differs from LibRaw there on purpose. To compare against LibRaw on APS-C files, our row y+6 equals LibRaw's row y for 12 <= y < h - 24 (LibRaw's rows 0-11 and the last 18 rows of the shifted overlap differ); on full frame compare directly: the 12-bit codes match over the whole frame. ### Corpus @@ -74,9 +129,9 @@ LibRaw assumes the full-frame grid (s = 0) for every tile. On the APS-C crop tha These 12 files are CC0 1.0. RawDB's record of the set, (the data behind , accessed 2026-10-10), says `"license":"CC0 1.0"` for the set (uploaded by abbradar, 2026-08-29) and again for each of the 12 files, next to the SHA-256 values in the table. -They live in the gitignored corpus. `cargo xtask corpus --download` fetches two of them, one per geometry and compression mode (full frame Compressed, APS-C HQ), and checks each against its SHA-256, pinned in `RAW_SAMPLES` (`xtask/src/main.rs`). Fetch the other ten by hand: the server answers 303 to a signed object URL, so `curl -L -o corpus/raw/ https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/`, then compare with the SHA-256 above. `cargo test -p lightcraft-raw corpus_sony -- --nocapture` checks the decoder's sensor sum and position-weighted sum of the two pinned files against the Phase 0 reference sums and skips absent files. +They live in the gitignored corpus. `cargo xtask corpus --download` fetches two of them, one per geometry and compression mode (full frame Compressed, APS-C HQ), and checks each against its SHA-256, pinned in `RAW_SAMPLES` (`xtask/src/main.rs`). Fetch the other ten by hand: the server answers 303 to a signed object URL, so `curl -L -o corpus/raw/ https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/`, then compare with the SHA-256 above. `cargo test -p lightcraft-raw corpus_sony -- --nocapture` checks the decoder's sensor sum and position-weighted sum of the two pinned files and skips absent files. The sums are regression values from LightCraft's decoder with the derived curve; the 12-bit codes behind them were verified against the oracle in Phase 0. -Nine further full-frame HQ photos from the maintainer's A7R VI were compared with the oracle locally; they are private and never committed or published. All 9 private FF photos (ISO 100-12800, incl. two near-black night shots) decode bit-exact over the full frame (0 mismatching pixels of 66.8 MP each). +Nine further full-frame HQ photos from the maintainer's A7R VI were compared with the oracle locally; they are private and never committed or published. On all 9 (ISO 100-12800, incl. two near-black night shots) the 12-bit codes matched the oracle over the full frame (0 mismatching pixels of 66.8 MP each). Unconditional synthetic tests (encode -> decode round trips for both geometries, the RDD 34 worked example, the dequantiser, hostile and truncated input) run without the corpus. @@ -84,16 +139,15 @@ Unconditional synthetic tests (encode -> decode round trips for both geometries, | Coverage | Status | |---|---| -| ILCE-7RM6 Compressed and HQ, full frame, landscape and portrait | 4 files, exact against the reference sums | -| ILCE-7RM6 Compressed and HQ, APS-C crop, landscape and portrait | 4 files, exact against the reference sums (interior-exact against LibRaw after the 6-row shift; LibRaw's own edge rows differ) | +| ILCE-7RM6 Compressed and HQ, full frame, landscape and portrait | 4 files, 12-bit codes exact against the oracle; output through our measured curve | +| ILCE-7RM6 Compressed and HQ, APS-C crop, landscape and portrait | 4 files, 12-bit codes exact against the Phase 0 model (interior-exact against LibRaw after the 6-row shift; LibRaw's own edge rows differ) | | ILCE-7RM6 lossless (existing LJ92 path) | 4 files decode; not in the corpus test | -| Private A7R VI HQ photos | 9 files, bit-exact over the full frame against the oracle (local) | +| Private A7R VI HQ photos | 9 files, 12-bit codes exact over the full frame against the oracle (local) | ## Not covered - The 12-bit Compressed mode (electronic shutter with continuous drive): no sample exists, so it returns `Unsupported` unless its headers prove identical. - The ILCE-7M5: same codec, no sample; unverified. -- The x2 scale is an assumption backed by shadow-floor evidence (the darkest pixels of all eight ISO 100 files sit at 1037..1059, just above 2 x 512, and the lossless sibling's shadows match at x2; x2.38 would put them 76 DN below black). A tripod-matched lossless / compressed pair would confirm it. If wrong, only the reported black and white levels change. - Tiles whose plane width is not a multiple of 8. - First-half shifts other than 0 and 3 (other crops / bodies): the geometry is generic and round-trip tested, but no real sample exists. - Memory: one FF decode peaks at about 896 MB RSS (about 6.7 x the 134 MB output; the lossless path peaks at 249 MB). Follow-ups: dequantise straight into bands, place tiles as they arrive. @@ -102,9 +156,9 @@ Unconditional synthetic tests (encode -> decode round trips for both geometries, ## Sources - SMPTE RDD 34:2015 "LLVC (Low Latency Video Codec) for Network Transfer", (accessed 2026-10-09): picture / TU structure, VLD, inverse quantisation, 5/3 lifting with symmetric extension. -- LibRaw master `d1f0dd95`, run only as a black-box oracle (not a product, test or build dependency). +- LibRaw master `d1f0dd95`, run only as a black-box oracle (not a product, test or build dependency) for the 12-bit codes; the companding curve was measured without it and compared with it only afterwards. - The embedded JPEG of each file, for the geometry check. -- Not read, by licence: LibRaw, rawspeed, dnglab, RawTherapee and other ARW6 decoder sources. Exact byte layouts, deviations, geometry and the table were established through sample analysis and black-box comparison. +- Not read, by licence: LibRaw, rawspeed, dnglab, RawTherapee and other ARW6 decoder sources. Exact byte layouts, deviations and geometry were established through sample analysis and black-box comparison; the curve was measured from the CC0 lossless / ARW6 pairs. ## Timings diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 46199a90..06349514 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -80,8 +80,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate, photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop; masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs; Adobe profile formats deliberately unsupported | | LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); browsed photos stay out of All Photos, albums and counts; folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back; a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | -| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG, PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP; DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared linear primaries without clipping or gamut mapping, checked on one real file with 108 lossy tiles, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`, FF files bit-exact over the full frame, APS-C files interior-exact (LibRaw's own edge rows differ); 8 CC0 files checked against a black-box oracle and the Phase 0 reference sums, geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth but CFA and black unverified), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8 (`crates/raw/tests/cr3_corpus.rs`, `docs/cr3.md`). Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), NEFs labelled compressed (34713) but stored uncompressed without a `0x0096` table (Z 6 packed 14-bit, D850 12-bit uncompressed), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and Kodak DCS TIFFs: IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Canon CRW, Minolta MRW and Sigma X3F (containers recognised by magic, preview found by a structural JPEG scan), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan), and any decode failure of a recognised raw, not only an unsupported variant; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate) | -| LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/corpus.rs`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535; pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 sensor arrays verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; private Z 8 crop verified. | +| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG, PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP; DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared linear primaries without clipping or gamut mapping, checked on one real file with 108 lossy tiles, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth but CFA and black unverified), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8 (`crates/raw/tests/cr3_corpus.rs`, `docs/cr3.md`). Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), NEFs labelled compressed (34713) but stored uncompressed without a `0x0096` table (Z 6 packed 14-bit, D850 12-bit uncompressed), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and Kodak DCS TIFFs: IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Canon CRW, Minolta MRW and Sigma X3F (containers recognised by magic, preview found by a structural JPEG scan), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan), and any decode failure of a recognised raw, not only an unsupported variant; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate) | +| LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/corpus.rs`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535; pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; private Z 8 crop verified. | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | | LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests_import_move.rs`, `crates/ui-egui/src/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving | | LR-IMP-DNG-CONVERT | Convert to DNG on import [Classic] | P2 | ✅ | `cmd:library.import` (`dng`), `crates/ui-egui/src/import.rs` | copy imports: Raw files ▸ Copy as DNG (lossless; the card is untouched); the raw copy is removed only once its DNG is verified and on disk (issue #106) |