mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Raw: decode uncompressed Fujifilm RAF, Bayer and X-Trans (#1872)
RAF's header, metadata records and Fuji IFD give size, packing (16-bit, 12-bit LSB-first, 14-bit in 32-bit words), layout, black, WB, crop and exposure bias; X-Trans and other periodic non-Bayer CFAs go through a new edge-directed demosaic. Compressed and early SuperCCD RAF stay unsupported (preview fallback). Tests use synthetic files only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
82148e77f5
commit
c0541baf6a
11 files changed
+1115
-43
No files matched your search
+18
-8
@@ -27,7 +27,10 @@ Implemented only from public specifications, papers and observation of files:
|
||||
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.
|
||||
(0x2020) preview tags, the Fujifilm RAF header and metadata records (RawImageCropTopLeft /
|
||||
RawImageCroppedSize, FujiLayout, XTransLayout, WB_GRGBLevels, RawExposureBias) and FujiIFD
|
||||
(RawImageFullWidth / Height, BitsPerSample, StripOffsets / ByteCounts, BlackLevel,
|
||||
WB_GRBLevels).
|
||||
* Nikon compressed NEF: Laurent Clévy's NEF structure notes and Bill Claff's "NEF Compression"
|
||||
(prose: the `0x0096` table layout, a lossy curve followed by a fixed-table Huffman stage),
|
||||
ExifTool's Nikon tag-name documentation and ITU-T T.81 Annex F / H. The Huffman tables are not
|
||||
@@ -37,10 +40,14 @@ Implemented only from public specifications, papers and observation of files:
|
||||
* 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).
|
||||
* Panasonic RW2 RawFormat 5, uncompressed Olympus ORF and uncompressed Fujifilm RAF: established
|
||||
by observation of sample files (bit packing, page layout, sample justification; for RAF the
|
||||
three sample storages and the reversed order of the X-Trans / Bayer layout records, each
|
||||
verified by developing with every candidate phase against the camera's preview).
|
||||
* Demosaicing: Malvar, He & Cutler (ICASSP 2004); Hirakawa & Parks, "Adaptive
|
||||
homogeneity-directed demosaicing" (IEEE TIP 2005).
|
||||
homogeneity-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
|
||||
and performance measures", IEEE TIP 2003) with edge-aware colour differences.
|
||||
* McCamy's CCT approximation (1992); the Bradford chromatic adaptation transform.
|
||||
|
||||
No code from dcraw, LibRaw, rawspeed, rawler, rawloader or darktable was read or used, and no
|
||||
@@ -60,21 +67,24 @@ camera colour tables were copied.
|
||||
| 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 "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 |
|
||||
| CR3, RAF | Recognised, unsupported (preview fallback where a preview is found) |
|
||||
| X-Trans and other non-Bayer CFAs | Unsupported |
|
||||
| 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 | Recognised, unsupported (preview fallback where a preview is found) |
|
||||
| X-Trans and other periodic non-Bayer CFAs (up to 16×16) | Demosaiced by one pattern-agnostic edge-directed method, whatever `Demosaic` is chosen |
|
||||
|
||||
## Development pipeline
|
||||
|
||||
1. Linearization table, per-position black level, scale to the white level.
|
||||
2. White balance (as shot; or grey-world when the file has none; or explicit multipliers),
|
||||
normalized so the smallest multiplier is 1, then clip to 1 so blown highlights stay white.
|
||||
3. Demosaic: `Bilinear`, `Mhc` (Malvar–He–Cutler) or `Ahd` (default).
|
||||
3. Demosaic: `Bilinear`, `Mhc` (Malvar–He–Cutler) or `Ahd` (default) for Bayer; non-Bayer CFAs
|
||||
(X-Trans) always use the edge-directed generic method (`demosaic_cfa`).
|
||||
4. Camera → XYZ (D50) per the DNG specification (ColorMatrix interpolated by the white's
|
||||
correlated colour temperature, or ForwardMatrix), → linear ProPhoto; exposure
|
||||
(BaselineExposure + user EV); gamma 1.8; 16 bits.
|
||||
5. Orientation.
|
||||
|
||||
Files without colour calibration (CR2, NEF, ARW, RW2, ORF…) use a documented neutral fallback: the
|
||||
Files without colour calibration (CR2, NEF, ARW, RW2, ORF, RAF…) 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.
|
||||
|
||||
@@ -15,6 +15,23 @@
|
||||
//! `phase` gives the colours (0 = R, 1 = G, 2 = B) of the 2×2 cell at the
|
||||
//! image origin, row major. Output is interleaved RGB. Work is split in row
|
||||
//! bands run in parallel.
|
||||
//!
|
||||
//! Other periodic CFAs (Fujifilm X-Trans' 6×6 pattern) go through
|
||||
//! [`demosaic_cfa`], a pattern-agnostic edge-directed interpolation:
|
||||
//!
|
||||
//! 1. Green at non-green sites: per axis (horizontal, vertical), the mean of
|
||||
//! the green neighbours on that axis, weighted by the inverse square of the
|
||||
//! local gradient along it (mean absolute difference of same-colour sample
|
||||
//! pairs on the axis within a 5×5 window), as in gradient-weighted
|
||||
//! interpolation (e.g. W. Lu, Y.-P. Tan, "Color filter array demosaicking:
|
||||
//! new method and performance measures", IEEE TIP 12(10), 2003).
|
||||
//! 2. Red and blue everywhere from colour differences: the green estimate plus
|
||||
//! the weighted mean of (sample − green) at the same-colour sites of the 5×5
|
||||
//! window, weighted by inverse squared distance and by green similarity (so
|
||||
//! differences are not carried across edges).
|
||||
//!
|
||||
//! The pattern breaks under mirror padding when its period is not 2, so this
|
||||
//! path reads only interior samples and drops taps outside the image.
|
||||
|
||||
use crate::color::Mat3;
|
||||
use crate::par;
|
||||
@@ -220,6 +237,195 @@ pub(crate) fn demosaic(p: &Padded, phase: [u8; 4], method: Demosaic, to_xyz: &Ma
|
||||
out
|
||||
}
|
||||
|
||||
/// A CFA repeat as seen from the plane's origin: colour of plane pixel
|
||||
/// (x, y) is `colors[(y % h) * w + x % w]`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Pattern {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub colors: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Pattern {
|
||||
/// The repeat of `cfa` starting at data coordinates (`x0`, `y0`).
|
||||
pub fn of(cfa: &crate::sensor::Cfa, x0: usize, y0: usize) -> Self {
|
||||
let (w, h) = (cfa.width.clamp(1, 16), cfa.height.clamp(1, 16));
|
||||
Pattern { w, h, colors: (0..w * h).map(|i| cfa.color(x0 + i % w, y0 + i / w).min(2)).collect() }
|
||||
}
|
||||
|
||||
fn at(&self, x: isize, y: isize) -> u8 {
|
||||
let (w, h) = (self.w.max(1) as isize, self.h.max(1) as isize);
|
||||
self.colors.get((y.rem_euclid(h) * w + x.rem_euclid(w)) as usize).copied().unwrap_or(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Tap radius of the generic demosaic (a 5×5 window).
|
||||
const RADIUS: isize = 2;
|
||||
|
||||
type Off = (isize, isize);
|
||||
|
||||
/// One interpolation axis at a non-green site.
|
||||
#[derive(Default)]
|
||||
struct Axis {
|
||||
/// Green neighbours at distance 1 on the axis.
|
||||
near: Vec<Off>,
|
||||
/// Same-colour sample pairs along the axis (a, b, 1 / distance).
|
||||
pairs: Vec<(Off, Off, f32)>,
|
||||
}
|
||||
|
||||
/// The taps of one CFA phase.
|
||||
struct Taps {
|
||||
own: u8,
|
||||
axes: [Axis; 2],
|
||||
/// Greens of the 3×3 (or 5×5) window, when no axis has a green neighbour.
|
||||
greens: Vec<Off>,
|
||||
/// Per colour, its sites in the window with weight 1 / distance².
|
||||
sites: [Vec<(Off, f32)>; 3],
|
||||
}
|
||||
|
||||
fn phase_taps(pat: &Pattern, px: isize, py: isize) -> Taps {
|
||||
let col = |dx: isize, dy: isize| pat.at(px + dx, py + dy);
|
||||
let window: Vec<Off> = (-RADIUS..=RADIUS).flat_map(|dy| (-RADIUS..=RADIUS).map(move |dx| (dx, dy))).collect();
|
||||
let axes = [(1isize, 0isize), (0, 1)].map(|(ax, ay)| {
|
||||
let near = [(ax, ay), (-ax, -ay)].into_iter().filter(|&(dx, dy)| col(dx, dy) == 1).collect();
|
||||
let mut pairs = Vec::new();
|
||||
for &(dx, dy) in &window {
|
||||
// Pairs on the axis line or the lines next to it.
|
||||
if (ax == 1 && dy.abs() > 1) || (ay == 1 && dx.abs() > 1) {
|
||||
continue;
|
||||
}
|
||||
for k in 1..=2 {
|
||||
let (bx, by) = (dx + k * ax, dy + k * ay);
|
||||
if bx.abs() <= RADIUS && by.abs() <= RADIUS && col(dx, dy) == col(bx, by) {
|
||||
pairs.push(((dx, dy), (bx, by), 1.0 / k as f32));
|
||||
}
|
||||
}
|
||||
}
|
||||
Axis { near, pairs }
|
||||
});
|
||||
let ring = |r: isize| -> Vec<Off> {
|
||||
window.iter().copied().filter(|&(dx, dy)| dx.abs() <= r && dy.abs() <= r && (dx, dy) != (0, 0) && col(dx, dy) == 1).collect()
|
||||
};
|
||||
let greens = Some(ring(1)).filter(|g| !g.is_empty()).unwrap_or_else(|| ring(RADIUS));
|
||||
let sites = [0u8, 1, 2].map(|c| {
|
||||
window.iter().filter(|&&(dx, dy)| (dx, dy) != (0, 0) && col(dx, dy) == c).map(|&(dx, dy)| ((dx, dy), 1.0 / (dx * dx + dy * dy) as f32)).collect()
|
||||
});
|
||||
Taps { own: col(0, 0), axes, greens, sites }
|
||||
}
|
||||
|
||||
/// Demosaics a padded plane with any periodic CFA (see the module docs) into
|
||||
/// interleaved RGB. There is one algorithm for every [`Demosaic`] choice:
|
||||
/// without the edge-directed weights it is no faster and leaves zipper
|
||||
/// artefacts along every edge of an X-Trans image.
|
||||
pub(crate) fn demosaic_cfa(p: &Padded, pat: &Pattern) -> Vec<f32> {
|
||||
let (w, h, s) = (p.w, p.h, p.stride);
|
||||
let mut out = vec![0.0f32; w * h * 3];
|
||||
if w == 0 || h == 0 || pat.w == 0 || pat.h == 0 || pat.colors.len() < pat.w * pat.h || p.data.len() < s * (h + 2 * PAD) {
|
||||
return out;
|
||||
}
|
||||
let taps: Vec<Taps> = (0..pat.w * pat.h).map(|i| phase_taps(pat, (i % pat.w) as isize, (i / pat.w) as isize)).collect();
|
||||
let tap_at = |x: usize, y: usize| &taps[(y % pat.h) * pat.w + x % pat.w];
|
||||
let d = &p.data;
|
||||
// Sample at (x + dx, y + dy), or None outside the image.
|
||||
let get = |plane: &[f32], stride: usize, pad: usize, x: usize, y: usize, (dx, dy): Off| -> Option<f32> {
|
||||
let (xx, yy) = (x.checked_add_signed(dx)?, y.checked_add_signed(dy)?);
|
||||
(xx < w && yy < h).then(|| plane.get((yy + pad) * stride + pad + xx).copied()).flatten()
|
||||
};
|
||||
let raw = |x: usize, y: usize, o: Off| get(d, s, PAD, x, y, o);
|
||||
let band = par::band_rows(w);
|
||||
|
||||
// 1. Green everywhere.
|
||||
let mut green = vec![0.0f32; w * h];
|
||||
par::chunks_mut(&mut green, band * w, |b, chunk| {
|
||||
for (r, row) in chunk.chunks_exact_mut(w).enumerate() {
|
||||
let y = b * band + r;
|
||||
for (x, g) in row.iter_mut().enumerate() {
|
||||
let t = tap_at(x, y);
|
||||
let v = raw(x, y, (0, 0)).unwrap_or(0.0);
|
||||
if t.own == 1 {
|
||||
*g = v;
|
||||
continue;
|
||||
}
|
||||
let (mut num, mut den) = (0.0f32, 0.0f32);
|
||||
for a in &t.axes {
|
||||
let (mut sum, mut n) = (0.0f32, 0u32);
|
||||
for &o in &a.near {
|
||||
if let Some(v) = raw(x, y, o) {
|
||||
sum += v;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
continue;
|
||||
}
|
||||
let (mut grad, mut m) = (0.0f32, 0.0f32);
|
||||
for &(oa, ob, k) in &a.pairs {
|
||||
if let (Some(va), Some(vb)) = (raw(x, y, oa), raw(x, y, ob)) {
|
||||
grad += (va - vb).abs() * k;
|
||||
m += 1.0;
|
||||
}
|
||||
}
|
||||
let grad = if m > 0.0 { grad / m } else { 0.0 };
|
||||
let wt = 1.0 / ((GRAD_EPS + grad) * (GRAD_EPS + grad));
|
||||
num += wt * sum / n as f32;
|
||||
den += wt;
|
||||
}
|
||||
*g = if den > 0.0 {
|
||||
num / den
|
||||
} else {
|
||||
let (mut sum, mut n) = (0.0f32, 0u32);
|
||||
for &o in &t.greens {
|
||||
if let Some(v) = raw(x, y, o) {
|
||||
sum += v;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
if n > 0 { sum / n as f32 } else { v }
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Red and blue from colour differences.
|
||||
let gref = &green;
|
||||
let gat = |x: usize, y: usize, o: Off| get(gref, w, 0, x, y, o);
|
||||
par::chunks_mut(&mut out, band * w * 3, |b, chunk| {
|
||||
for (r, row) in chunk.chunks_exact_mut(w * 3).enumerate() {
|
||||
let y = b * band + r;
|
||||
for (x, o) in row.as_chunks_mut::<3>().0.iter_mut().enumerate() {
|
||||
let t = tap_at(x, y);
|
||||
let g = gref.get(y * w + x).copied().unwrap_or(0.0);
|
||||
let v = raw(x, y, (0, 0)).unwrap_or(0.0);
|
||||
o[1] = g;
|
||||
for c in [0usize, 2] {
|
||||
if usize::from(t.own) == c {
|
||||
o[c] = v;
|
||||
continue;
|
||||
}
|
||||
let (mut num, mut den) = (0.0f32, 0.0f32);
|
||||
for &(off, base) in &t.sites[c] {
|
||||
if let (Some(vq), Some(gq)) = (raw(x, y, off), gat(x, y, off)) {
|
||||
let wt = base / (DIFF_EPS + (gq - g).abs());
|
||||
num += wt * (vq - gq);
|
||||
den += wt;
|
||||
}
|
||||
}
|
||||
o[c] = if den > 0.0 { g + num / den } else { g };
|
||||
}
|
||||
for v in o.iter_mut() {
|
||||
*v = v.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Regularizes the inverse-gradient weights (normalized units, about 1/256 of full scale).
|
||||
const GRAD_EPS: f32 = 1.0 / 256.0;
|
||||
/// Regularizes the green-similarity weights of the colour differences.
|
||||
const DIFF_EPS: f32 = 1.0 / 64.0;
|
||||
|
||||
/// CIE f(t) for L*a*b*, tabulated on 0..2 with linear interpolation.
|
||||
struct LabF {
|
||||
table: Vec<f32>,
|
||||
@@ -488,6 +694,104 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The X-Trans repeat as observed at a sensor's data origin.
|
||||
const XTRANS: [&str; 6] = ["GGRGGB", "GGBGGR", "BRGRBG", "GGBGGR", "GGRGGB", "RBGBRG"];
|
||||
|
||||
fn pattern(rows: &[&str]) -> Pattern {
|
||||
let colors = rows
|
||||
.concat()
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'R' => 0,
|
||||
'G' => 1,
|
||||
_ => 2,
|
||||
})
|
||||
.collect();
|
||||
Pattern { w: rows[0].len(), h: rows.len(), colors }
|
||||
}
|
||||
|
||||
fn mosaic_pat(rgb: &[[f32; 3]], w: usize, pat: &Pattern) -> Vec<f32> {
|
||||
(0..rgb.len()).map(|i| rgb[i][usize::from(pat.at((i % w) as isize, (i / w) as isize))]).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xtrans_flat_colour_is_exact() {
|
||||
let (w, h) = (25, 19);
|
||||
let rgb = vec![[0.2f32, 0.5, 0.8]; w * h];
|
||||
let pat = pattern(&XTRANS);
|
||||
// Every phase of the pattern at the plane origin.
|
||||
for (sx, sy) in [(0, 0), (1, 0), (2, 3), (5, 5)] {
|
||||
let shifted = Pattern { colors: (0..36).map(|i| pat.at((i % 6 + sx) as isize, (i / 6 + sy) as isize)).collect(), ..pat.clone() };
|
||||
let out = demosaic_cfa(&Padded::from_plane(&mosaic_pat(&rgb, w, &shifted), w, h), &shifted);
|
||||
for (i, v) in out.as_chunks::<3>().0.iter().enumerate() {
|
||||
for c in 0..3 {
|
||||
assert!((v[c] - rgb[i][c]).abs() < 1e-5, "shift ({sx},{sy}) px {i} c {c}: {}", v[c]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xtrans_quality() {
|
||||
let pat = pattern(&XTRANS);
|
||||
// A smooth colour field.
|
||||
let (w, h) = (66, 48);
|
||||
let rgb: Vec<[f32; 3]> = (0..w * h)
|
||||
.map(|i| {
|
||||
let (x, y) = ((i % w) as f32 / w as f32, (i / w) as f32 / h as f32);
|
||||
[0.2 + 0.6 * x, 0.3 + 0.4 * (x * y), 0.8 - 0.5 * y]
|
||||
})
|
||||
.collect();
|
||||
let out = demosaic_cfa(&Padded::from_plane(&mosaic_pat(&rgb, w, &pat), w, h), &pat);
|
||||
let smooth = psnr(&out, &rgb, w, h, 2);
|
||||
assert!(smooth > 40.0, "smooth field {smooth:.1} dB");
|
||||
// Grey stripes 3 pixels wide, vertical then horizontal: the edge-directed
|
||||
// green must beat a plain neighbour average by a wide margin.
|
||||
let (w, h) = (48, 48);
|
||||
let rgb: Vec<[f32; 3]> = (0..w * h)
|
||||
.map(|i| {
|
||||
let (x, y) = (i % w, i / w);
|
||||
let v = if y < h / 2 { ((x / 3) % 2) as f32 } else { ((y / 3) % 2) as f32 };
|
||||
[0.1 + 0.8 * v; 3]
|
||||
})
|
||||
.collect();
|
||||
let cfa = mosaic_pat(&rgb, w, &pat);
|
||||
let adaptive = psnr(&demosaic_cfa(&Padded::from_plane(&cfa, w, h), &pat), &rgb, w, h, 3);
|
||||
// Plain average of the 3×3 greens, colour differences unweighted.
|
||||
let plain: Vec<f32> = (0..w * h)
|
||||
.flat_map(|i| {
|
||||
let (x, y) = ((i % w) as isize, (i / w) as isize);
|
||||
let mean = |c: u8| {
|
||||
let v: Vec<f32> = (-1..=1)
|
||||
.flat_map(|dy| (-1..=1).map(move |dx| (x + dx, y + dy)))
|
||||
.filter(|&(xx, yy)| xx >= 0 && yy >= 0 && xx < w as isize && yy < h as isize && pat.at(xx, yy) == c)
|
||||
.map(|(xx, yy)| cfa[yy as usize * w + xx as usize])
|
||||
.collect();
|
||||
if v.is_empty() { 0.5 } else { v.iter().sum::<f32>() / v.len() as f32 }
|
||||
};
|
||||
[mean(0), mean(1), mean(2)]
|
||||
})
|
||||
.collect();
|
||||
let plain = psnr(&plain, &rgb, w, h, 3);
|
||||
assert!(adaptive > plain + 6.0, "adaptive {adaptive:.1} dB vs plain {plain:.1} dB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_patterns_do_not_panic() {
|
||||
// A 3×3 pattern without blue, a 1×1 all-green one, and a 2×2 non-Bayer one.
|
||||
for rows in [&["RGG", "GGR", "GRG"][..], &["G"][..], &["RG", "BR"][..]] {
|
||||
let pat = pattern(rows);
|
||||
for (w, h) in [(1, 1), (2, 3), (7, 5), (13, 1)] {
|
||||
let out = demosaic_cfa(&Padded::from_plane(&vec![0.5; w * h], w, h), &pat);
|
||||
assert_eq!(out.len(), w * h * 3);
|
||||
assert!(out.iter().all(|v| v.is_finite()));
|
||||
}
|
||||
}
|
||||
// A degenerate pattern is rejected, not indexed out of range.
|
||||
let bad = Pattern { w: 6, h: 6, colors: vec![1; 4] };
|
||||
assert!(demosaic_cfa(&Padded::from_plane(&[0.5; 4], 2, 2), &bad).iter().all(|v| *v == 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiny_planes_do_not_panic() {
|
||||
for (w, h) in [(1, 1), (2, 1), (1, 3), (2, 2), (3, 3), (7, 9), (40, 1)] {
|
||||
|
||||
+38
-24
@@ -3,7 +3,7 @@
|
||||
//! exposure, gamma 1.8 encode to 16 bits, orientation.
|
||||
|
||||
use crate::color::{self, Mat3};
|
||||
use crate::demosaic::{Demosaic, PAD, Padded, demosaic};
|
||||
use crate::demosaic::{Demosaic, PAD, Padded, Pattern, demosaic, demosaic_cfa};
|
||||
use crate::error::{RawError, Result};
|
||||
use crate::sensor::Sensor;
|
||||
use crate::{Limits, RawFormat, par};
|
||||
@@ -47,7 +47,9 @@ pub struct RawInfo {
|
||||
/// Sensor data size.
|
||||
pub sensor_width: usize,
|
||||
pub sensor_height: usize,
|
||||
/// CFA pattern at the crop origin, e.g. `"RGGB"`; `None` for LinearRaw.
|
||||
/// CFA pattern at the crop origin: `"RGGB"` for Bayer; other patterns list
|
||||
/// their whole repeat row by row, rows separated by `/` (X-Trans:
|
||||
/// `"GGRGGB/GGBGGR/…"`); `None` for LinearRaw.
|
||||
pub cfa: Option<String>,
|
||||
/// White-balance multipliers used (R, G, B, normalized to a minimum of 1).
|
||||
pub wb_multipliers: [f64; 3],
|
||||
@@ -147,8 +149,10 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {
|
||||
if s.samples != 1 && s.samples != 3 {
|
||||
return Err(RawError::unsupported(format!("{} samples per pixel", s.samples)));
|
||||
}
|
||||
// Working buffers: one f32 plane plus f32 RGB plus u16 RGB per pixel.
|
||||
opts.limits.check(c.width as u64, c.height as u64, 4 + 12 + 6)?;
|
||||
// Working buffers: one f32 plane plus f32 RGB plus u16 RGB per pixel, and
|
||||
// a green plane for non-Bayer patterns.
|
||||
let bayer = s.cfa.as_ref().is_none_or(|cfa| cfa.is_bayer());
|
||||
opts.limits.check(c.width as u64, c.height as u64, if bayer { 4 + 12 + 6 } else { 4 + 4 + 12 + 6 })?;
|
||||
let mut warnings = s.warnings.clone();
|
||||
let sc = Scale { s, lin: s.linearization.as_deref() };
|
||||
|
||||
@@ -191,39 +195,42 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {
|
||||
let (w, h) = (c.width, c.height);
|
||||
let band = par::band_rows(w);
|
||||
let mut rgb: Vec<f32>;
|
||||
let phase;
|
||||
let pattern: Option<String>;
|
||||
match &s.cfa {
|
||||
Some(cfa) => {
|
||||
// Normalized, balanced, clipped CFA plane.
|
||||
let mut plane = Padded::new(w, h);
|
||||
let stride = plane.stride;
|
||||
// Fast path: black varies at most per 2×2 position (the Bayer period).
|
||||
// Fast path: black varies at most per 2×2 position, so black and gain
|
||||
// repeat every `period` columns (the CFA width, made even).
|
||||
let bl = &s.black;
|
||||
let periodic = bl.delta_h.is_empty() && bl.delta_v.is_empty() && matches!(bl.rows, 1 | 2) && matches!(bl.cols, 1 | 2);
|
||||
let periodic = bl.delta_h.is_empty() && bl.delta_v.is_empty() && matches!(bl.rows, 1 | 2) && matches!(bl.cols, 1 | 2) && cfa.width <= 16;
|
||||
let period = if cfa.width % 2 == 0 { cfa.width.max(2) } else { cfa.width * 2 };
|
||||
plane.fill_rows(band, |y0, chunk| {
|
||||
for (r, prow) in chunk.chunks_exact_mut(stride).enumerate() {
|
||||
let row = &mut prow[PAD..PAD + w];
|
||||
let y = c.y + y0 + r;
|
||||
if periodic {
|
||||
// Per column parity: black and the combined scale × white-balance gain.
|
||||
let k: [(f32, f32); 2] = std::array::from_fn(|p| {
|
||||
let x = c.x + p;
|
||||
let black = bl.at(x.saturating_sub(s.active.x), y.saturating_sub(s.active.y), 0, 1);
|
||||
let range = s.white[0] - black;
|
||||
let gain = if range >= 1.0 { mult[usize::from(cfa.color(x, y)).min(2)] / range } else { 0.0 };
|
||||
(black, gain)
|
||||
});
|
||||
// Per column of the period: black and the combined scale × white-balance gain.
|
||||
let k: Vec<(f32, f32)> = (0..period)
|
||||
.map(|p| {
|
||||
let x = c.x + p;
|
||||
let black = bl.at(x.saturating_sub(s.active.x), y.saturating_sub(s.active.y), 0, 1);
|
||||
let range = s.white[0] - black;
|
||||
let gain = if range >= 1.0 { mult[usize::from(cfa.color(x, y)).min(2)] / range } else { 0.0 };
|
||||
(black, gain)
|
||||
})
|
||||
.collect();
|
||||
let src = &s.data[y * s.width + c.x..y * s.width + c.x + w];
|
||||
let ks = k.iter().cycle();
|
||||
match &sc.lin {
|
||||
None => {
|
||||
for (i, (v, &raw)) in row.iter_mut().zip(src).enumerate() {
|
||||
let (black, gain) = k[i & 1];
|
||||
for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) {
|
||||
*v = ((f32::from(raw) - black) * gain).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
Some(l) => {
|
||||
for (i, (v, &raw)) in row.iter_mut().zip(src).enumerate() {
|
||||
let (black, gain) = k[i & 1];
|
||||
for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) {
|
||||
let lin = f32::from(l.get(usize::from(raw)).or_else(|| l.last()).copied().unwrap_or(raw));
|
||||
*v = ((lin - black) * gain).clamp(0.0, 1.0);
|
||||
}
|
||||
@@ -246,13 +253,20 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {
|
||||
}
|
||||
});
|
||||
plane.fill_borders();
|
||||
let p = cfa.phase(c.x, c.y);
|
||||
phase = Some(p);
|
||||
rgb = demosaic(&plane, p, opts.demosaic, &to_xyz);
|
||||
let names = |p: &[u8]| p.iter().map(|c| ['R', 'G', 'B'][usize::from(*c).min(2)]).collect::<String>();
|
||||
if bayer {
|
||||
let p = cfa.phase(c.x, c.y);
|
||||
pattern = Some(names(&p));
|
||||
rgb = demosaic(&plane, p, opts.demosaic, &to_xyz);
|
||||
} else {
|
||||
let pat = Pattern::of(cfa, c.x, c.y);
|
||||
pattern = Some(pat.colors.chunks(pat.w.max(1)).map(names).collect::<Vec<_>>().join("/"));
|
||||
rgb = demosaic_cfa(&plane, &pat);
|
||||
}
|
||||
drop(plane);
|
||||
}
|
||||
None => {
|
||||
phase = None;
|
||||
pattern = None;
|
||||
rgb = vec![0.0f32; w * h * 3];
|
||||
par::chunks_mut(&mut rgb, band * w * 3, |b, chunk| {
|
||||
for (r, row) in chunk.chunks_exact_mut(w * 3).enumerate() {
|
||||
@@ -301,7 +315,7 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {
|
||||
model: s.model.clone(),
|
||||
sensor_width: s.width,
|
||||
sensor_height: s.height,
|
||||
cfa: phase.map(|p| p.iter().map(|c| ['R', 'G', 'B'][usize::from(*c).min(2)]).collect()),
|
||||
cfa: pattern,
|
||||
wb_multipliers: mult.map(|m| f64::from(m / nmax)),
|
||||
orientation: s.orientation,
|
||||
baseline_exposure: s.baseline_exposure,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! 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, published descriptions of Sony's cRAW code, public maker-note
|
||||
//! tag tables, Nikon Huffman tables recovered by black-box analysis of CC0
|
||||
//! and RAF tag tables, Nikon Huffman tables recovered by black-box analysis of CC0
|
||||
//! samples (see `nefc.rs`), observation of sample files, and the demosaicing
|
||||
//! papers cited in [`Demosaic`]. No code from dcraw, LibRaw, rawspeed,
|
||||
//! rawler, rawloader or darktable was used.
|
||||
@@ -27,7 +27,9 @@
|
||||
//! 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) and uncompressed Olympus ORF. Everything else reports [`RawError::Unsupported`].
|
||||
//! Panasonic RW2 (RawFormat 5), 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 are
|
||||
@@ -49,6 +51,7 @@ mod opcodes;
|
||||
mod orf;
|
||||
mod par;
|
||||
mod preview;
|
||||
mod raf;
|
||||
mod rw2;
|
||||
mod sensor;
|
||||
mod sony;
|
||||
@@ -177,7 +180,7 @@ pub fn identify(bytes: &[u8]) -> Option<RawFormat> {
|
||||
if bytes.get(4..12) == Some(b"ftypcrx ") {
|
||||
return Some(RawFormat::Cr3);
|
||||
}
|
||||
if bytes.starts_with(b"FUJIFILMCCD-RAW") {
|
||||
if bytes.starts_with(raf::MAGIC) {
|
||||
return Some(RawFormat::Raf);
|
||||
}
|
||||
let t = Tiff::new(bytes)?;
|
||||
@@ -213,7 +216,7 @@ pub fn decode(bytes: &[u8], limits: &Limits) -> Result<Sensor, RawError> {
|
||||
let format = identify(bytes).ok_or(RawError::NotRaw)?;
|
||||
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::Raf => raf::decode(bytes, limits),
|
||||
_ => {
|
||||
let t = Tiff::new(bytes).ok_or(RawError::NotRaw)?;
|
||||
match format {
|
||||
|
||||
@@ -50,10 +50,9 @@ fn candidate(data: &[u8], offset: usize, len: usize) -> Option<Preview<'_>> {
|
||||
/// The largest embedded JPEG preview of a raw file (TIFF-based raws and RAF).
|
||||
pub fn embedded_preview(bytes: &[u8]) -> Option<Preview<'_>> {
|
||||
let mut found: Vec<Preview> = Vec::new();
|
||||
if bytes.starts_with(b"FUJIFILMCCD-RAW") {
|
||||
if bytes.starts_with(crate::raf::MAGIC) {
|
||||
// RAF header: big-endian JPEG offset and length at bytes 84 and 88.
|
||||
let be = |o: usize| bytes.get(o..o + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize);
|
||||
if let (Some(off), Some(len)) = (be(84), be(88)) {
|
||||
if let Some((off, len)) = crate::raf::preview_range(bytes) {
|
||||
found.extend(candidate(bytes, off, len));
|
||||
}
|
||||
} else if let Some(t) = Tiff::new(bytes) {
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
//! Fujifilm RAF.
|
||||
//!
|
||||
//! A RAF file starts with a big-endian header: the magic
|
||||
//! `FUJIFILMCCD-RAW `, a format version, a camera id and the model name (32
|
||||
//! bytes at 28), then (offset, length) pairs for the camera's JPEG preview (at
|
||||
//! 84), a metadata directory (at 92) and the CFA region (at 100).
|
||||
//!
|
||||
//! The metadata directory is a big-endian record count followed by (tag,
|
||||
//! size, data) records. The tags used here are documented in ExifTool's
|
||||
//! FujiFilm RAF table: RawImageCropTopLeft (0x110: top, left),
|
||||
//! RawImageCroppedSize (0x111: height, width), FujiLayout (0x130), XTransLayout (0x131), WB_GRGBLevels (0x2FF0)
|
||||
//! and RawExposureBias (0x9650: a signed 16-bit fraction).
|
||||
//!
|
||||
//! In every body since about 2010 the CFA region is a small TIFF whose IFD0
|
||||
//! points (tag 0xF000) at a Fuji IFD (ExifTool's FujiIFD table):
|
||||
//! RawImageFullWidth / Height (0xF001 / 0xF002), BitsPerSample (0xF003),
|
||||
//! StripOffsets / StripByteCounts (0xF007 / 0xF008, relative to the CFA
|
||||
//! region), BlackLevel (0xF00A) and WB_GRBLevels (0xF00E: G, R, B). Offsets in
|
||||
//! it are relative to the CFA region.
|
||||
//!
|
||||
//! The rest was established by observation of sample files (raw.pixls.us
|
||||
//! CC0 samples of the X-Pro1, X-E2, X100, XF1, X-A5 and GFX 50S, and an
|
||||
//! X-T30 III file):
|
||||
//!
|
||||
//! * Sample storage, told apart by the strip's byte count: 16-bit
|
||||
//! containers in the CFA TIFF's byte order (14- and 16-bit bodies: X-Trans
|
||||
//! II to V, GFX); 12-bit samples packed into a little-endian bit stream,
|
||||
//! least significant bit first (X-Trans I, X100, XF1, X-A1…); 14-bit
|
||||
//! samples packed into little-endian 32-bit words, most significant bit
|
||||
//! first (X-A3/5/7, X-T100/200, XF10). A shorter strip is Fujifilm's own
|
||||
//! lossless compression (it starts with `IS`), which has no public
|
||||
//! description and is reported as unsupported, as are the pre-2010
|
||||
//! FinePix / SuperCCD files without the CFA TIFF.
|
||||
//! * XTransLayout lists the 6×6 X-Trans pattern (0 = R, 1 = G, 2 = B) in
|
||||
//! reverse order: its last byte is the colour at data (0, 0), its first
|
||||
//! the colour at (5, 5).
|
||||
//! * On Bayer bodies FujiLayout lists the 2×2 pattern the same way, reversed,
|
||||
//! with the colour in the low two bits (0 = R, 1 and 3 = G, 2 = B):
|
||||
//! `0A 0B 09 08` is RGGB and `08 09 0B 0A` is BGGR at data (0, 0).
|
||||
//! * The crop records address the data as stored; the preview JPEG's EXIF
|
||||
//! orientation applies to the raw image too.
|
||||
//!
|
||||
//! Both layouts were verified per sample by developing with every candidate
|
||||
//! phase and comparing with the camera's preview.
|
||||
|
||||
use crate::cr2::clip_level;
|
||||
use crate::error::{RawError, Result};
|
||||
use crate::sensor::{BlackLevels, Cfa, Rect, Sensor};
|
||||
use crate::tiff::{Tiff, tag};
|
||||
use crate::{Limits, RawFormat, par};
|
||||
|
||||
pub(crate) const MAGIC: &[u8] = b"FUJIFILMCCD-RAW";
|
||||
|
||||
const CROP_TOP_LEFT: u16 = 0x0110;
|
||||
const CROPPED_SIZE: u16 = 0x0111;
|
||||
const FUJI_LAYOUT: u16 = 0x0130;
|
||||
const XTRANS_LAYOUT: u16 = 0x0131;
|
||||
const WB_GRGB_LEVELS: u16 = 0x2FF0;
|
||||
const RAW_EXPOSURE_BIAS: u16 = 0x9650;
|
||||
|
||||
const FUJI_IFD: u16 = 0xF000;
|
||||
const RAW_WIDTH: u16 = 0xF001;
|
||||
const RAW_HEIGHT: u16 = 0xF002;
|
||||
const RAW_BITS: u16 = 0xF003;
|
||||
const STRIP_OFFSET: u16 = 0xF007;
|
||||
const STRIP_BYTE_COUNT: u16 = 0xF008;
|
||||
const BLACK_LEVEL: u16 = 0xF00A;
|
||||
const WB_GRB_LEVELS: u16 = 0xF00E;
|
||||
|
||||
/// Most metadata records read.
|
||||
const MAX_RECORDS: usize = 512;
|
||||
|
||||
fn be32(b: &[u8], at: usize) -> Option<usize> {
|
||||
let s: [u8; 4] = b.get(at..at.checked_add(4)?)?.try_into().ok()?;
|
||||
Some(u32::from_be_bytes(s) as usize)
|
||||
}
|
||||
|
||||
fn be16(b: &[u8], at: usize) -> Option<u16> {
|
||||
let s: [u8; 2] = b.get(at..at.checked_add(2)?)?.try_into().ok()?;
|
||||
Some(u16::from_be_bytes(s))
|
||||
}
|
||||
|
||||
/// Offset and length of the preview JPEG (header bytes 84 and 88).
|
||||
pub(crate) fn preview_range(bytes: &[u8]) -> Option<(usize, usize)> {
|
||||
Some((be32(bytes, 84)?, be32(bytes, 88)?))
|
||||
}
|
||||
|
||||
/// The metadata directory's records as (tag, data).
|
||||
fn records(bytes: &[u8]) -> Vec<(u16, &[u8])> {
|
||||
let mut out = Vec::new();
|
||||
let (Some(at), Some(len)) = (be32(bytes, 92), be32(bytes, 96)) else { return out };
|
||||
let Some(dir) = at.checked_add(len).and_then(|end| bytes.get(at..end)) else { return out };
|
||||
let n = be32(dir, 0).unwrap_or(0).min(MAX_RECORDS);
|
||||
let mut p = 4usize;
|
||||
for _ in 0..n {
|
||||
let (Some(tag), Some(size)) = (be16(dir, p), be16(dir, p + 2)) else { break };
|
||||
let start = p + 4;
|
||||
let Some(data) = dir.get(start..start + usize::from(size)) else { break };
|
||||
out.push((tag, data));
|
||||
p = start + usize::from(size);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn record<'a>(recs: &[(u16, &'a [u8])], tag: u16) -> Option<&'a [u8]> {
|
||||
recs.iter().find(|(t, _)| *t == tag).map(|(_, d)| *d)
|
||||
}
|
||||
|
||||
/// A record holding two big-endian 16-bit values.
|
||||
fn pair(recs: &[(u16, &[u8])], tag: u16) -> Option<(usize, usize)> {
|
||||
let d = record(recs, tag)?;
|
||||
Some((usize::from(be16(d, 0)?), usize::from(be16(d, 2)?)))
|
||||
}
|
||||
|
||||
/// The CFA from XTransLayout (6×6) or FujiLayout (2×2), both stored reversed.
|
||||
fn layout_cfa(recs: &[(u16, &[u8])]) -> Option<Cfa> {
|
||||
if let Some(d) = record(recs, XTRANS_LAYOUT).filter(|d| d.len() == 36) {
|
||||
let colors = d.iter().rev().map(|&c| (c <= 2).then_some(c)).collect::<Option<Vec<u8>>>()?;
|
||||
return Some(Cfa { width: 6, height: 6, colors, origin_x: 0, origin_y: 0 });
|
||||
}
|
||||
let d = record(recs, FUJI_LAYOUT).filter(|d| d.len() == 4)?;
|
||||
let colors: Vec<u8> = d.iter().rev().map(|&c| if c & 3 == 3 { 1 } else { c & 3 }).collect();
|
||||
let cfa = Cfa { width: 2, height: 2, colors, origin_x: 0, origin_y: 0 };
|
||||
cfa.is_bayer().then_some(cfa)
|
||||
}
|
||||
|
||||
/// How the samples of the strip are stored.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Packing {
|
||||
/// 16-bit containers in the given byte order.
|
||||
U16 { le: bool },
|
||||
/// Little-endian bit stream, least significant bit first (12-bit bodies).
|
||||
LsbFirst,
|
||||
/// Little-endian 32-bit words, most significant bit first (14-bit bodies).
|
||||
Words32MsbFirst,
|
||||
}
|
||||
|
||||
/// Reads `bits`-bit (≤ 16) sample `i` of a packed stream (`src` holds the
|
||||
/// whole stream; bytes past its end read as 0).
|
||||
#[inline]
|
||||
fn packed_sample(src: &[u8], i: usize, bits: u32, packing: Packing) -> u16 {
|
||||
let at = i * bits as usize;
|
||||
let (byte, shift) = (at / 8, (at % 8) as u32);
|
||||
let mask = (1u32 << bits.min(16)) - 1;
|
||||
match packing {
|
||||
Packing::LsbFirst => {
|
||||
let w = (0..4).fold(0u32, |w, k| w | u32::from(src.get(byte + k).copied().unwrap_or(0)) << (8 * k));
|
||||
((w >> shift) & mask) as u16
|
||||
}
|
||||
Packing::Words32MsbFirst => {
|
||||
// Logical byte k is physical byte k with its position in the 32-bit word reversed.
|
||||
let phys = |k: usize| src.get((k & !3) | (3 - (k & 3))).copied().unwrap_or(0);
|
||||
let w = (0..4).fold(0u32, |w, k| (w << 8) | u32::from(phys(byte + k)));
|
||||
((w >> (32 - shift - bits.min(16))) & mask) as u16
|
||||
}
|
||||
Packing::U16 { le } => {
|
||||
let b = [src.get(2 * i).copied().unwrap_or(0), src.get(2 * i + 1).copied().unwrap_or(0)];
|
||||
if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Unpacks a `width × height` strip.
|
||||
pub(crate) fn unpack(src: &[u8], width: usize, height: usize, bits: u32, packing: Packing) -> Vec<u16> {
|
||||
let mut data = vec![0u16; width * height];
|
||||
let band = par::band_rows(width);
|
||||
par::chunks_mut(&mut data, band * width, |b, chunk| {
|
||||
let first = b * band * width;
|
||||
for (k, v) in chunk.iter_mut().enumerate() {
|
||||
*v = packed_sample(src, first + k, bits, packing);
|
||||
}
|
||||
});
|
||||
data
|
||||
}
|
||||
|
||||
/// Orientation, make and model from the preview JPEG's EXIF (APP1) block.
|
||||
fn preview_exif(bytes: &[u8]) -> (Option<u16>, Option<String>, Option<String>) {
|
||||
let none = (None, None, None);
|
||||
let Some((off, len)) = preview_range(bytes) else { return none };
|
||||
let Some(jpeg) = off.checked_add(len).and_then(|end| bytes.get(off..end)) else { return none };
|
||||
if jpeg.get(0..4) != Some(&[0xFF, 0xD8, 0xFF, 0xE1]) || jpeg.get(6..12) != Some(b"Exif\0\0") {
|
||||
return none;
|
||||
}
|
||||
let Some(t) = jpeg.get(12..).and_then(Tiff::new) else { return none };
|
||||
let Some(ifd0) = t.ifd_at(t.first_ifd, 0) else { return none };
|
||||
let orientation = t.tag_uint(&ifd0, tag::ORIENTATION).and_then(|o| u16::try_from(o).ok()).filter(|o| (1..=8).contains(o));
|
||||
(orientation, t.tag_ascii(&ifd0, tag::MAKE), t.tag_ascii(&ifd0, tag::MODEL))
|
||||
}
|
||||
|
||||
/// The model name in the RAF header (bytes 28..60).
|
||||
fn header_model(bytes: &[u8]) -> Option<String> {
|
||||
let b = bytes.get(28..60)?;
|
||||
let end = b.iter().position(|&c| c == 0).unwrap_or(b.len());
|
||||
let s = String::from_utf8_lossy(&b[..end]).trim().to_string();
|
||||
(!s.is_empty()).then_some(s)
|
||||
}
|
||||
|
||||
pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Sensor> {
|
||||
let cfa_at = be32(bytes, 100).ok_or_else(|| RawError::malformed("RAF header is truncated"))?;
|
||||
let cfa_len = be32(bytes, 104).unwrap_or(0);
|
||||
let region = bytes.get(cfa_at..).ok_or_else(|| RawError::malformed("RAF CFA region lies outside the file"))?;
|
||||
let region = if cfa_len > 0 { region.get(..cfa_len).unwrap_or(region) } else { region };
|
||||
let Some(t) = Tiff::new(region) else {
|
||||
return Err(RawError::unsupported("Fujifilm RAF of an early FinePix / SuperCCD body (no CFA TIFF) is not decoded yet"));
|
||||
};
|
||||
let ifd0 = t.ifd_at(t.first_ifd, 0).ok_or_else(|| RawError::malformed("RAF CFA TIFF has no IFD0"))?;
|
||||
let fuji_at = t.tag_uint(&ifd0, FUJI_IFD).ok_or_else(|| RawError::unsupported("RAF without a Fuji raw IFD"))?;
|
||||
let fuji = t.ifd_at(fuji_at as usize, 0).ok_or_else(|| RawError::malformed("RAF Fuji raw IFD is unreadable"))?;
|
||||
|
||||
let width = t.tag_uint(&fuji, RAW_WIDTH).ok_or_else(|| RawError::malformed("RAF has no raw width"))? as usize;
|
||||
let height = t.tag_uint(&fuji, RAW_HEIGHT).ok_or_else(|| RawError::malformed("RAF has no raw height"))? as usize;
|
||||
let bits = t.tag_uint(&fuji, RAW_BITS).unwrap_or(14);
|
||||
if !(8..=16).contains(&bits) {
|
||||
return Err(RawError::unsupported(format!("RAF with {bits}-bit samples")));
|
||||
}
|
||||
limits.check(width as u64, height as u64, 2)?;
|
||||
let offset = t.tag_uint(&fuji, STRIP_OFFSET).ok_or_else(|| RawError::malformed("RAF has no strip offset"))? as usize;
|
||||
let count = t.tag_uint(&fuji, STRIP_BYTE_COUNT).unwrap_or(0) as usize;
|
||||
let src = region.get(offset..).ok_or_else(|| RawError::malformed("RAF raw data lies outside the file"))?;
|
||||
let src = if count > 0 { src.get(..count).unwrap_or(src) } else { src };
|
||||
let pixels = width * height;
|
||||
let packed = pixels.saturating_mul(bits as usize).div_ceil(8);
|
||||
let packing = if count >= pixels * 2 {
|
||||
Packing::U16 { le: t.le }
|
||||
} else if count >= packed && bits == 12 {
|
||||
Packing::LsbFirst
|
||||
} else if count >= packed && bits == 14 {
|
||||
Packing::Words32MsbFirst
|
||||
} else if count >= packed {
|
||||
return Err(RawError::unsupported(format!("Fujifilm RAF with packed {bits}-bit samples")));
|
||||
} else {
|
||||
return Err(RawError::unsupported("Fujifilm compressed RAF is not decoded (no public description of the format)"));
|
||||
};
|
||||
let need = if matches!(packing, Packing::U16 { .. }) { pixels * 2 } else { packed };
|
||||
if src.len() < need {
|
||||
return Err(RawError::malformed("RAF raw data is truncated"));
|
||||
}
|
||||
let data = unpack(src, width, height, bits, packing);
|
||||
|
||||
let recs = records(bytes);
|
||||
let cfa = layout_cfa(&recs).ok_or_else(|| RawError::unsupported("Fujifilm RAF without a recognised CFA layout"))?;
|
||||
let full = Rect::new(0, 0, width, height);
|
||||
let mut warnings = Vec::new();
|
||||
|
||||
let black = t.tag_floats(&fuji, BLACK_LEVEL);
|
||||
let black = if black.is_empty() || black.iter().any(|v| *v < 0.0) {
|
||||
warnings.push("RAF: black level not recorded; assumed 0".to_string());
|
||||
BlackLevels::uniform(0.0)
|
||||
} else {
|
||||
// One value per CFA position; the order is not established, and the
|
||||
// values observed differ by at most a couple of units, so use their mean.
|
||||
BlackLevels::uniform((black.iter().sum::<f64>() / black.len() as f64) as f32)
|
||||
};
|
||||
let white = clip_level(&data, bits);
|
||||
|
||||
let camera_wb = match t.tag_floats(&fuji, WB_GRB_LEVELS).as_slice() {
|
||||
[g, r, b, ..] if *g > 0.0 => Some([r / g, 1.0, b / g]),
|
||||
_ => record(&recs, WB_GRGB_LEVELS).and_then(|d| {
|
||||
let v: Vec<f64> = (0..4).map_while(|k| be16(d, 2 * k).map(f64::from)).collect();
|
||||
match v.as_slice() {
|
||||
[g1, r, g2, b] if g1 + g2 > 0.0 => Some([2.0 * r / (g1 + g2), 1.0, 2.0 * b / (g1 + g2)]),
|
||||
_ => None,
|
||||
}
|
||||
}),
|
||||
}
|
||||
.filter(|m| m.iter().all(|v| (0.25..8.0).contains(v)));
|
||||
|
||||
let crop = match (pair(&recs, CROP_TOP_LEFT), pair(&recs, CROPPED_SIZE)) {
|
||||
(Some((top, left)), Some((h, w))) => Rect::new(left, top, w, h).intersect(&full),
|
||||
_ => full,
|
||||
};
|
||||
let crop = if crop.is_empty() { full } else { crop };
|
||||
|
||||
// RawExposureBias: how far the raw was exposed below the camera's
|
||||
// rendering (dynamic-range modes); undone like a DNG BaselineExposure.
|
||||
let baseline_exposure = record(&recs, RAW_EXPOSURE_BIAS)
|
||||
.and_then(|d| {
|
||||
let (n, den) = (be16(d, 0)? as i16, be16(d, 2)? as i16);
|
||||
(den != 0).then(|| -f64::from(n) / f64::from(den))
|
||||
})
|
||||
.filter(|v| v.is_finite() && v.abs() <= 8.0)
|
||||
.unwrap_or(0.0);
|
||||
|
||||
let (orientation, make, model) = preview_exif(bytes);
|
||||
Ok(Sensor {
|
||||
format: RawFormat::Raf,
|
||||
make: make.or_else(|| Some("FUJIFILM".to_string())),
|
||||
model: model.or_else(|| header_model(bytes)),
|
||||
width,
|
||||
height,
|
||||
samples: 1,
|
||||
data,
|
||||
cfa: Some(cfa),
|
||||
linearization: None,
|
||||
black,
|
||||
white: [white; 3],
|
||||
active: full,
|
||||
crop,
|
||||
color: Default::default(),
|
||||
camera_wb,
|
||||
orientation: orientation.unwrap_or(1),
|
||||
baseline_exposure,
|
||||
gain_maps: Vec::new(),
|
||||
tone_curve: Vec::new(),
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lsb_first_12_bit() {
|
||||
// 0xABC, 0x123 LSB first: byte0 = 0xBC, byte1 = 0x3A, byte2 = 0x12.
|
||||
let src = [0xBC, 0x3A, 0x12];
|
||||
assert_eq!(unpack(&src, 2, 1, 12, Packing::LsbFirst), vec![0xABC, 0x123]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_32_msb_first_14_bit() {
|
||||
// Four 14-bit samples MSB first in the logical stream, stored as
|
||||
// little-endian 32-bit words.
|
||||
let vals: [u16; 4] = [0x3FFF, 0x0001, 0x2AAA, 0x1555];
|
||||
let mut acc: u64 = 0;
|
||||
for v in vals {
|
||||
acc = (acc << 14) | u64::from(v);
|
||||
}
|
||||
let logical: Vec<u8> = (0..7).map(|k| (acc >> (8 * (6 - k))) as u8).chain([0]).collect();
|
||||
let phys: Vec<u8> = logical.chunks(4).flat_map(|w| w.iter().rev().copied().collect::<Vec<_>>()).collect();
|
||||
assert_eq!(unpack(&phys, 4, 1, 14, Packing::Words32MsbFirst), vals.to_vec());
|
||||
// A short buffer reads as zeros rather than panicking.
|
||||
assert_eq!(unpack(&phys[..3], 4, 1, 14, Packing::Words32MsbFirst).len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layouts_are_reversed() {
|
||||
let fuji = |v: &[u8]| layout_cfa(&[(FUJI_LAYOUT, v)]).map(|c| c.phase(0, 0));
|
||||
assert_eq!(fuji(&[0x0A, 0x0B, 0x09, 0x08]), Some([0, 1, 1, 2]));
|
||||
assert_eq!(fuji(&[0x08, 0x09, 0x0B, 0x0A]), Some([2, 1, 1, 0]));
|
||||
assert_eq!(fuji(&[0x0C, 0x0C, 0x0C, 0x0C]), None);
|
||||
let xt: Vec<u8> = (0..36).map(|i| [0, 1, 2][i % 3]).collect();
|
||||
let c = layout_cfa(&[(FUJI_LAYOUT, &[0x0C; 4]), (XTRANS_LAYOUT, &xt)]).unwrap();
|
||||
assert_eq!((c.width, c.height), (6, 6));
|
||||
assert_eq!(c.color(0, 0), xt[35]);
|
||||
assert_eq!(c.color(5, 5), xt[0]);
|
||||
assert!(layout_cfa(&[(XTRANS_LAYOUT, &[3; 36])]).is_none());
|
||||
}
|
||||
}
|
||||
+254
-2
@@ -1,6 +1,6 @@
|
||||
//! Synthetic raw-file generators for tests and fuzz seeds: a lossless-JPEG
|
||||
//! (T.81 process 14) encoder, a small TIFF writer, and DNG / CR2 / TIFF-EP
|
||||
//! builders. The files are written from the public specifications only and
|
||||
//! (T.81 process 14) encoder, a small TIFF writer, and DNG / CR2 / TIFF-EP /
|
||||
//! RW2 / ORF / RAF builders. The files are written from the public specifications only and
|
||||
//! are meant to exercise the decoder, not to be camera-accurate.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]
|
||||
@@ -1046,6 +1046,258 @@ pub fn orf(width: usize, height: usize, data: &[u16]) -> Vec<u8> {
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Fujifilm RAF
|
||||
|
||||
/// How a synthetic RAF stores its samples (see `raf.rs`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RafPacking {
|
||||
/// 16-bit containers; little-endian (`II`) or big-endian (`MM`) CFA TIFF.
|
||||
U16 { le: bool },
|
||||
/// 12-bit, little-endian bit stream, least significant bit first.
|
||||
Lsb12,
|
||||
/// 14-bit, most significant bit first in little-endian 32-bit words.
|
||||
Words14,
|
||||
/// A short `IS…` strip standing in for Fujifilm's compressed data.
|
||||
Compressed,
|
||||
}
|
||||
|
||||
/// The X-Trans repeat at the data origin, as observed (row major, 0 = R, 1 = G, 2 = B).
|
||||
pub const XTRANS: [u8; 36] = [
|
||||
1, 1, 0, 1, 1, 2, //
|
||||
1, 1, 2, 1, 1, 0, //
|
||||
2, 0, 1, 0, 2, 1, //
|
||||
1, 1, 2, 1, 1, 0, //
|
||||
1, 1, 0, 1, 1, 2, //
|
||||
0, 2, 1, 2, 0, 1,
|
||||
];
|
||||
|
||||
/// A synthetic Fujifilm RAF.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RafSpec {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub data: Vec<u16>,
|
||||
pub bits: u32,
|
||||
pub packing: RafPacking,
|
||||
/// CFA colours at the data origin: 36 (X-Trans, 6×6) or 4 (Bayer, 2×2), row major.
|
||||
pub cfa: Vec<u8>,
|
||||
/// RawImageCropTopLeft / RawImageCroppedSize: top, left, height, width.
|
||||
pub crop: Option<[u16; 4]>,
|
||||
pub black: Vec<u32>,
|
||||
/// WB_GRBLevels: G, R, B.
|
||||
pub wb_grb: Option<[u32; 3]>,
|
||||
/// RawExposureBias as numerator / denominator.
|
||||
pub exposure_bias: Option<(i16, i16)>,
|
||||
/// EXIF orientation of the preview JPEG.
|
||||
pub orientation: u16,
|
||||
/// `false` writes an early-FinePix-style file without the CFA TIFF.
|
||||
pub cfa_tiff: bool,
|
||||
}
|
||||
|
||||
impl RafSpec {
|
||||
pub fn new(width: usize, height: usize, data: Vec<u16>, cfa: Vec<u8>) -> Self {
|
||||
RafSpec {
|
||||
width,
|
||||
height,
|
||||
data,
|
||||
bits: 14,
|
||||
packing: RafPacking::U16 { le: true },
|
||||
cfa,
|
||||
crop: None,
|
||||
black: vec![1024],
|
||||
wb_grb: Some([302, 604, 453]),
|
||||
exposure_bias: None,
|
||||
orientation: 1,
|
||||
cfa_tiff: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The samples as stored.
|
||||
fn strip(&self) -> Vec<u8> {
|
||||
match self.packing {
|
||||
RafPacking::U16 { le } => self.data.iter().flat_map(|v| if le { v.to_le_bytes() } else { v.to_be_bytes() }).collect(),
|
||||
RafPacking::Lsb12 => {
|
||||
let (mut out, mut acc, mut n) = (Vec::new(), 0u64, 0u32);
|
||||
for &v in &self.data {
|
||||
acc |= u64::from(v & 0xFFF) << n;
|
||||
n += 12;
|
||||
while n >= 8 {
|
||||
out.push(acc as u8);
|
||||
acc >>= 8;
|
||||
n -= 8;
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
out.push(acc as u8);
|
||||
}
|
||||
out
|
||||
}
|
||||
RafPacking::Words14 => {
|
||||
let (mut logical, mut acc, mut n) = (Vec::new(), 0u64, 0u32);
|
||||
for &v in &self.data {
|
||||
acc = (acc << 14) | u64::from(v & 0x3FFF);
|
||||
n += 14;
|
||||
while n >= 8 {
|
||||
logical.push((acc >> (n - 8)) as u8);
|
||||
n -= 8;
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
logical.push((acc << (8 - n)) as u8);
|
||||
}
|
||||
logical.resize(logical.len().next_multiple_of(4), 0);
|
||||
logical.chunks(4).flat_map(|w| w.iter().rev().copied().collect::<Vec<u8>>()).collect()
|
||||
}
|
||||
RafPacking::Compressed => {
|
||||
let mut v = b"IS\x01\x00".to_vec();
|
||||
v.resize(self.width * self.height / 2, 0x5A);
|
||||
v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The CFA region: a TIFF whose IFD0 points (0xF000) at the Fuji raw IFD.
|
||||
fn cfa_region(&self) -> Vec<u8> {
|
||||
let le = !matches!(self.packing, RafPacking::U16 { le: false });
|
||||
let u16b = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() };
|
||||
let u32b = |v: u32| if le { v.to_le_bytes() } else { v.to_be_bytes() };
|
||||
let strip = self.strip();
|
||||
let strip_at = 2048u32;
|
||||
let entries: Vec<(u16, Vec<u32>)> = vec![
|
||||
(0xF001, vec![self.width as u32]),
|
||||
(0xF002, vec![self.height as u32]),
|
||||
(0xF003, vec![self.bits]),
|
||||
(0xF007, vec![strip_at]),
|
||||
(0xF008, vec![strip.len() as u32]),
|
||||
(0xF00A, self.black.clone()),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(self.wb_grb.map(|w| (0xF00E, w.to_vec())))
|
||||
.collect();
|
||||
let mut out = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() };
|
||||
out.extend_from_slice(&u32b(8));
|
||||
// IFD0: one entry, 0xF000 (type IFD) → the Fuji IFD at 26.
|
||||
out.extend_from_slice(&u16b(1));
|
||||
out.extend_from_slice(&u16b(0xF000));
|
||||
out.extend_from_slice(&u16b(13));
|
||||
out.extend_from_slice(&u32b(1));
|
||||
out.extend_from_slice(&u32b(26));
|
||||
out.extend_from_slice(&u32b(0));
|
||||
let fuji_at = out.len();
|
||||
let mut extra_at = fuji_at + 2 + 12 * entries.len() + 4;
|
||||
let mut extra = Vec::new();
|
||||
out.extend_from_slice(&u16b(entries.len() as u16));
|
||||
for (tag, vals) in &entries {
|
||||
out.extend_from_slice(&u16b(*tag));
|
||||
out.extend_from_slice(&u16b(4));
|
||||
out.extend_from_slice(&u32b(vals.len() as u32));
|
||||
if vals.len() == 1 {
|
||||
out.extend_from_slice(&u32b(vals[0]));
|
||||
} else {
|
||||
out.extend_from_slice(&u32b(extra_at as u32));
|
||||
for v in vals {
|
||||
extra.extend_from_slice(&u32b(*v));
|
||||
}
|
||||
extra_at += 4 * vals.len();
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(&u32b(0));
|
||||
out.extend_from_slice(&extra);
|
||||
assert!(out.len() <= strip_at as usize);
|
||||
out.resize(strip_at as usize, 0);
|
||||
out.extend_from_slice(&strip);
|
||||
out
|
||||
}
|
||||
|
||||
/// A tiny baseline-JPEG preview (APP1 EXIF with make, model and
|
||||
/// orientation; SOF0 32×24; EOI).
|
||||
fn preview(&self) -> Vec<u8> {
|
||||
let mut t = TiffBuilder::default();
|
||||
let ifd0 = t.ifd(vec![(271, Val::Ascii("FUJIFILM".into())), (272, Val::Ascii("X-Synthetic".into())), (274, Val::Short(vec![self.orientation]))]);
|
||||
t.chain = vec![ifd0];
|
||||
let mut app1 = b"Exif\0\0".to_vec();
|
||||
app1.extend_from_slice(&t.build());
|
||||
let mut j = vec![0xFF, 0xD8, 0xFF, 0xE1];
|
||||
j.extend_from_slice(&((app1.len() + 2) as u16).to_be_bytes());
|
||||
j.extend_from_slice(&app1);
|
||||
j.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x0B, 8, 0x00, 24, 0x00, 32, 1, 1, 0x11, 0, 0xFF, 0xD9]);
|
||||
j
|
||||
}
|
||||
|
||||
/// The metadata directory.
|
||||
fn meta(&self) -> Vec<u8> {
|
||||
let mut recs: Vec<(u16, Vec<u8>)> = Vec::new();
|
||||
if let Some([top, left, h, w]) = self.crop {
|
||||
recs.push((0x0110, [top.to_be_bytes(), left.to_be_bytes()].concat()));
|
||||
recs.push((0x0111, [h.to_be_bytes(), w.to_be_bytes()].concat()));
|
||||
}
|
||||
if self.cfa.len() == 36 {
|
||||
recs.push((0x0130, vec![0x0C; 4]));
|
||||
recs.push((0x0131, self.cfa.iter().rev().copied().collect()));
|
||||
} else {
|
||||
// Bayer: reversed, colour in the low two bits, the second green as 3.
|
||||
let mut greens = 0;
|
||||
let codes: Vec<u8> = self
|
||||
.cfa
|
||||
.iter()
|
||||
.map(|&c| {
|
||||
if c == 1 {
|
||||
greens += 1;
|
||||
if greens == 1 { 0x09 } else { 0x0B }
|
||||
} else {
|
||||
0x08 | c
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
recs.push((0x0130, codes.into_iter().rev().collect()));
|
||||
}
|
||||
if let Some((n, d)) = self.exposure_bias {
|
||||
recs.push((0x9650, [n.to_be_bytes(), d.to_be_bytes()].concat()));
|
||||
}
|
||||
let mut out = (recs.len() as u32).to_be_bytes().to_vec();
|
||||
for (tag, d) in recs {
|
||||
out.extend_from_slice(&tag.to_be_bytes());
|
||||
out.extend_from_slice(&(d.len() as u16).to_be_bytes());
|
||||
out.extend_from_slice(&d);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn build(&self) -> Vec<u8> {
|
||||
let mut b = b"FUJIFILMCCD-RAW 0201FF000000".to_vec();
|
||||
b.extend_from_slice(b"X-Synthetic");
|
||||
b.resize(60, 0);
|
||||
b.extend_from_slice(b"0100");
|
||||
b.resize(160, 0);
|
||||
let preview = self.preview();
|
||||
let meta = self.meta();
|
||||
let region = if self.cfa_tiff { self.cfa_region() } else { self.strip() };
|
||||
let (p_at, m_at) = (b.len(), b.len() + preview.len());
|
||||
let c_at = m_at + meta.len();
|
||||
for (at, v) in [(84, p_at), (88, preview.len()), (92, m_at), (96, meta.len()), (100, c_at), (104, region.len())] {
|
||||
b[at..at + 4].copy_from_slice(&(v as u32).to_be_bytes());
|
||||
}
|
||||
b.extend_from_slice(&preview);
|
||||
b.extend_from_slice(&meta);
|
||||
b.extend_from_slice(®ion);
|
||||
b
|
||||
}
|
||||
}
|
||||
|
||||
/// Mosaics linear RGB through any CFA repeat (`cfa`: `cfa_w` colours per
|
||||
/// row) anchored at (0, 0), like [`mosaic`].
|
||||
pub fn mosaic_cfa(rgb: &[[f32; 3]], width: usize, cfa: &[u8], cfa_w: usize, black: u16, white: u16) -> Vec<u16> {
|
||||
let cfa_h = cfa.len() / cfa_w;
|
||||
rgb.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| {
|
||||
let (x, y) = (i % width, i / width);
|
||||
let c = cfa[(y % cfa_h) * cfa_w + x % cfa_w] as usize;
|
||||
(f32::from(black) + p[c].clamp(0.0, 1.0) * f32::from(white - black)).round() as u16
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- scenes
|
||||
|
||||
/// A smooth, colourful synthetic scene as linear RGB in 0..1.
|
||||
|
||||
@@ -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, orf, rw2, scene, sony_craw, tiff_ep};
|
||||
use photocraft_raw::testgen::{Cr2Spec, DngSpec, DngStorage, RafPacking, RafSpec, XTRANS, mosaic, mosaic_cfa, orf, rw2, scene, sony_craw, tiff_ep};
|
||||
use photocraft_raw::*;
|
||||
|
||||
fn samples() -> Vec<Vec<u8>> {
|
||||
@@ -46,6 +46,14 @@ fn samples() -> Vec<Vec<u8>> {
|
||||
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));
|
||||
let xt = mosaic_cfa(&scene(w, h), w, &XTRANS, 6, 256, 4000);
|
||||
for packing in [RafPacking::U16 { le: true }, RafPacking::Lsb12] {
|
||||
let raf =
|
||||
RafSpec { bits: 12, packing, black: vec![256; 36], crop: Some([1, 2, 10, 20]), orientation: 8, ..RafSpec::new(w, h, xt.clone(), XTRANS.to_vec()) };
|
||||
out.push(raf.build());
|
||||
}
|
||||
let bayer = RafSpec { packing: RafPacking::Words14, exposure_bias: Some((-100, 100)), ..RafSpec::new(w, h, cfa.clone(), vec![0, 1, 1, 2]) };
|
||||
out.push(bayer.build());
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Synthetic Fujifilm RAF files: every sample storage, X-Trans and Bayer
|
||||
//! layouts, metadata, and the unsupported variants.
|
||||
|
||||
use photocraft_raw::testgen::{RafPacking, RafSpec, XTRANS, mosaic_cfa, scene};
|
||||
use photocraft_raw::*;
|
||||
|
||||
const RGGB: [u8; 4] = [0, 1, 1, 2];
|
||||
|
||||
/// A 30×18 X-Trans RAF with a 2-pixel masked border.
|
||||
fn xtrans(packing: RafPacking, bits: u32) -> RafSpec {
|
||||
let (w, h) = (30, 18);
|
||||
let white = ((1u32 << bits) - 1) as u16;
|
||||
let mut s = RafSpec::new(w, h, mosaic_cfa(&scene(w, h), w, &XTRANS, 6, 256, white), XTRANS.to_vec());
|
||||
s.bits = bits;
|
||||
s.packing = packing;
|
||||
s.black = vec![256; 36];
|
||||
s.crop = Some([2, 2, 14, 26]);
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_storage_decodes_exactly() {
|
||||
for (packing, bits) in [(RafPacking::U16 { le: true }, 14), (RafPacking::U16 { le: false }, 16), (RafPacking::Lsb12, 12), (RafPacking::Words14, 14)] {
|
||||
let spec = xtrans(packing, bits);
|
||||
let b = spec.build();
|
||||
assert_eq!(identify(&b), Some(RawFormat::Raf));
|
||||
let s = decode(&b, &Limits::default()).unwrap_or_else(|e| panic!("{packing:?}: {e}"));
|
||||
assert_eq!((s.width, s.height), (30, 18));
|
||||
assert_eq!(s.data, spec.data, "{packing:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xtrans_metadata() {
|
||||
let mut spec = xtrans(RafPacking::U16 { le: true }, 14);
|
||||
spec.exposure_bias = Some((-72, 100));
|
||||
spec.orientation = 6;
|
||||
let s = decode(&spec.build(), &Limits::default()).unwrap();
|
||||
let cfa = s.cfa.as_ref().unwrap();
|
||||
assert_eq!((cfa.width, cfa.height), (6, 6));
|
||||
for (i, &c) in XTRANS.iter().enumerate() {
|
||||
assert_eq!(cfa.color(i % 6, i / 6), c, "position {i}");
|
||||
}
|
||||
assert!(!cfa.is_bayer());
|
||||
assert_eq!(s.crop, Rect::new(2, 2, 26, 14));
|
||||
assert_eq!(s.black, BlackLevels::uniform(256.0));
|
||||
assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5]));
|
||||
assert!((s.baseline_exposure - 0.72).abs() < 1e-9);
|
||||
assert_eq!(s.orientation, 6);
|
||||
assert_eq!((s.make.as_deref(), s.model.as_deref()), (Some("FUJIFILM"), Some("X-Synthetic")));
|
||||
assert!(s.warnings.is_empty(), "{:?}", s.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xtrans_develops() {
|
||||
let mut spec = xtrans(RafPacking::U16 { le: true }, 14);
|
||||
spec.orientation = 6;
|
||||
let b = spec.build();
|
||||
for m in [Demosaic::Bilinear, Demosaic::Mhc, Demosaic::Ahd] {
|
||||
let d = develop(&b, &DevelopOptions { demosaic: m, ..Default::default() }).unwrap();
|
||||
// Cropped to 26×14, then rotated.
|
||||
assert_eq!((d.width, d.height), (14, 26));
|
||||
assert_eq!(d.info.format, RawFormat::Raf);
|
||||
// The repeat seen from the crop origin (2, 2).
|
||||
assert_eq!(d.info.cfa.as_deref(), Some("GRBGBR/BGGRGG/RGGBGG/GBRGRB/RGGBGG/BGGRGG"));
|
||||
assert_eq!(d.info.wb_multipliers, [2.0, 1.0, 1.5]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xtrans_white_balance_is_per_site() {
|
||||
// A neutral grey recorded through WB gains R ×2, B ×1.5: developed with the
|
||||
// as-shot balance it must come out neutral at every X-Trans site (a gain
|
||||
// applied per column pair, as for Bayer, would tint it).
|
||||
let (w, h) = (36, 24);
|
||||
let rgb: Vec<[f32; 3]> = vec![[0.4 / 2.0, 0.4, 0.4 / 1.5]; w * h];
|
||||
let spec = RafSpec { black: vec![256], ..RafSpec::new(w, h, mosaic_cfa(&rgb, w, &XTRANS, 6, 256, 16383), XTRANS.to_vec()) };
|
||||
let d = develop(&spec.build(), &DevelopOptions::default()).unwrap();
|
||||
for p in d.rgb.as_chunks::<3>().0 {
|
||||
assert!(p[0].abs_diff(p[1]) <= 2 && p[2].abs_diff(p[1]) <= 2, "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bayer_layouts() {
|
||||
let (w, h) = (24, 16);
|
||||
for cfa in [RGGB, [2, 1, 1, 0]] {
|
||||
for (packing, bits) in [(RafPacking::Lsb12, 12), (RafPacking::Words14, 14), (RafPacking::U16 { le: true }, 14)] {
|
||||
let white = ((1u32 << bits) - 1) as u16;
|
||||
let data = mosaic_cfa(&scene(w, h), w, &cfa, 2, 64, white);
|
||||
let spec = RafSpec { bits, packing, black: vec![64, 64, 64, 64], ..RafSpec::new(w, h, data, cfa.to_vec()) };
|
||||
let s = decode(&spec.build(), &Limits::default()).unwrap();
|
||||
assert_eq!(s.data, spec.data);
|
||||
assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), cfa, "{packing:?}");
|
||||
let d = develop_sensor(&s, &DevelopOptions::default()).unwrap();
|
||||
assert_eq!(d.info.cfa.as_deref(), Some(if cfa == RGGB { "RGGB" } else { "BGGR" }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_variants_report_and_keep_the_preview() {
|
||||
let mut spec = xtrans(RafPacking::Compressed, 14);
|
||||
let b = spec.build();
|
||||
match decode(&b, &Limits::default()) {
|
||||
Err(RawError::Unsupported(m)) => assert!(m.contains("compressed"), "{m}"),
|
||||
other => panic!("expected unsupported, got {other:?}"),
|
||||
}
|
||||
let p = embedded_preview(&b).unwrap();
|
||||
assert_eq!((p.width, p.height), (32, 24));
|
||||
|
||||
spec.packing = RafPacking::U16 { le: true };
|
||||
spec.cfa_tiff = false;
|
||||
match decode(&spec.build(), &Limits::default()) {
|
||||
Err(RawError::Unsupported(m)) => assert!(m.contains("FinePix"), "{m}"),
|
||||
other => panic!("expected unsupported, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_layouts_and_sizes_fail_cleanly() {
|
||||
// A Bayer FujiLayout that is not a Bayer pattern.
|
||||
let spec = RafSpec::new(8, 4, vec![100; 32], vec![0, 0, 2, 2]);
|
||||
assert!(matches!(decode(&spec.build(), &Limits::default()), Err(RawError::Unsupported(_))));
|
||||
// Dimensions beyond the limits are rejected before allocating.
|
||||
let spec = xtrans(RafPacking::U16 { le: true }, 14);
|
||||
let limits = Limits { max_pixels: 100, ..Limits::default() };
|
||||
assert!(matches!(decode(&spec.build(), &limits), Err(RawError::LimitExceeded(_))));
|
||||
// A truncated strip.
|
||||
let b = spec.build();
|
||||
assert!(matches!(decode(&b[..b.len() - 7], &Limits::default()), Err(RawError::Malformed(_))));
|
||||
}
|
||||
@@ -109,6 +109,7 @@ fn other_raw_containers_are_recognised_but_unsupported() {
|
||||
cr3.extend_from_slice(&[0; 12]);
|
||||
assert_eq!(identify(&cr3), Some(RawFormat::Cr3));
|
||||
assert!(matches!(decode(&cr3, &Limits::default()), Err(RawError::Unsupported(_))));
|
||||
// A bare RAF header has no CFA TIFF (like early FinePix files): recognised, unsupported.
|
||||
let mut raf = b"FUJIFILMCCD-RAW 0201FF383501".to_vec();
|
||||
raf.resize(200, 0);
|
||||
assert_eq!(identify(&raf), Some(RawFormat::Raf));
|
||||
|
||||
+1
-1
@@ -87,7 +87,7 @@ Confidence: moderate — the next users of 0.2.x will move these numbers either
|
||||
| Colour management | Colour-managed canvas (document → monitor), embedded CMYK profiles, linear EXR/HDR, 16-bit float canvas | medium-high | Monitor profile follows only at launch. |
|
||||
| Performance | 14k+ px on the GPU at ~⅓ the memory; adjustment preview 285 ms → 4–9 ms; font-size edits 297 ms → 4.6 ms; 2026-10-07: 30 MP TIFF open (banded, parallel strip/tile decode) Deflate 345 → 32 ms, LZW 428 → 43 ms, BigTIFF and every IFD readable; 2026-10-09: 4.2 MP Indexed Color, 256 colours, full-resolution CPU preview p50 3018 → 1061 ms (Ryzen AI 7 350, three measured runs; GPU upload excluded) | medium-high on rasters | Complex layout documents still laggy (#125/#128); >16384 px GPU tiling in progress (#49). Native Indexed Color previews run on one background worker with stale-result rejection; large palettes can still take about a second to compute. Web previews remain synchronous. |
|
||||
| Stability | Never-crash lint series, crash guard, `panic_hunt` fuzzing in the gate | medium-high | No field crash data yet. |
|
||||
| Camera RAW | DNG, CR2, Sony ARW (lossless + compressed), Nikon NEF (lossless + lossy compressed), RW2, uncompressed ORF | medium | CR3, RAF, Nikon "lossy after split" and calibrated colour for non-DNG cameras still open (#50). |
|
||||
| Camera RAW | DNG, CR2, Sony ARW (lossless + compressed), Nikon NEF (lossless + lossy compressed), RW2, uncompressed ORF; 2026-10-09: uncompressed Fujifilm RAF, Bayer and X-Trans (edge-directed X-Trans demosaic; 26 MP X-Trans develop 306 ms on 12 cores) | medium | CR3, compressed RAF, Nikon "lossy after split" and calibrated colour for non-DNG cameras (no Fuji colour calibration: neutral fallback) still open (#50). |
|
||||
| AI / generative | none | ~0% | Deferred by decision (#41). |
|
||||
| Ecosystem | Sandboxed WebAssembly plug-ins instead of .8BF; no ExtendScript/UXP/.atn; no Adobe Fonts/Libraries/cloud docs | low | By design for 8BF; scripting compatibility open. |
|
||||
| Platforms | macOS (notarized), Windows, Linux (AppImage/deb/rpm/Flatpak bundle), web | medium-high | Flathub later (#173); Windows signing material pending. |
|
||||
|
||||
Reference in new issue
Block a user