io: open camera raws through photocraft-raw (16-bit ProPhoto), preview fallback

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Brandon ThomasandClaude Opus 5.5 committed 2026-10-04 15:18:17 -04:00
1 parent c7bd4224ed
commit d7cab2a18f
5 files changed
+174 -2

No files matched your search

+2
View File
@@ -18,11 +18,13 @@ photocraft-doc = { workspace = true }
photocraft-compose = { workspace = true }
photocraft-psd = { workspace = true }
photocraft-codecs = { workspace = true }
photocraft-raw = { workspace = true }
photocraft-text = { workspace = true }
photocraft-format = { path = "../format" }
thiserror = { workspace = true }
[dev-dependencies]
photocraft-psd = { workspace = true, features = ["testgen"] }
photocraft-raw = { workspace = true, features = ["testgen"] }
proptest = { workspace = true }
photocraft-vector = { workspace = true }
+5
View File
@@ -13,6 +13,11 @@ use crate::{ExportOptions, ExportResult, ImportResult, IoError};
/// Decodes a flat image into a single-layer document.
pub fn import_flat(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
let img = codecs::decode(bytes)?;
image_to_document(name, &img)
}
/// A decoded flat image as a single-layer document.
pub(crate) fn image_to_document(name: &str, img: &Image) -> Result<ImportResult, IoError> {
let mut warnings = Vec::new();
let (mode, target_layout) = match img.layout() {
ChannelLayout::Gray | ChannelLayout::GrayA => (ColorMode::Grayscale, ChannelLayout::GrayA),
+12 -2
View File
@@ -10,6 +10,9 @@
//! and smart-object data) and re-export writes them back; text, shape and
//! smart-object layers also keep their pixels as the cached raster, and fill
//! layers keep Photoshop's rendering in `Layer::fill_cache`.
//! * Camera raws (DNG, CR2, uncompressed / lossless TIFF-EP raws) via
//! `photocraft-raw`, developed into a 16-bit ProPhoto RGB "Background"
//! layer; unsupported raw variants fall back to the embedded JPEG preview.
//! * Every other format goes through `photocraft-codecs` as a single
//! "Background" layer (depth and Gray/RGB/CMYK model preserved).
//!
@@ -32,6 +35,7 @@ pub mod pattern_map;
mod pixels;
mod psd_export;
mod psd_import;
pub mod raw;
pub mod slices_map;
pub mod text_styles_map;
pub mod vector_map;
@@ -63,6 +67,9 @@ pub enum IoError {
/// Native `.pcraft` bundle failure.
#[error("pcraft: {0}")]
Pcraft(#[from] photocraft_format::FormatError),
/// Camera raw decode failure.
#[error("{0}")]
Raw(#[from] photocraft_raw::RawError),
}
/// Result of [`import`].
@@ -97,8 +104,8 @@ pub fn is_psd(bytes: &[u8]) -> bool {
bytes.starts_with(b"8BPS")
}
/// Imports a file. PSD/PSB are detected by magic; everything else is decoded
/// with `photocraft-codecs`.
/// Imports a file. PSD/PSB and camera raws are detected by magic; everything
/// else is decoded with `photocraft-codecs`.
pub fn import(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
if photocraft_format::is_pcraft(bytes) {
return Ok(ImportResult { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new() });
@@ -109,6 +116,9 @@ pub fn import(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
document.name = name.to_string();
return Ok(ImportResult { document, warnings });
}
if raw::is_raw(bytes) {
return raw::import_raw(name, bytes);
}
flat::import_flat(name, bytes)
}
+65
View File
@@ -0,0 +1,65 @@
//! Camera raw files via `photocraft-raw`: developed to a 16-bit RGB document
//! in ProPhoto RGB (the embedded profile is the built-in ProPhoto-compatible
//! profile), or, for raw variants not decoded yet, the camera's embedded
//! JPEG preview with a warning.
use std::sync::Arc;
use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image};
use photocraft_raw::{DevelopOptions, Limits, RawError};
use crate::flat::image_to_document;
use crate::{ImportResult, IoError};
/// `true` if `bytes` are a camera raw file `photocraft-raw` recognises.
pub fn is_raw(bytes: &[u8]) -> bool {
photocraft_raw::is_raw(bytes)
}
/// The decode limits shared with the flat codecs.
fn limits() -> Limits {
let l = codecs::Limits::default();
Limits { max_width: l.max_width, max_height: l.max_height, max_pixels: l.max_pixels, max_alloc: l.max_alloc }
}
/// Develops a raw file with the default settings.
pub fn import_raw(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
import_raw_with(name, bytes, &DevelopOptions { limits: limits(), ..Default::default() })
}
/// Develops a raw file with explicit settings.
pub fn import_raw_with(name: &str, bytes: &[u8], opts: &DevelopOptions) -> Result<ImportResult, IoError> {
let format = photocraft_raw::identify(bytes).map(|f| f.name()).unwrap_or("camera raw");
match photocraft_raw::develop(bytes, opts) {
Ok(dev) => {
let img = Image::from_u16(dev.width, dev.height, ChannelLayout::Rgb, &dev.rgb)?;
let mut r = image_to_document(name, &img)?;
r.document.icc_profile = Some(Arc::new(photocraft_cms::Builtin::ProPhotoCompat.profile().to_bytes().to_vec()));
let camera = [dev.info.make.as_deref(), dev.info.model.as_deref()].into_iter().flatten().collect::<Vec<_>>().join(" ");
r.warnings.push(format!(
"{format}{} developed with default settings ({} demosaic, as-shot white balance) into 16-bit {}",
if camera.is_empty() { String::new() } else { format!(" from {camera}") },
opts.demosaic.id(),
photocraft_raw::OUTPUT_SPACE
));
r.warnings.extend(dev.warnings);
Ok(r)
}
Err(RawError::Unsupported(reason)) => match photocraft_raw::embedded_preview(bytes) {
Some(p) => {
let img = codecs::decode_as(Format::Jpeg, p.jpeg)?;
let mut r = image_to_document(name, &img)?;
r.warnings.insert(
0,
format!(
"{format}: {reason} is not supported yet; opened the camera's embedded {}x{} JPEG preview instead (8-bit, not the raw sensor data)",
p.width, p.height
),
);
Ok(r)
}
None => Err(IoError::Raw(RawError::Unsupported(reason))),
},
Err(e) => Err(IoError::Raw(e)),
}
}
+90
View File
@@ -0,0 +1,90 @@
//! Camera raw import: synthetic DNG / CR2 develop into a 16-bit ProPhoto
//! document; unsupported raw variants fall back to the embedded preview.
use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image};
use photocraft_color::{ColorMode, SampleType};
use photocraft_io::{IoError, import};
use photocraft_raw::testgen::{Cr2Spec, DngSpec, TiffBuilder, Val, mosaic, scene};
#[test]
fn dng_opens_as_16_bit_prophoto() {
let (w, h) = (40, 24);
let mut spec = DngSpec::cfa(w, h, mosaic(&scene(w, h), w, [0, 1, 1, 2], 0, 65535));
spec.as_shot_neutral = Some([0.6, 1.0, 0.8]);
let r = import("shot.dng", &spec.build()).unwrap();
let d = &r.document;
assert_eq!((d.size.width, d.size.height), (40, 24));
assert_eq!(d.mode, ColorMode::Rgb);
assert_eq!(d.depth, SampleType::U16);
assert_eq!(d.layers.len(), 1);
let icc = d.icc_profile.as_ref().expect("profile");
assert_eq!(icc.as_slice(), &photocraft_cms::Builtin::ProPhotoCompat.profile().to_bytes()[..]);
assert!(r.warnings.iter().any(|w| w.contains("DNG") && w.contains("ProPhoto")), "{:?}", r.warnings);
}
#[test]
fn cr2_opens() {
let (w, h) = (48, 16);
let data = mosaic(&scene(w, h), w, [0, 1, 1, 2], 256, 12000);
let spec = Cr2Spec { width: w, height: h, data, precision: 14, components: 2, slices: vec![24, 24], borders: None, wb_rggb: None, orientation: 6 };
let r = import("IMG_0001.CR2", &spec.build()).unwrap();
// Orientation 6 rotates the 48×16 sensor image to 16×48.
assert_eq!((r.document.size.width, r.document.size.height), (16, 48));
assert_eq!(r.document.depth, SampleType::U16);
}
/// A NEF-like file with Nikon's (undocumented) compression and a full-size
/// baseline JPEG preview in IFD0.
fn nef_with_preview() -> Vec<u8> {
let img = Image::from_u8(32, 20, ChannelLayout::Rgb, vec![180; 32 * 20 * 3]).unwrap();
let jpeg = photocraft_codecs::encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();
let mut t = TiffBuilder::default();
let strip = t.blob(vec![0; 64]);
let preview = t.blob(jpeg.clone());
let raw = t.ifd(vec![
(256, Val::Long(vec![8])),
(257, Val::Long(vec![8])),
(258, Val::Short(vec![12])),
(259, Val::Short(vec![34713])),
(262, Val::Short(vec![32803])),
(273, Val::Blobs(vec![strip])),
(279, Val::Long(vec![64])),
(33421, Val::Short(vec![2, 2])),
(33422, Val::Byte(vec![0, 1, 1, 2])),
]);
let ifd0 = t.ifd(vec![
(271, Val::Ascii("NIKON CORPORATION".into())),
(330, Val::Ifds(vec![raw])),
(513, Val::Blobs(vec![preview])),
(514, Val::Long(vec![jpeg.len() as u32])),
]);
t.chain = vec![ifd0];
t.build()
}
#[test]
fn unsupported_raw_falls_back_to_the_embedded_preview() {
let r = import("DSC_0001.NEF", &nef_with_preview()).unwrap();
assert_eq!((r.document.size.width, r.document.size.height), (32, 20));
assert!(r.warnings.first().is_some_and(|w| w.contains("Nikon compressed NEF") && w.contains("embedded")), "{:?}", r.warnings);
}
#[test]
fn unsupported_raw_without_preview_is_a_clear_error() {
let mut cr3 = vec![0, 0, 0, 24];
cr3.extend_from_slice(b"ftypcrx ");
cr3.extend_from_slice(&[0; 12]);
match import("IMG_0001.CR3", &cr3) {
Err(e @ IoError::Raw(_)) => assert!(e.to_string().contains("CR3"), "{e}"),
Err(e) => panic!("expected a raw error, got {e}"),
Ok(_) => panic!("CR3 must not decode yet"),
}
}
#[test]
fn truncated_raws_do_not_panic() {
let b = nef_with_preview();
for n in (0..b.len()).step_by(7) {
let _ = import("x.nef", &b[..n]);
}
}