Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

DNG: deflate compression 8 with the TIFF predictors (#1971)

Elvis33LE08ca44578208
diff --git a/Cargo.lock b/Cargo.lock
index 599dc4d9a..11b88c8ae 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4297,6 +4297,7 @@ dependencies = [
name = "photocraft-raw"
version = "0.5.0"
dependencies = [
+ "flate2",
"photocraft-raw",
"png 0.18.1",
"rayon",
diff --git a/crates/raw/Cargo.toml b/crates/raw/Cargo.toml
index 55960b33c..608594c5b 100644
--- a/crates/raw/Cargo.toml
+++ b/crates/raw/Cargo.toml
@@ -15,6 +15,8 @@ testgen = []
corpus = []
[dependencies]
+# Adobe DNG compression 8: zlib (RFC 1950) with the TIFF predictor (pure-Rust backend).
+flate2 = { workspace = true }
# Parallel bands on native; wasm builds stay single-threaded.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
diff --git a/crates/raw/src/sensor.rs b/crates/raw/src/sensor.rs
index dc7ad52f3..9eae9c5b0 100644
--- a/crates/raw/src/sensor.rs
+++ b/crates/raw/src/sensor.rs
@@ -209,8 +209,7 @@ pub(crate) fn read_plane(t: &Tiff, ifd: &Ifd, limits: &Limits, layout: JpegLayou
return Err(RawError::unsupported("planar raw data"));
}
match compression {
- 1 | 7 => {}
- 8 => return Err(RawError::unsupported("Deflate-compressed (floating-point) DNG")),
+ 1 | 7 | 8 => {}
34892 => return Err(RawError::unsupported("lossy-compressed DNG")),
52546 => return Err(RawError::unsupported("JPEG XL-compressed DNG")),
34713 => return Err(RawError::unsupported("Nikon compressed NEF")),
@@ -227,6 +226,26 @@ pub(crate) fn read_plane(t: &Tiff, ifd: &Ifd, limits: &Limits, layout: JpegLayou
let src = t.bytes(s.offset, s.len).ok_or_else(|| RawError::malformed("raw data lies outside the file"))?;
match compression {
1 => unpack(src, s.w, rows, samples, bits, le),
+ 8 => {
+ // Adobe DNG compression 8: zlib streams (RFC 1950). The output is capped at the
+ // tile's size in whole bytes per sample, so a bomb cannot grow past the tile;
+ // `unpack` then reads it bit-packed or in 16-bit containers by its length.
+ let too_big = || RawError::malformed("deflate tile is too large");
+ let need =
+ s.w.checked_mul(rows).and_then(|n| n.checked_mul(samples)).and_then(|n| n.checked_mul((bits as usize).div_ceil(8))).ok_or_else(too_big)?;
+ let mut out = vec![0u8; need];
+ let mut d = flate2::Decompress::new(true);
+ d.decompress(src, &mut out, flate2::FlushDecompress::Finish).map_err(|_| RawError::malformed("deflate tile does not decompress"))?;
+ out.truncate(usize::try_from(d.total_out()).unwrap_or(need).min(need));
+ let v = unpack(&out, s.w, rows, samples, bits, le)?;
+ // The TIFF predictor runs after unpacking, per row, per sample plane.
+ match t.tag_uint(ifd, tag::PREDICTOR).unwrap_or(1) {
+ 1 => Ok(v),
+ 2 => Ok(undelta(&v, samples, s.w * samples, rows, bits)),
+ 3 => Err(RawError::unsupported("floating-point predictor (compression 8, predictor 3)")),
+ p => Err(RawError::malformed(format!("unknown predictor {p}"))),
+ }
+ }
_ => {
let need = s.w * rows * samples;
let max = s.w.saturating_mul(s.h).saturating_mul(samples).saturating_mul(4);
@@ -306,6 +325,21 @@ pub(crate) fn segments(t: &Tiff, ifd: &Ifd, width: usize, height: usize) -> Resu
Ok(out)
}
+/// Reverses TIFF predictor 2 (horizontal differencing) on interleaved samples: each sample
+/// gains its channel's predecessor in the row, wrapping at the sample's container (8 or 16 bits).
+fn undelta(v: &[u16], plane: usize, row_samples: usize, rows: usize, bits: u32) -> Vec<u16> {
+ let mask: u16 = if bits <= 8 { 0xFF } else { 0xFFFF };
+ let mut out = v.to_vec();
+ for row in out.chunks_mut(row_samples.max(1)).take(rows) {
+ for i in plane..row.len() {
+ if let (Some(&prev), Some(&cur)) = (row.get(i - plane), row.get(i)) {
+ row[i] = cur.wrapping_add(prev) & mask;
+ }
+ }
+ }
+ out
+}
+
/// Unpacks uncompressed samples: 8-bit, 16-bit in the file's byte order, or
/// MSB-first bit-packed rows padded to a byte (TIFF 6.0). 9–15-bit data
/// stored in 16-bit containers (common in camera raws) is recognised by its
diff --git a/crates/raw/src/testgen.rs b/crates/raw/src/testgen.rs
index f9faf0d98..e3611d8ed 100644
--- a/crates/raw/src/testgen.rs
+++ b/crates/raw/src/testgen.rs
@@ -368,6 +368,9 @@ fn urat(v: f64) -> (u32, u32) {
pub enum DngStorage {
/// One strip per `rows` rows, uncompressed at `bits` per sample (8, 12, 16…).
Strips { rows: usize },
+ /// Adobe DNG compression 8: zlib streams with the TIFF predictor (1 = none, 2 = horizontal
+ /// differencing) applied before compressing.
+ DeflateStrips { rows: usize, predictor: u16 },
/// Lossless-JPEG tiles of this size (2 components per JPEG row, as Adobe writes CFA tiles).
Lj92Tiles { width: usize, height: usize },
/// Lossless-JPEG strips of this many rows, 1 component.
@@ -496,6 +499,42 @@ impl DngSpec {
raw.push((50711, Val::Short(vec![1])));
}
match self.storage {
+ DngStorage::DeflateStrips { rows, predictor } => {
+ use std::io::Write;
+ let mut offs = Vec::new();
+ let mut lens = Vec::new();
+ for y in (0..self.height).step_by(rows) {
+ let r = (y + rows).min(self.height) - y;
+ let n = self.width * self.samples;
+ let mut v: Vec<u16> = self.data[y * n..(y + r) * n].to_vec();
+ if predictor == 2 {
+ // Horizontal differencing on the sample values, before byte packing
+ // (the reader undoes predictor after unpacking, per row, per channel).
+ let plane = if self.samples.is_multiple_of(3) { 3 } else { 1 };
+ for row in v.chunks_mut(n) {
+ for i in (plane..row.len()).rev() {
+ row[i] = row[i].wrapping_sub(row[i - plane]);
+ }
+ }
+ }
+ // Pack the delta'd values with the file's byte order and bit depth.
+ let bytes: Vec<u8> = match self.bits {
+ 8 => v.iter().map(|&x| x as u8).collect(),
+ 16 => v.iter().flat_map(|&x| if self.big_endian { x.to_be_bytes() } else { x.to_le_bytes() }).collect(),
+ _ => v.iter().flat_map(|x| x.to_le_bytes()).collect(),
+ };
+ let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
+ e.write_all(&bytes).expect("zlib");
+ let z = e.finish().expect("zlib");
+ lens.push(z.len() as u32);
+ offs.push(t.blob(z));
+ }
+ raw.push((259, Val::Short(vec![8])));
+ raw.push((317, Val::Short(vec![predictor])));
+ raw.push((278, Val::Long(vec![rows as u32])));
+ raw.push((273, Val::Blobs(offs)));
+ raw.push((279, Val::Long(lens)));
+ }
DngStorage::Strips { rows } => {
let mut offs = Vec::new();
let mut lens = Vec::new();
diff --git a/crates/raw/src/tiff.rs b/crates/raw/src/tiff.rs
index 6313f52e8..e5cb396c6 100644
--- a/crates/raw/src/tiff.rs
+++ b/crates/raw/src/tiff.rs
@@ -13,6 +13,7 @@ pub(crate) mod tag {
pub const IMAGE_LENGTH: u16 = 257;
pub const BITS_PER_SAMPLE: u16 = 258;
pub const COMPRESSION: u16 = 259;
+ pub const PREDICTOR: u16 = 317;
pub const PHOTOMETRIC: u16 = 262;
pub const MAKE: u16 = 271;
pub const MODEL: u16 = 272;
diff --git a/crates/raw/tests/dng.rs b/crates/raw/tests/dng.rs
index eaf6e2e2a..9bd2886ac 100644
--- a/crates/raw/tests/dng.rs
+++ b/crates/raw/tests/dng.rs
@@ -371,3 +371,82 @@ fn limits_are_enforced_before_allocating() {
let tiny = Limits { max_alloc: 1000, ..Limits::default() };
assert!(matches!(decode(&b, &tiny), Err(RawError::LimitExceeded(_))));
}
+
+/// Adobe DNG compression 8 (zlib): with and without the horizontal-differencing predictor,
+/// with and without 12-bit packing, and both byte orders — each decodes to the exact samples.
+#[test]
+fn deflate_strips_round_trip() {
+ let (w, h) = (48, 40);
+ for (name, bits, storage, be) in [
+ ("deflate 16-bit", 16, DngStorage::DeflateStrips { rows: 16, predictor: 1 }, false),
+ ("deflate 16-bit predictor 2", 16, DngStorage::DeflateStrips { rows: 16, predictor: 2 }, false),
+ ("deflate 12-bit predictor 2", 12, DngStorage::DeflateStrips { rows: 12, predictor: 2 }, false),
+ ("deflate 16-bit predictor 2 BE", 16, DngStorage::DeflateStrips { rows: 16, predictor: 2 }, true),
+ ("deflate LinearRaw predictor 2", 16, DngStorage::DeflateStrips { rows: 40, predictor: 2 }, false),
+ ] {
+ let samples = if name.contains("LinearRaw") { 3 } else { 1 };
+ let data = noise(w * h * samples, bits);
+ let mut spec = DngSpec::cfa(w, h, data.clone());
+ spec.samples = samples;
+ spec.bits = bits;
+ spec.storage = storage;
+ spec.big_endian = be;
+ spec.white = (1 << bits) - 1;
+ let s = sensor(&spec.build());
+ assert_eq!((s.width, s.height, s.samples), (w, h, samples), "{name}");
+ assert_eq!(s.data, data, "{name}");
+ }
+}
+
+/// A zlib stream cut short must fail cleanly (decompression comes up short or errors), and a
+/// declared-but-absent giant tile must trip the limits instead of allocating.
+#[test]
+fn deflate_hostile_fails_cleanly() {
+ let (w, h) = (32, 32);
+ let data = noise(w * h, 16);
+ let mut spec = DngSpec::cfa(w, h, data);
+ spec.storage = DngStorage::DeflateStrips { rows: 32, predictor: 2 };
+ let bytes = spec.build();
+ assert_eq!(sensor(&bytes).data.len(), w * h);
+ // Locate the zlib stream (78 9c header of the single strip) and cut it mid-stream.
+ let at = bytes.windows(2).position(|w| w == [0x78, 0x9c]).expect("zlib header") + 2;
+ let cut = &bytes[..at + (bytes.len() - at) / 2];
+ assert!(decode(cut, &Limits::default()).is_err(), "a cut zlib stream must not decode");
+}
+
+/// Predictor 2 on 8-bit samples wraps at 8 bits, and 12-bit samples bit-packed inside the zlib
+/// stream (not in 16-bit containers) decode too.
+#[test]
+fn deflate_8_bit_predictor_and_packed_12_bit() {
+ use std::io::Write as _;
+ let (w, h) = (16usize, 4usize);
+ let zlib = |bytes: &[u8]| {
+ let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
+ e.write_all(bytes).unwrap();
+ e.finish().unwrap()
+ };
+ // 8-bit, predictor 2: a row falling from 250 to 10 has deltas that wrap mod 256.
+ let data8: Vec<u16> = (0..w * h).map(|i| if i % w < w / 2 { 250 } else { 10 }).collect();
+ let mut spec = DngSpec::cfa(w, h, data8.clone());
+ spec.bits = 8;
+ spec.white = 255;
+ spec.storage = DngStorage::DeflateStrips { rows: h, predictor: 2 };
+ assert_eq!(sensor(&spec.build()).data, data8, "8-bit predictor 2");
+ // 12-bit packed: two samples in three bytes, MSB first. Swap the testgen's 16-bit
+ // containers for a packed stream of the same samples.
+ let data12: Vec<u16> = (0..w * h).map(|i| (i as u16 * 61) & 0xFFF).collect();
+ let mut spec = DngSpec::cfa(w, h, data12.clone());
+ spec.bits = 12;
+ spec.white = 4095;
+ spec.storage = DngStorage::DeflateStrips { rows: h, predictor: 1 };
+ let mut bytes = spec.build();
+ let containers: Vec<u8> = data12.iter().flat_map(|v| v.to_le_bytes()).collect();
+ let old = zlib(&containers);
+ let packed: Vec<u8> = data12.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 0xF) << 4 | p[1] >> 8) as u8, p[1] as u8]).collect();
+ let mut new = zlib(&packed);
+ let at = bytes.windows(old.len()).position(|c| c == old.as_slice()).expect("the strip");
+ assert!(new.len() <= old.len());
+ new.resize(old.len(), 0); // trailing bytes after the zlib stream are ignored
+ bytes[at..at + old.len()].copy_from_slice(&new);
+ assert_eq!(sensor(&bytes).data, data12, "12-bit packed");
+}