diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 63788351..ea61c347 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 = 56; +pub const RENDER_CACHE_VERSION: u64 = 57; /// 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]; diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index b2996db3..139c80d4 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..0e2cc39c --- /dev/null +++ b/crates/raw/src/llvc.rs @@ -0,0 +1,471 @@ +//! 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. + +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> { + 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); + 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")); + } + } + } +} + +/// 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) +} + +/// 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)| 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 = sat(i64::from(hv) + ((i64::from(at(&even, k as isize - p)) + i64::from(at(&even, k as isize + 1 - p))) >> 1)); + } + Ok(x) +} + +/// 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())); + } + 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::*; + 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 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 + 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 0usize..300) { + let mut b = Bits::new(&src); + 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 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)); + 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/arw.rs b/crates/raw/src/vendor/arw.rs index 18e51e08..e8c76600 100644 --- a/crates/raw/src/vendor/arw.rs +++ b/crates/raw/src/vendor/arw.rs @@ -37,10 +37,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; @@ -630,6 +633,14 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { (RawData::U16(Vec::new()), bits) } }, + 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 without exactly one strip".into())), 1 => { let word16 = strip_len >= (w * h * 2) as u64; let packing = if word16 { Packing::Word16 } else { Packing::Msb }; @@ -667,11 +678,20 @@ 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; without the tag the white is the + // 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 } 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)) + 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(); let mn = tiff .exif() diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs new file mode 100644 index 00000000..f6f535bd --- /dev/null +++ b/crates/raw/src/vendor/arw6.rs @@ -0,0 +1,994 @@ +//! 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 +//! 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::curve; +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}")) +} + +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, *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) +} + +/// 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 { + 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, + /// 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 (*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, 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) +} + +// ---- sensor-anchored frame geometry and tile reconstruction (*Frame geometry*) ---- + +/// Halves of `vs` plane rows are anchored to the sensor: half `n` covers plane rows `8n - 6 + s .. 8n + 1 + s`, so +/// `ceil((vs - 2 - s) / 8) + 1` halves are needed, two per TU (*Container*). +pub(crate) fn tu_count(vs: usize, s: u8) -> 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` (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); + 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 (*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; + } + // 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")), + } +} + +/// 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)); + 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")); + } + } + // 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() +} + +/// 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 *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 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")); + } + for (&row, line) in r.l3.iter().zip(l0) { + let mut acc = if c == 0 { 2048i32 } else { 0 }; + 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::>().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) { + 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 }) +} + +/// 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. +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).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)]; + 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::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) { + 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) + } + + /// 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.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], ntu).unwrap(); + assert_eq!(g3.len(), 4); + assert_eq!(g3[0].qi, [1, 1, 2]); + 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(); + 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 + } + + 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, tu_count(24, 0)).is_err()); + let outside = StreamRef { index_words: 0xffff, ..s.clone() }; + assert!(stream_halves(&tile, &outside, tu_count(24, 0)).is_err()); + } + + #[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(); + let ntu = tu_count(24, s); + for st in &h.streams { + 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], 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); + } + + #[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(&tile[..n], 64, 48); + let _ = decode_tile(&tile, 64, 48); + } + } + + 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], 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 + } + + #[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); + 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 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 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) < curve(4095)); + } + } + } + } + } + + #[test] + 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(); + 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] + 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() + .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(); + 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!() }; + 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 + } +} diff --git a/crates/raw/src/vendor/arw6_curve.rs b/crates/raw/src/vendor/arw6_curve.rs new file mode 100644 index 00000000..f7c748a1 --- /dev/null +++ b/crates/raw/src/vendor/arw6_curve.rs @@ -0,0 +1,55 @@ +//! 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*). + +use std::sync::OnceLock; + +/// 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/src/vendor/arw6_testenc.rs b/crates/raw/src/vendor/arw6_testenc.rs new file mode 100644 index 00000000..54933112 --- /dev/null +++ b/crates/raw/src/vendor/arw6_testenc.rs @@ -0,0 +1,483 @@ +//! 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; +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 { + 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 (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); + 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 } +} + +// ---- 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)] +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 (*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 (*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 (*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); + 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 = if c == 0 { 2048 } else { 0 }; + 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 { + 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, 14) +} + +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; + 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![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])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); + raw.set(0x7310, Value::Short(vec![512; 4])); + 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())); + 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() +} + +/// 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 (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}; + 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 == 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, + 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, 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]), + 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) +} diff --git a/crates/raw/src/vendor/mod.rs b/crates/raw/src/vendor/mod.rs index f2e0b6a3..f0478a94 100644 --- a/crates/raw/src/vendor/mod.rs +++ b/crates/raw/src/vendor/mod.rs @@ -1,6 +1,10 @@ //! Vendor raw formats (TIFF-based) and helpers shared by them. pub mod arw; +pub mod arw6; +mod arw6_curve; +#[cfg(test)] +pub(crate) mod arw6_testenc; mod arw_lens; pub mod cr2; pub mod cr3; diff --git a/crates/raw/tests/corpus.rs b/crates/raw/tests/corpus.rs index 920965bf..b58bacdd 100644 --- a/crates/raw/tests/corpus.rs +++ b/crates/raw/tests/corpus.rs @@ -902,6 +902,39 @@ fn corpus_fujifilm_compressed_samples() { eprintln!("verified {seen} Fujifilm compressed sensor arrays"); } +/// 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 Ok(bytes) = std::fs::read(dir.join(name)) else { continue }; + 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 +} + +/// 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, 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"); +} + /// 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/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 { diff --git a/docs/arw6-compression.md b/docs/arw6-compression.md new file mode 100644 index 00000000..3b65c1d3 --- /dev/null +++ b/docs/arw6-compression.md @@ -0,0 +1,174 @@ +# 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 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. 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. + +### 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 (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 + +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 + ((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 curve) + +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 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 12-bit codes match over the whole frame. + +### Corpus + +| 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. 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 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. 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. + +## Coverage + +| Coverage | Status | +|---|---| +| 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, 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. +- 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 + +- 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) 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 and geometry were established through sample analysis and black-box comparison; the curve was measured from the CC0 lossless / ARW6 pairs. + +## Timings + +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.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. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index d30e4f30..96d754b2 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 (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); 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 (album commands skip them and the album menus say to Add to My Photos first, issue #684); 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), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), 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. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. 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`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. 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 the Kodak DCS Pro / DCS760C TIFFs (compression 65000): 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 and 4 pinned EOS R5 Mark II files (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, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); 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; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). | +| 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), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), 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. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. 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`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. 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 the Kodak DCS Pro / DCS760C TIFFs (compression 65000): 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 and 4 pinned EOS R5 Mark II files (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, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); 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; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). | | 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 dcbd7d76..39544fc4 100644 --- a/docs/raw-parity.md +++ b/docs/raw-parity.md @@ -123,6 +123,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 6d411dc3..08ef435c 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -808,6 +808,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, 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-ff-land-c.arw", + "https://rawdb.dnglab.org/api/download/Sony/ILCE-7RM6/arw6/ILCE-7RM6_FF_land_RAW-C.ARW", + "d900d6cbe838be864269ad54de4a33fcac7eb3a3d4f91009739f770b8f85a23b", + ), ( "rw2-panasonic-g9-b.rw2", "https://raw.pixls.us/getfile.php/2348/nice/Panasonic%20-%20DC-G9%20-%204:3.RW2",