From 366b1d218c2edee679ae03f5a8298aa06e73d4ce Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 12 Oct 2026 03:58:14 +1000 Subject: [PATCH] LR-PROF-IMPORT: import the user's own DNG camera profiles (.dcp) profile.import (File > Import Profiles & Presets, drag & drop) now also reads DNG Camera Profiles: the user's own .dcp files, e.g. made with a colour-checker tool. They appear in the profile browser and menu under Camera Profiles with dcp:- ids; profiles.camera lists them and profile.deleteCamera / profile.deleteImported remove them. A library on disk keeps a copy in Profiles/. No profile ships with the app and the repository holds none: tests build theirs in memory (write_dcp). lightcraft_raw::dcp parses the file per DNG spec ch. 6 (magic RC in place of 42; IFD 0 read through the existing DNG colour builders) and DcpProfile::applied_to puts its matrices, illuminants and look in place of a raw file's, keeping the shot's white balance, analog balance and baseline exposure. Choosing one (develop.profile) replaces the raw file's colour model when it is decoded, before the starting colour and the white-balance scale (WbScaleOf) are worked out, so the matrix path takes over from the fitted JPEG look (CR3/CR2/ARW...) and white balance follows the profile. A profile without a tone curve of its own (most chart-made ones) keeps the photo's contrast: the DNG's tone curve, else the tone of the camera-JPEG fit. The profile travels with SourceRef::File into FileLoader / PairLoader (new Option<&DcpProfile> argument); a decoded source records the profile it was made with and is not reused for another. Smart previews and the web render worker keep the file's own colour; rendered (non-raw) photos ignore it. This reverses the documented "Adobe profile formats deliberately unsupported" stance for user-supplied files only; docs updated. Split out of #1012. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft-web/src/store.rs | 6 +- crates/engine/src/cmd/dcp_profiles.rs | 175 +++++++++++ crates/engine/src/cmd/develop.rs | 5 +- crates/engine/src/cmd/lut_profiles.rs | 11 +- crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/cmd/previews.rs | 14 +- crates/engine/src/files.rs | 54 +++- crates/engine/src/lib.rs | 5 + crates/engine/src/library.rs | 5 + crates/engine/src/media.rs | 76 ++++- crates/engine/src/presets.rs | 38 ++- crates/engine/src/smart.rs | 8 +- crates/engine/src/tests_dcp.rs | 141 +++++++++ crates/engine/src/tests_import.rs | 4 +- crates/raw/src/dcp.rs | 278 ++++++++++++++++++ crates/raw/src/lib.rs | 1 + .../ui-egui/examples/thumb_request_bench.rs | 2 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/menus.rs | 13 +- crates/ui-egui/src/panels/edit.rs | 16 +- crates/ui-egui/src/panels/profiles.rs | 14 +- crates/ui-egui/src/pick.rs | 2 +- crates/ui-egui/src/render.rs | 4 +- docs/file-format-parity.md | 5 +- docs/parity-checklist.md | 11 +- docs/raw-parity.md | 5 +- docs/roadmap.md | 5 +- docs/xmp-interop.md | 19 +- 28 files changed, 838 insertions(+), 83 deletions(-) create mode 100644 crates/engine/src/cmd/dcp_profiles.rs create mode 100644 crates/engine/src/tests_dcp.rs create mode 100644 crates/raw/src/dcp.rs diff --git a/apps/lightcraft-web/src/store.rs b/apps/lightcraft-web/src/store.rs index 729e794077..96750ba6d9 100644 --- a/apps/lightcraft-web/src/store.rs +++ b/apps/lightcraft-web/src/store.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; -use lightcraft_engine::files::{load_bytes, probe_bytes}; +use lightcraft_engine::files::{load_bytes_with, probe_bytes}; use lightcraft_engine::media::{FileLoader, FileProbe}; /// Prefix of the catalog paths of files kept in browser storage. @@ -144,9 +144,9 @@ impl Originals { /// Engine hooks that decode/probe from memory. pub fn hooks(&self) -> (FileLoader, FileProbe) { let s = self.clone(); - let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize| { + let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, dcp: Option<&lightcraft_engine::media::DcpProfile>| { let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?; - load_bytes(&bytes, max_edge) + load_bytes_with(&bytes, max_edge, dcp) }); let s = self.clone(); let probe: FileProbe = Arc::new(move |path: &str| { diff --git a/crates/engine/src/cmd/dcp_profiles.rs b/crates/engine/src/cmd/dcp_profiles.rs new file mode 100644 index 0000000000..a603848038 --- /dev/null +++ b/crates/engine/src/cmd/dcp_profiles.rs @@ -0,0 +1,175 @@ +//! Imported camera profiles: the user's own DNG Camera Profiles (`.dcp`), chosen like any other +//! profile (`develop.profile {id: "dcp:…"}`). Unlike the built-in looks and LUT profiles, which +//! work on developed colour, a camera profile replaces the raw file's colour model when it is +//! decoded (its matrices and hue/saturation map; see [`lightcraft_raw::dcp`]), so the photo's +//! source is decoded again when it changes. Other photos (JPEG, TIFF…) ignore it. +//! +//! A library on disk keeps a copy of each file in its `Profiles/` folder; the list lives in the +//! library's prefs and the profiles are parsed again when the library opens. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use lightcraft_raw::dcp::DcpProfile; +use serde_json::{Value, json}; + +use super::{CommandSpec, always, bad, cmd, str_param}; +use crate::{Result, Session}; + +/// Profile id prefix of imported camera profiles. +pub const DCP_PREFIX: &str = "dcp:"; +/// Profile browser group of imported camera profiles. +pub const DCP_GROUP: &str = "Camera Profiles"; + +/// One imported camera profile. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DcpEntry { + /// `dcp:`. + pub id: String, + /// `ProfileName`, else the file name. + pub name: String, + /// The camera it was made for (`UniqueCameraModel`). + #[serde(default)] + pub camera_model: String, + /// The `.dcp` file (the library's copy when there is a library on disk). + pub file: String, +} + +/// Is `id` an imported camera profile id? +pub fn is_dcp_id(id: &str) -> bool { + id.starts_with(DCP_PREFIX) +} + +fn profiles_dir(s: &Session) -> Option { + s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Profiles")) +} + +/// Parse every imported camera profile again and hand them to the decoder (missing or damaged +/// files are skipped: photos using them develop with the file's own colour). +pub fn register_all(s: &mut Session) { + let loaded: Vec<(String, Arc)> = s + .dcp_profiles + .iter() + .filter_map(|p| std::fs::read(&p.file).ok().and_then(|b| lightcraft_raw::dcp::parse_dcp(&b).ok()).map(|d| (p.id.clone(), Arc::new(d)))) + .collect(); + s.media.camera_profiles = loaded.into_iter().collect(); +} + +/// `.dcp` files under `paths` (folders searched). +pub fn dcp_files(paths: &[String]) -> Vec { + let is_dcp = |f: &Path| f.extension().is_some_and(|x| x.eq_ignore_ascii_case("dcp")); + let mut out = Vec::new(); + for p in paths { + let path = Path::new(p); + if path.is_dir() { + out.extend(crate::walk::files_in(path, None, crate::walk::Limits::default(), is_dcp).files); + } else if is_dcp(path) { + out.push(path.to_path_buf()); + } + } + out +} + +/// Import the `.dcp` files under `paths` → (imported `[{id, name, cameraModel}]`, failed `[[file, error]]`). +/// A profile already imported (same name, camera and bytes) is not added twice. +pub fn import_files(s: &mut Session, paths: &[String]) -> Result<(Vec, Vec)> { + const C: &str = "profile.import"; + let dir = profiles_dir(s); + if let Some(d) = &dir { + std::fs::create_dir_all(d).map_err(|e| bad(C, format!("{}: {e}", d.display())))?; + } + let (mut imported, mut failed) = (Vec::new(), Vec::new()); + for f in dcp_files(paths) { + let shown = f.display().to_string(); + let bytes = match std::fs::read(&f) { + Ok(b) => b, + Err(e) => { + failed.push(json!([shown, e.to_string()])); + continue; + } + }; + let profile = match lightcraft_raw::dcp::parse_dcp(&bytes) { + Ok(p) => p, + Err(e) => { + failed.push(json!([shown, e.to_string()])); + continue; + } + }; + let stem = f.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Camera Profile".into()); + let name = if profile.name.trim().is_empty() { stem.clone() } else { profile.name.trim().to_string() }; + // the same profile imported again: keep the one there is + let same = s + .dcp_profiles + .iter() + .find(|p| p.name == name && p.camera_model == profile.camera_model && std::fs::read(&p.file).is_ok_and(|b| b == bytes)); + if let Some(p) = same { + imported.push(json!({"id": p.id, "name": p.name, "cameraModel": p.camera_model, "existing": true})); + continue; + } + // (the file name keeps profiles with the same ProfileName apart, e.g. per-body copies) + let slug = crate::presets::slug(&format!("{}-{stem}", profile.camera_model)); + let mut id = format!("{DCP_PREFIX}{slug}"); + let mut n = 2; + while s.dcp_profiles.iter().any(|x| x.id == id) { + id = format!("{DCP_PREFIX}{slug}-{n}"); + n += 1; + } + let file = match &dir { + Some(d) => { + let to = d.join(format!("{}.dcp", id.trim_start_matches(DCP_PREFIX))); + std::fs::write(&to, &bytes).map_err(|e| bad(C, format!("{}: {e}", to.display())))?; + to.to_string_lossy().to_string() + } + // no library on disk: remember the original (the in-memory session ends with the app) + None => f.to_string_lossy().to_string(), + }; + s.media.camera_profiles.insert(id.clone(), Arc::new(profile.clone())); + s.dcp_profiles.push(DcpEntry { id: id.clone(), name: name.clone(), camera_model: profile.camera_model.clone(), file }); + imported.push(json!({"id": id, "name": name, "cameraModel": profile.camera_model})); + } + Ok((imported, failed)) +} + +fn delete(s: &mut Session, p: &Value) -> Result { + const C: &str = "profile.deleteCamera"; + let id = str_param(p, "id").ok_or_else(|| bad(C, "missing id"))?.to_string(); + let Some(i) = s.dcp_profiles.iter().position(|x| x.id == id) else { + return Err(bad(C, format!("no imported camera profile `{id}`"))); + }; + let entry = s.dcp_profiles.remove(i); + s.media.camera_profiles.remove(&id); + // the library's copy goes; a file outside the library is the user's and stays + if let Some(d) = profiles_dir(s) + && Path::new(&entry.file).starts_with(&d) + { + let _ = std::fs::remove_file(&entry.file); + } + s.profile_favorites.retain(|f| f != &id); + s.profile_recent.retain(|f| f != &id); + s.save_prefs()?; + Ok(json!({"deleted": id})) +} + +pub fn specs() -> Vec { + vec![ + cmd!( + query "profiles.camera", + "Imported Camera Profiles", + [], + None, + "{} → {profiles: [{id, name, cameraModel, file}]}: the imported .dcp camera profiles (use with develop.profile)", + always, + |s, _| Ok(json!({"profiles": s.dcp_profiles})) + ), + cmd!( + "profile.deleteCamera", + "Delete Imported Camera Profile", + [], + None, + "{id: dcp:…} — photos using it develop with their file's own colour again", + always, + delete + ), + ] +} diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 42f59fe727..14b11a2374 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -470,7 +470,10 @@ pub fn specs() -> Vec { }), cmd!("develop.profile", "Set Profile", [], None, "{id: profile id (see profiles.list), amount?: 0..200}", has_active, |s, p| { let id = str_param(p, "id").ok_or_else(|| bad("develop.profile", "missing id"))?.to_string(); - if !crate::presets::PROFILES.iter().any(|x| x.id == id) && !s.lut_profiles.iter().any(|x| x.id == id) { + if !crate::presets::PROFILES.iter().any(|x| x.id == id) + && !s.lut_profiles.iter().any(|x| x.id == id) + && !s.dcp_profiles.iter().any(|x| x.id == id) + { return Err(bad("develop.profile", format!("unknown profile `{id}`"))); } edit(s, "develop.profile", "Profile", |d| { diff --git a/crates/engine/src/cmd/lut_profiles.rs b/crates/engine/src/cmd/lut_profiles.rs index 349e66ea80..b9c6ecc902 100644 --- a/crates/engine/src/cmd/lut_profiles.rs +++ b/crates/engine/src/cmd/lut_profiles.rs @@ -134,6 +134,10 @@ fn import(s: &mut Session, p: &Value) -> Result { s.lut_profiles.push(LutProfile { id: id.clone(), name: display.clone(), group: group.clone(), file }); imported.push(json!({"id": id, "name": display, "group": group})); } + // camera profiles (.dcp) among them + let (cameras, camera_failed) = super::dcp_profiles::import_files(s, &paths)?; + imported.extend(cameras); + failed.extend(camera_failed); s.save_prefs()?; Ok(json!({"imported": imported, "failed": failed})) } @@ -145,12 +149,15 @@ pub fn specs() -> Vec { "Import Profiles", [], None, - "{paths: [.cube file, folder or .zip]} — 3D LUTs become creative profiles (Amount 0–200 %; rendered on the CPU) in the profile browser's groups (folder / zip name, else Imported) → {imported: [{id, name, group}], failed}", + "{paths: [.cube / .dcp file, folder or .zip]} — 3D LUTs become creative profiles (Amount 0–200 %; rendered on the CPU) in the profile browser's groups (folder / zip name, else Imported); DNG camera profiles (.dcp, the user's own) become camera profiles (dcp: ids, group Camera Profiles) that replace a raw file's colour model when it is decoded → {imported: [{id, name, group | cameraModel}], failed}", always, import ), - cmd!("profile.deleteImported", "Delete Imported Profile", [], None, "{id: lut:…}", always, |s, p| { + cmd!("profile.deleteImported", "Delete Imported Profile", [], None, "{id: lut:… | dcp:…}", always, |s, p| { let id = str_param(p, "id").ok_or_else(|| bad("profile.deleteImported", "missing id"))?.to_string(); + if super::dcp_profiles::is_dcp_id(&id) { + return s.execute("profile.deleteCamera", p); + } let Some(i) = s.lut_profiles.iter().position(|x| x.id == id) else { return Err(bad("profile.deleteImported", format!("no imported profile `{id}`"))); }; diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 4de460761f..deb089acc3 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -11,6 +11,7 @@ mod color; pub(crate) mod convert; mod cull; pub mod curves; +pub mod dcp_profiles; pub(crate) mod denoise; mod develop; mod edit; @@ -145,6 +146,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(manage::specs()); v.extend(previews::specs()); v.extend(lut_profiles::specs()); + v.extend(dcp_profiles::specs()); v.extend(cull::specs()); v.extend(convert::specs()); v.extend(convert::edit_specs()); diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 4fc7ababa6..d022fcb060 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -212,7 +212,10 @@ struct SmartCounts { fn original_only(source: crate::media::SourceRef) -> Option { use crate::media::SourceRef; match source { - SourceRef::File { path, max_edge, loader, denoise, .. } => Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise }), + // (a smart preview keeps the file's own colour: an imported camera profile is applied when the original is read) + SourceRef::File { path, max_edge, loader, denoise, .. } => { + Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None }) + } SourceRef::Loaded(d) if d.info.is_some() => Some(SourceRef::Loaded(d)), _ => None, } @@ -548,7 +551,14 @@ mod tests { let mut jobs = jobs_for(&mut s, id, Some(512)); assert_eq!(jobs.len(), 2, "view and thumbnail"); assert!(jobs[0].view_cache.is_some(), "the view renders first"); - jobs[1].source = SourceRef::File { path: "/nonexistent/photo.arw".into(), max_edge: 512, loader: None, fallback: None, denoise: None }; + jobs[1].source = SourceRef::File { + path: "/nonexistent/photo.arw".into(), + max_edge: 512, + loader: None, + fallback: None, + denoise: None, + camera_profile: None, + }; assert!(run_photo(jobs), "the thumbnail rendered from the view's decoded source"); } diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index c48aaff77c..455171fc7f 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -11,6 +11,8 @@ use lightcraft_pipeline::SourceInfo; use lightcraft_raster::Rgb32f; use lightcraft_raster::resample::{Filter, fit}; +use lightcraft_raw::dcp::DcpProfile; + use crate::media::{DenoiseSpec, FileLoader, FileProbe, PairLoader, PreviewLoader, ProbeInfo}; fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option) { @@ -340,20 +342,30 @@ pub fn bin_factor(raw: &lightcraft_raw::RawImage, max_edge: usize) -> Option Result<(Rgb32f, SourceInfo), String> { - rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None).map(|(img, _, info)| (img, info))) + rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, None).map(|(img, _, info)| (img, info))) +} + +/// [`load_bytes`] developing a raw file with an imported camera profile (`dcp`) in place of its own colour model. +pub fn load_bytes_with(bytes: &[u8], max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> { + rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, dcp).map(|(img, _, info)| (img, info))) } /// [`load_bytes`] taking the file's bytes: a raw file's bytes are freed as soon as it is decoded /// (less memory held while it is developed). -pub fn load_vec(bytes: Vec, max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> { - rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None).map(|(img, _, info)| (img, info))) +pub fn load_vec(bytes: Vec, max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> { + rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, dcp).map(|(img, _, info)| (img, info))) } /// [`load_vec`] that also develops the photo's cached denoised picture (`spec`) from the same decode: the plain /// picture, the denoised one (`None` when it cannot be read or does not fit this raw: the plain one is then all /// there is) and the source facts. Both pictures are the same size. -pub fn load_vec_pair(bytes: Vec, max_edge: usize, spec: &DenoiseSpec) -> Result<(Rgb32f, Option, SourceInfo), String> { - rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec))) +pub fn load_vec_pair( + bytes: Vec, + max_edge: usize, + spec: &DenoiseSpec, + dcp: Option<&DcpProfile>, +) -> Result<(Rgb32f, Option, SourceInfo), String> { + rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), dcp)) } /// The denoised camera RGB of `raw` from its cached product, as the plain development would have it: the default @@ -382,6 +394,7 @@ fn load_bytes_now( bytes: std::borrow::Cow<'_, [u8]>, max_edge: usize, denoise: Option<&DenoiseSpec>, + dcp: Option<&DcpProfile>, ) -> Result<(Rgb32f, Option, SourceInfo), String> { if lightcraft_raw::probe(&bytes).is_some() { let mut raw = match lightcraft_raw::decode(&bytes).map_err(|e| preview_reason(&bytes, e)) { @@ -399,6 +412,24 @@ fn load_bytes_now( let info = raw.info(); let lens = crate::lens_profiles::for_raw(&info, || lightcraft_meta::extract(&bytes)); raw.opcodes.list3.retain(|op| !op.is_lens_correction()); + // A camera profile without a tone curve of its own (most chart-made ones: a matrix, maybe a hue/saturation map) + // keeps the contrast the photo has without it: the file's own DNG tone curve, else the tone of the look fitted + // to its camera JPEG. (A chart pins colour, not a rendering: its curve would be a choice, and this one is the + // camera's.) + let kept_tone = match dcp { + Some(p) if p.color.profile.tone_curve.is_none() => raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve).or_else(|| { + let own = raw.color.clone(); + let tone = crate::camera_preview::starting_colour(&mut raw, &bytes).2.map(|look| look.tone); + raw.color = own; + tone + }), + _ => None, + }; + // An imported camera profile replaces the file's colour model (its matrices and look; the shot's white stays), so + // the starting colour and the white balance scale below come from it, not from a fitted or built-in look. + if let Some(p) = dcp { + raw.color = p.applied_to(&raw.color); + } // Which scale white balance is edited on, and the as-shot white on it, from the file's own colour tags or // the camera's measured matrices (`Photo::relative_wb` decides the same from the catalog's camera) let scale = WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata); @@ -476,7 +507,8 @@ fn load_bytes_now( let tags = lightcraft_raw::ColorData { profile: Default::default(), ..raw.color.clone() }; Arc::new(lightcraft_pipeline::CameraColor { tags, developed_for: xy }) }); - let camera_tone = camera_look.as_ref().map(|p| p.tone).or_else(|| raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve)); + let camera_tone = + camera_look.as_ref().map(|p| p.tone).or_else(|| raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve)).or(kept_tone); let local_tone = local_tone(&raw); let (temp, tint) = scale.as_shot(xy); return Ok(( @@ -821,13 +853,13 @@ fn quick_image_srgb(header: &[u8], window: &[u8], max_edge: usize) -> Option PairLoader { - Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec| { + Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec, dcp: Option<&DcpProfile>| { let len = std::fs::metadata(path).map(|m| m.len() as usize).unwrap_or(0); let weight = len * if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 4 } else { 10 }; let gate = crate::memory::work_gate(); let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) }; let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; - let r = load_vec_pair(bytes, max_edge, spec); + let r = load_vec_pair(bytes, max_edge, spec, dcp); crate::memory::release(); r }) @@ -841,13 +873,13 @@ pub fn fs_pair_loader() -> PairLoader { /// interactive loads (the loupe, exports) never wait — they are counted, so background work /// yields to them. pub fn fs_hooks() -> (FileLoader, FileProbe) { - let loader: FileLoader = Arc::new(|path: &str, max_edge: usize| { + let loader: FileLoader = Arc::new(|path: &str, max_edge: usize, dcp: Option<&DcpProfile>| { let len = std::fs::metadata(path).map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).unwrap_or(0); let weight = len * if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 3 } else { 6 }; let gate = crate::memory::work_gate(); let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) }; let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; - let r = load_vec(bytes, max_edge); + let r = load_vec(bytes, max_edge, dcp); // the file, the samples and the intermediate images are gone: give their pages back crate::memory::release(); r @@ -1068,7 +1100,7 @@ mod tests { product::write(&path, &camera_rgb, key).unwrap(); let spec = DenoiseSpec { product: path, key: key.into(), make: None }; let (ordinary, _) = load_bytes(&bytes, 2048).unwrap(); - let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec).unwrap(); + let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec, None).unwrap(); assert_eq!(plain.data, ordinary.data, "requesting a twin must not change the ordinary path"); let cached = cached.unwrap(); assert_eq!((plain.width, plain.height), (24, 32)); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3bc6c431ee..0ddeafdcd8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -257,6 +257,8 @@ pub struct Session { /// The user's point-curve presets (`curve.*`; built-ins: [`cmd::curves::builtin_presets`]), /// persisted in prefs.json. pub curve_presets: Vec, + /// Imported camera profiles (`.dcp`). + pub dcp_profiles: Vec, /// Saved colour-label name sets. pub label_sets: Vec, /// Look-alike signatures by content key (Find Similar). @@ -373,6 +375,7 @@ impl Session { metadata_presets: Vec::new(), filter_presets: Vec::new(), curve_presets: Vec::new(), + dcp_profiles: Vec::new(), label_sets: Vec::new(), signatures: Default::default(), lut_profiles: Vec::new(), @@ -984,6 +987,8 @@ mod tests_color; #[cfg(test)] mod tests_crop_angle; #[cfg(test)] +mod tests_dcp; +#[cfg(test)] mod tests_denoise; #[cfg(test)] mod tests_export; diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 2bb5511c2d..51523b4e61 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -171,6 +171,8 @@ struct PrefsFile { label_sets: Vec, /// Imported LUT profiles. lut_profiles: Vec, + /// Imported camera profiles (`.dcp`). + dcp_profiles: Vec, /// Keyword sets, the one in use, recent keywords. keyword_sets: Vec, keyword_set: Option, @@ -399,6 +401,8 @@ impl Session { self.label_sets = prefs.label_sets; self.lut_profiles = prefs.lut_profiles; crate::cmd::lut_profiles::register_all(self); + self.dcp_profiles = prefs.dcp_profiles; + crate::cmd::dcp_profiles::register_all(self); self.keyword_sets = prefs.keyword_sets; self.keyword_set = prefs.keyword_set; self.recent_keywords = prefs.recent_keywords; @@ -633,6 +637,7 @@ impl Session { curve_presets: self.curve_presets.clone(), label_sets: self.label_sets.clone(), lut_profiles: self.lut_profiles.clone(), + dcp_profiles: self.dcp_profiles.clone(), keyword_sets: self.keyword_sets.clone(), keyword_set: self.keyword_set.clone(), recent_keywords: self.recent_keywords.clone(), diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 6f6f0359c4..c62a62232f 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -24,6 +24,7 @@ use lightcraft_develop::DevelopSettings; use lightcraft_pipeline::{Quality, RenderRequest, Rendered, SourceInfo, StageCache}; use lightcraft_preview::{Hash128, Hasher128, Lru, PreviewCache}; use lightcraft_raster::{Histogram, Rgb32f, Rgba8}; +pub use lightcraft_raw::dcp::DcpProfile; use serde::{Deserialize, Serialize}; const SETTINGS_HASH_ENTRIES: usize = 1024; @@ -119,7 +120,9 @@ fn source_edge_needed(p: &Photo, settings: &DevelopSettings, apply_crop: bool, o } /// Decodes a file into a linear Rec.2020 image no larger than `max_edge` (set by the app). -pub type FileLoader = Arc Result<(Rgb32f, SourceInfo), String> + Send + Sync>; +/// The third argument is the photo's imported camera profile ([`crate::cmd::dcp_profiles`]): a raw file is developed +/// with its colour model. +pub type FileLoader = Arc) -> Result<(Rgb32f, SourceInfo), String> + Send + Sync>; /// A raw file's embedded (camera-rendered) preview as display sRGB, oriented, no larger than /// `max_edge` (set by the app). `None`: no usable preview. @@ -142,7 +145,8 @@ pub struct DenoiseSpec { /// Decodes a raw file once and develops it twice: as usual, and from the denoised picture in `spec` when that can be /// read (`None` when it cannot). Both are at most `max_edge` long and the same size. -pub type PairLoader = Arc Result<(Rgb32f, Option, SourceInfo), String> + Send + Sync>; +pub type PairLoader = + Arc) -> Result<(Rgb32f, Option, SourceInfo), String> + Send + Sync>; /// A photo's denoised picture next to its plain one, and the last mix of the two that was asked for. pub struct Twin { @@ -172,11 +176,14 @@ pub struct DecodedSource { pub camera_tone: Option, /// The same picture developed from the AI-denoised mosaic, when the photo has one cached. pub denoised: Option>, + /// The imported camera profile (`dcp:…` id) the raw file was developed with, if any: a cached source made with + /// another one (or none) doesn't stand in for it. + pub camera_profile: Option, } impl DecodedSource { pub fn new(image: Arc, info: Option) -> Self { - DecodedSource { image, info, camera_tone: None, denoised: None } + DecodedSource { image, info, camera_tone: None, denoised: None, camera_profile: None } } /// The picture to develop for a Denoise `amount` (0 to 1, see [`DevelopSettings::denoise_amount`]): the plain one, @@ -236,6 +243,8 @@ pub enum SourceRef { fallback: Option, /// The photo has a cached denoised picture: load it with the plain one (see [`PairLoader`]). denoise: Option<(DenoiseSpec, PairLoader)>, + /// The photo's imported camera profile (id and profile): its raw file is developed with it. + camera_profile: Option<(String, Arc)>, }, /// A smart preview standing in for a missing original. Smart { @@ -252,9 +261,12 @@ impl SourceRef { let image = match self { SourceRef::Loaded(a) => return Ok((**a).clone()), SourceRef::Demo { scene, max_edge } => crate::demo::scene_pixels(scene, *max_edge)?, - SourceRef::File { path, max_edge, loader, fallback, denoise } => { + SourceRef::File { path, max_edge, loader, fallback, denoise, camera_profile } => { + let dcp = camera_profile.as_ref().map(|(_, p)| p.as_ref()); + let made_with = camera_profile.as_ref().map(|(id, _)| id.clone()); let plain = || match loader { - Some(l) => l(path, *max_edge).map(|(image, info)| DecodedSource::new(Arc::new(image), Some(info))), + Some(l) => l(path, *max_edge, dcp) + .map(|(image, info)| DecodedSource { camera_profile: made_with.clone(), ..DecodedSource::new(Arc::new(image), Some(info)) }), None => Err(format!("no decoder available for {path}")), }; // the denoised picture comes with the plain one from a single decode; when it cannot be read the @@ -268,7 +280,7 @@ impl SourceRef { None => true, }; if made { - pair(path, *max_edge, spec).and_then(|(image, twin, info)| { + pair(path, *max_edge, spec, dcp).and_then(|(image, twin, info)| { if spec.make.is_some() && twin.is_none() { return Err("the cached AI Denoise picture could not be read; clear the denoise cache and retry".into()); } @@ -277,6 +289,7 @@ impl SourceRef { info: Some(info), camera_tone: None, denoised: twin.map(|t| Arc::new(Twin::new(Arc::new(t)))), + camera_profile: made_with.clone(), }) }) } else { @@ -334,6 +347,8 @@ pub struct MediaCache { pub rendered: Arc, /// Which photos have a cached denoised picture, and how to read it. pub denoise: DenoiseIndex, + /// Imported camera profiles by id ([`crate::cmd::dcp_profiles`]), handed to the decoder of photos using them. + pub camera_profiles: std::collections::HashMap>, } /// The photos that have a cached denoised picture for the denoise model in use. Only memory: nothing here touches the @@ -402,6 +417,7 @@ impl Default for MediaCache { scenes: Vec::new(), rendered: Arc::new(PreviewCache::memory(rendered_budget(budget))), denoise: DenoiseIndex::default(), + camera_profiles: HashMap::new(), } } } @@ -622,7 +638,12 @@ impl MediaCache { } fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool) -> SourceRef { - if cached && let Some(a) = self.get_source(p.id, level) { + let wanted = self.camera_profile_of(p); + // (a source developed with another camera profile, or none, doesn't stand in) + if cached + && let Some(a) = self.get_source(p.id, level) + && a.camera_profile == wanted.as_ref().map(|(id, _)| id.clone()) + { return SourceRef::Loaded(Box::new(a)); } // Procedural scenes have a nominal size: "full" is that size, not unbounded. @@ -644,12 +665,26 @@ impl MediaCache { return SourceRef::Smart { path: sp }; } let mut r = self.origin_ref(&p.source, max_edge); - if let SourceRef::File { fallback, .. } = &mut r { + if let SourceRef::File { fallback, camera_profile, .. } = &mut r { *fallback = Some(sp); + *camera_profile = wanted; } return r; } - self.origin_ref(&p.source, max_edge) + let mut r = self.origin_ref(&p.source, max_edge); + if let SourceRef::File { camera_profile, .. } = &mut r { + *camera_profile = wanted; + } + r + } + + /// The imported camera profile photo `p` develops with: its profile setting names one this library has. + pub fn camera_profile_of(&self, p: &Photo) -> Option<(String, Arc)> { + let id = &p.develop.profile.id; + if !crate::cmd::dcp_profiles::is_dcp_id(id) { + return None; + } + self.camera_profiles.get(id).map(|d| (id.clone(), d.clone())) } /// How to load `origin` at most `max_edge` pixels long, ignoring decoded sources in memory (a @@ -662,12 +697,19 @@ impl MediaCache { } match self.scenes.iter().find(|s| s.id == *scene) { Some(s) => SourceRef::Demo { scene: Box::new(s.clone()), max_edge }, - None => SourceRef::File { path: format!("demo:{scene}"), max_edge, loader: None, fallback: None, denoise: None }, + None => { + SourceRef::File { path: format!("demo:{scene}"), max_edge, loader: None, fallback: None, denoise: None, camera_profile: None } + } } } - Source::File { path } => { - SourceRef::File { path: path.clone(), max_edge, loader: self.file_loader.clone(), fallback: None, denoise: None } - } + Source::File { path } => SourceRef::File { + path: path.clone(), + max_edge, + loader: self.file_loader.clone(), + fallback: None, + denoise: None, + camera_profile: None, + }, } } } @@ -1571,7 +1613,7 @@ mod thumbnail_hash_tests { #[test] fn source_from_before_content_reload_is_not_accepted() { let mut s = session(); - s.media.file_loader = Some(Arc::new(|_, _| Ok((Rgb32f::new(8, 8), SourceInfo::default())))); + s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default())))); let old = s.thumb_job(PhotoId(1), 256).unwrap().run(); assert!(old.loaded.is_some()); s.catalog @@ -1640,13 +1682,14 @@ mod tests { job.source = SourceRef::File { path: "synthetic.arw".into(), max_edge: 64, - loader: Some(Arc::new(move |_, _| { + loader: Some(Arc::new(move |_, _, _| { let mut image = Rgb32f::new(64, 64); image.data.fill([0.1; 3]); Ok((image, loaded_info.clone())) })), fallback: None, denoise: None, + camera_profile: None, }; job.info = SourceInfo::default(); // Header facts cannot override decoder facts. job.settings = Arc::new(DevelopSettings::default()); @@ -1699,9 +1742,10 @@ mod tests { job.source = SourceRef::File { path: "/photos/DSC00001.ARW".into(), max_edge: 64, - loader: Some(Arc::new(move |_, _| Ok((loaded_pixels.clone(), loaded_info.clone())))), + loader: Some(Arc::new(move |_, _, _| Ok((loaded_pixels.clone(), loaded_info.clone())))), fallback: None, denoise: None, + camera_profile: None, }; let undo_before = s.undo.len(); let request = job.request; diff --git a/crates/engine/src/presets.rs b/crates/engine/src/presets.rs index 8c36aa7429..92b04dd03d 100644 --- a/crates/engine/src/presets.rs +++ b/crates/engine/src/presets.rs @@ -445,7 +445,17 @@ impl Session { if let Some(p) = profile(id) { return Some((p.name, p.group)); } - self.lut_profiles.iter().find(|p| p.id == id).map(|p| (p.name.as_str(), p.group.as_str())) + if let Some(p) = self.lut_profiles.iter().find(|p| p.id == id) { + return Some((p.name.as_str(), p.group.as_str())); + } + self.dcp_profiles.iter().find(|p| p.id == id).map(|p| (p.name.as_str(), crate::cmd::dcp_profiles::DCP_GROUP)) + } + + /// The imported profiles as (id, name, group): LUT profiles, then camera profiles (`.dcp`). + pub fn imported_profiles(&self) -> Vec<(String, String, String)> { + let luts = self.lut_profiles.iter().map(|p| (p.id.clone(), p.name.clone(), p.group.clone())); + let dcps = self.dcp_profiles.iter().map(|p| (p.id.clone(), p.name.clone(), crate::cmd::dcp_profiles::DCP_GROUP.to_string())); + luts.chain(dcps).collect() } /// Remember `id` as the most recently applied profile. @@ -459,28 +469,30 @@ impl Session { pub fn profile_menu(&self) -> Value { let item = |p: &ProfileInfo| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.iter().any(|f| f == p.id)}); - let lut_item = |id: &str| { - self.lut_profiles - .iter() - .find(|p| p.id == id) - .map(|p| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.contains(&p.id), "imported": true})) + let imported = self.imported_profiles(); + let imported_item = |(id, name, group): &(String, String, String)| { + let mut v = json!({"id": id, "name": name, "group": group, "favorite": self.profile_favorites.contains(id), "imported": true}); + if let Some(d) = self.dcp_profiles.iter().find(|d| &d.id == id) { + v["cameraModel"] = json!(d.camera_model); + } + v }; + let lut_item = |id: &str| imported.iter().find(|p| p.0 == id).map(imported_item); let list = |ids: &[String]| ids.iter().filter_map(|id| profile(id).map(item).or_else(|| lut_item(id))).collect::>(); let mut groups: Vec = profile_groups() .into_iter() .map(|g| json!({"name": g, "profiles": PROFILES.iter().filter(|p| p.group == g).map(item).collect::>()})) .collect(); - // imported LUT profiles, by their groups + // imported LUT profiles by their groups, then camera profiles let mut lut_groups: Vec<&str> = self.lut_profiles.iter().map(|p| p.group.as_str()).collect(); lut_groups.sort_unstable(); lut_groups.dedup(); + if !self.dcp_profiles.is_empty() { + lut_groups.push(crate::cmd::dcp_profiles::DCP_GROUP); + } + lut_groups.dedup(); for g in lut_groups { - let profiles: Vec = self - .lut_profiles - .iter() - .filter(|p| p.group == g) - .map(|p| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.contains(&p.id), "imported": true})) - .collect(); + let profiles: Vec = imported.iter().filter(|p| p.2 == g).map(imported_item).collect(); groups.push(json!({"name": g, "profiles": profiles, "imported": true})); } json!({ diff --git a/crates/engine/src/smart.rs b/crates/engine/src/smart.rs index 3628f188ce..3cadded593 100644 --- a/crates/engine/src/smart.rs +++ b/crates/engine/src/smart.rs @@ -312,7 +312,13 @@ pub fn mark_look_checked(dir: &Path) -> Result<(), String> { /// Load the proxy at `path`. pub fn load(path: &Path) -> Result { let b = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?; - decode(&b).map(|(image, camera_tone)| crate::media::DecodedSource { image: Arc::new(image), info: None, camera_tone, denoised: None }) + decode(&b).map(|(image, camera_tone)| crate::media::DecodedSource { + image: Arc::new(image), + info: None, + camera_tone, + denoised: None, + camera_profile: None, + }) } #[cfg(test)] diff --git a/crates/engine/src/tests_dcp.rs b/crates/engine/src/tests_dcp.rs new file mode 100644 index 0000000000..aa3c791681 --- /dev/null +++ b/crates/engine/src/tests_dcp.rs @@ -0,0 +1,141 @@ +//! Imported camera profiles (`.dcp`): import, choosing one for a raw photo, decoding with it, the +//! source cache, persistence and deletion. Profiles are built in memory (no profile file is committed). + +use std::path::PathBuf; + +use lightcraft_catalog::PhotoId; +use lightcraft_raw::dcp::{DcpProfile, write_dcp}; +use lightcraft_raw::{ColorData, Mat3}; +use serde_json::json; + +use crate::Session; +use crate::media::SourceRef; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-dcp-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A profile whose matrix swaps the camera's red and blue (our own numbers): photos developed with it +/// come out with red and blue exchanged, which is easy to see in a test. +fn swapping_profile(name: &str) -> DcpProfile { + let m = Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]); + let xyz_to_cam = m.mul(&Mat3([[3.2406, -1.5372, -0.4986], [-0.9689, 1.8758, 0.0415], [0.0557, -0.2040, 1.0570]])); + DcpProfile { + name: name.into(), + camera_model: "LightCraft Test Camera".into(), + color: ColorData { illuminant: [21, 0], color_matrix: [Some(xyz_to_cam), None], ..Default::default() }, + } +} + +fn mean_rgb(img: &lightcraft_raster::Rgb32f) -> [f32; 3] { + let n = img.data.len().max(1) as f32; + let s = img.data.iter().fold([0.0f32; 3], |a, p| [a[0] + p[0], a[1] + p[1], a[2] + p[2]]); + [s[0] / n, s[1] / n, s[2] / n] +} + +#[test] +fn a_camera_profile_replaces_the_raw_colour_model_when_decoding() { + let dng = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + let (plain, plain_info) = crate::files::load_bytes(&dng, 64).unwrap(); + let p = swapping_profile("Swap"); + let (with, info) = crate::files::load_bytes_with(&dng, 64, Some(&p)).unwrap(); + let (a, b) = (mean_rgb(&plain), mean_rgb(&with)); + assert!((a[0] - b[0]).abs() > 1e-3 || (a[2] - b[2]).abs() > 1e-3, "the profile changes the colour: {a:?} vs {b:?}"); + // white balance at render time works from the profile's matrices + let tags = &info.camera_color.as_ref().expect("a matrix colour model").tags; + assert_eq!(tags.color_matrix, p.color.color_matrix); + assert_ne!(plain_info.camera_color.as_ref().map(|c| c.tags.color_matrix), Some(p.color.color_matrix)); +} + +#[test] +fn a_profile_without_a_tone_curve_keeps_the_photos_contrast() { + use lightcraft_raw::profile::ToneCurve; + // a DNG with a tone curve of its own (our numbers: 18 % grey → 30 %) + let plain = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + let mut raw = lightcraft_raw::decode(&plain).unwrap(); + raw.color.profile.tone_curve = ToneCurve::from_tag(&[0.0, 0.0, 0.18, 0.3, 1.0, 1.0]); + let dng = lightcraft_raw::write_dng(&raw, &Default::default()).unwrap(); + // a chart-style profile (no curve) keeps the file's curve + let (_, info) = crate::files::load_bytes_with(&dng, 64, Some(&swapping_profile("Swap"))).unwrap(); + let tone = info.camera_tone.expect("the file's tone curve stays"); + assert!((tone.apply(0.18) - 0.3).abs() < 0.01, "{}", tone.apply(0.18)); + // a profile with a curve of its own uses that one (18 % → 45 %) + let mut curved = swapping_profile("Curved"); + curved.color.profile.tone_curve = ToneCurve::from_tag(&[0.0, 0.0, 0.18, 0.45, 1.0, 1.0]); + let (_, info) = crate::files::load_bytes_with(&dng, 64, Some(&curved)).unwrap(); + let tone = info.camera_tone.expect("the profile's tone curve"); + assert!((tone.apply(0.18) - 0.45).abs() < 0.01, "{}", tone.apply(0.18)); +} + +#[test] +fn import_choose_cache_persist_and_delete() { + let dir = temp_dir("session"); + let (lib, files) = (dir.join("lib"), dir.join("files")); + std::fs::create_dir_all(files.join("profiles")).unwrap(); + let raw = files.join("IMG_0001.dng"); + std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + std::fs::write(files.join("profiles").join("Swap.dcp"), write_dcp(&swapping_profile("Swap")).unwrap()).unwrap(); + std::fs::write(files.join("profiles").join("Broken.dcp"), b"IIRC\x08\0\0\0junk").unwrap(); + let id; + let dcp_id; + { + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap(); + id = PhotoId(r["imported"][0].as_u64().unwrap()); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + // a folder: the good profile comes in, the broken one is reported + let r = s.execute("profile.import", &json!({"paths": [files.join("profiles").to_string_lossy()]})).unwrap(); + assert_eq!(r["imported"].as_array().unwrap().len(), 1, "{r}"); + assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}"); + dcp_id = r["imported"][0]["id"].as_str().unwrap().to_string(); + assert!(dcp_id.starts_with("dcp:")); + assert_eq!(r["imported"][0]["cameraModel"], "LightCraft Test Camera"); + // importing it again adds nothing + let again = s.execute("profile.import", &json!({"paths": [files.join("profiles").join("Swap.dcp").to_string_lossy()]})).unwrap(); + assert_eq!(again["imported"][0]["existing"], true); + assert_eq!(s.dcp_profiles.len(), 1); + // the library keeps its own copy + assert!(std::path::Path::new(&s.dcp_profiles[0].file).starts_with(&lib)); + // listed in the profile menu under Camera Profiles + let menu = s.profile_menu(); + let group = menu["groups"].as_array().unwrap().iter().find(|g| g["name"] == "Camera Profiles").expect("a Camera Profiles group"); + assert_eq!(group["profiles"][0]["id"], dcp_id.as_str()); + // develop the photo with it: a decode made without it doesn't stand in + let before = s.render_job(id, 48, 48, false, true).unwrap().run(); + let loaded = before.loaded.clone().expect("decoded from the file"); + assert!(loaded.camera_profile.is_none()); + s.media.insert(id, before.level, loaded.image.clone()); + assert!(matches!(s.render_job(id, 48, 48, false, true).unwrap().source, SourceRef::Loaded(_)), "cached while nothing changed"); + s.execute("develop.profile", &json!({"id": dcp_id})).unwrap(); + let job = s.render_job(id, 48, 48, false, true).unwrap(); + match &job.source { + SourceRef::File { camera_profile: Some((pid, _)), .. } => assert_eq!(pid, &dcp_id), + _ => panic!("the photo is decoded again with its camera profile"), + } + let after = job.run(); + assert_eq!(after.loaded.as_ref().and_then(|l| l.camera_profile.clone()).as_deref(), Some(dcp_id.as_str())); + assert!(after.rendered.is_ok()); + assert_ne!(mean_rgb(&before.loaded.unwrap().image), mean_rgb(&after.loaded.unwrap().image)); + s.persist().unwrap(); + s.close_library().unwrap(); + } + // reopened: the profile is there and decodes again + let mut s = Session::new().with_fs(); + s.open_library(&lib, false).unwrap(); + assert_eq!(s.dcp_profiles.len(), 1); + assert!(s.media.camera_profiles.contains_key(&dcp_id)); + assert_eq!(s.catalog.photo(id).unwrap().develop.profile.id, dcp_id); + assert_eq!(s.profile_info(&dcp_id).map(|(_, g)| g), Some("Camera Profiles")); + // deleted: photos using it develop with their file's own colour, the library's copy goes + let file = s.dcp_profiles[0].file.clone(); + s.execute("profile.deleteImported", &json!({"id": dcp_id})).unwrap(); + assert!(s.dcp_profiles.is_empty() && !std::path::Path::new(&file).exists()); + let p = s.catalog.photo(id).unwrap().clone(); + assert!(s.media.camera_profile_of(&p).is_none()); + assert!(s.execute("develop.profile", &json!({"id": dcp_id})).is_err(), "no longer a known profile"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests_import.rs b/crates/engine/src/tests_import.rs index 185993494a..d8e6b4df15 100644 --- a/crates/engine/src/tests_import.rs +++ b/crates/engine/src/tests_import.rs @@ -1280,9 +1280,9 @@ fn look_loader( tone: lightcraft_pipeline::tone::CameraTone, calls: std::sync::Arc, ) -> crate::media::FileLoader { - std::sync::Arc::new(move |path, max_edge| { + std::sync::Arc::new(move |path, max_edge, dcp| { calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let (img, mut info) = plain(path, max_edge)?; + let (img, mut info) = plain(path, max_edge, dcp)?; info.camera_tone = Some(tone); Ok((img, info)) }) diff --git a/crates/raw/src/dcp.rs b/crates/raw/src/dcp.rs new file mode 100644 index 0000000000..0f2aa95fe9 --- /dev/null +++ b/crates/raw/src/dcp.rs @@ -0,0 +1,278 @@ +//! DNG Camera Profiles (`.dcp`): the user's own camera colour profiles, read at run time from +//! files they supply (DNG specification, chapter 6 "Camera Profiles"). A `.dcp` is a TIFF-structured +//! file whose header carries the magic `RC` (0x4352) in place of 42, with the profile tags in IFD 0: +//! `UniqueCameraModel`, `ProfileName`, the colour/forward matrices and calibration illuminants, the +//! hue/saturation map, look table and tone curve. Nothing here ships a profile. + +use lightcraft_tiff::{Ifd, ParseOptions, Tiff, tags as t}; + +use crate::ColorData; +use crate::dng::color_data; + +/// The magic number of a DNG camera profile file (`IIRC` / `MMCR`). +pub const DCP_MAGIC: u16 = 0x4352; + +/// A parsed camera profile. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct DcpProfile { + /// `ProfileName` (empty when the file has none). + pub name: String, + /// `UniqueCameraModel`: the camera the profile was made for (empty when absent). + pub camera_model: String, + /// The colour model: illuminants, matrices and the profile look (hue/sat map, look table, tone curve). + pub color: ColorData, +} + +impl DcpProfile { + /// `color` (a raw file's own colour facts) with this profile's colour model in place of the + /// file's: its matrices, illuminants and look. The file's white balance (as-shot neutral or + /// white), analog balance and baseline exposure stay, plus its camera calibration when the + /// profile has the same calibration illuminants (DNG 6.3: calibration belongs to the camera, + /// the profile to the look). + pub fn applied_to(&self, color: &ColorData) -> ColorData { + let calibration = if self.color.illuminant == color.illuminant { color.camera_calibration } else { [None, None] }; + ColorData { + illuminant: self.color.illuminant, + color_matrix: self.color.color_matrix, + forward_matrix: self.color.forward_matrix, + camera_calibration: calibration, + analog_balance: color.analog_balance, + as_shot_neutral: color.as_shot_neutral, + as_shot_white_xy: color.as_shot_white_xy, + baseline_exposure: color.baseline_exposure + self.color.baseline_exposure, + baseline_sharpness: color.baseline_sharpness, + profile: crate::profile::ProfileLook { gain_table_map: color.profile.gain_table_map.clone(), ..self.color.profile.clone() }, + } + } +} + +/// Errors reading a `.dcp`. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum DcpError { + #[error("not a DNG camera profile (.dcp)")] + NotDcp, + #[error("damaged camera profile: {0}")] + Damaged(String), + #[error("the camera profile has no usable colour matrix")] + NoMatrix, +} + +/// Is `bytes` a DCP file (by its header)? +pub fn is_dcp(bytes: &[u8]) -> bool { + matches!(bytes.get(0..4), Some([b'I', b'I', b'R', b'C'] | [b'M', b'M', b'C', b'R'])) +} + +/// Parse a `.dcp` file. Files above 64 MiB are refused (real profiles are kilobytes to a few MB). +pub fn parse_dcp(bytes: &[u8]) -> Result { + if !is_dcp(bytes) { + return Err(DcpError::NotDcp); + } + if bytes.len() > 64 << 20 { + return Err(DcpError::Damaged("larger than 64 MiB".into())); + } + // the TIFF reader only knows 42 / BigTIFF / raw magics: give it a header with 42 in place of RC + let mut data = bytes.to_vec(); + let forty_two: [u8; 2] = if bytes.first() == Some(&b'I') { [42, 0] } else { [0, 42] }; + if let Some(m) = data.get_mut(2..4) { + m.copy_from_slice(&forty_two); + } + let opts = ParseOptions { follow_children: false, max_ifds: 4, value_budget: Some(64 << 20), ..Default::default() }; + let tiff = Tiff::parse_with(&data, &opts).map_err(|e| DcpError::Damaged(e.to_string()))?; + let ifd: &Ifd = tiff.ifds.first().ok_or_else(|| DcpError::Damaged("no IFD".into()))?; + let mut color = color_data(ifd, ifd, tiff.order); + // a profile carries no white balance or calibration of a particular shot + color.as_shot_neutral = None; + color.as_shot_white_xy = None; + color.analog_balance = None; + color.camera_calibration = [None, None]; + color.baseline_sharpness = None; + color.profile.gain_table_map = None; + // only BaselineExposureOffset belongs to a profile (BaselineExposure is the camera's) + color.baseline_exposure = + ifd.f64s(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-4.0, 4.0); + // a single-illuminant profile names one illuminant; its second matrix slot stays empty + if color.color_matrix[0].is_none() { + // the first slot is the one every profile must fill (DNG: ColorMatrix1 is required) + return Err(DcpError::NoMatrix); + } + let text = |tag: u16| ifd.string(tag).map(|s| s.trim_matches(char::from(0)).trim().to_string()).unwrap_or_default(); + Ok(DcpProfile { name: text(t::PROFILE_NAME), camera_model: text(t::UNIQUE_CAMERA_MODEL), color }) +} + +/// Write `p` as a `.dcp` file (little-endian): its name, camera, illuminants, matrices, hue/saturation +/// map, look table, tone curve and baseline exposure offset. +pub fn write_dcp(p: &DcpProfile) -> Result, DcpError> { + use lightcraft_tiff::writer::srational; + use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + let c = &p.color; + let mut ifd = IfdBuilder::new(); + ifd.set(t::UNIQUE_CAMERA_MODEL, Value::Ascii(p.camera_model.clone())); + ifd.set(t::PROFILE_NAME, Value::Ascii(p.name.clone())); + let mat = |m: &lightcraft_color::Mat3| Value::SRational(m.0.iter().flatten().map(|v| srational(*v)).collect()); + for i in 0..2 { + if let Some(m) = &c.color_matrix[i] { + ifd.set([t::CALIBRATION_ILLUMINANT_1, t::CALIBRATION_ILLUMINANT_2][i], Value::Short(vec![c.illuminant[i]])); + ifd.set([t::COLOR_MATRIX_1, t::COLOR_MATRIX_2][i], mat(m)); + } + if let Some(m) = &c.forward_matrix[i] { + ifd.set([t::FORWARD_MATRIX_1, t::FORWARD_MATRIX_2][i], mat(m)); + } + } + let flat = |table: &crate::profile::HsvTable| Value::Float(table.data.iter().flatten().copied().collect()); + let dims = + |table: &crate::profile::HsvTable| Value::Long(vec![table.hue_divisions as u32, table.sat_divisions as u32, table.val_divisions as u32]); + if let Some(a) = c.profile.hue_sat_map[0].as_ref() { + ifd.set(t::PROFILE_HUE_SAT_MAP_DIMS, dims(a)); + ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_1, flat(a)); + if a.srgb_value { + ifd.set(t::PROFILE_HUE_SAT_MAP_ENCODING, Value::Long(vec![1])); + } + if let Some(b) = c.profile.hue_sat_map[1] + .as_ref() + .filter(|b| (b.hue_divisions, b.sat_divisions, b.val_divisions) == (a.hue_divisions, a.sat_divisions, a.val_divisions)) + { + ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_2, flat(b)); + } + } + if let Some(l) = &c.profile.look_table { + ifd.set(t::PROFILE_LOOK_TABLE_DIMS, dims(l)); + ifd.set(t::PROFILE_LOOK_TABLE_DATA, flat(l)); + if l.srgb_value { + ifd.set(t::PROFILE_LOOK_TABLE_ENCODING, Value::Long(vec![1])); + } + } + if let Some(tc) = &c.profile.tone_curve { + ifd.set(t::PROFILE_TONE_CURVE, Value::Float(tc.points.iter().flatten().copied().collect())); + } + if c.baseline_exposure != 0.0 { + ifd.set(t::BASELINE_EXPOSURE_OFFSET, Value::SRational(vec![srational(c.baseline_exposure)])); + } + let mut out = TiffWriter::new(ByteOrder::Little, false).write(&[ifd]).map_err(|e| DcpError::Damaged(e.to_string()))?; + // the DCP magic in place of 42 + if let Some(m) = out.get_mut(2..4) { + m.copy_from_slice(&DCP_MAGIC.to_le_bytes()); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A minimal single-illuminant profile (our own numbers) built in memory: no profile file is + /// committed to the repository. + pub(crate) fn synthetic_dcp(little: bool, with_hue_sat: bool) -> Vec { + // entries: (tag, type, count, payload bytes) + let mut entries: Vec<(u16, u16, u32, Vec)> = Vec::new(); + let u16b = |v: u16| if little { v.to_le_bytes().to_vec() } else { v.to_be_bytes().to_vec() }; + let u32b = |v: u32| if little { v.to_le_bytes().to_vec() } else { v.to_be_bytes().to_vec() }; + let srat = |v: f64| { + let (n, d) = ((v * 10000.0).round() as i32, 10000i32); + let mut b = if little { n.to_le_bytes().to_vec() } else { n.to_be_bytes().to_vec() }; + b.extend(if little { d.to_le_bytes() } else { d.to_be_bytes() }); + b + }; + let ascii = |s: &str| { + let mut b = s.as_bytes().to_vec(); + b.push(0); + b + }; + entries.push((t::UNIQUE_CAMERA_MODEL, 2, 13, ascii("Test Camera1"))); + let m = [0.9, -0.3, -0.05, -0.4, 1.2, 0.2, -0.05, 0.15, 0.7]; + entries.push((t::COLOR_MATRIX_1, 10, 9, m.iter().flat_map(|v| srat(*v)).collect())); + entries.push((t::CALIBRATION_ILLUMINANT_1, 3, 1, [u16b(21), vec![0, 0]].concat())); + entries.push((t::PROFILE_NAME, 2, 9, ascii("My Look"))); + if with_hue_sat { + // 2 hues × 2 sats × 1 value: hue shift, sat scale, value scale per entry (FLOAT) + entries.push((t::PROFILE_HUE_SAT_MAP_DIMS, 4, 3, [u32b(2), u32b(2), u32b(1)].concat())); + let f = |v: f32| if little { v.to_le_bytes().to_vec() } else { v.to_be_bytes().to_vec() }; + entries.push(( + t::PROFILE_HUE_SAT_MAP_DATA_1, + 11, + 12, + [f(0.0), f(1.0), f(1.0), f(5.0), f(1.1), f(1.0), f(0.0), f(1.0), f(1.0), f(-5.0), f(0.9), f(1.0)].concat(), + )); + } + entries.sort_by_key(|e| e.0); + let mut out = if little { b"IIRC".to_vec() } else { b"MMCR".to_vec() }; + out.extend(u32b(8)); + let n = entries.len(); + let mut data_off = 8 + 2 + n * 12 + 4; + let mut ifd = u16b(n as u16); + let mut tail = Vec::new(); + for (tag, ty, count, payload) in &entries { + ifd.extend(u16b(*tag)); + ifd.extend(u16b(*ty)); + ifd.extend(u32b(*count)); + if payload.len() <= 4 { + let mut p = payload.clone(); + p.resize(4, 0); + ifd.extend(p); + } else { + ifd.extend(u32b(data_off as u32)); + tail.extend(payload); + data_off += payload.len(); + if data_off % 2 == 1 { + tail.push(0); + data_off += 1; + } + } + } + ifd.extend(u32b(0)); + out.extend(ifd); + out.extend(tail); + out + } + + #[test] + fn reads_a_single_illuminant_profile_in_both_byte_orders() { + for little in [true, false] { + let p = parse_dcp(&synthetic_dcp(little, true)).unwrap(); + assert_eq!(p.name, "My Look"); + assert_eq!(p.camera_model, "Test Camera1"); + assert_eq!(p.color.illuminant, [21, 0]); + let m = p.color.color_matrix[0].unwrap(); + assert!((m.0[1][1] - 1.2).abs() < 1e-4, "{m:?}"); + assert!(p.color.color_matrix[1].is_none()); + assert!(p.color.profile.hue_sat_map[0].is_some()); + assert!(p.color.as_shot_neutral.is_none()); + } + assert!(parse_dcp(&synthetic_dcp(true, false)).unwrap().color.profile.hue_sat_map[0].is_none()); + } + + #[test] + fn rejects_other_files_and_damage_without_panicking() { + assert_eq!(parse_dcp(b"II*\0\x08\0\0\0"), Err(DcpError::NotDcp)); + assert_eq!(parse_dcp(b""), Err(DcpError::NotDcp)); + let good = synthetic_dcp(true, true); + for cut in [4, 8, 10, 30, good.len() / 2, good.len() - 1] { + let _ = parse_dcp(&good[..cut]); + } + let mut bad = good.clone(); + bad[4..8].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(parse_dcp(&bad).is_err()); + } + + #[test] + fn written_profiles_read_back() { + let p = parse_dcp(&synthetic_dcp(false, true)).unwrap(); + let back = parse_dcp(&write_dcp(&p).unwrap()).unwrap(); + assert_eq!(back.name, p.name); + assert_eq!(back.camera_model, p.camera_model); + assert_eq!(back.color.illuminant, p.color.illuminant); + assert_eq!(back.color.profile.hue_sat_map, p.color.profile.hue_sat_map); + let (a, b) = (back.color.color_matrix[0].unwrap(), p.color.color_matrix[0].unwrap()); + assert!(a.0.iter().flatten().zip(b.0.iter().flatten()).all(|(x, y)| (x - y).abs() < 1e-6)); + } + + #[test] + fn applying_keeps_the_shot_and_replaces_the_look() { + let p = parse_dcp(&synthetic_dcp(true, true)).unwrap(); + let file = ColorData { as_shot_neutral: Some([0.5, 1.0, 0.7]), baseline_exposure: 0.25, ..Default::default() }; + let c = p.applied_to(&file); + assert_eq!(c.as_shot_neutral, Some([0.5, 1.0, 0.7])); + assert_eq!(c.color_matrix, p.color.color_matrix); + assert!(c.profile.hue_sat_map[0].is_some()); + assert!((c.baseline_exposure - 0.25).abs() < 1e-12); + } +} diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index 8a09a9edb4..6e3a6fa840 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -27,6 +27,7 @@ mod binned; pub mod color; +pub mod dcp; pub mod demosaic; mod dng; pub mod dngwrite; diff --git a/crates/ui-egui/examples/thumb_request_bench.rs b/crates/ui-egui/examples/thumb_request_bench.rs index 675c920d52..75bf04532a 100644 --- a/crates/ui-egui/examples/thumb_request_bench.rs +++ b/crates/ui-egui/examples/thumb_request_bench.rs @@ -157,7 +157,7 @@ fn verify_texture(h: &Headless, id: PhotoId) { let edge = tex.size[0].max(tex.size[1]); assert!([128, 256, 384, 512].contains(&edge), "thumbnail must use a supported size bucket"); let Source::File { path } = &p.source else { unreachable!() }; - let (source, info) = h.app.session.media.file_loader.as_ref().unwrap()(path, 512).unwrap(); + let (source, info) = h.app.session.media.file_loader.as_ref().unwrap()(path, 512, None).unwrap(); println!("decode,path={path},raw={},preview_only={:?}", info.raw, p.preview_only); if std::env::var_os("REQUIRE_RAW").is_some() { assert!(p.preview_only.is_none(), "embedded-preview fallback does not validate RAW decoding"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9a387c77cd..767b40a7fb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1385,7 +1385,7 @@ pub fn is_model_file(path: &str) -> bool { /// Files dropped on the window that are presets rather than photos. pub fn is_preset_file(path: &str) -> bool { let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); - ["lcpreset", "lrtemplate", "xmp", "zip", "cube", "lmp", "mplumpack"].contains(&ext.as_str()) + ["lcpreset", "lrtemplate", "xmp", "zip", "cube", "dcp", "lmp", "mplumpack"].contains(&ext.as_str()) } /// Splits dropped files into presets and everything else. An `.xmp` dropped next to a photo with the same diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index daf0f08e0e..ad344de5aa 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1513,12 +1513,12 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option = paths .iter() .filter(|p| { let l = p.to_ascii_lowercase(); - l.ends_with(".cube") || l.ends_with(".zip") || std::path::Path::new(p.as_str()).is_dir() + l.ends_with(".cube") || l.ends_with(".dcp") || l.ends_with(".zip") || std::path::Path::new(p.as_str()).is_dir() }) .collect(); // one toast for both halves (a second toast would replace the first) @@ -1550,7 +1550,14 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option = paths.iter().filter(|p| !p.to_ascii_lowercase().ends_with(".cube")).collect(); + // (.dcp camera profiles went to profile.import above) + let preset_paths: Vec<&String> = paths + .iter() + .filter(|p| { + let l = p.to_ascii_lowercase(); + !l.ends_with(".cube") && !l.ends_with(".dcp") + }) + .collect(); let r = if preset_paths.is_empty() { Ok(json!({"imported": [], "failed": [], "skipped": 0})) } else { diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index ed2ee46359..46530d5f16 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -443,16 +443,20 @@ fn profile_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings) }); register(ui.ctx(), format!("profileMenu:groupMenu:{g}"), r.response.rect); } - // imported LUT profile groups - let mut lut_groups: Vec = app.session.lut_profiles.iter().map(|p| p.group.clone()).collect(); - lut_groups.sort_unstable(); - lut_groups.dedup(); + // imported profile groups: LUT folders, then camera profiles + let imported = app.session.imported_profiles(); + let mut lut_groups: Vec = Vec::new(); + for (_, _, g) in &imported { + if !lut_groups.contains(g) { + lut_groups.push(g.clone()); + } + } for g in &lut_groups { // a folder's name as it is, and its own widget id even when it matches a built-in group let r = ui.menu_button(g.as_str(), |ui| { ui.set_min_width(170.0); - for p in app.session.lut_profiles.iter().filter(|p| &p.group == g) { - item(ui, "group", &p.id, &p.name, &mut pick); + for (id, name, _) in imported.iter().filter(|p| &p.2 == g) { + item(ui, "group", id, name, &mut pick); } }); register(ui.ctx(), format!("profileMenu:lutGroupMenu:{g}"), r.response.rect); diff --git a/crates/ui-egui/src/panels/profiles.rs b/crates/ui-egui/src/panels/profiles.rs index 6294d1e64c..b72ce4fe6d 100644 --- a/crates/ui-egui/src/panels/profiles.rs +++ b/crates/ui-egui/src/panels/profiles.rs @@ -66,12 +66,16 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { PROFILES.iter().filter(|p| p.group == g).map(|p| (p.id.to_string(), p.name.to_string(), p.group.to_string())).collect(), )); } - // imported LUT profile groups - let mut lut_groups: Vec = app.session.lut_profiles.iter().map(|p| p.group.clone()).collect(); - lut_groups.sort_unstable(); - lut_groups.dedup(); + // imported profile groups: LUT folders, then camera profiles + let imported = app.session.imported_profiles(); + let mut lut_groups: Vec = Vec::new(); + for (_, _, g) in &imported { + if !lut_groups.contains(g) { + lut_groups.push(g.clone()); + } + } for g in &lut_groups { - let profiles = app.session.lut_profiles.iter().filter(|p| &p.group == g).map(|p| (p.id.clone(), p.name.clone(), p.group.clone())).collect(); + let profiles = imported.iter().filter(|p| &p.2 == g).cloned().collect(); sections.push((g.as_str(), "", true, profiles)); } for (title, tag, imported, list) in sections { diff --git a/crates/ui-egui/src/pick.rs b/crates/ui-egui/src/pick.rs index 1032a5cd98..90c3087110 100644 --- a/crates/ui-egui/src/pick.rs +++ b/crates/ui-egui/src/pick.rs @@ -58,7 +58,7 @@ impl PickRequest { } /// What File ▸ Import Profiles & Presets… opens. -pub const PRESET_EXTENSIONS: &[&str] = &["lcpreset", "xmp", "lrtemplate", "zip", "dng", "lmp", "mplumpack", "cube"]; +pub const PRESET_EXTENSIONS: &[&str] = &["lcpreset", "xmp", "lrtemplate", "zip", "dng", "lmp", "mplumpack", "cube", "dcp"]; /// What Import Point Curve Presets… opens. pub const CURVE_PRESET_EXTENSIONS: &[&str] = &["lccurve", "json"]; diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rs index 66bce01ffb..e7fcb4a03a 100644 --- a/crates/ui-egui/src/render.rs +++ b/crates/ui-egui/src/render.rs @@ -972,7 +972,7 @@ mod thumbnail_tests { fixture_with(Session::new(), (*photo()).clone()) } fn fixture_with(mut s: Session, photo: Photo) -> (crate::LightcraftApp, std::rc::Rc>, egui::Context) { - s.media.file_loader = Some(Arc::new(|_, _| { + s.media.file_loader = Some(Arc::new(|_, _, _| { let mut image = lightcraft_raster::Rgb32f::new(8, 8); image.data.fill([0.3, 0.2, 0.1]); Ok((image, Default::default())) @@ -1171,7 +1171,7 @@ mod thumbnail_tests { let photo = app.session.catalog.photo(PhotoId(1)).unwrap().as_ref().clone(); app.session = lightcraft_engine::Session::new(); app.session.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); - app.session.media.file_loader = Some(Arc::new(|_, _| { + app.session.media.file_loader = Some(Arc::new(|_, _, _| { let mut image = lightcraft_raster::Rgb32f::new(8, 8); image.data.fill([0.1, 0.2, 0.9]); Ok((image, Default::default())) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 79c66b69c6..a4e2dc42a4 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** major (created; formats measured from the code and the target's Info.plist) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (LR-PROF-IMPORT: the user's own `.dcp` camera profiles import) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 Every format Lightroom reads or writes, with our support, fidelity and tests. Camera raw formats are deep enough to have their own document: [raw-parity.md](raw-parity.md). @@ -48,7 +48,7 @@ import and export formats. Ours come from `crates/codecs/src/sniff.rs`, `crates/ | EXIF / IPTC / XMP embedded on export | ✅ | ✅ with metadata filters | `crates/meta` | | Develop presets `.xmp` | ✅ | ✅ import (mapping of supported settings) | | | Legacy presets `.lrtemplate` | ✅ (converted) | ✅ import | | -| Camera / creative profiles (`.dcp`, `.xmp` profiles) | ✅ | ⬜ deliberately (Adobe profile formats are never used); `.cube` LUT profiles ✅ | | +| Camera / creative profiles (`.dcp`, `.xmp` profiles) | ✅ | 🟡 the user's own `.dcp` camera profiles import (`profile.import`) and replace a raw file's colour model; none ship with the app; `.xmp` profiles ⬜; `.cube` LUT profiles ✅ | | | Lens profiles `.lcp` | ✅ | ⬜ deliberately | | | Other apps' presets | — | ✅ Luminar `.lmp` / `.mplumpack`, `.zip` bundles | beyond target | | Lightroom Classic catalog `.lrcat` | native | 🟡 import (ratings, flags, labels, keywords, collections, virtual copies, supported develop settings; read-only pure-Rust SQLite incl. WAL) | [lightroom-catalog-import.md](lightroom-catalog-import.md) | @@ -75,5 +75,6 @@ Remaining: **26–47 h** (AVIF decode 8–15 h if a permissive decoder is writte | Date | Change | Summary | |---|---|---| +| 2026-10-12 | minor | LR-PROF-IMPORT: the user's own DNG camera profiles (`.dcp`) import as camera profiles; none ship | | 2026-10-10 | major | Created from the code and the installed Lightroom's document types | | 2026-10-10 | minor | JPEG XL export (#247): JXL write ✅ (native only), PQ JPEG XL HDR | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 77ae26e4c5..aa66fc6284 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (rapid slider entry; LR-PROF-CAMERACOLOR: tone curve from black-and-white camera JPEGs; LR-VIEW-ZOOM, LR-VIEW-COMPARE: Compare and Reference zoom windows; LR-IMP-FORMATS, LR-IMP-CAMERA-COVERAGE: EOS R5 Mark II CR3 decodes; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md; filesystem history retry/Undo/Redo evidence; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (LR-PROF-IMPORT: the user's own `.dcp` camera profiles import; rapid slider entry; LR-PROF-CAMERACOLOR: tone curve from black-and-white camera JPEGs; LR-VIEW-ZOOM, LR-VIEW-COMPARE: Compare and Reference zoom windows; LR-IMP-FORMATS, LR-IMP-CAMERA-COVERAGE: EOS R5 Mark II CR3 decodes; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md; filesystem history retry/Undo/Redo evidence; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -53,9 +53,9 @@ cited here still exists. Formerly docs/parity.md. | Y. Menus | 84 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 76 | 3 | 3 | 1 | 49/52 (94%) | 23/24 (96%) | | Lightroom Classic extras | 34 | 16 | 35 | 8 | — | 24/26 (92%) | -| **Total** | 407 | 50 | 73 | 35 | 192/200 (96%) | 145/157 (92%) | +| **Total** | 408 | 51 | 72 | 35 | 193/201 (96%) | 145/157 (92%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **81.5%** of 530 in-scope rows — P0 98.0% of 200 · P1 95.2% of 157 · P2 49.7% of 172. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **81.6%** of 531 in-scope rows — P0 98.0% of 201 · P1 95.2% of 157 · P2 50.0% of 172. ## Top gaps and shortcut notes @@ -234,12 +234,12 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-PROF-ADOBE | Standard raw looks (own equivalents) | P0 | ✅ | `crates/engine/src/presets.rs` (`PROFILES`), `crates/pipeline/src/profiles.rs` | six own looks: Color, Neutral, Vivid, Landscape, Portrait, Monochrome | | LR-PROF-ADAPTIVE | Adaptive profiles | P2 | ⬜ | | | | LR-PROF-CAMERA | Camera-matching looks | P2 | ⬜ | | | -| LR-PROF-CAMERACOLOR | Camera colour calibration (own) | P0 | 🟡 | `crates/raw/src/color.rs`, `crates/raw/src/profile.rs`, `crates/raw/src/gaintable.rs`, `crates/engine/src/camera_preview.rs` | DNG files use the colour matrices and the camera-profile look they carry (`ProfileHueSatMap`, `ProfileLookTable`, `ProfileToneCurve`, read from the file at run time per DNG spec ch. 6 — Lightroom-converted DNGs rendered flat and muted without them, issue #138). A DNG's `ProfileGainTableMap` / `ProfileGainTableMap2` (Apple ProRAW's local tone map; both versions, DNG 1.7 precedence, the file's byte order with a big-endian fallback) is read and written back by DNG export and not rendered by default, as Lightroom Classic renders ProRAW without it (measured on one CC0 iPhone 12 Pro ProRAW); the Profile option "Camera local tone mapping" (`profile.camera_local_tone`, per photo, off by default, `crates/pipeline/src/local_tone.rs`) renders it as the camera does, per output pixel in the scene-linear stage (CPU, also under the GPU path); Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3 and CR2, Pentax PEF, Samsung SRW and Olympus ORF get a guarded file-local fit to their own embedded JPEG — chromaticity matrix + hue/saturation/value table + tone and chroma curves, relative WB — or, with a bundled or local per-model profile pooled from many photos (`lightcraft-cli calibrate`, ARW, NEF and RAF so far, `crates/engine/src/camera_profiles.rs`), the profile's colour and only their own tone/chroma curves (on 29 held-out ILCE-7M4 photos mean ΔE vs the camera JPEG 3.54 → 3.10; bundled ILCE-7CR from 125 photos: 26 held-out 4.07 → 3.29, and every one of the 131 photos accepted, 8 of which fell back to neutral without it), kept with smart previews (see docs/camera-preview-colour.md); Sony ARWs shot with DRO on (maker note `0xb025`, on by default) keep that colour but their tone curve is lowered to Sony's curve without DRO, whose lifted shadows are in the camera JPEG only (issue #244: 8 ILCE-7CR photos +6.4 → +0.8 L* from Lightroom's default, median ΔE 7.5 → 3.3); 52 models without a profile whose JPEG fit fails (or that have no usable JPEG) start from DNG-style matrices fitted to their measured spectral sensitivities instead of the neutral fallback (`crates/raw/src/spectral.rs`, rawtoaces-data v1.1.0, Apache-2.0, aliases included; not yet measured against the camera JPEG); ARW: on 10 public raw.pixls.us samples from 8 bodies 7 fits were accepted, mean ΔE vs the camera JPEG 17–26 → 3–10; NEF: 13 of 13 decodable samples (D750, D780, D850, D7500, Z 50 and local D7500 shots) accepted, ΔE 13–46 → 3–8 (issue #150); RW2 / RWL: 140 of 174 public samples accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 with matching lightness (13 of the 14 corpus files with a preview: ΔE 9.6–27 → 2.8–8.9; most rejections are compacts and kit zooms whose camera JPEG is distortion-corrected); a fit that fails the gates on all pixels is retried away from edges, where a lens-corrected camera JPEG still lines up (issue #232: the six distortion-corrected public ILCE-7RM2 samples ΔE 16.6–16.9 → 3.7–3.8, the corpus GX80 19.1 → 7.9); RAF: bundled X-H2S/X-T4 profiles from 201/545 photos; on 150 withheld files mean ΔE improves slightly over per-file fitting (X-H2S 1.70 → 1.62, X-T4 2.43 → 2.34); 23 of 24 references from 13 bodies accepted, including the dark X-H2S samples (8.74 → 2.25); ORF: the 3 decodable corpus files (E-1, E-400, XZ-2) accepted (`docs/camera-preview-colour.md`); a raw whose camera JPEG is black and white (a monochrome picture style) takes only the JPEG's tone curve, on the camera profile's, spectral or neutral colour (issue #577); this is not measured camera calibration; other raws and rejected fits use a neutral fallback (camera RGB ≈ linear sRGB, `matrix_is_fallback`) with as-shot white balance, so colours are muted and not accurate. Needs our own per-camera calibration: matrices the files carry themselves (e.g. Olympus `ColorMatrix`), fitting each camera to its own embedded JPEG, then chart shots. Adobe matrices / DCPs are never used. Biggest image-quality gap today | +| LR-PROF-CAMERACOLOR | Camera colour calibration (own) | P0 | 🟡 | `crates/raw/src/color.rs`, `crates/raw/src/profile.rs`, `crates/raw/src/gaintable.rs`, `crates/engine/src/camera_preview.rs` | DNG files use the colour matrices and the camera-profile look they carry (`ProfileHueSatMap`, `ProfileLookTable`, `ProfileToneCurve`, read from the file at run time per DNG spec ch. 6 — Lightroom-converted DNGs rendered flat and muted without them, issue #138). A DNG's `ProfileGainTableMap` / `ProfileGainTableMap2` (Apple ProRAW's local tone map; both versions, DNG 1.7 precedence, the file's byte order with a big-endian fallback) is read and written back by DNG export and not rendered by default, as Lightroom Classic renders ProRAW without it (measured on one CC0 iPhone 12 Pro ProRAW); the Profile option "Camera local tone mapping" (`profile.camera_local_tone`, per photo, off by default, `crates/pipeline/src/local_tone.rs`) renders it as the camera does, per output pixel in the scene-linear stage (CPU, also under the GPU path); Sony ARW, Nikon NEF, Panasonic RW2, Fujifilm RAF, Canon CR3 and CR2, Pentax PEF, Samsung SRW and Olympus ORF get a guarded file-local fit to their own embedded JPEG — chromaticity matrix + hue/saturation/value table + tone and chroma curves, relative WB — or, with a bundled or local per-model profile pooled from many photos (`lightcraft-cli calibrate`, ARW, NEF and RAF so far, `crates/engine/src/camera_profiles.rs`), the profile's colour and only their own tone/chroma curves (on 29 held-out ILCE-7M4 photos mean ΔE vs the camera JPEG 3.54 → 3.10; bundled ILCE-7CR from 125 photos: 26 held-out 4.07 → 3.29, and every one of the 131 photos accepted, 8 of which fell back to neutral without it), kept with smart previews (see docs/camera-preview-colour.md); Sony ARWs shot with DRO on (maker note `0xb025`, on by default) keep that colour but their tone curve is lowered to Sony's curve without DRO, whose lifted shadows are in the camera JPEG only (issue #244: 8 ILCE-7CR photos +6.4 → +0.8 L* from Lightroom's default, median ΔE 7.5 → 3.3); 52 models without a profile whose JPEG fit fails (or that have no usable JPEG) start from DNG-style matrices fitted to their measured spectral sensitivities instead of the neutral fallback (`crates/raw/src/spectral.rs`, rawtoaces-data v1.1.0, Apache-2.0, aliases included; not yet measured against the camera JPEG); ARW: on 10 public raw.pixls.us samples from 8 bodies 7 fits were accepted, mean ΔE vs the camera JPEG 17–26 → 3–10; NEF: 13 of 13 decodable samples (D750, D780, D850, D7500, Z 50 and local D7500 shots) accepted, ΔE 13–46 → 3–8 (issue #150); RW2 / RWL: 140 of 174 public samples accepted, from 93 of the 114 bodies with a preview, median ΔE 5.0 with matching lightness (13 of the 14 corpus files with a preview: ΔE 9.6–27 → 2.8–8.9; most rejections are compacts and kit zooms whose camera JPEG is distortion-corrected); a fit that fails the gates on all pixels is retried away from edges, where a lens-corrected camera JPEG still lines up (issue #232: the six distortion-corrected public ILCE-7RM2 samples ΔE 16.6–16.9 → 3.7–3.8, the corpus GX80 19.1 → 7.9); RAF: bundled X-H2S/X-T4 profiles from 201/545 photos; on 150 withheld files mean ΔE improves slightly over per-file fitting (X-H2S 1.70 → 1.62, X-T4 2.43 → 2.34); 23 of 24 references from 13 bodies accepted, including the dark X-H2S samples (8.74 → 2.25); ORF: the 3 decodable corpus files (E-1, E-400, XZ-2) accepted (`docs/camera-preview-colour.md`); a raw whose camera JPEG is black and white (a monochrome picture style) takes only the JPEG's tone curve, on the camera profile's, spectral or neutral colour (issue #577); this is not measured camera calibration; other raws and rejected fits use a neutral fallback (camera RGB ≈ linear sRGB, `matrix_is_fallback`) with as-shot white balance, so colours are muted and not accurate. Needs our own per-camera calibration: matrices the files carry themselves (e.g. Olympus `ColorMatrix`), fitting each camera to its own embedded JPEG, then chart shots. Adobe's matrices / DCPs are never shipped or used (a user can import their own `.dcp`, LR-PROF-IMPORT). Biggest image-quality gap today | | LR-PROF-CREATIVE | Creative profiles (own) | P2 | ✅ | `cmd:develop.profile`, `crates/pipeline/src/profiles.rs` | 16 own looks in Film / Cinematic / Muted / B&W (tone + point-curve fades, colour grading, mixer / B&W mix); scale with `ctl:profile.amount`; sliders untouched | | LR-PROF-LEGACY | Legacy profiles | P2 | ⬜ | | | | LR-PROF-NONRAW | Profiles for non-raw files | P0 | ✅ | `cmd:develop.profile` | same looks apply to JPEG/TIFF | | LR-PROF-AMOUNT | Profile amount | P1 | ✅ | `ctl:profile.amount` | | -| LR-PROF-IMPORT | Import profiles | P1 | ✅ | `cmd:profile.import`, `cmd:profile.deleteImported`, `crates/pipeline/src/lut.rs`, `crates/engine/src/cmd/lut_profiles.rs`, `crates/ui-egui/src/panels/edit.rs`, `crates/ui-egui/src/panels/profiles.rs` | `.cube` 3D LUTs (files, folders, zips) become creative profiles with Amount, grouped in the profile browser, kept with the library; rendered on the CPU; Adobe profile formats deliberately unsupported | +| LR-PROF-IMPORT | Import profiles | P1 | ✅ | `cmd:profile.import`, `cmd:profile.deleteImported`, `crates/pipeline/src/lut.rs`, `crates/engine/src/cmd/lut_profiles.rs`, `cmd:profiles.camera`, `cmd:profile.deleteCamera`, `crates/engine/src/cmd/dcp_profiles.rs`, `crates/raw/src/dcp.rs`, `crates/ui-egui/src/panels/edit.rs`, `crates/ui-egui/src/panels/profiles.rs` | `.cube` 3D LUTs (files, folders, zips) become creative profiles with Amount, grouped in the profile browser, kept with the library; rendered on the CPU; the user's own DNG camera profiles (`.dcp`: matrices, illuminants, hue/sat map, look table, tone curve) become camera profiles (`dcp:` ids, group Camera Profiles) that replace a raw file's colour model when it is decoded (a profile without a tone curve keeps the photo's own contrast; the photo is decoded again when the profile changes; smart previews and the web worker keep the file's own colour); none ship with the app; XMP camera/creative profiles unsupported | ## H. Crop & rotate (CROP) @@ -787,6 +787,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-12 | minor | LR-PROF-IMPORT: the user's own DNG camera profiles (`.dcp`) import as camera profiles; none ship | | 2026-10-11 | minor | KEY-SLIDER-TYPE: honor immediate Return/Escape and keep typed keys in the value editor; add regression references | | 2026-10-11 | minor | LR-PROF-CAMERACOLOR: raws with a black-and-white camera JPEG take its tone curve (issue #577) | | 2026-10-11 | minor | LR-VIEW-ZOOM and LR-VIEW-COMPARE: Compare and Reference are sharp at 1:1 (zoom windows per pane, two originals kept decoded while they are open); statuses unchanged | diff --git a/docs/raw-parity.md b/docs/raw-parity.md index 2b4b9efb5e..b144fddc0b 100644 --- a/docs/raw-parity.md +++ b/docs/raw-parity.md @@ -1,6 +1,6 @@ # RAW parity: cameras, formats, demosaic, colour and lens profiles -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (EOS R5 Mark II decoded and verified: CRX QP-map escape, odd-height planes) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 (Camera Raw 18.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (LR-PROF-IMPORT: the user's own `.dcp` camera profiles import) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 (Camera Raw 18.7) Raw processing is the deepest single dimension of Lightroom parity: a photographer whose camera does not decode, or decodes with the wrong colour, cannot switch. This document measures it model by @@ -187,7 +187,7 @@ sample files. A pointer for contributors, not legal advice. | Default profile per model | Adobe Standard for every model (1,500 profile names in the bundle) | the DNG's own matrices; else a pooled profile (**4 bundled**: ILCE-7CR, ILCE-7M4, X-H2S, X-T4); else a guarded per-file fit to the camera's embedded JPEG; else spectral matrices (**52 models**, rawtoaces-data); else a neutral matrix | | Camera Matching looks | 481 models (plus phone-maker looks) | none (the per-file JPEG fit imitates the camera's own look) | | Creative profiles | Adobe Color, Portrait, Landscape, Vivid, Monochrome… | our own looks (Color, Neutral, Vivid, Landscape, Portrait, Monochrome) | -| DCP / dual-illuminant model | ✅ | dual-illuminant DNG colour (ColorMatrix / ForwardMatrix 1-2, CameraCalibration, AnalogBalance), HueSatMap, LookTable, ProfileToneCurve; external `.dcp` never loaded (clean-room) | +| DCP / dual-illuminant model | ✅ | dual-illuminant DNG colour (ColorMatrix / ForwardMatrix 1-2, CameraCalibration, AnalogBalance), HueSatMap, LookTable, ProfileToneCurve; the user's own `.dcp` files can be imported as camera profiles (`crates/raw/src/dcp.rs`), none ship with the app (clean-room) | | White balance in Kelvin | ✅ for every model | absolute Kelvin where the camera has colour matrices (its own, or one of the 52 spectral rows), also for files whose look is a per-file fit (#730); other raws keep the relative scale (#296) | **How far the default rendering is from Adobe's** (CIE ΔE; measured where stated): @@ -266,6 +266,7 @@ Beyond decoding: | Date | Change | Summary | |---|---|---| +| 2026-10-12 | minor | LR-PROF-IMPORT: the user's own DNG camera profiles (`.dcp`) import as camera profiles; none ship | | 2026-10-10 | minor | Compressed ORF: pointer to the two Olympus patents that describe the method, as a clean-room starting point | | 2026-10-11 | minor | EOS R5 Mark II verified (CRX QP-map first literal and limited-length escape, odd-height Bayer planes; 4 CC0 files pinned, QP maps of 33,665 private files): 235 verified, 942 unverified; use-weighted 85% (42% on verified bodies); decoding 77%, RAW readiness unchanged at ~56% | | 2026-10-10 (later) | major | Model-by-model measurement against Adobe's published list (1,446 models: 234 verified, 943 unverified, 233 preview, 36 unsupported); `docs/raw/` data and re-measure script; use-weighted share 84% (40% on verified bodies); variant matrix; colour and lens sections with scores; ranked next cameras; RAW readiness ~56% from written parts | diff --git a/docs/roadmap.md b/docs/roadmap.md index f50d368867..46fb2cbd43 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones, current focus and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** major (created; milestones moved here from ROADMAP.md, focus re-ranked after the 2026-10-10 re-measure) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (LR-PROF-IMPORT: the user's own `.dcp` camera profiles import) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 Forward-looking plan. The summary with the headline numbers is [ROADMAP.md](../ROADMAP.md); the ranked shortfalls are [gaps.md](gaps.md); the numbers come from [target-app-parity.md](target-app-parity.md). @@ -84,7 +84,7 @@ calibration: M0–M13 took ≈ 25 active hours against an estimate of ≈ 110– - **AI features** (subject / sky / people masks, generative remove) need model weights with licences we can ship; classical fallbacks first. No permissively licensed sky-segmentation or raw-denoise model was found; we may need to train our own. -- **Camera colour and lens data** is a data problem: we never use Adobe's matrices, DCPs or LCPs. +- **Camera colour and lens data** is a data problem: we never use Adobe's matrices, DCPs or LCPs (users may import their own `.dcp` camera profiles). DNG-embedded data first, then our own calibration; long-tail coverage grows over time and needs people with cameras, lenses and charts. - **Raw-format sources:** decoders are written from prose format descriptions (even ones published @@ -108,6 +108,7 @@ calibration: M0–M13 took ≈ 25 active hours against an estimate of ≈ 110– | Date | Change | Summary | |---|---|---| +| 2026-10-12 | minor | LR-PROF-IMPORT: the user's own DNG camera profiles (`.dcp`) import as camera profiles; none ship | | 2026-10-10 | minor | Beta hours 340–600; full ready ~59% in the gate note | | 2026-10-10 | minor | Added the Alpha gate table (core-workflow gate from the revised standard): passes, stays alpha | | 2026-10-10 | major | Created: milestones moved from ROADMAP.md (statuses refreshed: M3 ✅, M11 / M12 / M15 detail), current focus re-ranked toward beta, risks and design notes kept | diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 3669d1199d..c79bf9d70d 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -233,5 +233,20 @@ with a blend mode other than Normal or with a mask are reported, not applied. Bi or `.zip` bundles — as creative profiles: they appear in the profile browser under their folder's (or zip's) name and take the Amount slider (0–200 %) like the built-in looks. The LUT is applied to the finished, display-encoded colour (trilinear; `DOMAIN_MIN` / `DOMAIN_MAX` honoured; 1D LUTs are not supported); photos with a LUT profile render on the -CPU. A library on disk keeps a copy of each file in its `Profiles/` folder. Adobe's own profile formats (`.dcp`, XMP -camera/creative profiles with embedded tables) are deliberately not read. +CPU. A library on disk keeps a copy of each file in its `Profiles/` folder. XMP camera/creative profiles with embedded +tables are not read. + +## Profiles: camera profiles (`.dcp`) + +The same command (and File ▸ Import Profiles & Presets…, drag & drop) reads DNG Camera Profiles — the user's own `.dcp` +files, e.g. made with a colour-checker tool — as camera profiles (`dcp:-` ids, group *Camera Profiles*, +listed by `profiles.camera`). Read per DNG specification chapter 6 (`crates/raw/src/dcp.rs`): `ProfileName`, +`UniqueCameraModel`, `CalibrationIlluminant1/2`, `ColorMatrix1/2`, `ForwardMatrix1/2`, `ProfileHueSatMap*`, +`ProfileLookTable*`, `ProfileToneCurve` and `BaselineExposureOffset`. Choosing one (`develop.profile {id}`) replaces a raw +file's colour model when it is decoded — the file's own white balance, analog balance and baseline exposure stay, and a +profile without a `ProfileToneCurve` (most chart-made ones) keeps the photo's own contrast: the DNG's tone curve, else the +tone of the look fitted to its camera JPEG — so the +photo's source is decoded again when its profile changes; rendered (non-raw) photos ignore it. Smart previews and the +web build's render worker keep the file's own colour. A library on disk keeps a copy of each file in `Profiles/`; +`profile.deleteCamera` (or `profile.deleteImported`) removes one. No profile ships with LightCraft, and the repository +holds none: tests build theirs in memory (`lightcraft_raw::dcp::write_dcp`).