Skip to content

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

raw: Sony cRAW, Panasonic RW2 (RawFormat 5), uncompressed ORF + ORF previews; NEF blocked (clean-room) (#83)

Brandon Thomas2149f7f6467e
diff --git a/crates/raw/README.md b/crates/raw/README.md
index f868a7d64..2e6cda93f 100644
--- a/crates/raw/README.md
+++ b/crates/raw/README.md
@@ -23,9 +23,16 @@ Implemented only from public specifications, papers and observation of files:
* TIFF 6.0, TIFF/EP (ISO 12234-2) and the Adobe DNG Specification 1.7.
* ITU-T T.81 (ISO 10918-1) Annex H: lossless JPEG, process 14 ("LJ92").
* The published description of Canon's CR2 container (header, raw IFD, slice tag 0xC640).
-* Publicly documented maker-note / private tags: Canon SensorInfo (0x00E0) and ColorData
- (0x4001), Nikon WB_RBLevels (0x000C) and BlackLevel (0x003D), Sony BlackLevel (0x7310) and
- WB_RGGBLevels (0x7313).
+* Publicly documented maker-note / private tags (ExifTool's tag tables): Canon SensorInfo
+ (0x00E0) and ColorData (0x4001), Nikon WB_RBLevels (0x000C) and BlackLevel (0x003D), Sony
+ BlackLevel (0x7310), WB_RGGBLevels (0x7313), SonyRawFileType (0x7000) and SonyToneCurve
+ (0x7010), the PanasonicRaw IFD0 tags, Olympus ImageProcessing (0x2040) and CameraSettings
+ (0x2020) preview tags.
+* Sony cRAW (ARW 2): H. Dietz, "Sony ARW2 Compression: Artifacts And Credible Repair"
+ (Electronic Imaging 2016) and the RawDigger / diglloyd write-ups of the 11 + 7-bit scheme;
+ the exact bit layout and tone-curve scale were established by observation of sample files.
+* Panasonic RW2 RawFormat 5 and uncompressed Olympus ORF: established by observation of sample
+ files (bit packing, page layout, sample justification).
* Demosaicing: Malvar, He & Cutler (ICASSP 2004); Hirakawa & Parks, "Adaptive
homogeneity-directed demosaicing" (IEEE TIP 2005).
* McCamy's CCT approximation (1992); the Bradford chromatic adaptation transform.
@@ -42,8 +49,11 @@ camera colour tables were copied.
| CR2 | Lossless JPEG with slices, borders and as-shot white balance from the maker note, black measured on the masked border |
| CR2 sRAW / mRAW | Unsupported |
| NEF / NRW, ARW, PEF and other TIFF/EP raws | Uncompressed and lossless-JPEG (incl. Sony lossless ARW) CFA data |
-| Nikon compressed NEF, Sony compressed ARW, Pentax compressed PEF | Unsupported (vendor compression; `photocraft-io` opens the embedded JPEG preview instead) |
-| CR3, RAF, ORF, RW2 | Recognised, unsupported (preview fallback where a preview is found) |
+| Sony compressed ARW ("cRAW", SonyRawFileType 2) | Decoded: 11-bit min/max + 7-bit delta blocks, SonyToneCurve to 14 bits |
+| Panasonic / Leica RW2, RawFormat 5 (12- and 14-bit packed) | Decoded, with PanasonicRaw black / white / WB / sensor borders |
+| Olympus ORF, uncompressed 16-bit (E-1, E-400…) | Decoded, with ImageProcessing black / WB / ValidBits / crop |
+| Nikon compressed NEF (lossless and lossy), 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 |
+| CR3, RAF | Recognised, unsupported (preview fallback where a preview is found) |
| X-Trans and other non-Bayer CFAs | Unsupported |
## Development pipeline
@@ -57,7 +67,7 @@ camera colour tables were copied.
(BaselineExposure + user EV); gamma 1.8; 16 bits.
5. Orientation.
-Files without colour calibration (CR2, NEF, ARW…) use a documented neutral fallback: the
+Files without colour calibration (CR2, NEF, ARW, RW2, ORF…) use a documented neutral fallback: the
white-balanced camera channels are treated as linear sRGB primaries (colours are plausible but
less saturated than a calibrated profile; converting to DNG gives calibrated colour). No tone
curve is applied: the result is a scene-referred rendering, flatter than a camera JPEG.
diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs
index 8871e319f..f667b22fe 100644
--- a/crates/raw/src/lib.rs
+++ b/crates/raw/src/lib.rs
@@ -3,7 +3,9 @@
//! Implemented only from public specifications and papers: TIFF 6.0,
//! TIFF/EP (ISO 12234-2), the Adobe DNG Specification 1.7, ITU-T T.81
//! (lossless JPEG, process 14), the published structure of Canon's CR2
-//! container, and the demosaicing papers cited in [`Demosaic`]. No code from
+//! container, published descriptions of Sony's cRAW code, public maker-note
+//! tag tables, observation of sample files, and the demosaicing papers cited
+//! in [`Demosaic`]. No code from
//! dcraw, LibRaw, rawspeed, rawler, rawloader or darktable was used.
//!
//! * [`identify`] / [`is_raw`] recognise raw files from their bytes.
@@ -16,9 +18,10 @@
//! formats whose sensor data is not decoded yet.
//!
//! Decoded today: DNG (uncompressed and lossless-JPEG, strips and tiles, CFA
-//! and LinearRaw), CR2 (lossless JPEG with Canon slices) and uncompressed or
-//! lossless-JPEG TIFF/EP raws (NEF, ARW, PEF… when not vendor-compressed).
-//! Everything else reports [`RawError::Unsupported`].
+//! and LinearRaw), CR2 (lossless JPEG with Canon slices), uncompressed or
+//! lossless-JPEG TIFF/EP raws (NEF, ARW, PEF… when not vendor-compressed),
+//! Sony compressed ARW (cRAW), Panasonic RW2 (RawFormat 5) and uncompressed
+//! Olympus ORF. 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 are
@@ -35,9 +38,12 @@ mod dng;
mod error;
mod ljpeg;
mod opcodes;
+mod orf;
mod par;
mod preview;
+mod rw2;
mod sensor;
+mod sony;
mod tiff;
mod tiffep;
@@ -200,13 +206,13 @@ pub fn decode(bytes: &[u8], limits: &Limits) -> Result<Sensor, RawError> {
match format {
RawFormat::Cr3 => Err(RawError::unsupported("Canon CR3 (ISO BMFF / CRX) is not decoded yet")),
RawFormat::Raf => Err(RawError::unsupported("Fujifilm RAF is not decoded yet")),
- RawFormat::Rw2 => Err(RawError::unsupported("Panasonic RW2 is not decoded yet")),
- RawFormat::Orf => Err(RawError::unsupported("Olympus ORF is not decoded yet")),
_ => {
let t = Tiff::new(bytes).ok_or(RawError::NotRaw)?;
match format {
RawFormat::Dng => dng::decode(&t, limits),
RawFormat::Cr2 => cr2::decode(&t, limits),
+ RawFormat::Rw2 => rw2::decode(&t, limits),
+ RawFormat::Orf => orf::decode(&t, limits),
f => tiffep::decode(&t, f, limits),
}
}
diff --git a/crates/raw/src/orf.rs b/crates/raw/src/orf.rs
new file mode 100644
index 000000000..7f489cea9
--- /dev/null
+++ b/crates/raw/src/orf.rs
@@ -0,0 +1,147 @@
+//! Olympus ORF with uncompressed sensor data (older Four Thirds bodies such as
+//! the E-1 and E-400).
+//!
+//! The container is TIFF with an `IIRO` / `IIRS` / `MMOR` header; the sensor
+//! data is IFD0's strips, 16-bit samples whose top ValidBits bits are
+//! significant. The CFA
+//! comes from the EXIF CFAPattern. Levels come from the publicly documented
+//! Olympus maker-note ImageProcessing tags (ExifTool's Olympus table):
+//! WB_RBLevels (0x0100), WB_GLevel (0x011F), BlackLevel2 (0x0600), ValidBits
+//! (0x0611) and CropLeft / CropTop / CropWidth / CropHeight (0x0612–0x0615).
+//!
+//! Later bodies store Olympus' own compressed data, which has no public
+//! description and is not decoded.
+
+use crate::error::{RawError, Result};
+use crate::sensor::{BlackLevels, JpegLayout, Rect, Sensor, read_plane};
+use crate::tiff::{Ifd, Tiff, tag};
+use crate::tiffep::{cfa, rggb_by_position};
+use crate::{Limits, RawFormat};
+
+const CAMERA_SETTINGS: u16 = 0x2020;
+const PREVIEW_IMAGE_START: u16 = 0x0101;
+const PREVIEW_IMAGE_LENGTH: u16 = 0x0102;
+const IMAGE_PROCESSING: u16 = 0x2040;
+const WB_RB_LEVELS: u16 = 0x0100;
+const WB_G_LEVEL: u16 = 0x011F;
+const BLACK_LEVEL_2: u16 = 0x0600;
+const VALID_BITS: u16 = 0x0611;
+const CROP: [u16; 4] = [0x0612, 0x0613, 0x0614, 0x0615];
+
+/// A sub-IFD of the Olympus maker note (`sub`: 0x2020 CameraSettings, 0x2040
+/// ImageProcessing…), with the TIFF view its offsets are relative to and that
+/// view's absolute position in the file. New-style notes (`OLYMPUS\0` + byte
+/// order) are relative to the note; old-style ones (`OLYMP\0`) to the file.
+fn maker_subifd<'a>(t: &Tiff<'a>, ifds: &[Ifd], sub: u16) -> Option<(Tiff<'a>, Ifd, usize)> {
+ let e = ifds.iter().find_map(|i| i.get(tag::MAKER_NOTE).copied())?;
+ let head = t.bytes(e.at, 12)?;
+ let (view, main, base) = if head.starts_with(b"OLYMPUS\0") {
+ let le = match head.get(8..10)? {
+ b"II" => true,
+ b"MM" => false,
+ _ => return None,
+ };
+ let inner = Tiff { data: t.data.get(e.at..)?, le, first_ifd: 12 };
+ let ifd = inner.ifd_at(12, 0)?;
+ (inner, ifd, e.at)
+ } else if head.starts_with(b"OLYMP\0") {
+ (*t, t.ifd_at(e.at.checked_add(8)?, 0)?, 0)
+ } else {
+ return None;
+ };
+ let ip = main.get(sub)?;
+ let at = match ip.typ {
+ 4 | 13 => view.uint(ip, 0)? as usize,
+ _ => ip.at,
+ };
+ let ifd = view.ifd_at(at, 0)?;
+ Some((view, ifd, base))
+}
+
+/// Absolute offset and length of the camera's preview JPEG (maker note
+/// CameraSettings PreviewImageStart / PreviewImageLength, 0x0101 / 0x0102).
+pub(crate) fn preview_range(t: &Tiff) -> Option<(usize, usize)> {
+ let (view, cs, base) = maker_subifd(t, &t.all_ifds(), CAMERA_SETTINGS)?;
+ let start = view.tag_uint(&cs, PREVIEW_IMAGE_START)? as usize;
+ let len = view.tag_uint(&cs, PREVIEW_IMAGE_LENGTH)? as usize;
+ Some((base.checked_add(start)?, len))
+}
+
+pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {
+ let ifds = t.all_ifds();
+ let raw = t.ifd_at(t.first_ifd, 0).ok_or_else(|| RawError::malformed("ORF has no IFD0"))?;
+ let width = u64::from(t.tag_uint(&raw, tag::IMAGE_WIDTH).unwrap_or(0));
+ let height = u64::from(t.tag_uint(&raw, tag::IMAGE_LENGTH).unwrap_or(0));
+ let stored: u64 = t.tag_uints(&raw, tag::STRIP_BYTE_COUNTS).iter().map(|&c| u64::from(c)).sum();
+ if t.tag_uint(&raw, tag::COMPRESSION).unwrap_or(1) != 1 || stored < width.saturating_mul(height).saturating_mul(2) {
+ return Err(RawError::unsupported("Olympus compressed (or packed) ORF is not decoded"));
+ }
+ let plane = read_plane(t, &raw, limits, JpegLayout::Flat)?;
+ if plane.samples != 1 {
+ return Err(RawError::unsupported(format!("ORF with {} samples per pixel", plane.samples)));
+ }
+ let cfa = cfa(t, &raw, &ifds).ok_or_else(|| RawError::unsupported("ORF: CFA pattern not recorded"))?;
+ if !cfa.is_bayer() {
+ return Err(RawError::unsupported("ORF: non-Bayer CFA"));
+ }
+ let full = Rect::new(0, 0, plane.width, plane.height);
+ let mut warnings = Vec::new();
+ let ip = maker_subifd(t, &ifds, IMAGE_PROCESSING);
+ let floats = |tg: u16| ip.as_ref().map(|(v, i, _)| v.tag_floats(i, tg)).unwrap_or_default();
+
+ let black = match rggb_by_position(&cfa, &floats(BLACK_LEVEL_2)) {
+ Some(v) => BlackLevels { rows: 2, cols: 2, values: v.to_vec(), delta_h: Vec::new(), delta_v: Vec::new() },
+ None => {
+ warnings.push("ORF: black level not recorded; assumed 0".to_string());
+ BlackLevels::uniform(0.0)
+ }
+ };
+ let mut data = plane.data;
+ let white = match floats(VALID_BITS).first() {
+ Some(&b) if (8.0..=16.0).contains(&b) => {
+ let bits = b as u32;
+ let top = (1u32 << bits) - 1;
+ // Observed: the E-1 / E-400 store the valid bits left-justified in
+ // the 16-bit container (samples are multiples of 16 up to 65520).
+ if data.iter().any(|&v| u32::from(v) > top) {
+ let shift = 16 - bits;
+ data.iter_mut().for_each(|v| *v >>= shift);
+ }
+ top as f32
+ }
+ _ => crate::cr2::clip_level(&data, plane.bits),
+ };
+ let g = floats(WB_G_LEVEL).first().copied().filter(|g| *g > 0.0).unwrap_or(256.0);
+ let camera_wb = match floats(WB_RB_LEVELS).as_slice() {
+ [r, b, ..] => Some([r / g, 1.0, b / g]).filter(|m| m.iter().all(|v| (0.25..8.0).contains(v))),
+ _ => None,
+ };
+ let crop = match CROP.map(|tg| floats(tg).first().copied()) {
+ [Some(x), Some(y), Some(w), Some(h)] if [x, y, w, h].iter().all(|v| (0.0..1e6).contains(v)) => {
+ let r = Rect::new(x as usize, y as usize, w as usize, h as usize).intersect(&full);
+ if r.is_empty() { full } else { r }
+ }
+ _ => full,
+ };
+ Ok(Sensor {
+ format: RawFormat::Orf,
+ make: ifds.iter().find_map(|i| t.tag_ascii(i, tag::MAKE)),
+ model: ifds.iter().find_map(|i| t.tag_ascii(i, tag::MODEL)),
+ width: plane.width,
+ height: plane.height,
+ samples: 1,
+ data,
+ cfa: Some(cfa),
+ linearization: None,
+ black,
+ white: [white; 3],
+ active: full,
+ crop,
+ color: Default::default(),
+ camera_wb,
+ orientation: t.tag_uint(&raw, tag::ORIENTATION).map(|o| o as u16).filter(|o| (1..=8).contains(o)).unwrap_or(1),
+ baseline_exposure: 0.0,
+ gain_maps: Vec::new(),
+ warnings,
+ })
+}
diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs
index adeb68650..310f0bd2e 100644
--- a/crates/raw/src/preview.rs
+++ b/crates/raw/src/preview.rs
@@ -57,6 +57,12 @@ pub fn embedded_preview(bytes: &[u8]) -> Option<Preview<'_>> {
found.extend(candidate(bytes, off, len));
}
} else if let Some(t) = Tiff::new(bytes) {
+ // Olympus ORF: the preview is referenced from the maker note.
+ if matches!(bytes.get(0..4), Some(b"IIRO" | b"IIRS" | b"MMOR"))
+ && let Some((off, len)) = crate::orf::preview_range(&t)
+ {
+ found.extend(candidate(bytes, off, len));
+ }
for ifd in t.all_ifds() {
if let (Some(off), Some(len)) = (t.tag_uint(&ifd, tag::JPEG_INTERCHANGE_FORMAT), t.tag_uint(&ifd, tag::JPEG_INTERCHANGE_FORMAT_LENGTH)) {
found.extend(candidate(bytes, off as usize, len as usize));
diff --git a/crates/raw/src/rw2.rs b/crates/raw/src/rw2.rs
new file mode 100644
index 000000000..6f903140b
--- /dev/null
+++ b/crates/raw/src/rw2.rs
@@ -0,0 +1,205 @@
+//! Panasonic / Leica RW2 with the bit-packed sensor layout (PanasonicRaw
+//! RawFormat 5, written by recent Lumix bodies).
+//!
+//! The container is TIFF-like (`IIU\0`); IFD0 holds Panasonic's own tags,
+//! whose ids and meanings are public (ExifTool's PanasonicRaw table):
+//! SensorWidth/Height (2, 3), Sensor{Top,Left,Bottom,Right}Border (4–7),
+//! CFAPattern (9), BitsPerSample (0x0A), LinearityLimit{Red,Green,Blue}
+//! (0x0E–0x10), BlackLevel{Red,Green,Blue} (0x1C–0x1E),
+//! WB{Red,Green,Blue}Level (0x24–0x26), RawFormat (0x2D) and RawDataOffset
+//! (0x118).
+//!
+//! 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
+//! bytes 0x1FF8..0x4000 followed by bytes 0..0x1FF8).
+//! * The logical stream is a sequence of 16-byte blocks, each read as a
+//! little-endian 128-bit number holding 10 12-bit (or 9 14-bit) pixels from
+//! 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.
+
+use crate::error::{RawError, Result};
+use crate::sensor::{BlackLevels, Cfa, Rect, Sensor};
+use crate::tiff::{Tiff, tag};
+use crate::{Limits, RawFormat, par};
+
+const SENSOR_WIDTH: u16 = 0x0002;
+const SENSOR_HEIGHT: u16 = 0x0003;
+const SENSOR_TOP_BORDER: u16 = 0x0004;
+const SENSOR_LEFT_BORDER: u16 = 0x0005;
+const SENSOR_BOTTOM_BORDER: u16 = 0x0006;
+const SENSOR_RIGHT_BORDER: u16 = 0x0007;
+const CFA_PATTERN: u16 = 0x0009;
+const BITS_PER_SAMPLE: u16 = 0x000A;
+const LINEARITY_LIMIT: [u16; 3] = [0x000E, 0x000F, 0x0010];
+const BLACK_LEVEL: [u16; 3] = [0x001C, 0x001D, 0x001E];
+const WB_LEVEL: [u16; 3] = [0x0024, 0x0025, 0x0026];
+const RAW_FORMAT: u16 = 0x002D;
+const RAW_DATA_OFFSET: u16 = 0x0118;
+
+/// Page size and split point of the stored stream (observed).
+const PAGE: usize = 0x4000;
+const SPLIT: usize = 0x1FF8;
+
+/// Physical offset (relative to RawDataOffset) of logical byte `i`.
+#[inline]
+pub(crate) fn physical(i: usize) -> usize {
+ let page = i - i % PAGE;
+ page + (i % PAGE + SPLIT) % PAGE
+}
+
+/// Pixels per 16-byte block for `bits`-bit samples.
+pub(crate) fn pixels_per_block(bits: u32) -> Option<usize> {
+ match bits {
+ 12 => Some(10),
+ 14 => Some(9),
+ _ => None,
+ }
+}
+
+/// Unpacks one 16-byte block of `bits`-bit pixels into `out`.
+#[inline]
+pub(crate) fn unpack_block(b: &[u8; 16], bits: u32, out: &mut [u16]) {
+ let v = u128::from_le_bytes(*b);
+ let mask = (1u128 << bits) - 1;
+ for (i, o) in out.iter_mut().enumerate() {
+ let at = bits * i as u32;
+ if at + bits > 128 {
+ break;
+ }
+ *o = ((v >> at) & mask) as 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);
+ 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) {
+ return Err(RawError::malformed("RW2 raw data is truncated"));
+ }
+ let half = |l: usize| -> [u8; 8] { src.get(physical(l)..).and_then(|b| b.get(..8)).and_then(|b| <[u8; 8]>::try_from(b).ok()).unwrap_or([0; 8]) };
+ 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() {
+ let at = (i * band + r) * row_bytes;
+ for (k, px) in out.chunks_exact_mut(ppb).enumerate() {
+ // SPLIT and PAGE are multiples of 8, so each 8-byte half is contiguous.
+ let l = at + k * 16;
+ let mut b = [0u8; 16];
+ b[..8].copy_from_slice(&half(l));
+ b[8..].copy_from_slice(&half(l + 8));
+ unpack_block(&b, bits, px);
+ }
+ }
+ });
+
+ 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) {
+ [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() }
+ }
+ _ => {
+ warnings.push("RW2: black level not recorded; assumed 0".to_string());
+ BlackLevels::uniform(0.0)
+ }
+ };
+ let max = ((1u32 << bits) - 1) as f32;
+ let white = LINEARITY_LIMIT.map(|tg| level(tg).map(|v| v as f32).filter(|v| *v > 0.0 && *v <= max).unwrap_or(max));
+ let camera_wb = match WB_LEVEL.map(level) {
+ [Some(r), Some(g), Some(b)] if g > 0.0 => Some([r / g, 1.0, b / g]).filter(|m| m.iter().all(|v| (0.25..8.0).contains(v))),
+ _ => None,
+ };
+ let border = [SENSOR_LEFT_BORDER, SENSOR_TOP_BORDER, SENSOR_RIGHT_BORDER, SENSOR_BOTTOM_BORDER].map(|tg| t.tag_uint(&ifd, tg).map(|v| v as usize));
+ let crop = match border {
+ [Some(l), Some(tp), Some(r), Some(b)] if r > l && b > tp => Rect::new(l, tp, r - l, b - tp).intersect(&full),
+ _ => full,
+ };
+ let crop = if crop.is_empty() { full } else { crop };
+ Ok(Sensor {
+ format: RawFormat::Rw2,
+ make: t.tag_ascii(&ifd, tag::MAKE),
+ model: t.tag_ascii(&ifd, tag::MODEL),
+ width,
+ height,
+ samples: 1,
+ data,
+ cfa: Some(cfa),
+ linearization: None,
+ black,
+ white,
+ active: full,
+ crop,
+ color: Default::default(),
+ camera_wb,
+ orientation: t.tag_uint(&ifd, tag::ORIENTATION).map(|o| o as u16).filter(|o| (1..=8).contains(o)).unwrap_or(1),
+ baseline_exposure: 0.0,
+ gain_maps: Vec::new(),
+ warnings,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn pages_are_split() {
+ assert_eq!(physical(0), 0x1FF8);
+ assert_eq!(physical(7), 0x1FFF);
+ assert_eq!(physical(8), 0x2000);
+ assert_eq!(physical(0x2007), 0x3FFF);
+ assert_eq!(physical(0x2008), 0);
+ assert_eq!(physical(0x3FFF), 0x1FF7);
+ assert_eq!(physical(0x4000), 0x5FF8);
+ }
+
+ #[test]
+ fn unpacks_lsb_first() {
+ let mut v: u128 = 0;
+ for i in 0..10u128 {
+ v |= (0x100 + i) << (12 * i);
+ }
+ let mut out = [0u16; 10];
+ unpack_block(&v.to_le_bytes(), 12, &mut out);
+ assert_eq!(out, [0x100, 0x101, 0x102, 0x103, 0x104, 0x105, 0x106, 0x107, 0x108, 0x109]);
+ let mut out = [0u16; 12];
+ unpack_block(&[0xFF; 16], 14, &mut out);
+ assert_eq!(&out[..9], &[0x3FFF; 9]);
+ assert_eq!(&out[9..], &[0; 3]);
+ }
+}
diff --git a/crates/raw/src/sensor.rs b/crates/raw/src/sensor.rs
index 59ec38f5d..26ff956b5 100644
--- a/crates/raw/src/sensor.rs
+++ b/crates/raw/src/sensor.rs
@@ -165,14 +165,14 @@ pub(crate) struct Plane {
pub data: Vec<u16>,
}
-struct Segment {
- x: usize,
- y: usize,
+pub(crate) struct Segment {
+ pub x: usize,
+ pub y: usize,
/// Encoded width and height (tile size, or image width × rows per strip).
- w: usize,
- h: usize,
- offset: usize,
- len: usize,
+ pub w: usize,
+ pub h: usize,
+ pub offset: usize,
+ pub len: usize,
}
/// How a lossless-JPEG tile's samples map onto the tile.
@@ -259,7 +259,7 @@ pub(crate) fn read_plane(t: &Tiff, ifd: &Ifd, limits: &Limits, layout: JpegLayou
Ok(Plane { width, height, samples, bits, data })
}
-fn segments(t: &Tiff, ifd: &Ifd, width: usize, height: usize) -> Result<Vec<Segment>> {
+pub(crate) fn segments(t: &Tiff, ifd: &Ifd, width: usize, height: usize) -> Result<Vec<Segment>> {
let mut out = Vec::new();
if let (Some(tw), Some(th)) = (t.tag_uint(ifd, tag::TILE_WIDTH), t.tag_uint(ifd, tag::TILE_LENGTH)) {
let (tw, th) = (tw as usize, th as usize);
diff --git a/crates/raw/src/sony.rs b/crates/raw/src/sony.rs
new file mode 100644
index 000000000..e1961680d
--- /dev/null
+++ b/crates/raw/src/sony.rs
@@ -0,0 +1,176 @@
+//! Sony compressed ARW ("cRAW", ARW 2): a fixed-rate lossy code of one byte
+//! per pixel, used by default on most Sony bodies.
+//!
+//! Implemented from the public descriptions of the format (H. Dietz, "Sony
+//! ARW2 Compression: Artifacts And Credible Repair", Electronic Imaging 2016;
+//! the RawDigger and diglloyd write-ups of the 11 + 7-bit scheme) and from
+//! observation of sample files. No decoder source code was consulted.
+//!
+//! * Each row is cut into runs of 32 pixels, which the Bayer pattern makes
+//! two interleaved runs of 16 same-colour pixels; the run of even columns is
+//! stored first, then the run of odd columns, 16 bytes each.
+//! * A 16-byte block, read as a little-endian 128-bit number from the least
+//! significant bit, holds an 11-bit maximum, an 11-bit minimum, the 4-bit
+//! positions of the maximum and of the minimum, and fourteen 7-bit deltas
+//! for the other positions in order.
+//! * The step of the deltas is the smallest power of two `s` with
+//! `128 * s > max - min`; a pixel is `min + delta * s`.
+//! * The 11-bit codes go through a five-segment linear tone curve whose step
+//! doubles at each knot (1, 2, 4, 8, 16). The knots are the four values of
+//! the SonyToneCurve tag (0x7010), on a scale of eight times the code; the
+//! output is 14-bit. Observed in sample files: the 512 black level maps to
+//! code 256 and the clipping code maps to the 16383 white level.
+
+use crate::error::{RawError, Result};
+use crate::sensor::{Plane, segments};
+use crate::tiff::{Ifd, Tiff, tag};
+use crate::{Limits, par};
+
+/// SonyRawFileType (ExifTool): 2 = compressed RAW.
+pub(crate) const SONY_RAW_FILE_TYPE: u16 = 0x7000;
+/// SonyToneCurve: the four knots of the cRAW tone curve.
+pub(crate) const SONY_TONE_CURVE: u16 = 0x7010;
+const MAX_14: u32 = 16383;
+
+/// The 2048-entry code → 14-bit value table of a tone curve given by its four
+/// knots (SonyToneCurve), or `None` when the knots are not increasing or
+/// out of range.
+pub(crate) fn tone_lut(knots: &[u32]) -> Option<Vec<u16>> {
+ let [a, b, c, d] = <[u32; 4]>::try_from(knots).ok()?;
+ let pts = [0, a, b, c, d, 1 << 14];
+ if pts.windows(2).any(|w| w[0] > w[1]) {
+ return None;
+ }
+ let lut = (0..2048u32)
+ .map(|code| {
+ // On the knots' scale a code is 8 × code; the first segment maps it
+ // to 2 × code, i.e. a quarter of the scaled position.
+ let x = code * 8;
+ let mut y = 0u32;
+ for (seg, w) in pts.windows(2).enumerate() {
+ if x > w[0] {
+ y += (x.min(w[1]) - w[0]) << seg;
+ }
+ }
+ (y / 4).min(MAX_14) as u16
+ })
+ .collect();
+ Some(lut)
+}
+
+/// Decodes one 16-byte block into 16 codes.
+#[inline]
+pub(crate) fn decode_block(b: &[u8; 16]) -> [u16; 16] {
+ let v = u128::from_le_bytes(*b);
+ let field = |at: u32, bits: u32| ((v >> at) & ((1u128 << bits) - 1)) as u16;
+ let max = field(0, 11);
+ let min = field(11, 11);
+ let imax = usize::from(field(22, 4));
+ let imin = usize::from(field(26, 4));
+ let range = max.saturating_sub(min);
+ let mut sh = 0u32;
+ while (128u16 << sh) <= range {
+ sh += 1;
+ }
+ let mut out = [0u16; 16];
+ let mut at = 30u32;
+ for (i, o) in out.iter_mut().enumerate() {
+ *o = if i == imax {
+ max
+ } else if i == imin {
+ min
+ } else if at + 7 <= 128 {
+ let d = field(at, 7);
+ at += 7;
+ (min + (d << sh)).min(2047)
+ } else {
+ // Only when a damaged block names the same position twice.
+ min
+ };
+ }
+ out
+}
+
+/// `true` when the raw IFD holds cRAW data: Sony's private compression with
+/// one byte per pixel.
+pub(crate) fn is_craw(t: &Tiff, ifd: &Ifd) -> bool {
+ if t.tag_uint(ifd, tag::COMPRESSION) != Some(32767) {
+ return false;
+ }
+ let (w, h) = (t.tag_uint(ifd, tag::IMAGE_WIDTH).unwrap_or(0), t.tag_uint(ifd, tag::IMAGE_LENGTH).unwrap_or(0));
+ let bytes: u64 = t.tag_uints(ifd, tag::STRIP_BYTE_COUNTS).iter().map(|&c| u64::from(c)).sum();
+ match t.tag_uint(ifd, SONY_RAW_FILE_TYPE) {
+ Some(kind) => kind == 2,
+ None => bytes > 0 && bytes == u64::from(w) * u64::from(h),
+ }
+}
+
+/// Reads the cRAW image of a raw IFD.
+pub(crate) fn read_craw(t: &Tiff, ifd: &Ifd, limits: &Limits) -> Result<Plane> {
+ let width = t.tag_uint(ifd, tag::IMAGE_WIDTH).ok_or_else(|| RawError::malformed("raw image has no width"))? as usize;
+ let height = t.tag_uint(ifd, tag::IMAGE_LENGTH).ok_or_else(|| RawError::malformed("raw image has no height"))? as usize;
+ if !width.is_multiple_of(32) {
+ return Err(RawError::unsupported(format!("Sony compressed ARW {width} pixels wide (not a multiple of 32)")));
+ }
+ let lut = tone_lut(&t.tag_uints(ifd, SONY_TONE_CURVE)).ok_or_else(|| RawError::unsupported("Sony compressed ARW without a usable tone curve (0x7010)"))?;
+ limits.check(width as u64, height as u64, 2)?;
+ // One byte per pixel: locate every row in the strips.
+ let mut rows: Vec<&[u8]> = Vec::with_capacity(height);
+ for s in segments(t, ifd, width, height)? {
+ let n = s.h.min(height.saturating_sub(s.y));
+ for r in 0..n {
+ let at = s.offset.checked_add(r * width).ok_or_else(|| RawError::malformed("raw strip offset overflows"))?;
+ if (r + 1) * width > s.len {
+ return Err(RawError::malformed("compressed ARW strip is shorter than its rows"));
+ }
+ rows.push(t.bytes(at, width).ok_or_else(|| RawError::malformed("compressed ARW data lies outside the file"))?);
+ }
+ }
+ if rows.len() != height {
+ return Err(RawError::malformed("compressed ARW strips do not cover the image"));
+ }
+ 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() {
+ let Some(src) = rows.get(i * band + r) else { return };
+ for (group, px) in src.as_chunks::<32>().0.iter().zip(out.as_chunks_mut::<32>().0) {
+ let (Ok(even), Ok(odd)) = (<&[u8; 16]>::try_from(&group[..16]), <&[u8; 16]>::try_from(&group[16..])) else { continue };
+ for (k, (e, o)) in decode_block(even).into_iter().zip(decode_block(odd)).enumerate() {
+ px[2 * k] = lut.get(usize::from(e)).copied().unwrap_or(0);
+ px[2 * k + 1] = lut.get(usize::from(o)).copied().unwrap_or(0);
+ }
+ }
+ }
+ });
+ Ok(Plane { width, height, samples: 1, bits: 14, data })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn tone_curve_matches_observed_anchors() {
+ // Knots written by an ILCE-7M3.
+ let lut = tone_lut(&[8000, 10400, 12900, 14100]).unwrap();
+ assert_eq!(lut[0], 0);
+ assert_eq!(lut[256], 512); // black
+ assert_eq!(lut[999], 1998);
+ // Steps double at each knot.
+ assert_eq!(lut[1001] - lut[1000], 2 * (lut[1000] - lut[999]));
+ assert!(lut[2021] >= 16300, "{}", lut[2021]); // clipping code ≈ white
+ assert_eq!(lut[2047], 16383);
+ assert!(lut.windows(2).all(|w| w[0] <= w[1]));
+ assert!(tone_lut(&[9000, 8000, 12000, 13000]).is_none());
+ assert!(tone_lut(&[1, 2, 3]).is_none());
+ assert!(tone_lut(&[0, 0, 0, 20000]).is_none());
+ }
+
+ #[test]
+ fn hostile_blocks_do_not_panic() {
+ for b in [[0xFFu8; 16], [0u8; 16], [0x55; 16]] {
+ let _ = decode_block(&b);
+ }
+ }
+}
diff --git a/crates/raw/src/testgen.rs b/crates/raw/src/testgen.rs
index 4e229d10b..dcbe833ba 100644
--- a/crates/raw/src/testgen.rs
+++ b/crates/raw/src/testgen.rs
@@ -755,6 +755,239 @@ pub fn tiff_ep(make: &str, width: usize, height: usize, data: &[u16], cfa: [u8;
t.build()
}
+// ---------------------------------------------------------------- Sony cRAW
+
+/// Encodes 16 same-colour 11-bit codes as one cRAW block (see the decoder in
+/// `sony.rs`): maximum, minimum, their positions, then 7-bit deltas at the
+/// smallest power-of-two step that covers the range (rounded down).
+pub fn craw_block(codes: &[u16; 16]) -> [u8; 16] {
+ let max = *codes.iter().max().unwrap();
+ let min = *codes.iter().min().unwrap();
+ let imax = codes.iter().position(|&c| c == max).unwrap();
+ let mut imin = codes.iter().position(|&c| c == min).unwrap();
+ if imin == imax {
+ imin = (imax + 1) % 16;
+ }
+ let mut sh = 0;
+ while (128u16 << sh) <= max - min {
+ sh += 1;
+ }
+ let mut v: u128 = u128::from(max) | u128::from(min) << 11 | (imax as u128) << 22 | (imin as u128) << 26;
+ let mut at = 30;
+ for (i, &c) in codes.iter().enumerate() {
+ if i != imax && i != imin {
+ v |= u128::from(((c - min) >> sh).min(127)) << at;
+ at += 7;
+ }
+ }
+ v.to_le_bytes()
+}
+
+/// Encodes a mosaic of 11-bit codes (`width` a multiple of 32) as cRAW rows.
+pub fn craw_encode(codes: &[u16], width: usize, height: usize) -> Vec<u8> {
+ assert_eq!(width % 32, 0);
+ let mut out = Vec::with_capacity(width * height);
+ for row in codes.chunks_exact(width).take(height) {
+ for g in row.as_chunks::<32>().0 {
+ for parity in 0..2 {
+ let seq: [u16; 16] = std::array::from_fn(|i| g[2 * i + parity].min(2047));
+ out.extend_from_slice(&craw_block(&seq));
+ }
+ }
+ }
+ out
+}
+
+/// A synthetic Sony compressed ARW: IFD0 with Make, the cRAW image in a
+/// SubIFD with SonyRawFileType 2, the tone curve (0x7010), black (0x7310),
+/// white (50717) and WB_RGGBLevels (0x7313).
+pub fn sony_craw(width: usize, height: usize, codes: &[u16], curve: [u16; 4]) -> Vec<u8> {
+ let bytes = craw_encode(codes, width, height);
+ let mut t = TiffBuilder::default();
+ let n = bytes.len();
+ let strip = t.blob(bytes);
+ let raw_ifd = t.ifd(vec![
+ (254, Val::Long(vec![0])),
+ (256, Val::Long(vec![width as u32])),
+ (257, Val::Long(vec![height as u32])),
+ (258, Val::Short(vec![12])),
+ (259, Val::Short(vec![32767])),
+ (262, Val::Short(vec![32803])),
+ (273, Val::Blobs(vec![strip])),
+ (277, Val::Short(vec![1])),
+ (278, Val::Long(vec![height as u32])),
+ (279, Val::Long(vec![n as u32])),
+ (33421, Val::Short(vec![2, 2])),
+ (33422, Val::Byte(vec![0, 1, 1, 2])),
+ (0x7000, Val::Short(vec![2])),
+ (0x7010, Val::Short(curve.to_vec())),
+ (0x7310, Val::Short(vec![512; 4])),
+ (0x7313, Val::Short(vec![2048, 1024, 1024, 1536])),
+ (50717, Val::Short(vec![16383])),
+ ]);
+ let ifd0 = t.ifd(vec![(271, Val::Ascii("SONY".into())), (272, Val::Ascii("ILCE-Synthetic".into())), (330, Val::Ifds(vec![raw_ifd]))]);
+ t.chain = vec![ifd0];
+ t.build()
+}
+
+// ---------------------------------------------------------------- Panasonic RW2
+
+/// Page size and split point of the RW2 stream (see `rw2.rs`).
+const RW2_PAGE: usize = 0x4000;
+const RW2_SPLIT: usize = 0x1FF8;
+
+/// Packs `bits`-bit samples (12: 10 per block, 14: 9 per block) into the RW2
+/// RawFormat 5 layout: 16-byte little-endian blocks, stored in 0x4000-byte
+/// pages split at 0x1FF8.
+pub fn rw2_pack(data: &[u16], width: usize, bits: u32) -> Vec<u8> {
+ let ppb = if bits == 14 { 9 } else { 10 };
+ assert_eq!(width % ppb, 0);
+ let mut logical = Vec::new();
+ for px in data.chunks_exact(ppb) {
+ let mut v: u128 = 0;
+ for (i, &p) in px.iter().enumerate() {
+ v |= u128::from(p & ((1 << bits) - 1)) << (bits as usize * i);
+ }
+ logical.extend_from_slice(&v.to_le_bytes());
+ }
+ logical.resize(logical.len().div_ceil(RW2_PAGE) * RW2_PAGE, 0);
+ let mut out = vec![0u8; logical.len()];
+ for (i, &b) in logical.iter().enumerate() {
+ let page = i - i % RW2_PAGE;
+ out[page + (i % RW2_PAGE + RW2_SPLIT) % RW2_PAGE] = b;
+ }
+ out
+}
+
+/// A synthetic Panasonic RW2 (RawFormat 5) with an RGGB sensor, a 2-pixel
+/// border on every side, black levels 128 / 129 / 130 and WB levels
+/// 512 / 256 / 384.
+pub fn rw2(width: usize, height: usize, data: &[u16], bits: u32) -> Vec<u8> {
+ let mut t = TiffBuilder::default();
+ let raw = t.blob(rw2_pack(data, width, bits));
+ let white = ((1u32 << bits) - 1) as u16;
+ 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![bits as u16])),
+ (0x000E, Val::Short(vec![white])),
+ (0x000F, Val::Short(vec![white])),
+ (0x0010, Val::Short(vec![white])),
+ (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![5])),
+ (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 IFD
+/// itself sits at `base_offset` from that base). Entries: (tag, type, count,
+/// value bytes).
+fn relative_ifd(entries: &[(u16, u16, u32, Vec<u8>)], base_offset: usize) -> Vec<u8> {
+ let head = 2 + 12 * entries.len() + 4;
+ let mut out = Vec::new();
+ let mut extra = Vec::new();
+ out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
+ for (tag, typ, count, bytes) in entries {
+ out.extend_from_slice(&tag.to_le_bytes());
+ out.extend_from_slice(&typ.to_le_bytes());
+ out.extend_from_slice(&count.to_le_bytes());
+ if bytes.len() <= 4 {
+ let mut v = bytes.clone();
+ v.resize(4, 0);
+ out.extend_from_slice(&v);
+ } else {
+ out.extend_from_slice(&((base_offset + head + extra.len()) as u32).to_le_bytes());
+ extra.extend_from_slice(bytes);
+ }
+ }
+ out.extend_from_slice(&0u32.to_le_bytes());
+ out.extend_from_slice(&extra);
+ out
+}
+
+fn shorts(v: &[u16]) -> Vec<u8> {
+ v.iter().flat_map(|x| x.to_le_bytes()).collect()
+}
+
+/// A synthetic uncompressed Olympus ORF (`IIRO`): 12-bit `data` stored
+/// left-justified in 16-bit samples, a GRBG EXIF CFAPattern and a new-style
+/// maker note with ImageProcessing levels (black 64, WB 2.0 / 1.5, crop of a
+/// 2-pixel border) and CameraSettings pointing at a tiny preview JPEG.
+pub fn orf(width: usize, height: usize, data: &[u16]) -> Vec<u8> {
+ let ip = relative_ifd(
+ &[
+ (0x0100, 3, 2, shorts(&[512, 384])),
+ (0x011F, 3, 1, shorts(&[256])),
+ (0x0600, 3, 4, shorts(&[64, 64, 64, 64])),
+ (0x0611, 3, 2, shorts(&[12, 0])),
+ (0x0612, 3, 2, shorts(&[2, 0])),
+ (0x0613, 3, 2, shorts(&[2, 0])),
+ (0x0614, 4, 1, ((width - 4) as u32).to_le_bytes().to_vec()),
+ (0x0615, 4, 1, ((height - 4) as u32).to_le_bytes().to_vec()),
+ ],
+ 64,
+ );
+ // CameraSettings with a preview JPEG (SOI, SOF0 16×8, EOI) right after it.
+ let jpeg = [0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x0B, 8, 0x00, 0x08, 0x00, 0x10, 1, 1, 0x11, 0, 0xFF, 0xD9];
+ let cs_at = 64 + ip.len().next_multiple_of(4);
+ let cs_len = 2 + 12 * 3 + 4;
+ let cs = relative_ifd(
+ &[
+ (0x0100, 4, 1, 1u32.to_le_bytes().to_vec()),
+ (0x0101, 4, 1, ((cs_at + cs_len) as u32).to_le_bytes().to_vec()),
+ (0x0102, 4, 1, (jpeg.len() as u32).to_le_bytes().to_vec()),
+ ],
+ cs_at,
+ );
+ let mut note = b"OLYMPUS\0II\x03\0".to_vec();
+ note.extend_from_slice(&relative_ifd(&[(0x2020, 13, 1, (cs_at as u32).to_le_bytes().to_vec()), (0x2040, 13, 1, 64u32.to_le_bytes().to_vec())], 12));
+ note.resize(64, 0);
+ note.extend_from_slice(&ip);
+ note.resize(cs_at, 0);
+ note.extend_from_slice(&cs);
+ note.extend_from_slice(&jpeg);
+ let mut t = TiffBuilder::default();
+ let strip = t.blob(data.iter().flat_map(|v| (v << 4).to_le_bytes()).collect());
+ let exif = t.ifd(vec![(37500, Val::Undefined(note)), (41730, Val::Undefined(vec![2, 0, 2, 0, 1, 0, 2, 1]))]);
+ let ifd0 = t.ifd(vec![
+ (256, Val::Long(vec![width as u32])),
+ (257, Val::Long(vec![height as u32])),
+ (258, Val::Short(vec![16])),
+ (259, Val::Short(vec![1])),
+ (262, Val::Short(vec![1])),
+ (271, Val::Ascii("OLYMPUS IMAGING CORP.".into())),
+ (272, Val::Ascii("E-Synthetic".into())),
+ (273, Val::Blobs(vec![strip])),
+ (277, Val::Short(vec![1])),
+ (278, Val::Long(vec![height as u32])),
+ (279, Val::Long(vec![(data.len() * 2) as u32])),
+ (34665, Val::Ifds(vec![exif])),
+ ]);
+ t.chain = vec![ifd0];
+ let mut b = t.build();
+ b[2..4].copy_from_slice(b"RO");
+ b
+}
+
// ---------------------------------------------------------------- scenes
/// A smooth, colourful synthetic scene as linear RGB in 0..1.
diff --git a/crates/raw/src/tiffep.rs b/crates/raw/src/tiffep.rs
index d7f7be887..d8a347858 100644
--- a/crates/raw/src/tiffep.rs
+++ b/crates/raw/src/tiffep.rs
@@ -1,7 +1,8 @@
//! TIFF/EP-structured raws (NEF, ARW, PEF and others) whose sensor data is
//! stored uncompressed or as lossless JPEG in a standard CFA IFD (TIFF/EP,
//! ISO 12234-2: PhotometricInterpretation 32803, CFARepeatPatternDim and
-//! CFAPattern). Vendor-specific compressions are reported as unsupported.
+//! CFAPattern), plus Sony's compressed ARW (see [`crate::sony`]). Other
+//! vendor-specific compressions are reported as unsupported.
//!
//! Black and white levels use DNG-style tags when the camera writes them,
//! then the vendor's publicly documented tags (Nikon maker note BlackLevel,
@@ -13,13 +14,13 @@
use crate::cr2::clip_level;
use crate::error::{RawError, Result};
use crate::sensor::{BlackLevels, Cfa, JpegLayout, Rect, Sensor, read_plane};
+use crate::sony::{self, SONY_RAW_FILE_TYPE};
use crate::tiff::{Ifd, Tiff, tag};
use crate::{Limits, RawFormat};
const PHOTOMETRIC_CFA: u32 = 32803;
const NIKON_WB_RB_LEVELS: u16 = 0x000C;
const NIKON_BLACK_LEVEL: u16 = 0x003D;
-const SONY_RAW_FILE_TYPE: u16 = 0x7000;
const SONY_BLACK_LEVEL: u16 = 0x7310;
const SONY_WB_RGGB_LEVELS: u16 = 0x7313;
@@ -37,7 +38,7 @@ pub(crate) fn is_sony_non_cfa(t: &Tiff, ifds: &[Ifd]) -> bool {
}
/// CFA from the TIFF/EP tags of the raw IFD, or the EXIF CFAPattern.
-fn cfa(t: &Tiff, raw: &Ifd, ifds: &[Ifd]) -> Option<Cfa> {
+pub(crate) fn cfa(t: &Tiff, raw: &Ifd, ifds: &[Ifd]) -> Option<Cfa> {
let dim = t.tag_uints(raw, tag::CFA_REPEAT_PATTERN_DIM);
let pat = t.tag_uints(raw, tag::CFA_PATTERN);
let (rows, cols, colors) = match (dim.as_slice(), pat) {
@@ -75,7 +76,7 @@ fn nikon_maker_note<'a>(t: &Tiff<'a>, ifds: &[Ifd]) -> Option<(Tiff<'a>, Ifd)> {
/// Four levels listed in R, G, G, B order, placed at their 2×2 CFA positions
/// (data parity).
-fn rggb_by_position(cfa: &Cfa, v: &[f64]) -> Option<[f32; 4]> {
+pub(crate) fn rggb_by_position(cfa: &Cfa, v: &[f64]) -> Option<[f32; 4]> {
let [r, g1, g2, b] = <[f64; 4]>::try_from(v).ok()?;
if [r, g1, g2, b].iter().any(|x| !x.is_finite() || *x < 0.0) {
return None;
@@ -100,7 +101,8 @@ pub(crate) fn decode(t: &Tiff, format: RawFormat, limits: &Limits) -> Result<Sen
}
return Err(RawError::unsupported(format!("{}: no CFA image found", format.name())));
};
- let plane = read_plane(t, &raw, limits, JpegLayout::Quads)?;
+ let plane =
+ if format == RawFormat::Arw && sony::is_craw(t, &raw) { sony::read_craw(t, &raw, limits)? } else { read_plane(t, &raw, limits, JpegLayout::Quads)? };
if plane.samples != 1 {
return Err(RawError::unsupported(format!("CFA data with {} samples per pixel", plane.samples)));
}
diff --git a/crates/raw/tests/hostile.rs b/crates/raw/tests/hostile.rs
index e78ee337c..e388cf3d8 100644
--- a/crates/raw/tests/hostile.rs
+++ b/crates/raw/tests/hostile.rs
@@ -1,7 +1,7 @@
//! Truncated and corrupted raw files must fail cleanly, never panic, and
//! never allocate beyond the limits.
-use photocraft_raw::testgen::{Cr2Spec, DngSpec, DngStorage, mosaic, scene, tiff_ep};
+use photocraft_raw::testgen::{Cr2Spec, DngSpec, DngStorage, mosaic, orf, rw2, scene, sony_craw, tiff_ep};
use photocraft_raw::*;
fn samples() -> Vec<Vec<u8>> {
@@ -41,6 +41,10 @@ fn samples() -> Vec<Vec<u8>> {
.build(),
);
out.push(tiff_ep("NIKON", w, h, &cfa, [0, 1, 1, 2], 12, vec![]));
+ let codes = mosaic(&scene(64, 6), 64, [0, 1, 1, 2], 256, 1900);
+ out.push(sony_craw(64, 6, &codes, [8000, 10400, 12900, 14100]));
+ out.push(rw2(30, 8, &mosaic(&scene(30, 8), 30, [0, 1, 1, 2], 128, 4095), 12));
+ out.push(orf(w, h, &cfa));
out
}
diff --git a/crates/raw/tests/vendor_codecs.rs b/crates/raw/tests/vendor_codecs.rs
new file mode 100644
index 000000000..cd5624dae
--- /dev/null
+++ b/crates/raw/tests/vendor_codecs.rs
@@ -0,0 +1,194 @@
+//! Vendor raw codecs, round-tripped through the in-test synthetic encoders:
+//! 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::*;
+
+const CURVE: [u16; 4] = [8000, 10400, 12900, 14100];
+
+/// The cRAW tone curve as the decoder documents it (independent re-statement
+/// for the tests): step 1, 2, 4, 8, 16 per 1/8 code between the knots, ÷ 4.
+fn tone(code: u16) -> u16 {
+ let pts = [0u32, 8000, 10400, 12900, 14100, 16384];
+ let x = u32::from(code) * 8;
+ let y: u32 = pts.windows(2).enumerate().filter(|(_, w)| x > w[0]).map(|(i, w)| (x.min(w[1]) - w[0]) << i).sum();
+ (y / 4).min(16383) as u16
+}
+
+/// 11-bit codes over a smooth scene: every 16-pixel run spans < 128 codes, so
+/// cRAW is exact.
+fn smooth_codes(w: usize, h: usize) -> Vec<u16> {
+ mosaic(&scene(w, h), w, [0, 1, 1, 2], 256, 1900)
+}
+
+#[test]
+fn craw_round_trip_is_exact_on_smooth_data() {
+ let (w, h) = (640, 8);
+ let codes = smooth_codes(w, h);
+ let b = sony_craw(w, h, &codes, CURVE);
+ assert_eq!(identify(&b), Some(RawFormat::Arw));
+ let s = decode(&b, &Limits::default()).unwrap();
+ assert_eq!((s.width, s.height), (w, h));
+ let want: Vec<u16> = codes.iter().map(|&c| tone(c)).collect();
+ assert_eq!(s.data, want);
+ assert_eq!(s.black.values, vec![512.0; 4]);
+ assert_eq!(s.white, [16383.0; 3]);
+ assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5]));
+ let d = develop_sensor(&s, &DevelopOptions::default()).unwrap();
+ assert_eq!((d.width as usize, d.height as usize), (w, h));
+}
+
+#[test]
+fn craw_wide_ranges_lose_only_low_bits() {
+ // Pseudo-random codes: wide ranges force steps of 2..16.
+ let (w, h) = (64, 8);
+ let mut s = 12345u32;
+ let codes: Vec<u16> = (0..w * h)
+ .map(|_| {
+ s = s.wrapping_mul(1103515245).wrapping_add(12345);
+ ((s >> 16) % 2000) as u16
+ })
+ .collect();
+ let b = sony_craw(w, h, &codes, CURVE);
+ let d = decode(&b, &Limits::default()).unwrap();
+ // Re-derive each pixel's step from its block and check the code error.
+ for y in 0..h {
+ for g in 0..w / 32 {
+ for parity in 0..2 {
+ let run: Vec<u16> = (0..16).map(|i| codes[y * w + g * 32 + 2 * i + parity]).collect();
+ let range = run.iter().max().unwrap() - run.iter().min().unwrap();
+ let step = (0..5).map(|k| 1u16 << k).find(|s| 128 * s > range).unwrap();
+ for (i, &c) in run.iter().enumerate() {
+ let got = d.data[y * w + g * 32 + 2 * i + parity];
+ let lo = tone(c.saturating_sub(step - 1));
+ assert!(got <= tone(c) && got >= lo, "code {c} step {step}: got {got}, want {lo}..={}", tone(c));
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn craw_block_layout() {
+ // Max 300 at 3, min 100 at 9, others 100 + 2k: range 200 → step 2.
+ let mut codes = [0u16; 16];
+ for (i, c) in codes.iter_mut().enumerate() {
+ *c = 100 + 2 * i as u16;
+ }
+ codes[3] = 300;
+ codes[9] = 100;
+ codes[0] = 101; // odd: rounds down to 100 at step 2
+ let b = u128::from_le_bytes(craw_block(&codes));
+ assert_eq!(b & 0x7FF, 300);
+ assert_eq!((b >> 11) & 0x7FF, 100);
+ assert_eq!((b >> 22) & 0xF, 3);
+ assert_eq!((b >> 26) & 0xF, 9);
+ assert_eq!((b >> 30) & 0x7F, 0); // pixel 0: (101 - 100) >> 1
+}
+
+#[test]
+fn craw_unusual_variants_are_unsupported() {
+ let h = 4;
+ let codes32 = vec![300u16; 32 * h];
+ let ok = sony_craw(32, h, &codes32, CURVE);
+ assert!(decode(&ok, &Limits::default()).is_ok());
+ // A non-increasing tone curve is not guessed at.
+ let bad_curve = sony_craw(32, h, &codes32, [9000, 8000, 12000, 13000]);
+ assert!(matches!(decode(&bad_curve, &Limits::default()), Err(RawError::Unsupported(_))));
+ // Truncated strip.
+ let cut = &ok[..ok.len() - 20];
+ assert!(decode(cut, &Limits::default()).is_err());
+}
+
+#[test]
+fn rw2_round_trip_12_and_14_bit() {
+ for (bits, w, h) in [(12u32, 120usize, 300usize), (14, 117, 260)] {
+ let max = (1u16 << bits) - 1;
+ let data = mosaic(&scene(w, h), w, [0, 1, 1, 2], 128, max);
+ let b = rw2(w, h, &data, bits);
+ assert!(b.len() > 3 * 0x4000, "spans several pages");
+ 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, "{bits}-bit");
+ assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [0, 1, 1, 2]);
+ assert_eq!(s.black.values, vec![128.0, 129.0, 129.0, 130.0]);
+ assert_eq!(s.white, [f32::from(max); 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));
+ let d = develop_sensor(&s, &DevelopOptions::default()).unwrap();
+ assert_eq!((d.width as usize, d.height as usize), (w - 4, h - 4));
+ }
+}
+
+/// Sets the value of a SHORT entry of IFD0 in a little-endian TIFF-like file.
+fn patch_ifd0_short(b: &mut [u8], tag: u16, v: u16) {
+ let ifd = u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize;
+ let n = u16::from_le_bytes([b[ifd], b[ifd + 1]]) as usize;
+ for i in 0..n {
+ let e = ifd + 2 + 12 * i;
+ if u16::from_le_bytes([b[e], b[e + 1]]) == tag {
+ b[e + 8..e + 10].copy_from_slice(&v.to_le_bytes());
+ return;
+ }
+ }
+ panic!("tag {tag:#x} not found");
+}
+
+#[test]
+fn rw2_compressed_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);
+ match decode(&b, &Limits::default()) {
+ Err(RawError::Unsupported(m)) => assert!(m.contains("raw format 4"), "{m}"),
+ other => panic!("expected unsupported, got {other:?}"),
+ }
+ // Width not made of whole blocks.
+ let mut b = rw2(20, 4, &data, 12);
+ patch_ifd0_short(&mut b, 0x0002, 19);
+ assert!(matches!(decode(&b, &Limits::default()), Err(RawError::Unsupported(_))));
+ // Sizes beyond the limits are refused before allocating.
+ let mut b = rw2(20, 4, &data, 12);
+ patch_ifd0_short(&mut b, 0x0003, 60000);
+ let tight = Limits { max_pixels: 1 << 16, ..Limits::default() };
+ assert!(matches!(decode(&b, &tight), Err(RawError::LimitExceeded(_))));
+}
+
+#[test]
+fn orf_uncompressed_round_trip() {
+ let (w, h) = (40, 24);
+ let data = mosaic(&scene(w, h), w, [1, 0, 2, 1], 64, 4095);
+ let b = orf(w, h, &data);
+ assert_eq!(identify(&b), Some(RawFormat::Orf));
+ let s = decode(&b, &Limits::default()).unwrap();
+ assert_eq!(s.data, data, "left-justified samples are shifted back");
+ assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [1, 0, 2, 1]);
+ assert_eq!(s.black.values, vec![64.0; 4]);
+ 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);
+ assert!(develop_sensor(&s, &DevelopOptions::default()).is_ok());
+ // The maker-note preview is found too (used when the data is compressed).
+ let p = embedded_preview(&b).unwrap();
+ assert_eq!((p.width, p.height), (16, 8));
+}
+
+#[test]
+fn orf_packed_or_compressed_falls_back() {
+ let (w, h) = (40, 24);
+ let mut b = orf(w, h, &vec![1000u16; w * h]);
+ // Halve the declared strip size: no longer 16 bits per sample.
+ let ifd = u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize;
+ let n = u16::from_le_bytes([b[ifd], b[ifd + 1]]) as usize;
+ for i in 0..n {
+ let e = ifd + 2 + 12 * i;
+ if u16::from_le_bytes([b[e], b[e + 1]]) == 279 {
+ b[e + 8..e + 12].copy_from_slice(&((w * h) as u32).to_le_bytes());
+ }
+ }
+ assert!(matches!(decode(&b, &Limits::default()), Err(RawError::Unsupported(_))));
+}