mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-21 17:37:14 +00:00
* TIFF: read and write CIE L*a*b* (CIELab, ICCLab); Lab documents stay Lab Photoshop saves Lab documents as CIELab TIFFs (PhotometricInterpretation 8, a* and b* signed), which PhotoCraft could not open, and PhotoCraft saved Lab documents as sRGB TIFFs. - codecs: a Lab channel layout (Lab, LabA) holding a* and b* as PhotoCraft's Lab documents do ((a + 128) / 255; 16 bits like the PSD importer), with its own Lab <-> sRGB conversion (same formulas as photocraft-color; codecs stays standalone) for formats without Lab, which now warn LabConverted. - TIFF read: CIELab and ICCLab (8 and 16 bits, alpha) are handed to the tiff crate as RGB and labelled Lab; a* and b* are converted from the file's encoding (signed a / 256a, or offset). - TIFF write: Lab and LabA as CIELab, as Photoshop writes it; float Lab is written with 16 bits (DepthReduced). - io: a Lab TIFF opens as a Lab document; a Lab document with one plain layer is written to TIFF in Lab (other formats still use sRGB). Photoshop 2025's Lab TIFFs open with the colours Photoshop shows (its own RGB conversion matches within one level at 8 bits and exactly at 16 bits), and Photoshop reads PhotoCraft's Lab TIFFs back with the same L*a*b* values. Fixes #4936 * DNG: decode lossy (JPEG-compressed) DNG tiles (FILE-215-11) DNG 1.4 lossy JPEG (compression 34892) stores each tile or strip as a baseline-DCT JPEG of 8-bit samples: a gray stream for CFA data, a YCbCr stream for three-sample LinearRaw. The decoder arm from #2021 read the streams but widened every sample by 257, so the values no longer matched the file's levels: an 8-bit WhiteLevel (or its default, 255) clipped everything to white and a 256-entry LinearizationTable was indexed past its end. It also required the JPEG frame to match the clipped row count, which rejected the padded edge tiles real tiled files carry. The arm is now `lossy_jpeg()` in sensor.rs. The decoded 8-bit values are the stored samples, and BlackLevel, WhiteLevel (default 255 for 8-bit data) and the LinearizationTable apply to them exactly as for every other compression. A tile may be coded at the full tile size (edge tiles padded, as the spec says) or at the image's row count; a strip at its row count; the width must be the segment's. BitsPerSample must be 8 and the JPEG's component count must equal SamplesPerPixel (1 or 3); anything else is an error, never a silent conversion. The frame header is checked before any pixel is decoded and the JPEG decoder's own size cap is the segment the IFD declares (already charged against the limits), so a hostile SOF cannot size a buffer past the tile. testgen writes true 8-bit lossy fixtures (`LossyJpegTiles`, and strips via the new `LossyJpegStrips`), accepts pre-encoded `lossy_segments` for hostile-input tests, exposes `baseline_jpeg()`, and leaves WhiteLevel out when `white` is 0. The DNG tests cover CFA and LinearRaw RGB from tiles and strips at 37x23 (partial edge tiles, a short last strip), the default white level, black/white scaling and a LinearizationTable against the uncompressed path, and hostile inputs: a truncated tile, frame-size and component-count mismatches, a 65535x65535 SOF under default and tight limits, a tile over the allocation budget, and 12/16-bit or 4-sample files. The hostile mutation set gains a lossy CFA and a lossy LinearRaw file. The parity doc's DNG row is updated; the scorecard row is left for the coordinating branch. * Raw: measure the Nikon D90 image area (4288x2848 at (10, 10)) Aligning the decoded D90 sensor plane with the camera's own JPEG puts the image at (10, 10) in the 4352x2868 sensor plane, giving the camera's 4288x2848 frame (10-pixel margins; the right border reads the camera's flat 255 from column 4310). Add the measured ImageArea so a D90 NEF opens on the camera's frame instead of the uncropped plane, and make a measured profile leave a file that carries its own colour calibration (a DNG) untouched. * Codecs: open Cineon (.cin) film frames read-only Cineon is the 10-bit logarithmic film-scan format DPX grew from. Read it from the same Kodak header family: the generic header (big-endian, orientation at 192, channel count at 193, the channel-1 bits/dimensions), one or three channels, three 10-bit samples packed into each 32-bit word on a word boundary. The 10-bit code values open as U16 (round(c x 65535 / 1023)); the file's log black/white points are a display choice and are not applied. A depth other than 10 bits or a channel count other than 1/3 is Unsupported; truncation errors rather than panicking. Read-only (no Cineon writer), so .cin joins the open filters and Cineon read closes part of #1049's G10 gap. * Vector: bound flattening memory, keep over-budget dashes, cheaper edge build (#5195) - flatten: a path's flattened points are capped at 1 << 20; past it every curve keeps a proportional share of its pieces (at least one), so hostile handles from files (vmsk, SVG, effect outlines) cannot exhaust memory. fill_rasterizer flattens the whole path under one budget. - stroke: past the dash step budget (or below coordinate precision), dash_polyline keeps the dashes made so far and draws the rest solid instead of dropping the stroke. Open polylines are no longer copied. - raster: coordinates are clamped to +-1e15 and edges with a non-finite slope (vanishingly short) are skipped, so huge finite coordinates no longer produce NaN coverage. fill_rasterizer sorts edges once instead of after every component (stable sort, identical order). - Cleanups: dead miter `half`, dead loop-length check in trace_mask, shared mask render body, map_knots helper, shared straight-segment test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * PSD: cap pattern memory across a parse, reject mixed-depth pattern channels (#5198) - Patterns: one PatternBudget (decoded bytes + zero padding) is shared by every pattern of a block, a .pat file and the pattern blocks of one document; .abr patt sections are charged to the samples' budget. - Patterns: a channel whose depth differs from the first is rejected (the parsed pattern could not be written back). - Slices: descriptor numbers no longer wrap; out-of-range ids are no id, coordinates clamp to i32, and a v6 trailing entry without a usable id attaches its outsets to no slice. - LayerInfo::unpadded_len is computed from field sizes instead of serializing every record into a scratch buffer. - abr desc presets are moved out instead of cloned; UnFl and shmd counts use the bounded preallocation; ImageData::decode_channel (decoded every plane to return one, unused outside its test) is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Vector: bound stroke outline points (#5211) - stroke_polygons dashes all lines first, then counts round caps and joins. When their full-resolution tessellation would exceed 1 << 20 outline points, every round cap and join gets the same smaller segment count (down to 4 per circle, 1 per join; area-exact radius kept). Strokes under the budget are unchanged; no piece is dropped. - The dash step budget (100000) is now shared by all lines of a stroke instead of per polyline, so many subpaths cannot multiply the dash (and cap) count. Past it the rest is drawn solid, as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * PSD: write tiff blocks without copies, inflate merged ZIP once - ImageSourceData::to_bytes writes the global mask and global blocks straight from the model with 4-byte alignment instead of cloning each block (data included) to set its padding. Same bytes. - The tiff transcoder's nested regions and blocks write into the parent's buffer (taken and handed back, error or not) instead of building their own output and copying it up per nesting level. Bodies that fail or are not transcoded are truncated before being copied as stored or dropped. Same bytes. - PsdFile::from_bytes_and_merged decodes the merged image with the parse when asked: a ZIP stream is inflated once (the decode's stream check is the parse's); the parse-only check runs only when the decode fails, to keep from_bytes' errors. PSD import uses it with merged_needed. - PsdBuilder::composite documents that Gray/CMYK composites stay straight. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Content-Aware Fill: measure a thin hole by its thickness, not its bounds (#1366) Removing long, thin objects (coiled guitar strings, wires) left their outline as darker and lighter blotches and copied pieces of other strings into the fill. The pyramid shrank until the hole's bounding box was four patches across: for a string across the image that is a level where the hole has swallowed its surroundings, so the matches found there copy whatever looks like the blur, and the finer levels (refine-only for wide bounds) keep them. A hole at most a quarter as thick as its bounds are long now counts as thin: the pyramid stops while it is still about two patches thick, and that level starts from a membrane across it (over a few pixels, the surroundings themselves) instead of the onion peel, whose exhaustive search is what made a shallow pyramid unaffordable. Compact holes are unchanged bit for bit. Refs #1366 * perf(compose,gpu): effect caches reserve tile addresses instead of pinning layers Effect map cache entries kept a clone of their layer (a deep clone for groups) so the tile addresses the cache key hashes couldn't be reused. That kept an edited or deleted layer's pixels alive, uncounted, until the entry was evicted. Keep a Weak to each hashed tile instead: it reserves the address without keeping the pixels. The GPU compositor's styled-group pins and shape-source tile snapshots do the same. Part of #4530. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(history): count snapshot-only tiles against the history budget History panel snapshots outlived every budget: a Merged Layers snapshot is a full flattened copy that neither the history budget, the GPU budget's document bytes nor Purge accounted for. Trim now counts the tiles only snapshots hold as fixed cost, the GPU budget includes them, and Purge > Histories no longer reports tiles a kept snapshot still holds as freed. Part of #4530. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Content-Aware Fill: every part of a thin selection keeps its surroundings (#1366) Two more causes of ghosts when removing strings and the small knobs selected with them: * Auto sampling summarises the selection's surroundings by a few clusters. Around a long selection those come from the strings' surroundings, so a small part elsewhere (a tuning knob in a differently coloured corner) lost its own surroundings and was filled from far away in another colour. Around a thin selection the Auto area now always reaches as far as the selection is thick. * The membrane that starts a thin hole now starts a patch radius out, past the anti-aliased fringe or halo that a selection drawn close to the object leaves outside it. Refs #1366 * Content-Aware Fill: peel a thin hole where that stays affordable (#1366) Starting every thin hole from a membrane smoothed Spot Healing on film grain (spot_healing_keeps_film_grain_through_overlapping_strokes: grain 9.0 against 12.1 around). The onion peel copies the grain; it was only given up because its exhaustive search is too slow on the big level a long thin hole stops at. It now starts the thin hole whenever hole cells times sources stay within 2^28 comparisons, and the membrane only beyond. Refs #1366 * Select Subject: keep subject parts coloured like the backdrop, leave enclosed gaps open Users on #2788 reported Select Subject dropping clothes that are close in colour to a plain wall and bridging the gap between an arm and the torso. Both come from the same place: the saliency pass labels low-contrast parts of the subject as background, the background colour model then learns them and explains them away, and the final blind hole fill closes every enclosed gap up to 5 % of the mask. Two changes in crates/algo: - A second GrabCut pass whose background model only knows the backdrop. A colour model fitted to the image frame (minus a margin around the salient blob, in case the subject runs out of the picture) marks every pixel it explains as probable background; the blob and whatever the backdrop cannot account for start as probable foreground. Only components that touch the first pass's result survive. - Hole filling that consults the colour models: specks (<= 0.2 % of the mask) always fill, larger holes up to 5 % fill only when their pixels fit the foreground model better than the background's. Tests: two regressions (a cream-shouldered figure on a near-white wall keeps its shoulders; a ring keeps its backdrop-coloured hole open), plus ignored timing and picture-dump helpers. The 6 MP first run goes from about 100 ms to about 200 ms on one core; the P29 repeat path is untouched. * Keyboard shortcut sets: Set menu, New Set, Save, Delete, .kys Export and Summarize (K2) Edit › Keyboard Shortcuts gets Photoshop's set management. A set is a saved copy of the bindings (Preferences.shortcutSets, the one in use in shortcutSet; "" is PhotoCraft Defaults), and the Set menu shows "(modified)" when the bindings differ from it. New Set…, Save and Delete wait for OK like the rest of the dialog. Export… writes the dialog's bindings as a .kys file (commands then tools, Photoshop's macOS key spelling), each row carrying our id as pc-id so PhotoCraft imports its own sets back exactly, whatever the label; Summarize… writes Photoshop's HTML list of every bound command by menu. edit.keyboardShortcuts takes useSet (before the call's edits), saveSet, deleteSet, sets and activeSet (after them), exportKys and summarize; every reply reports the sets, the set in use and whether it is modified. Bad names, keys or counts are errors that change nothing. * .kys import: tool keys and sets saved on Windows (K3) Photoshop's <tool> rows now import: each matches our tool by name (our tool names are Photoshop's) or by pc-id in sets PhotoCraft exported, and a letter other than the tool's own becomes its override, while its own letter keeps the tool cycling with the others (#5036). A set saved on Windows spells the primary modifier Ctrl where a Mac set writes Cmd and keeps Control for the Control key. A set with no Cmd or Opt anywhere but some Ctrl is read as a Windows set, its Ctrl as our Cmd: Ctrl+L is the Cmd+L default, not a Control-key override that would also mean Control on a Mac. The import reports `windows`. * cargo fmt the extension lists Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Gert Pellin <gert@pellin.be> Co-authored-by: Vikram Bhaskaran <vikram.bhaskaran@outlook.com> Co-authored-by: vangel76 <vangel1976@googlemail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Finn Newick <finnnk@gmail.com> Co-authored-by: Brandon Thomas <echelon@gmail.com> Co-authored-by: Diego Chagas <drochachagas@gmail.com> Co-authored-by: Tanish Manku <tmanku.dev@gmail.com>
282 lines
10 KiB
Rust
282 lines
10 KiB
Rust
//! `photocraft-raw`: a clean-room, pure-Rust camera raw decoder and developer.
|
||
//!
|
||
//! 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, published descriptions of Sony's cRAW code, public maker-note
|
||
//! 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.
|
||
//!
|
||
//! * [`identify`] / [`is_raw`] recognise raw files from their bytes.
|
||
//! * [`decode`] reads the undeveloped [`Sensor`] data and metadata.
|
||
//! * [`develop`] turns it into 16-bit RGB in ProPhoto RGB (ROMM primaries,
|
||
//! D50 white, gamma 1.8): linearization, black/white levels, white balance,
|
||
//! highlight clipping, demosaicing, camera → XYZ → ProPhoto, exposure and
|
||
//! orientation.
|
||
//! * [`embedded_preview`] finds the camera's full-size JPEG preview, for
|
||
//! formats whose sensor data is not decoded yet; [`embedded_previews`] lists
|
||
//! every preview.
|
||
//! * [`fit_look`] fits a per-file colour matrix and tone curve ([`CameraLook`])
|
||
//! to the camera's own (decoded) JPEG, for files without colour calibration
|
||
//! (method after LightCraft's `docs/camera-preview-colour.md`,
|
||
//! storytold/lightcraft#165); pass it in [`DevelopOptions::camera_look`].
|
||
//! * Raws that carry no colour description (NEF) take a camera profile we
|
||
//! measured from the camera's own output when there is one (`cameras.rs`:
|
||
//! image area, levels, ForwardMatrix, tone curve; the Nikon D4 so far).
|
||
//! Bodies whose full profile is not measured yet can still carry a measured
|
||
//! image area (the D800E, the ILCE-7).
|
||
//!
|
||
//! Decoded today: DNG (uncompressed, deflate, lossless-JPEG, lossy-JPEG and JPEG XL, strips and
|
||
//! tiles, CFA and LinearRaw), CR2 (lossless JPEG with Canon slices), uncompressed or
|
||
//! lossless-JPEG TIFF/EP raws (NEF, ARW, PEF… when not vendor-compressed),
|
||
//! Nikon compressed NEF (lossless and lossy), Sony compressed ARW (cRAW),
|
||
//! Panasonic RW2 (RawFormat 5 packed and RawFormat 3/4 vendor-compressed),
|
||
//! uncompressed Olympus ORF and uncompressed Fujifilm RAF (Bayer and
|
||
//! X-Trans). Everything else reports [`RawError::Unsupported`].
|
||
//!
|
||
//! The crate is standalone (no workspace dependencies), does no I/O, builds for
|
||
//! `wasm32-unknown-unknown` and never panics on hostile input: sizes are
|
||
//! checked against [`Limits`] before allocating.
|
||
|
||
#![forbid(unsafe_code)]
|
||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||
|
||
mod cameras;
|
||
mod color;
|
||
mod cr2;
|
||
mod cr3;
|
||
mod demosaic;
|
||
mod develop;
|
||
mod dng;
|
||
mod error;
|
||
mod jxl;
|
||
mod ljpeg;
|
||
mod look;
|
||
mod nefc;
|
||
mod opcodes;
|
||
mod orf;
|
||
mod par;
|
||
mod preview;
|
||
mod raf;
|
||
mod rw2;
|
||
mod saturation;
|
||
mod sensor;
|
||
mod sony;
|
||
mod tiff;
|
||
mod tiffep;
|
||
mod tone;
|
||
|
||
#[cfg(feature = "testgen")]
|
||
pub mod testgen;
|
||
|
||
pub use crate::color::{Calibration, ColorInfo, Mat3};
|
||
pub use crate::demosaic::Demosaic;
|
||
pub use crate::develop::{DevelopOptions, Developed, RawInfo, WhiteBalance, develop_sensor};
|
||
pub use crate::error::RawError;
|
||
pub use crate::look::{CameraLook, LookRejected, PROXY_EDGE, Reference, ToneCurve, fit_look};
|
||
pub use crate::opcodes::GainMap;
|
||
pub use crate::preview::{Preview, PreviewColorSpace, embedded_preview, embedded_preview_color_space, embedded_previews};
|
||
pub use crate::sensor::{BlackLevels, Cfa, Rect, Sensor};
|
||
pub use crate::tone::{Tone, retone};
|
||
|
||
use crate::tiff::{Tiff, tag};
|
||
|
||
/// Name of the output colour space of [`develop`].
|
||
pub const OUTPUT_SPACE: &str = "ProPhoto RGB (ROMM primaries, D50, gamma 1.8)";
|
||
|
||
/// The raw container's orientation, when recorded (CR3 metadata or TIFF IFD0).
|
||
/// Useful for camera JPEGs that carry no orientation of their own.
|
||
pub fn orientation(bytes: &[u8]) -> Option<u16> {
|
||
if bytes.get(4..12) == Some(b"ftypcrx ") {
|
||
return cr3::orientation(bytes);
|
||
}
|
||
let tiff = Tiff::new(bytes)?;
|
||
let ifd = tiff.ifd_at(tiff.first_ifd, 0)?;
|
||
tiff.tag_uint(&ifd, tag::ORIENTATION).filter(|o| (1..=8).contains(o)).map(|o| o as u16)
|
||
}
|
||
|
||
/// Camera raw container families.
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||
pub enum RawFormat {
|
||
Dng,
|
||
/// Canon CR2.
|
||
Cr2,
|
||
/// Canon CR3 (ISO BMFF).
|
||
Cr3,
|
||
/// Nikon NEF / NRW.
|
||
Nef,
|
||
/// Sony ARW / SR2.
|
||
Arw,
|
||
/// Pentax PEF.
|
||
Pef,
|
||
/// Olympus ORF.
|
||
Orf,
|
||
/// Panasonic RW2.
|
||
Rw2,
|
||
/// Fujifilm RAF.
|
||
Raf,
|
||
/// Another TIFF/EP raw.
|
||
TiffEp,
|
||
}
|
||
|
||
impl RawFormat {
|
||
pub fn name(self) -> &'static str {
|
||
match self {
|
||
RawFormat::Dng => "DNG",
|
||
RawFormat::Cr2 => "CR2",
|
||
RawFormat::Cr3 => "CR3",
|
||
RawFormat::Nef => "NEF",
|
||
RawFormat::Arw => "ARW",
|
||
RawFormat::Pef => "PEF",
|
||
RawFormat::Orf => "ORF",
|
||
RawFormat::Rw2 => "RW2",
|
||
RawFormat::Raf => "RAF",
|
||
RawFormat::TiffEp => "TIFF/EP raw",
|
||
}
|
||
}
|
||
}
|
||
|
||
/// File extensions of the raw formats this crate recognises.
|
||
pub const EXTENSIONS: &[&str] = &["dng", "cr2", "cr3", "nef", "nrw", "arw", "srf", "sr2", "pef", "orf", "rw2", "raf"];
|
||
|
||
/// Decompression-bomb guards, checked on header values before allocating
|
||
/// (the same shape and defaults as `photocraft-codecs`' limits).
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub struct Limits {
|
||
pub max_width: u32,
|
||
pub max_height: u32,
|
||
/// Maximum `width * height`.
|
||
pub max_pixels: u64,
|
||
/// Maximum bytes of one buffer.
|
||
pub max_alloc: u64,
|
||
}
|
||
|
||
impl Default for Limits {
|
||
fn default() -> Self {
|
||
Limits { max_width: 1 << 18, max_height: 1 << 18, max_pixels: 1 << 28, max_alloc: 2 << 30 }
|
||
}
|
||
}
|
||
|
||
impl Limits {
|
||
/// Checks a `width × height` buffer of `bytes_per_pixel` bytes per pixel.
|
||
pub fn check(&self, width: u64, height: u64, bytes_per_pixel: u64) -> Result<(), RawError> {
|
||
if width == 0 || height == 0 {
|
||
return Err(RawError::Malformed(format!("zero-sized image {width}x{height}")));
|
||
}
|
||
if width > u64::from(self.max_width) || height > u64::from(self.max_height) {
|
||
return Err(RawError::LimitExceeded(format!("dimensions {width}x{height} exceed {}x{}", self.max_width, self.max_height)));
|
||
}
|
||
let pixels = width.saturating_mul(height);
|
||
if pixels > self.max_pixels {
|
||
return Err(RawError::LimitExceeded(format!("{pixels} pixels exceed {}", self.max_pixels)));
|
||
}
|
||
let bytes = pixels.saturating_mul(bytes_per_pixel);
|
||
if bytes > self.max_alloc || usize::try_from(bytes).is_err() {
|
||
return Err(RawError::LimitExceeded(format!("{bytes} bytes exceed {}", self.max_alloc)));
|
||
}
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
const PHOTOMETRIC_CFA: u32 = 32803;
|
||
const PHOTOMETRIC_LINEAR_RAW: u32 = 34892;
|
||
|
||
fn make_format(make: Option<&str>) -> RawFormat {
|
||
let m = make.unwrap_or("").to_ascii_uppercase();
|
||
if m.starts_with("NIKON") {
|
||
RawFormat::Nef
|
||
} else if m.starts_with("SONY") {
|
||
RawFormat::Arw
|
||
} else if m.starts_with("PENTAX") || m.starts_with("RICOH") {
|
||
RawFormat::Pef
|
||
} else if m.starts_with("OLYMPUS") || m.starts_with("OM DIGITAL") {
|
||
RawFormat::Orf
|
||
} else {
|
||
RawFormat::TiffEp
|
||
}
|
||
}
|
||
|
||
/// Recognises a camera raw file from its bytes (cheap: header and IFDs only).
|
||
pub fn identify(bytes: &[u8]) -> Option<RawFormat> {
|
||
if bytes.get(4..12) == Some(b"ftypcrx ") {
|
||
return Some(RawFormat::Cr3);
|
||
}
|
||
if bytes.starts_with(raf::MAGIC) {
|
||
return Some(RawFormat::Raf);
|
||
}
|
||
let t = Tiff::new(bytes)?;
|
||
match bytes.get(0..4) {
|
||
Some(b"IIRO" | b"IIRS" | b"MMOR") => return Some(RawFormat::Orf),
|
||
Some(b"IIU\0") => return Some(RawFormat::Rw2),
|
||
_ => {}
|
||
}
|
||
if bytes.get(8..11) == Some(b"CR\x02") {
|
||
return Some(RawFormat::Cr2);
|
||
}
|
||
let ifds = t.all_ifds();
|
||
if ifds.iter().any(|i| i.has(tag::DNG_VERSION)) {
|
||
return Some(RawFormat::Dng);
|
||
}
|
||
if ifds.iter().any(|i| matches!(t.tag_uint(i, tag::PHOTOMETRIC), Some(PHOTOMETRIC_CFA | PHOTOMETRIC_LINEAR_RAW))) {
|
||
let make = ifds.iter().find_map(|i| t.tag_ascii(i, tag::MAKE));
|
||
return Some(make_format(make.as_deref()));
|
||
}
|
||
if tiffep::is_sony_non_cfa(&t, &ifds) {
|
||
return Some(RawFormat::Arw);
|
||
}
|
||
None
|
||
}
|
||
|
||
/// `true` if `bytes` look like a camera raw file.
|
||
pub fn is_raw(bytes: &[u8]) -> bool {
|
||
identify(bytes).is_some()
|
||
}
|
||
|
||
/// Reads the undeveloped sensor data and metadata.
|
||
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 => raf::decode(bytes, limits),
|
||
_ => {
|
||
let t = Tiff::new(bytes).ok_or(RawError::NotRaw)?;
|
||
match format {
|
||
RawFormat::Dng => dng::decode(&t, limits).map(lift_clipped),
|
||
RawFormat::Cr2 => cr2::decode(&t, limits),
|
||
RawFormat::Rw2 => rw2::decode(&t, limits),
|
||
RawFormat::Orf => orf::decode(&t, limits),
|
||
f => tiffep::decode(&t, f, limits),
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// DNG writers can state a white level the sensor never reaches; samples stuck at the real saturation
|
||
/// point are raised to it so they clip together (see `saturation.rs`).
|
||
fn lift_clipped(mut s: Sensor) -> Sensor {
|
||
s.lift_clipped_samples();
|
||
s
|
||
}
|
||
|
||
/// Decodes a lossless JPEG (T.81 process 14) stream into `(width, height,
|
||
/// components, samples)`; at most `max_samples` samples are allocated.
|
||
/// Exposed for fuzzing and tools.
|
||
#[doc(hidden)]
|
||
pub fn decode_lossless_jpeg(bytes: &[u8], max_samples: usize) -> Result<(usize, usize, usize, Vec<u16>), RawError> {
|
||
ljpeg::decode(bytes, max_samples).map(|(f, v)| (f.width, f.height, f.components, v))
|
||
}
|
||
|
||
/// Lists the TIFF structure of a raw file (debugging aid).
|
||
#[doc(hidden)]
|
||
pub fn dump_structure(bytes: &[u8]) -> String {
|
||
tiff::dump(bytes)
|
||
}
|
||
|
||
/// Decodes and develops a raw file.
|
||
pub fn develop(bytes: &[u8], opts: &DevelopOptions) -> Result<Developed, RawError> {
|
||
let sensor = decode(bytes, &opts.limits)?;
|
||
develop_sensor(&sensor, opts)
|
||
}
|