PhotoCraft: An open-source, photo editor written by scratch in pure Rust
raw: decode Panasonic RW2 RawFormat 3 and 4 (vendor-compressed) (#3286)
Gotya-OFFCIAL34ce5766d2b4
diff --git a/crates/raw/README.md b/crates/raw/README.mdindex 232ef83b3..b8c75ebff 100644--- a/crates/raw/README.md+++ b/crates/raw/README.md@@ -45,6 +45,10 @@ Implemented only from public specifications, papers and observation of files:by observation of sample files (bit packing, page layout, sample justification; for RAF thethree sample storages and the reversed order of the X-Trans / Bayer layout records, eachverified by developing with every candidate phase against the camera's preview).+* Panasonic RW2 RawFormat 3/4 (vendor-compressed): the fixed-rate 16 bytes per 14 pixels, the+ predictor groups with per-parity predictors, the 2/4/8-bit field widths, the page-permuted+ downward bit order and the black level sitting 15 counts above the recorded tags were all+ established by observation of sample files.* Demosaicing: Malvar, He & Cutler (ICASSP 2004); Hirakawa & Parks, "Adaptivehomogeneity-directed demosaicing" (IEEE TIP 2005); for X-Trans and other non-Bayer CFAs,gradient-weighted green interpolation (Lu & Tan, "Color filter array demosaicking: new method@@ -71,8 +75,9 @@ camera colour tables were copied.| Nikon compressed NEF (compression 34713): lossless and lossy type 1 / 2, 12 and 14 bit | Decoded: fixed Huffman tables + maker-note `0x0096` seeds and curve (see `src/nefc.rs`). BlackLevel `0x003d` is read in 14-bit units. "Lossy after split" files are unsupported (preview fallback) || Sony compressed ARW ("cRAW", SonyRawFileType 2) | Decoded: 11-bit min/max + 7-bit delta blocks, SonyToneCurve to 14 bits, the curve's 512 black level when no BlackLevel tag is written (the first-generation bodies, e.g. the ILCE-7) || Panasonic / Leica RW2, RawFormat 5 (12- and 14-bit packed) | Decoded, with PanasonicRaw black / white / WB / sensor borders |+| Panasonic / Leica RW2, RawFormat 3 and 4 (vendor-compressed, 12-bit) | Decoded; the black level is read 15 counts above the recorded tag; PanasonicRaw white / WB / sensor borders || Olympus ORF, uncompressed 16-bit (E-1, E-400…) | Decoded, with ImageProcessing black / WB / ValidBits / crop |-| Nikon "lossy after split" NEF, Sony "Compressed RAW 2", Pentax compressed PEF, RW2 RawFormat 4 and older, Olympus compressed ORF | Unsupported: no public description of these codes was found apart from GPL decoder source, which this crate may not use (clean-room). `photocraft-io` opens the embedded JPEG preview instead |+| Nikon "lossy after split" NEF, Sony "Compressed RAW 2", Pentax compressed PEF, RW2 RawFormat 6 and newer, Olympus compressed ORF | Unsupported: no public description of these codes was found apart from GPL decoder source, which this crate may not use (clean-room). `photocraft-io` opens the embedded JPEG preview instead || Fujifilm RAF, uncompressed (X-Trans I–V, GFX and Bayer bodies since about 2010) | Decoded: 16-bit containers (either byte order), 12-bit LSB-first packing, 14-bit packing in 32-bit words; X-Trans 6×6 or Bayer 2×2 layout, black, as-shot WB, crop, RawExposureBias, orientation from the preview's EXIF || Fujifilm compressed RAF, early FinePix / SuperCCD RAF (no CFA TIFF) | Unsupported (no public description of the compression); preview fallback || CR3 | Native CRX unsupported; bounded JPEG-track/PRVW preview fallback with CMT1 orientation. I/O labels the result as an 8-bit camera preview |diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rsindex f8304b3cf..0bccf8ffa 100644--- a/crates/raw/src/lib.rs+++ b/crates/raw/src/lib.rs@@ -32,9 +32,9 @@//! tiles, CFA and LinearRaw), CR2 (lossless JPEG with Canon slices), uncompressed or//! lossless-JPEG TIFF/EP raws (NEF, ARW, PEF… when not vendor-compressed),//! Nikon compressed NEF (lossless and lossy), Sony compressed ARW (cRAW),-//! Panasonic RW2 (RawFormat 5), uncompressed Olympus ORF and uncompressed-//! Fujifilm RAF (Bayer and X-Trans). Everything else reports-//! [`RawError::Unsupported`].+//! Panasonic RW2 (RawFormat 5 packed and RawFormat 3/4 vendor-compressed),+//! uncompressed Olympus ORF and uncompressed Fujifilm RAF (Bayer and+//! X-Trans). Everything else reports [`RawError::Unsupported`].//!//! The crate is standalone (no workspace dependencies), does no I/O, builds for//! `wasm32-unknown-unknown` and never panics on hostile input: sizes arediff --git a/crates/raw/src/rw2.rs b/crates/raw/src/rw2.rsindex 231cd0971..c50d32c09 100644--- a/crates/raw/src/rw2.rs+++ b/crates/raw/src/rw2.rs@@ -1,5 +1,6 @@-//! Panasonic / Leica RW2 with the bit-packed sensor layout (PanasonicRaw-//! RawFormat 5, written by recent Lumix bodies).+//! Panasonic / Leica RW2: the bit-packed stream of recent Lumix bodies+//! (PanasonicRaw RawFormat 5) and the vendor-compressed stream of the earlier+//! ones (RawFormat 3 and 4).//!//! The container is TIFF-like (`IIU\0`); IFD0 holds Panasonic's own tags,//! whose ids and meanings are public (ExifTool's PanasonicRaw table):@@ -9,7 +10,7 @@//! WB{Red,Green,Blue}Level (0x24–0x26), RawFormat (0x2D) and RawDataOffset//! (0x118).//!-//! The packing was established by observation of sample files:+//! RawFormat 5 — the packing was established by observation of sample files://!//! * From RawDataOffset the data is stored in pages of 0x4000 bytes, each//! page split at 0x1FF8 with its second part first (the logical page is@@ -19,8 +20,26 @@//! the least significant bit up, the remaining top bits unused; rows are//! whole blocks.//!-//! The older RawFormat 4 (and earlier) store vendor-compressed data, which is-//! not decoded.+//! RawFormat 3 and 4 — the vendor-compressed layout, also established by+//! observation of sample files (verified by decoding whole frames against the+//! camera's embedded JPEG and the recorded levels):+//!+//! * The payload at RawDataOffset is a fixed-rate stream: 16 bytes per 14+//! pixels, so a row occupies `width / 14 * 16` bytes and rows are+//! byte-aligned. Bits are consumed down from the top of each 0x4000-byte+//! page, through the same page split as RawFormat 5 (`(i + 0x4000 - 0x2008)+//! % 0x4000`), reading fields LSB-first from the little-endian 16-bit word+//! the cursor points at.+//! * Pixels arrive in groups of 14 with two predictors carried over from one+//! group to the next (even and odd columns). Every third pixel carries a+//! 2-bit scale selector `sh` (0, 1, 2 or 4). The first value of each parity+//! is absolute (8 + 4 bits); the rest are 8-bit deltas around 0x80 scaled+//! by `sh`, wrapping in the low `sh` bits.+//! * The decoded samples sit 15 counts above the recorded BlackLevel tags+//! (measured on the darkest pixels of sample files), so 15 is added when+//! they are read.+//!+//! Every other RawFormat value is not decoded.use crate::error::{RawError, Result};use crate::sensor::{BlackLevels, Cfa, Rect, Sensor};@@ -44,6 +63,8 @@ const RAW_DATA_OFFSET: u16 = 0x0118;/// Page size and split point of the stored stream (observed).const PAGE: usize = 0x4000;const SPLIT: usize = 0x1FF8;+/// Byte split of the vendor-compressed stream (observed).+const COMPRESSED_SPLIT: usize = 0x2008;/// Physical offset (relative to RawDataOffset) of logical byte `i`.#[inline]@@ -75,34 +96,13 @@ pub(crate) fn unpack_block(b: &[u8; 16], bits: u32, out: &mut [u16]) {}}-pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {- let ifd = t.ifd_at(t.first_ifd, 0).ok_or_else(|| RawError::malformed("RW2 has no IFD0"))?;- let raw_format = t.tag_uint(&ifd, RAW_FORMAT);- if raw_format != Some(5) {- let f = raw_format.map(|v| v.to_string()).unwrap_or_else(|| "unknown".into());- return Err(RawError::unsupported(format!("Panasonic RW2 raw format {f} (vendor-compressed) is not decoded yet")));- }- let width = t.tag_uint(&ifd, SENSOR_WIDTH).ok_or_else(|| RawError::malformed("RW2 has no sensor width"))? as usize;- let height = t.tag_uint(&ifd, SENSOR_HEIGHT).ok_or_else(|| RawError::malformed("RW2 has no sensor height"))? as usize;- let bits = t.tag_uint(&ifd, BITS_PER_SAMPLE).unwrap_or(12);+/// Reads the bit-packed RawFormat 5 stream (`src` starts at RawDataOffset).+fn decode_packed(src: &[u8], width: usize, height: usize, bits: u32) -> Result<Vec<u16>> {let ppb = pixels_per_block(bits).ok_or_else(|| RawError::unsupported(format!("Panasonic RW2 with {bits}-bit samples")))?;if !width.is_multiple_of(ppb) {return Err(RawError::unsupported(format!("Panasonic RW2 {width} pixels wide (not whole {ppb}-pixel blocks)")));}- limits.check(width as u64, height as u64, 2)?;- let cfa = match t.tag_uint(&ifd, CFA_PATTERN) {- Some(1) => "RGGB",- Some(2) => "GRBG",- Some(3) => "GBRG",- Some(4) => "BGGR",- _ => return Err(RawError::unsupported("Panasonic RW2 without a CFA pattern")),- };- let cfa = Cfa::bayer(cfa).ok_or_else(|| RawError::malformed("bad CFA"))?;- let offset =- t.tag_uint(&ifd, RAW_DATA_OFFSET).or_else(|| t.tag_uint(&ifd, tag::STRIP_OFFSETS)).ok_or_else(|| RawError::malformed("RW2 has no raw data offset"))?- as usize;let row_bytes = width / ppb * 16;- let src = t.data.get(offset..).ok_or_else(|| RawError::malformed("RW2 raw data lies outside the file"))?;let need = row_bytes * height;// Whole pages are stored; tolerate a short final page (its missing bytes read as 0).if src.len() < need.saturating_sub(PAGE) {@@ -124,11 +124,138 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {}}});+ Ok(data)+}++/// LSB-first bit cursor of the vendor-compressed stream: it walks down from+/// the top of each 0x4000-byte page (addressed through `COMPRESSED_SPLIT`)+/// and refills by advancing one page.+struct Bits<'a> {+ buf: &'a [u8],+ base: usize,+ pos: usize,+ nbits: u32,+}++impl<'a> Bits<'a> {+ fn new(buf: &'a [u8], base: usize) -> Self {+ Bits { buf, base, pos: 0, nbits: 0 }+ }++ #[inline]+ fn get(&mut self, num: u32) -> u32 {+ if num > self.nbits {+ self.nbits += PAGE as u32 * 8;+ self.pos += PAGE;+ }+ let mut at = ((self.nbits - num) >> 3) as usize ^ 0x3FF0;+ at = (at + PAGE - COMPRESSED_SPLIT) % PAGE;+ let at = self.base + at + self.pos - PAGE;+ self.nbits -= num;+ // Out-of-range reads (a page short at the end of the file) read as 0.+ let lo = u32::from(self.buf.get(at).copied().unwrap_or(0));+ let hi = u32::from(self.buf.get(at + 1).copied().unwrap_or(0));+ ((lo | (hi << 8)) >> (self.nbits & 7)) & ((1u32 << num) - 1)+ }+}++/// Decodes one row of the vendor-compressed stream.+fn compressed_row(buf: &[u8], row_bytes: usize, row: usize, out: &mut [u16]) {+ let skip = row_bytes * row;+ let mut bits = Bits::new(buf, skip / PAGE * PAGE);+ for _ in 0..(skip % PAGE) {+ bits.get(8);+ }+ let mut sh: i32 = 0;+ for group in out.as_chunks_mut::<14>().0 {+ let mut pred = [0i32; 2];+ let mut nonz = [0i32; 2];+ for (i, px) in group.iter_mut().enumerate() {+ if i % 3 == 2 {+ sh = 4 >> (3 - bits.get(2));+ }+ let p = i & 1;+ if nonz[p] != 0 {+ let j = bits.get(8) as i32;+ if j != 0 {+ pred[p] -= 0x80 << sh;+ if pred[p] < 0 || sh == 4 {+ pred[p] &= !(-1 << sh);+ }+ pred[p] += j << sh;+ }+ } else {+ nonz[p] = bits.get(8) as i32;+ if nonz[p] != 0 || i > 11 {+ pred[p] = (nonz[p] << 4) | bits.get(4) as i32;+ }+ }+ *px = pred[p] as u16;+ }+ }+}++/// Reads the vendor-compressed RawFormat 3/4 stream (`src` starts at+/// RawDataOffset).+fn decode_compressed(src: &[u8], width: usize, height: usize, bits: u32) -> Result<Vec<u16>> {+ if bits != 12 {+ return Err(RawError::unsupported(format!("Panasonic RW2 with {bits}-bit compressed samples")));+ }+ if !width.is_multiple_of(14) {+ return Err(RawError::unsupported(format!("Panasonic RW2 {width} pixels wide (not whole 14-pixel blocks)")));+ }+ let row_bytes = width / 14 * 16;+ let need = row_bytes * height;+ // Whole pages are stored; tolerate a short final page (its missing bytes read as 0).+ if src.len() < need.saturating_sub(PAGE) {+ return Err(RawError::malformed("RW2 raw data is truncated"));+ }+ let mut data = vec![0u16; width * height];+ let band = par::band_rows(width);+ par::chunks_mut(&mut data, band * width, |i, chunk| {+ for (r, out) in chunk.chunks_exact_mut(width).enumerate() {+ compressed_row(src, row_bytes, i * band + r, out);+ }+ });+ Ok(data)+}++pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {+ let ifd = t.ifd_at(t.first_ifd, 0).ok_or_else(|| RawError::malformed("RW2 has no IFD0"))?;+ let raw_format = t.tag_uint(&ifd, RAW_FORMAT);+ let compressed = match raw_format {+ Some(5) => false,+ Some(3 | 4) => true,+ other => {+ let f = other.map(|v| v.to_string()).unwrap_or_else(|| "unknown".into());+ return Err(RawError::unsupported(format!("Panasonic RW2 raw format {f} (vendor-compressed) is not decoded yet")));+ }+ };+ let width = t.tag_uint(&ifd, SENSOR_WIDTH).ok_or_else(|| RawError::malformed("RW2 has no sensor width"))? as usize;+ let height = t.tag_uint(&ifd, SENSOR_HEIGHT).ok_or_else(|| RawError::malformed("RW2 has no sensor height"))? as usize;+ limits.check(width as u64, height as u64, 2)?;+ let bits = t.tag_uint(&ifd, BITS_PER_SAMPLE).unwrap_or(12);+ let cfa = match t.tag_uint(&ifd, CFA_PATTERN) {+ Some(1) => "RGGB",+ Some(2) => "GRBG",+ Some(3) => "GBRG",+ Some(4) => "BGGR",+ _ => return Err(RawError::unsupported("Panasonic RW2 without a CFA pattern")),+ };+ let cfa = Cfa::bayer(cfa).ok_or_else(|| RawError::malformed("bad CFA"))?;+ let offset =+ t.tag_uint(&ifd, RAW_DATA_OFFSET).or_else(|| t.tag_uint(&ifd, tag::STRIP_OFFSETS)).ok_or_else(|| RawError::malformed("RW2 has no raw data offset"))?+ as usize;+ let src = t.data.get(offset..).ok_or_else(|| RawError::malformed("RW2 raw data lies outside the file"))?;+ let data = if compressed { decode_compressed(src, width, height, bits)? } else { decode_packed(src, width, height, bits)? };let full = Rect::new(0, 0, width, height);let level = |tg: u16| t.tag_uint(&ifd, tg).map(f64::from);let mut warnings = Vec::new();- let black = match BLACK_LEVEL.map(level) {+ // The compressed variants record a black level 15 counts below the decoded black.+ let black_offset = if compressed { 15.0 } else { 0.0 };+ let black_level = |tg: u16| t.tag_uint(&ifd, tg).map(|v| f64::from(v) + black_offset);+ let black = match BLACK_LEVEL.map(black_level) {[Some(r), Some(g), Some(b)] => {let v = cfa.phase(0, 0).map(|c| [r, g, b][usize::from(c).min(2)] as f32);BlackLevels { rows: 2, cols: 2, values: v.to_vec(), delta_h: Vec::new(), delta_v: Vec::new() }@@ -204,4 +331,76 @@ mod tests {assert_eq!(&out[..9], &[0x3FFF; 9]);assert_eq!(&out[9..], &[0; 3]);}++ #[test]+ fn compressed_bits_walk_down_pages() {+ // A fresh cursor reads the word at 0x2007 first (the top of the first+ // page under the compressed split), then walks down.+ let mut buf = vec![0u8; 0x4000];+ buf[0x2007] = 0xAC;+ buf[0x2008] = 0x03;+ buf[0x2006] = 0x11;+ buf[0x2017] = 0x55;+ // A 4-bit field starts in the high nibble of the top word.+ let mut b = Bits::new(&buf, 0);+ assert_eq!(b.get(4), 0xA);+ let mut b = Bits::new(&buf, 0);+ assert_eq!(b.get(8), 0xAC);+ assert_eq!(b.get(8), 0x11);+ // 16 bytes later the cursor wraps to the end of the next 16-byte run.+ for _ in 0..14 {+ b.get(8);+ }+ assert_eq!(b.get(8), 0x55);+ }++ #[test]+ fn compressed_group_walks_predictors() {+ // One 14-pixel group: both parities start absolute, a delta of 0x80+ // keeps their value, and the scale selector is written before the+ // delta of every third pixel. The test writer mirrors `Bits` so the+ // fields land where the decoder reads them.+ let mut buf = vec![0u8; 0x4000];+ {+ let mut w = TestWriter { buf: &mut buf, pos: 0, nbits: 0 };+ w.put(0x10, 8);+ w.put(0x5, 4);+ w.put(0x2A, 8);+ w.put(0xA, 4);+ for i in 2..14 {+ if i % 3 == 2 {+ w.put(0, 2);+ }+ w.put(0x80, 8);+ }+ }+ let mut out = [0u16; 14];+ compressed_row(&buf, 16, 0, &mut out);+ assert_eq!(out, [0x105, 0x2AA, 0x105, 0x2AA, 0x105, 0x2AA, 0x105, 0x2AA, 0x105, 0x2AA, 0x105, 0x2AA, 0x105, 0x2AA]);+ }++ /// Mirror of [`Bits`] for unit tests: deposits fields where the reader+ /// will pick them up.+ struct TestWriter<'a> {+ buf: &'a mut [u8],+ pos: usize,+ nbits: u32,+ }++ impl TestWriter<'_> {+ fn put(&mut self, v: u32, num: u32) {+ if num > self.nbits {+ self.nbits += PAGE as u32 * 8;+ self.pos += PAGE;+ }+ let mut at = ((self.nbits - num) >> 3) as usize ^ 0x3FF0;+ at = (at + PAGE - COMPRESSED_SPLIT) % PAGE;+ let at = at + self.pos - PAGE;+ self.nbits -= num;+ let cur = u32::from(self.buf[at]) | (u32::from(self.buf[at + 1]) << 8);+ let cur = cur | ((v & ((1 << num) - 1)) << (self.nbits & 7));+ self.buf[at] = cur as u8;+ self.buf[at + 1] = (cur >> 8) as u8;+ }+ }}diff --git a/crates/raw/src/testgen.rs b/crates/raw/src/testgen.rsindex 823cd97ae..2de64ae4b 100644--- a/crates/raw/src/testgen.rs+++ b/crates/raw/src/testgen.rs@@ -1113,6 +1113,136 @@ pub fn rw2(width: usize, height: usize, data: &[u16], bits: u32) -> Vec<u8> {b}+/// Byte split of the vendor-compressed (RawFormat 3/4) stream (see `rw2.rs`).+const RW2_COMPRESSED_SPLIT: usize = 0x2008;++/// Writer for the vendor-compressed RW2 stream: mirrors the decoder's cursor+/// (page addressing, downward field order) and deposits every field where the+/// reader will pick it up.+struct V4Writer<'a> {+ buf: &'a mut [u8],+ base: usize,+ pos: usize,+ nbits: u32,+}++impl V4Writer<'_> {+ /// Consumes one byte of the row seek (the decoder reads 8-bit fields).+ fn skip_byte(&mut self) {+ if 8 > self.nbits {+ self.nbits += (RW2_PAGE as u32) * 8;+ self.pos += RW2_PAGE;+ }+ self.nbits -= 8;+ }++ fn put(&mut self, v: u32, num: u32) {+ if num > self.nbits {+ self.nbits += (RW2_PAGE as u32) * 8;+ self.pos += RW2_PAGE;+ }+ let mut at = ((self.nbits - num) >> 3) as usize ^ 0x3FF0;+ at = (at + RW2_PAGE - RW2_COMPRESSED_SPLIT) % RW2_PAGE;+ let at = self.base + at + self.pos - RW2_PAGE;+ self.nbits -= num;+ let cur = u32::from(self.buf[at]) | (u32::from(self.buf[at + 1]) << 8);+ let cur = cur | ((v & ((1 << num) - 1)) << (self.nbits & 7));+ self.buf[at] = cur as u8;+ self.buf[at + 1] = (cur >> 8) as u8;+ }++ /// Encodes one row as 14-pixel groups: the scale selector is always 0 and+ /// the two first pixels of each group are absolute (8 + 4 bits); later+ /// pixels use the 8-bit delta path. Callers keep values inside 16..4096+ /// and stepping by at most ±127 between pixels of the same parity.+ fn row(&mut self, pixels: &[u16]) {+ for group in pixels.as_chunks::<14>().0 {+ let mut pred = [0i32; 2];+ let mut nonz = [0i32; 2];+ for (i, &px) in group.iter().enumerate() {+ if i % 3 == 2 {+ self.put(0, 2); // sh = 0+ }+ let p = i & 1;+ let t = i32::from(px);+ if nonz[p] == 0 {+ let nz = (t >> 4) & 0xFF;+ self.put(nz as u32, 8);+ if nz != 0 || i > 11 {+ self.put((t & 0xF) as u32, 4);+ pred[p] = t;+ } else {+ pred[p] = 0;+ }+ nonz[p] = nz;+ } else {+ let q = (pred[p] - 0x80).max(0);+ let j = t - q;+ assert!((1..=0xFF).contains(&j), "{t} is not encodable from {}", pred[p]);+ self.put(j as u32, 8);+ pred[p] = q + j;+ }+ assert_eq!(pred[p], t);+ }+ }+ }+}++/// The vendor-compressed (RawFormat 3/4) stream of a whole image; see+/// [`V4Writer::row`] for the value constraints.+pub fn rw2_v4_pack(data: &[u16], width: usize) -> Vec<u8> {+ assert_eq!(width % 14, 0);+ let height = data.len() / width;+ assert_eq!(data.len(), width * height);+ let row_bytes = width / 14 * 16;+ let mut buf = vec![0u8; row_bytes * height + 2 * RW2_PAGE];+ for (row, pixels) in data.chunks_exact(width).enumerate() {+ let skip = row_bytes * row;+ let mut w = V4Writer { buf: &mut buf, base: skip / RW2_PAGE * RW2_PAGE, pos: 0, nbits: 0 };+ for _ in 0..(skip % RW2_PAGE) {+ w.skip_byte();+ }+ w.row(pixels);+ }+ buf+}++/// A synthetic Panasonic RW2 (RawFormat 4, vendor-compressed) with an RGGB+/// sensor, a 2-pixel border on every side, black levels 128 / 129 / 130 and+/// WB levels 512 / 256 / 384; see [`V4Writer::row`] for the pixel constraints.+pub fn rw2_format4(width: usize, height: usize, data: &[u16]) -> Vec<u8> {+ let mut t = TiffBuilder::default();+ let raw = t.blob(rw2_v4_pack(data, width));+ let ifd0 = t.ifd(vec![+ (0x0002, Val::Short(vec![width as u16])),+ (0x0003, Val::Short(vec![height as u16])),+ (0x0004, Val::Short(vec![2])),+ (0x0005, Val::Short(vec![2])),+ (0x0006, Val::Short(vec![height as u16 - 2])),+ (0x0007, Val::Short(vec![width as u16 - 2])),+ (0x0009, Val::Short(vec![1])),+ (0x000A, Val::Short(vec![12])),+ (0x000E, Val::Short(vec![4095])),+ (0x000F, Val::Short(vec![4095])),+ (0x0010, Val::Short(vec![4095])),+ (0x001C, Val::Short(vec![128])),+ (0x001D, Val::Short(vec![129])),+ (0x001E, Val::Short(vec![130])),+ (0x0024, Val::Short(vec![512])),+ (0x0025, Val::Short(vec![256])),+ (0x0026, Val::Short(vec![384])),+ (0x002D, Val::Short(vec![4])),+ (0x010F, Val::Ascii("Panasonic".into())),+ (0x0110, Val::Ascii("DC-Synthetic".into())),+ (0x0112, Val::Short(vec![1])),+ (0x0118, Val::Blobs(vec![raw])),+ ]);+ t.chain = vec![ifd0];+ let mut b = t.build();+ b[2..4].copy_from_slice(b"U\0");+ b+}+// ---------------------------------------------------------------- Olympus ORF/// A little-endian IFD whose value offsets are relative to `base` (the IFDdiff --git a/crates/raw/tests/vendor_codecs.rs b/crates/raw/tests/vendor_codecs.rsindex e210c6f31..2d91a322a 100644--- a/crates/raw/tests/vendor_codecs.rs+++ b/crates/raw/tests/vendor_codecs.rs@@ -2,7 +2,7 @@//! Sony compressed ARW (cRAW), Panasonic RW2 (RawFormat 5) and uncompressed//! Olympus ORF (with its maker-note preview).-use photocraft_raw::testgen::{craw_block, mosaic, orf, rw2, scene, sony_craw};+use photocraft_raw::testgen::{craw_block, mosaic, orf, rw2, rw2_format4, scene, sony_craw};use photocraft_raw::*;const CURVE: [u16; 4] = [8000, 10400, 12900, 14100];@@ -176,13 +176,63 @@ fn patch_ifd0_short(b: &mut [u8], tag: u16, v: u16) {}#[test]-fn rw2_compressed_formats_fall_back() {+fn rw2_format4_round_trip_is_exact() {+ let (w, h) = (42, 6);+ let mut data = Vec::with_capacity(w * h);+ for y in 0..h {+ for x in 0..w {+ data.push(200 + 4 * (y as u16) + 3 * (x as u16));+ }+ }+ let b = rw2_format4(w, h, &data);+ assert_eq!(identify(&b), Some(RawFormat::Rw2));+ let s = decode(&b, &Limits::default()).unwrap();+ assert_eq!((s.width, s.height), (w, h));+ assert_eq!(s.data, data);+ assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [0, 1, 1, 2]);+ // The compressed variants record a black level 15 counts below the black+ // of the decoded samples.+ assert_eq!(s.black.values, vec![143.0, 144.0, 144.0, 145.0]);+ assert_eq!(s.white, [4095.0; 3]);+ assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5]));+ assert_eq!(s.crop, Rect::new(2, 2, w - 4, h - 4));+ assert!(s.warnings.is_empty(), "{:?}", s.warnings);+ let d = develop_sensor(&s, &DevelopOptions::default()).unwrap();+ assert_eq!((d.width as usize, d.height as usize), (w - 4, h - 4));+}++#[test]+fn rw2_format4_crosses_pages() {+ // 16 bytes a row: 1100 rows walk past several 0x4000-byte page boundaries.+ let (w, h) = (14, 1100);+ let mut data = Vec::with_capacity(w * h);+ for y in 0..h {+ for x in 0..w {+ data.push(300 + 16 * ((y % 8) as u16) + 3 * (x as u16));+ }+ }+ let b = rw2_format4(w, h, &data);+ let s = decode(&b, &Limits::default()).unwrap();+ assert_eq!(s.data, data);+}++#[test]+fn rw2_format4_rejects_other_block_widths() {+ let (w, h) = (42, 2);+ let data: Vec<u16> = (0..w * h).map(|i| 200 + (i % 14) as u16 * 3).collect();+ let mut b = rw2_format4(w, h, &data);+ patch_ifd0_short(&mut b, 0x0002, 41);+ assert!(matches!(decode(&b, &Limits::default()), Err(RawError::Unsupported(_))));+}++#[test]+fn rw2_undecoded_formats_fall_back() {let data = vec![200u16; 20 * 4];let mut b = rw2(20, 4, &data, 12);assert!(decode(&b, &Limits::default()).is_ok());- patch_ifd0_short(&mut b, 0x002D, 4);+ patch_ifd0_short(&mut b, 0x002D, 6);match decode(&b, &Limits::default()) {- Err(RawError::Unsupported(m)) => assert!(m.contains("raw format 4"), "{m}"),+ Err(RawError::Unsupported(m)) => assert!(m.contains("raw format 6"), "{m}"),other => panic!("expected unsupported, got {other:?}"),}// Width not made of whole blocks.