diff --git a/.github/ISSUE_TEMPLATE/colour-pairs.yml b/.github/ISSUE_TEMPLATE/colour-pairs.yml new file mode 100644 index 00000000000..aa04e239a69 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/colour-pairs.yml @@ -0,0 +1,57 @@ +name: Share colour pairs for a camera profile +description: Contribute a pairs file from `lightcraft-cli calibrate --pairs` so a built-in camera profile can be fitted on more photographers' photos. +title: "Colour pairs: " +body: + - type: markdown + attributes: + value: | + Make the file with `lightcraft-cli calibrate --pairs -pairs.json ""`. Zip it, then drag the zip into the box below. This issue and its attachment are public. + + **What the file shows about your photos.** It has no images, file names, paths, GPS, serial numbers or dates. It does hold, for each photo: + - up to 4,000 colour samples and 4,000 tone samples taken from the photo, sorted by value. Sorting removes where in the frame each sample came from, but the samples still show which colours and brightness levels the photo contains, roughly like a detailed colour histogram. Nobody has shown that a picture can or can't be pieced back together from them. + - a content ID: a 128-bit hash of the raw file's bytes. Anyone who has the same raw file can tell it is in your pairs file, and the same photo shared in two pairs files can be matched up. + - the camera model, and Sony's DRO setting when the file records it. + + See `docs/camera-preview-colour.md`, "Sharing colour pairs", for the exact layout and for how accepted files are recorded. + - type: input + id: model + attributes: + label: Camera model + description: As LightCraft shows it, for example ILCE-7CR. + validations: + required: true + - type: input + id: photos + attributes: + label: Number of photos + description: The count `calibrate --pairs` printed. + validations: + required: true + - type: input + id: version + attributes: + label: LightCraft version + description: From `lightcraft-cli --version`. + validations: + required: true + - type: textarea + id: style + attributes: + label: Picture style (optional) + description: The creative style, picture control or film simulation you mostly shot with, and Sony DRO settings if you know them. + - type: textarea + id: file + attributes: + label: Pairs file + description: Drag the zipped pairs file here. + validations: + required: true + - type: checkboxes + id: licence + attributes: + label: Licence + options: + - label: I took these photos and I release this pairs file under CC0 1.0 (public domain dedication). + required: true + - label: I have read what the file shows about my photos (above) and agree to it being public here and used to fit a built-in profile. + required: true diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index 4c569062a33..5c0825bd158 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -10,7 +10,7 @@ //! lightcraft-cli denoise-serve [--model ID] [--models DIR] [--listen ADDR] [--token-env VAR] [--run-on auto|gpu|cpu] //! lightcraft-cli commands [--json] //! lightcraft-cli controls [--json] -//! lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES… +//! lightcraft-cli calibrate [--max N] [--out DIR] [--pairs FILE] [--from-pairs FILE]… FOLDERS/FILES… //! lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE] //! ``` #![forbid(unsafe_code)] @@ -106,12 +106,18 @@ USAGE: --max-connections N concurrent clients (default 8) lightcraft-cli commands [--json] list every command id with its parameters lightcraft-cli controls [--json] list every develop control id with its range - lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES… + lightcraft-cli calibrate [--max N] [--out DIR] [--pairs FILE] [--from-pairs FILE]… [FOLDERS/FILES…] Fit a colour profile per camera model from raw files and their embedded camera JPEGs (Sony ARW, Nikon NEF, Fujifilm RAF, Canon CRW): up to N files spread over the folders (default 300; 0 = all), pooled per model, written as .json to DIR (default: the profiles folder LightCraft reads, /camera-profiles, or $LIGHTCRAFT_CAMERA_PROFILES). Raws of a profiled model then take their colour from the profile and only their tone from their own JPEG. + --pairs FILE also write the sampled colour pairs to FILE, to share: per photo its camera model, + an id (a hash of the raw's bytes, not its name), Sony's DRO flag and the colour and tone samples; + no image, file name, GPS, serial number or date. Without --out, only FILE is written + (no profile is fitted or installed). + --from-pairs FILE pool the samples of a file written by --pairs (repeat for several, mix with folders); + the profile is the same as from the same raws. Photos listed twice count once. lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE] Time what culling a shoot costs on its own files: reading the folder (browse), the first screen of grid thumbnails, camera previews at loupe sizes and full size, a loupe render, @@ -260,9 +266,13 @@ fn calibrate(args: &[String]) -> Result<(), String> { let mut max = 300usize; let mut out: Option = None; let mut inputs = Vec::new(); + let mut pairs_out: Option = None; + let mut pairs_in: Vec = Vec::new(); let mut i = 0; while i < args.len() { match args[i].as_str() { + "--pairs" => pairs_out = Some(take_value(args, &mut i, "--pairs")?.into()), + "--from-pairs" => pairs_in.push(take_value(args, &mut i, "--from-pairs")?.into()), "--max" => max = take_value(args, &mut i, "--max")?.parse().map_err(|_| "--max needs a number".to_string())?, "--out" => out = Some(take_value(args, &mut i, "--out")?.into()), a if a.starts_with("--") => return Err(format!("unknown option `{a}`")), @@ -270,8 +280,8 @@ fn calibrate(args: &[String]) -> Result<(), String> { } i += 1; } - if inputs.is_empty() { - return Err("calibrate needs folders or raw files".into()); + if inputs.is_empty() && pairs_in.is_empty() { + return Err("calibrate needs folders, raw files or --from-pairs FILE".into()); } let mut files = Vec::new(); for input in &inputs { @@ -284,8 +294,23 @@ fn calibrate(args: &[String]) -> Result<(), String> { // spread over all folders (dates, scenes) rather than the first N files = (0..max).filter_map(|k| files.get(k * found / max).cloned()).collect(); } - eprintln!("calibrate: {} of {found} raw files", files.len()); - let dir = out.or_else(lightcraft_engine::camera_profiles::dir).ok_or("no profiles folder: pass --out DIR")?; + if !inputs.is_empty() { + eprintln!("calibrate: {} of {found} raw files", files.len()); + } + // `--pairs` alone only exports: no profile is fitted into the folder LightCraft reads + let fit = pairs_out.is_none() || out.is_some(); + let dir = if fit { Some(out.or_else(lightcraft_engine::camera_profiles::dir).ok_or("no profiles folder: pass --out DIR")?) } else { None }; + // pairs files first, so a bad one fails before any raw file is decoded (the pool's order doesn't matter) + let mut pool = lightcraft_engine::camera_profiles::Pool::default(); + for path in &pairs_in { + let size = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?.len(); + if size > lightcraft_engine::camera_pairs::MAX_FILE { + return Err(format!("{}: {size} bytes is too large for a pairs file", path.display())); + } + let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?; + let n = pool.add_pairs_file(&bytes, &path.display().to_string())?; + eprintln!("calibrate: {}: {n} photo(s) from a pairs file", path.display()); + } let workers = std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, 6); let next = std::sync::atomic::AtomicUsize::new(0); let done = std::sync::atomic::AtomicUsize::new(0); @@ -298,9 +323,12 @@ fn calibrate(args: &[String]) -> Result<(), String> { let result = std::fs::read(path).map_err(|e| e.to_string()).and_then(|bytes| pool.add(&bytes)); let n = done.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; match result { - Ok(Some(added)) if added.colour => eprintln!("[{n}/{}] {} ({})", files.len(), path.display(), added.model), Ok(Some(added)) => { - eprintln!("[{n}/{}] {} ({}, tone only: too dark or colourless)", files.len(), path.display(), added.model) + let note = if added.colour { "" } else { ", tone only: too dark or colourless" }; + eprintln!("[{n}/{}] {} ({}{note})", files.len(), path.display(), added.model); + if pairs_out.is_some() && !lightcraft_engine::camera_pairs::shareable_model(&added.model) { + eprintln!("{}: left out of --pairs: a pairs file can't hold its camera model", path.display()); + } } Ok(None) => eprintln!("[{n}/{}] {}: skipped (no usable or a black-and-white camera JPEG)", files.len(), path.display()), Err(e) => eprintln!("[{n}/{}] {}: {e}", files.len(), path.display()), @@ -312,10 +340,34 @@ fn calibrate(args: &[String]) -> Result<(), String> { .collect(); handles.into_iter().filter_map(|h| h.join().ok()).collect() }); - let mut pool = lightcraft_engine::camera_profiles::Pool::default(); for p in pools { pool.merge(p); } + calibrate_outputs(&pool, pairs_out.as_deref(), dir) +} + +/// What `calibrate` writes from its pooled photos: the pairs file, if asked for, then the profiles, if a folder is set. +fn calibrate_outputs( + pool: &lightcraft_engine::camera_profiles::Pool, + pairs_out: Option<&Path>, + dir: Option, +) -> Result<(), String> { + if let Some(path) = pairs_out { + let bytes = pool.pairs_file()?; + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; + } + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, &bytes).map_err(|e| format!("{}: {e}", tmp.display()))?; + std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))?; + let photos = pool.shareable_photos().len(); + println!("{photos} photos, {} bytes of calibration samples → {}", bytes.len(), path.display()); + // photos only a pairs file can't hold still fit, when there is a folder to fit into + if photos == 0 && (dir.is_none() || pool.photos().is_empty()) { + return Err("no photo contributed calibration samples".into()); + } + } + let Some(dir) = dir else { return Ok(()) }; let mut written = 0; for result in pool.fit(5) { match result { @@ -1185,6 +1237,51 @@ mod launch_profile_tests { #[cfg(test)] mod tests { + /// Photos no pairs file can hold (a camera model it refuses) leave the export empty but still fit; with nothing to + /// fit, or no folder to fit into, an empty export is the error it was. + #[test] + fn calibrate_fits_photos_a_pairs_file_cannot_hold() { + use lightcraft_engine::camera_profiles::{PhotoPairs, Pool}; + let mut state = 12345u32; + let mut next = move || { + state = state.wrapping_mul(1664525).wrapping_add(1013904223); + f64::from(state >> 8) / f64::from(1u32 << 24) + }; + let photos: Vec = (0..6) + .map(|k| PhotoPairs { + model: "M".repeat(65), + id: format!("{:032x}", k + 1), + dro: None, + tone: Vec::new(), + pairs: (0..400) + .map(|_| { + let c = [next() * 0.8 + 0.02, next() * 0.8 + 0.02, next() * 0.8 + 0.02]; + let y = [c[0] * 1.4 - c[1] * 0.2, c[1] * 1.3 - c[2] * 0.1, c[2] * 1.2 + 0.05 * c[0]].map(|v: f64| v.clamp(0.001, 1.0)); + (c, y) + }) + .collect(), + }) + .collect(); + let mut pool = Pool::default(); + pool.add_photos(photos); + assert!(pool.shareable_photos().is_empty()); + let base = std::env::temp_dir().join(format!("lc-calibrate-outputs-{}", std::process::id())); + std::fs::create_dir_all(&base).unwrap(); + let (pairs, profiles) = (base.join("out.pairs"), base.join("profiles")); + let refused = "no photo contributed calibration samples"; + + let both = super::calibrate_outputs(&pool, Some(&pairs), Some(profiles.clone())); + let written = std::fs::read_dir(&profiles).map_or(0, |d| d.count()); + let pairs_only = super::calibrate_outputs(&pool, Some(&pairs), None); + let empty = super::calibrate_outputs(&Pool::default(), Some(&pairs), Some(profiles.clone())); + let _ = std::fs::remove_dir_all(&base); + + assert_eq!(both, Ok(())); + assert_eq!(written, 1, "the fit ran"); + assert_eq!(pairs_only, Err(refused.to_string())); + assert_eq!(empty, Err(refused.to_string())); + } + /// `render` and `merge` read the lens database the desktop app downloaded, as the desktop does (the same raw /// gets the same profile everywhere), but never fetch it. #[test] diff --git a/apps/lightcraft-cli/tests/it/cli.rs b/apps/lightcraft-cli/tests/it/cli.rs index 2a052fc2d8d..290add81621 100644 --- a/apps/lightcraft-cli/tests/it/cli.rs +++ b/apps/lightcraft-cli/tests/it/cli.rs @@ -183,6 +183,102 @@ fn calibrate_reads_raf_inputs_and_reports_bad_files() { assert!(!out.join("X-T4.json").exists(), "bad input must not produce a profile"); } +#[test] +fn calibrate_pairs_options_check_their_inputs() { + let run = |args: &[&std::ffi::OsStr]| Command::new(binary()).arg("calibrate").args(args).output().unwrap(); + let text = |o: &std::process::Output| String::from_utf8_lossy(&o.stderr).into_owned(); + // nothing to fit from + let r = run(&[]); + assert!(!r.status.success() && text(&r).contains("--from-pairs"), "{}", text(&r)); + // `--pairs` needs a file name + let r = run(&["--pairs".as_ref()]); + assert!(!r.status.success() && text(&r).contains("--pairs"), "{}", text(&r)); + // a missing, foreign or damaged pairs file is refused with its name, and writes nothing + let out = tmp("pairs-profiles"); + for (name, content) in + [("junk.pairs", Some(&b"{not json"[..])), ("foreign.pairs", Some(&br#"{"format":"x","version":1,"photos":[]}"#[..])), ("missing.pairs", None)] + { + let path = tmp(name); + if let Some(c) = content { + std::fs::write(&path, c).unwrap(); + } + let r = run(&["--out".as_ref(), out.as_os_str(), "--from-pairs".as_ref(), path.as_os_str()]); + assert!(!r.status.success() && text(&r).contains(name), "{name}: {}", text(&r)); + } + assert!(!out.exists(), "a refused pairs file must not write a profile"); +} + +#[test] +fn calibrate_pairs_only_exports_and_pools_pairs_files() { + use lightcraft_engine::camera_pairs; + use lightcraft_engine::camera_profiles::PhotoPairs; + // six photos of one made-up model, in two files that overlap in one photo + let mut state = 12345u32; + let mut next = move || { + state = state.wrapping_mul(1664525).wrapping_add(1013904223); + f64::from(state >> 8) / f64::from(1u32 << 24) + }; + let photos: Vec = (0..6) + .map(|k| PhotoPairs { + model: "TEST-1".into(), + id: format!("{:032x}", k + 1), + dro: None, + tone: Vec::new(), + pairs: (0..400) + .map(|_| { + let c = [next() * 0.8 + 0.02, next() * 0.8 + 0.02, next() * 0.8 + 0.02]; + let y = [c[0] * 1.4 - c[1] * 0.2, c[1] * 1.3 - c[2] * 0.1, c[2] * 1.2 + 0.05 * c[0]].map(|v: f64| v.clamp(0.001, 1.0)); + let single = |v: [f64; 3]| v.map(|x| f64::from(x as f32)); + (single(c), single(y)) + }) + .collect(), + }) + .collect(); + let write = |name: &str, p: &[&PhotoPairs]| { + let path = tmp(name); + std::fs::write(&path, camera_pairs::write(p).unwrap()).unwrap(); + path + }; + let refs: Vec<&PhotoPairs> = photos.iter().collect(); + let (a, b, all) = (write("share-a.pairs", &refs[..4]), write("share-b.pairs", &refs[3..]), write("share-all.pairs", &refs)); + let fit = |inputs: &[&std::path::Path], dir: &str| { + let out = tmp(dir); + let mut cmd = Command::new(binary()); + cmd.args(["calibrate", "--out"]).arg(&out); + for i in inputs { + cmd.arg("--from-pairs").arg(i); + } + let r = cmd.output().unwrap(); + assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stderr)); + std::fs::read_to_string(out.join("TEST-1.json")).unwrap() + }; + let pooled = fit(&[&a, &b], "pairs-pooled"); + assert_eq!(pooled, fit(&[&all], "pairs-all"), "pooling two files of the same photos gives the same profile"); + assert_eq!(pooled, fit(&[&b, &a], "pairs-reversed")); + assert!(pooled.contains("\"files\": 6"), "the shared photo counts once: {pooled}"); + // `--pairs` alone re-exports the pooled photos and writes no profile + let merged = tmp("share-merged.pairs"); + let default_dir = tmp("pairs-default-profiles"); + let r = Command::new(binary()) + .env("LIGHTCRAFT_CAMERA_PROFILES", &default_dir) + .args(["calibrate", "--from-pairs"]) + .arg(&a) + .arg("--from-pairs") + .arg(&b) + .arg("--pairs") + .arg(&merged) + .output() + .unwrap(); + assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stderr)); + assert!(!default_dir.exists(), "--pairs without --out must not install a profile"); + // the same photos, each one's pairs in value order + let mut sorted = photos; + for photo in &mut sorted { + lightcraft_engine::camera_profiles::canonical_order(&mut photo.pairs); + } + assert_eq!(camera_pairs::read(&std::fs::read(&merged).unwrap(), "merged").unwrap(), sorted); +} + fn mean(path: &std::path::Path) -> f64 { let d = lightcraft_codecs::decode(&std::fs::read(path).unwrap(), Default::default()).unwrap(); let img = d.to_srgb8(); diff --git a/crates/engine/src/camera_pairs.rs b/crates/engine/src/camera_pairs.rs new file mode 100644 index 00000000000..a5b4927b2eb --- /dev/null +++ b/crates/engine/src/camera_pairs.rs @@ -0,0 +1,380 @@ +//! Pairs files: the sampled colour pairs of a library, shared without any images. +//! +//! `lightcraft-cli calibrate --pairs FILE` writes the colour pairs a camera profile is fitted from +//! (white-balanced camera RGB against the colour of the raw's own embedded camera JPEG, a few thousand +//! per photo) and `calibrate --from-pairs FILE…` pools them, with pairs sampled from raw files, into +//! the same fit. A photographer can share a file of their library's pairs so profiles can be fitted on +//! many photographers' cameras and light, with no photo leaving their disk. +//! +//! The file is UTF-8 JSON, format version 2 (version 1 is read as colour only): +//! +//! ```text +//! { "format": "lightcraft-colour-pairs", "version": 2, +//! "pair": "...describes the data layout...", +//! "photos": [ { "model": "ILCE-7CR", "id": "<32 hex>", "dro": true, "pairs": 4000, "data": "", "tone_samples": 4000, "tone_data": "" }, … ] } +//! ``` +//! +//! Per photo: `model` (Exif `Model`), `id` (a 128-bit hash of the raw file's bytes: it tells the same photo +//! apart across files and is neither the file name nor any metadata), `dro` (Sony's Dynamic Range Optimizer +//! was on, absent when the file doesn't say), `pairs` (the count) and `data`. `data` is `pairs` × 6 values +//! as little-endian `f32` (white-balanced camera RGB, then the camera JPEG's linear Rec.2020 RGB), each +//! pair after the other, then split into four planes by byte position (all first bytes, all second bytes, +//! …) so that zlib finds the repeated exponents, then zlib-compressed and base64-encoded. A file holds +//! nothing else: no file names or paths, GPS, serial numbers, dates or image data. Each photo's pairs are in value order +//! (sorted by their six values), never in the order they were sampled across the picture. +//! Tone samples use the same encoding with four values per row (camera RGB, then JPEG luminance). +//! Each photo's tone samples are sorted independently, and a dark or colourless photo may provide only tone. +use crate::camera_profiles::{PAIRS_PER_FILE, PhotoPairs, ToneSample, canonical_order, canonical_tone}; +use serde::{Deserialize, Serialize}; + +const FORMAT: &str = "lightcraft-colour-pairs"; +const VERSION: u32 = 2; +const LAYOUT: &str = "per photo, `pairs` x 6 little-endian f32 (white-balanced camera RGB, then the camera JPEG's linear Rec.2020 RGB), split into 4 byte planes, zlib, base64; tone uses tone_samples x 4 f32 (white-balanced camera RGB, then JPEG luminance), encoded the same way"; +/// Most photos read from one pairs file: several full `calibrate` runs (300 photos each by default). +/// Each decodes to at most 4,000 colour pairs and 4,000 tone samples (about 320 KB in memory). +pub const MAX_PHOTOS: usize = 2000; +const PAIR_BYTES: usize = 24; +const TONE_BYTES: usize = 16; +/// Longest JSON entry a real photo needs: its most pairs as bytes, base64 of a zlib stream that could +/// not shrink them (a few bytes of headers per 64 KB block) and room for its other fields. +const MAX_PHOTO_JSON: u64 = (PAIRS_PER_FILE * (PAIR_BYTES + TONE_BYTES) + 2048).div_ceil(3) as u64 * 4 + 1024; +/// Largest pairs file read: [`MAX_PHOTOS`] photos at their largest. +pub const MAX_FILE: u64 = MAX_PHOTOS as u64 * MAX_PHOTO_JSON + 4096; +/// Longest model name kept. +const MAX_MODEL: usize = 64; + +#[derive(Serialize, Deserialize)] +struct File { + format: String, + version: u32, + #[serde(default)] + pair: String, + photos: Vec, +} + +#[derive(Serialize, Deserialize)] +struct Photo { + model: String, + id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + dro: Option, + pairs: usize, + data: String, + #[serde(default)] + tone_samples: usize, + #[serde(default, skip_serializing_if = "Option::is_none")] + tone_data: Option, +} + +fn validate_model(model: &str) -> Result<&str, &'static str> { + let model = super::camera_profiles::model_key(model); + if model.is_empty() || model.chars().count() > MAX_MODEL || model.chars().any(char::is_control) { + return Err("unusable camera model"); + } + Ok(model) +} + +/// A pairs file can hold this camera model ([`read`] refuses any other). +pub fn shareable_model(model: &str) -> bool { + validate_model(model).is_ok() +} + +/// The pairs file for `photos`, each photo's pairs in value order ([`canonical_order`]). It holds only what +/// [`read`] takes back: too many photos, too many pairs in one or an unusable model is an error. +pub fn write(photos: &[&PhotoPairs]) -> Result, String> { + if photos.len() > MAX_PHOTOS { + return Err(format!("{} photos is more than a pairs file may hold ({MAX_PHOTOS})", photos.len())); + } + let photos = photos + .iter() + .enumerate() + .map(|(n, p)| { + let model = validate_model(&p.model).map_err(|why| format!("photo {}: {why}", n + 1))?; + if p.pairs.len() > PAIRS_PER_FILE { + return Err(format!("photo {}: too many colour pairs", n + 1)); + } + if p.tone.len() > PAIRS_PER_FILE { + return Err(format!("photo {}: too many tone samples", n + 1)); + } + let mut tone = p.tone.clone(); + canonical_tone(&mut tone); + let mut pairs = p.pairs.clone(); + canonical_order(&mut pairs); + Ok(Photo { + model: model.to_owned(), + id: p.id.clone(), + dro: p.dro, + pairs: pairs.len(), + data: base64(&pack(pairs.iter().map(|(a, b)| [a[0], a[1], a[2], b[0], b[1], b[2]]))), + tone_samples: tone.len(), + tone_data: (!tone.is_empty()).then(|| base64(&pack(tone.iter().map(|(a, y)| [a[0], a[1], a[2], *y])))), + }) + }) + .collect::, String>>()?; + serde_json::to_vec(&File { format: FORMAT.into(), version: VERSION, pair: LAYOUT.into(), photos }).map_err(|e| e.to_string()) +} + +/// Read and validate a pairs file (`origin` names it in errors). A damaged or hostile file is an error, never a panic +/// or a huge allocation: files over [`MAX_FILE`] bytes or [`MAX_PHOTOS`] photos are refused before any photo's data +/// is decoded, and each photo decodes to at most [`PAIRS_PER_FILE`] pairs. +pub fn read(bytes: &[u8], origin: &str) -> Result, String> { + if bytes.len() as u64 > MAX_FILE { + return Err(format!("{origin}: {} bytes is too large for a pairs file", bytes.len())); + } + let file: File = serde_json::from_slice(bytes).map_err(|e| format!("{origin}: not a pairs file: {e}"))?; + if file.format != FORMAT { + return Err(format!("{origin}: not a pairs file (format {:?})", file.format)); + } + if !matches!(file.version, 1 | VERSION) { + return Err(format!("{origin}: pairs file version {} is not supported (this build reads versions 1 and {VERSION})", file.version)); + } + if file.photos.len() > MAX_PHOTOS { + return Err(format!("{origin}: {} photos is more than a pairs file may hold ({MAX_PHOTOS})", file.photos.len())); + } + file.photos + .into_iter() + .enumerate() + .map(|(n, p)| { + let bad = |why: &str| format!("{origin}: photo {}: {why}", n + 1); + let model = validate_model(&p.model).map_err(bad)?; + if p.id.len() != 32 || !p.id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) { + return Err(bad("id is not 32 hex digits")); + } + if p.pairs > PAIRS_PER_FILE { + return Err(bad("too many colour pairs")); + } + let pairs = decode::<6>(&p.data, p.pairs).map_err(bad)?.into_iter().map(|[r, g, b, x, y, z]| ([r, g, b], [x, y, z])).collect(); + if p.tone_samples > PAIRS_PER_FILE { + return Err(bad("too many tone samples")); + } + let tone: Vec = match (file.version, p.tone_samples, p.tone_data.as_deref()) { + (_, 0, None) => Vec::new(), + (VERSION, n, Some(data)) if n > 0 => decode::<4>(data, n).map_err(bad)?.into_iter().map(|[r, g, b, y]| ([r, g, b], y)).collect(), + _ => return Err(bad("tone data is not valid for this version or sample count")), + }; + Ok(PhotoPairs { model: model.to_owned(), id: p.id, dro: p.dro, pairs, tone }) + }) + .collect() +} + +/// Little-endian f32 rows, shuffled into byte planes, then zlib-compressed. +fn pack(rows: impl ExactSizeIterator) -> Vec { + let stride = rows.len() * W; + let mut planes = vec![0u8; stride * 4]; + for (i, row) in rows.enumerate() { + for (k, value) in row.into_iter().enumerate() { + for (byte, x) in (value as f32).to_le_bytes().into_iter().enumerate() { + planes[byte * stride + i * W + k] = x; + } + } + } + miniz_oxide::deflate::compress_to_vec_zlib(&planes, 9) +} + +fn decode(data: &str, n: usize) -> Result, &'static str> { + let packed = unbase64(data).ok_or("data is not base64")?; + let stride = n * W; + let planes = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&packed, stride * 4 + 1).map_err(|_| "data does not decompress")?; + if planes.len() != stride * 4 { + return Err("data does not match its sample count"); + } + (0..n) + .map(|i| { + let mut row = [0.0; W]; + for (k, slot) in row.iter_mut().enumerate() { + let v = f32::from_le_bytes(std::array::from_fn(|byte| planes[byte * stride + i * W + k])); + if !v.is_finite() || v.abs() >= 1e6 { + return Err("data holds unusable sample values"); + } + *slot = f64::from(v); + } + Ok(row) + }) + .collect() +} + +const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +fn base64(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let n = (u32::from(chunk[0]) << 16) | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) | u32::from(*chunk.get(2).unwrap_or(&0)); + for k in 0..4 { + if k <= chunk.len() { + out.push(ALPHABET[((n >> (18 - 6 * k)) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + +fn unbase64(text: &str) -> Option> { + let text = text.trim_end_matches('=').as_bytes(); + if text.len() % 4 == 1 { + return None; + } + let mut out = Vec::with_capacity(text.len() * 3 / 4); + let (mut acc, mut bits) = (0u32, 0); + for &c in text { + let v = ALPHABET.iter().position(|&a| a == c)? as u32; + acc = (acc << 6) | v; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + acc &= (1 << bits) - 1; + } + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn photo(model: &str, id: &str, n: usize) -> PhotoPairs { + let single = |v: f64| f64::from(v as f32); + let pairs = (0..n) + .map(|i| { + let x = i as f64 / n.max(1) as f64; + ([single(x), single(x * 0.5 + 0.01), single(1.0 - x)], [single(x * x), single(x.sqrt()), single(0.3)]) + }) + .collect(); + PhotoPairs { model: model.into(), id: id.into(), dro: Some(true), pairs, tone: Vec::new() } + } + + const ID: &str = "00112233445566778899aabbccddeeff"; + + #[test] + fn version_one_is_explicitly_colour_only() { + let old = photo("ILCE-7CR", ID, 10); + let mut wire: serde_json::Value = serde_json::from_slice(&write(&[&old]).unwrap()).unwrap(); + wire["version"] = 1.into(); + wire["photos"][0].as_object_mut().unwrap().remove("tone_samples"); + assert_eq!(read(&serde_json::to_vec(&wire).unwrap(), "v1").unwrap(), vec![old]); + + wire["photos"][0]["tone_samples"] = 1.into(); + assert!(read(&serde_json::to_vec(&wire).unwrap(), "v1").is_err()); + wire["version"] = VERSION.into(); + assert!(read(&serde_json::to_vec(&wire).unwrap(), "v2").is_err(), "a positive tone count requires data"); + wire["photos"][0]["tone_data"] = base64(&pack(std::iter::once([0.1, 0.2, 0.3, 0.4]))).into(); + assert_eq!(read(&serde_json::to_vec(&wire).unwrap(), "v2").unwrap()[0].tone.len(), 1); + } + + #[test] + fn writer_and_reader_reject_unusable_models() { + let good = photo("ILCE-7CR", ID, 1); + let file: serde_json::Value = serde_json::from_slice(&write(&[&good]).unwrap()).unwrap(); + for model in + ["".into(), " \t\n".into(), "a\nb".into(), "a\0b".into(), "a\u{85}b".into(), "a".repeat(MAX_MODEL + 1), "\u{e9}".repeat(MAX_MODEL + 1)] + { + let invalid = photo(&model, ID, 1); + let error = write(&[&good, &invalid]).unwrap_err(); + assert_eq!(error, "photo 2: unusable camera model", "{model:?}"); + let mut file = file.clone(); + file["photos"][0]["model"] = model.clone().into(); + let error = read(&serde_json::to_vec(&file).unwrap(), "t").unwrap_err(); + assert_eq!(error, "t: photo 1: unusable camera model", "{model:?}"); + } + } + + #[test] + fn model_limits_count_unicode_characters_after_trimming() { + for model in ["ILCE-7CR".into(), "a".repeat(MAX_MODEL), "\u{e9}".repeat(MAX_MODEL)] { + let expected = photo(&model, ID, 1); + let padded = photo(&format!(" \t{model}\r\n"), ID, 1); + let bytes = write(&[&padded]).unwrap(); + let mut file: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(file["photos"][0]["model"], model); + assert_eq!(read(&bytes, "t").unwrap().as_slice(), std::slice::from_ref(&expected)); + file["photos"][0]["model"] = padded.model.into(); + assert_eq!(read(&serde_json::to_vec(&file).unwrap(), "t").unwrap(), [expected]); + } + } + + #[test] + fn write_enforces_photo_limit() { + let photo = photo("ILCE-7M4", ID, 1); + let mut photos = vec![&photo; MAX_PHOTOS]; + let bytes = write(&photos).unwrap(); + assert_eq!(read(&bytes, "at limit").unwrap().len(), MAX_PHOTOS); + photos.push(&photo); + let error = write(&photos).unwrap_err(); + assert!(error.contains("photos is more than a pairs file may hold"), "{error}"); + } + + #[test] + fn write_enforces_the_pair_limit_read_enforces() { + let bytes = write(&[&photo("ILCE-7M4", ID, PAIRS_PER_FILE)]).unwrap(); + assert_eq!(read(&bytes, "at limit").unwrap()[0].pairs.len(), PAIRS_PER_FILE); + let good = photo("ILCE-7M4", ID, 1); + let error = write(&[&good, &photo("ILCE-7M4", ID, PAIRS_PER_FILE + 1)]).unwrap_err(); + assert_eq!(error, "photo 2: too many colour pairs"); + } + + #[test] + fn base64_round_trips() { + for len in 0..9 { + let data: Vec = (0..len as u8).map(|b| b.wrapping_mul(37)).collect(); + assert_eq!(unbase64(&base64(&data)).unwrap(), data); + } + assert_eq!(base64(b"Man"), "TWFu"); + assert_eq!(base64(b"Ma"), "TWE="); + assert!(unbase64("a$bc").is_none()); + } + + #[test] + fn pairs_round_trip_exactly_and_hold_nothing_else() { + let photos = [photo("ILCE-7CR", ID, 500), photo("X-T4", "ffeeddccbbaa99887766554433221100", 3)]; + let bytes = write(&photos.iter().collect::>()).unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + assert!(text.contains(FORMAT) && !text.contains("path") && !text.contains(".ARW")); + assert_eq!(read(&bytes, "t").unwrap(), photos); + let none = write(&[]).unwrap(); + assert!(read(&none, "t").unwrap().is_empty()); + } + + #[test] + fn damaged_and_hostile_files_are_errors() { + let good: serde_json::Value = serde_json::from_slice(&write(&[&photo("ILCE-7CR", ID, 10)]).unwrap()).unwrap(); + let bad = |f: &dyn Fn(&mut serde_json::Value)| { + let mut w = good.clone(); + f(&mut w); + read(&serde_json::to_vec(&w).unwrap(), "t").is_err() + }; + assert!(bad(&|w| w["version"] = 3.into())); + assert!(bad(&|w| w["format"] = "other".into())); + assert!(bad(&|w| w["photos"][0]["model"] = "".into())); + assert!(bad(&|w| w["photos"][0]["model"] = "a\nb".into())); + assert!(bad(&|w| w["photos"][0]["id"] = "../../x".into())); + assert!(bad(&|w| w["photos"][0]["pairs"] = 11.into())); + assert!(bad(&|w| w["photos"][0]["pairs"] = 1_000_000_000u64.into())); + assert!(bad(&|w| w["photos"][0]["data"] = "!!!!".into())); + assert!(bad(&|w| w["photos"][0]["data"] = "AAAA".into())); + assert!(!bad(&|w| w["photos"][0]["dro"] = serde_json::Value::Null)); + assert!(read(b"{not json", "t").is_err()); + let mut p = photo("ILCE-7CR", ID, 4); + p.pairs[1].0[0] = f64::NAN; + assert!(read(&write(&[&p]).unwrap(), "t").is_err()); + } + + /// Tiny zlib streams of zeros inflate about 700×, so the photo count is capped before any data is decoded. + #[test] + fn too_many_photos_are_refused_before_decoding() { + let one = write(&[&photo("ILCE-7CR", ID, 0)]).unwrap(); + let w: serde_json::Value = serde_json::from_slice(&one).unwrap(); + let mut many = w.clone(); + many["photos"] = serde_json::Value::Array(vec![w["photos"][0].clone(); MAX_PHOTOS + 1]); + let bytes = serde_json::to_vec(&many).unwrap(); + assert!((bytes.len() as u64) < MAX_FILE); + let err = read(&bytes, "t").unwrap_err(); + assert!(err.contains("photos is more than"), "{err}"); + many["photos"] = serde_json::Value::Array(vec![w["photos"][0].clone(); MAX_PHOTOS]); + assert_eq!(read(&serde_json::to_vec(&many).unwrap(), "t").unwrap().len(), MAX_PHOTOS); + // a real photo at its most pairs fits the per-photo budget behind MAX_FILE + let full = write(&[&photo("ILCE-7CR", ID, PAIRS_PER_FILE)]).unwrap(); + assert!((full.len() as u64) < MAX_PHOTO_JSON + 4096); + } +} diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index ee64e5e80ac..3a7e469e5e7 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -1273,9 +1273,14 @@ fn configured_lens_geometry_reaches_pool_add_after_raw_decode() { let step = samples.len().div_ceil(4000).max(1); samples.into_iter().step_by(step).collect() } - let colour = capped(corrected.colour); + // The shareable pool rounds each value to f32 and puts samples in value order before fitting. + let single = |value: f64| f64::from(value as f32); + let mut colour: Vec<_> = capped(corrected.colour).into_iter().map(|(rgb, jpeg)| (rgb.map(single), jpeg.map(single))).collect(); + let mut tone_samples: Vec<_> = capped(corrected.tone).into_iter().map(|(rgb, y)| (rgb.map(single), single(y))).collect(); + crate::camera_profiles::canonical_order(&mut colour); + crate::camera_profiles::canonical_tone(&mut tone_samples); let (matrix, hue_sat) = fit_profile(&colour).expect("synthetic scene spans enough colours for pooled calibration"); - let tone = fit_profile_tone(&capped(corrected.tone), &matrix).expect("the camera JPEG supplies a pooled curve"); + let tone = fit_profile_tone(&tone_samples, &matrix).expect("the camera JPEG supplies a pooled curve"); let expected = crate::camera_profiles::CameraProfile::new("Uncalibrated", 1, colour.len(), matrix, hue_sat).with_tone(Some(tone)); let mut pool = crate::camera_profiles::Pool::default(); assert_eq!(pool.add(&file).unwrap(), Some(crate::camera_profiles::Added { model: "Uncalibrated".into(), colour: true })); diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index 0a21cae9c12..7b2640972af 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -15,7 +15,8 @@ use lightcraft_color::Mat3; use lightcraft_pipeline::tone::CameraTone; use lightcraft_raw::profile::HsvTable; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; +use std::cmp::Ordering; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock, PoisonError}; @@ -92,9 +93,15 @@ pub fn dir() -> Option { std::env::var_os("LIGHTCRAFT_CAMERA_PROFILES").map(PathBuf::from).or_else(|| config_dir().map(|d| d.join("camera-profiles"))) } +/// Canonical model key shared by metadata, pairs and profile lookup. Case and interior +/// whitespace are significant: distinct Exif model strings must stay distinct. +pub(crate) fn model_key(model: &str) -> &str { + model.trim() +} + /// File name of `model`'s profile: letters, digits, `-` and `_` kept, anything else `_`. pub fn file_name(model: &str) -> String { - let name: String = model.trim().chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect(); + let name: String = model_key(model).chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect(); format!("{name}.json") } @@ -196,7 +203,7 @@ pub fn get(model: &str) -> Option> { /// [`LIGHTCRAFT_CAMERA_PROFILES`] or the config folder. Separating it lets tests point the lookup /// at a temporary directory without changing process environment variables. fn get_from(model: &str, directory: Option<&Path>) -> Option> { - let model = model.trim(); + let model = model_key(model); if model.is_empty() { return None; } @@ -285,32 +292,89 @@ fn cache_key_for(directory: Option<&Path>) -> u64 { h.finish().0 as u64 } -/// Per camera model: the photos read and their pooled colour pairs and tone samples. -#[derive(Default)] -pub struct Pool { - models: HashMap, +/// What one raw contributed. A tone-only photo does not count toward the colour fit's minimum. +#[derive(Clone, Debug, PartialEq)] +pub struct Added { + pub model: String, + pub colour: bool, } #[derive(Default)] struct Model { - /// Photos that gave colour pairs (the colour fit's photo count). files: usize, - /// Photos that gave tone samples only (too dark or colourless for colour pairs). - tone_files: usize, - pairs: Vec<([f64; 3], [f64; 3])>, - tone: Vec<([f64; 3], f64)>, + pairs: Vec, + tone: Vec, } -/// What [`Pool::add`] took from one raw file. +/// One colour pair: white-balanced camera RGB, and the camera JPEG's linear Rec.2020 colour. +pub type Pair = ([f64; 3], [f64; 3]); +/// White-balanced camera RGB paired with the camera JPEG's luminance. +pub type ToneSample = ([f64; 3], f64); + +/// The colour pairs of one photo, as pooled for a fit and as shared in a pairs file +/// (`lightcraft-cli calibrate --pairs`, see [`crate::camera_pairs`]). #[derive(Clone, Debug, PartialEq)] -pub struct Added { +pub struct PhotoPairs { + /// The camera model as the file reports it (Exif `Model`). pub model: String, - /// Whether it gave colour pairs; `false`: tone samples only, not counted toward a profile's photos. - pub colour: bool, + /// Identifies the photo for de-duplication: a 128-bit hash of the raw file's bytes (32 hex digits). It is + /// not the file name, path or any metadata. + pub id: String, + /// Sony's Dynamic Range Optimizer was on for the photo (`None`: the file doesn't say). + pub dro: Option, + pub pairs: Vec, + pub tone: Vec, } -/// Most colour pairs (and, separately, tone samples) kept per photo, so a few busy photos can't dominate a profile. -const PAIRS_PER_FILE: usize = 4000; +/// The photos read, and their colour pairs, pooled per camera model by [`Pool::fit`]. +#[derive(Default)] +pub struct Pool { + photos: Vec, +} + +/// Maximum per photo for colour pairs and, separately, tone samples. +pub(crate) const PAIRS_PER_FILE: usize = 4000; + +/// Pairs are held at single precision, so pairs read back from a pairs file are bit-for-bit those +/// sampled from the raw and the same profile comes out of either. +fn single(pair: Pair) -> Pair { + let f = |v: [f64; 3]| v.map(|x| f64::from(x as f32)); + (f(pair.0), f(pair.1)) +} + +/// Puts a photo's pairs in value order (all six values, compared in turn): pairs are sampled in scan order over the +/// preview, and that order would keep the photo's coarse layout in a pairs file. Pairs are ordered when they enter the +/// pool, from a raw file or a pairs file, so either route gives the same fit (the fits hold out every third pair by +/// position, so they follow the order). +pub fn canonical_order(pairs: &mut [Pair]) { + pairs.sort_by(pair_order); +} + +fn pair_order(a: &Pair, b: &Pair) -> Ordering { + let key = |p: &Pair| -> [f64; 6] { [p.0[0], p.0[1], p.0[2], p.1[0], p.1[1], p.1[2]] }; + key(a).iter().zip(&key(b)).map(|(x, y)| x.total_cmp(y)).find(|o| o.is_ne()).unwrap_or(Ordering::Equal) +} + +/// The pool's order: model, then id. Records of one photo can differ (pairs files of different builds, say), so they +/// are ordered too and the first is the one used, whatever order they arrived in: most pairs, then the lowest values +/// (each record's pairs in [`canonical_order`]), then its DRO flag. +pub(crate) fn canonical_tone(samples: &mut [ToneSample]) { + samples.sort_by(tone_order); +} + +fn tone_order(a: &ToneSample, b: &ToneSample) -> Ordering { + a.0.iter().zip(&b.0).map(|(x, y)| x.total_cmp(y)).find(|o| o.is_ne()).unwrap_or_else(|| a.1.total_cmp(&b.1)) +} + +fn photo_order(a: &PhotoPairs, b: &PhotoPairs) -> Ordering { + (&a.model, &a.id) + .cmp(&(&b.model, &b.id)) + .then_with(|| b.pairs.len().cmp(&a.pairs.len())) + .then_with(|| a.pairs.iter().zip(&b.pairs).map(|(x, y)| pair_order(x, y)).find(|o| o.is_ne()).unwrap_or(Ordering::Equal)) + .then_with(|| b.tone.len().cmp(&a.tone.len())) + .then_with(|| a.tone.iter().zip(&b.tone).map(|(x, y)| tone_order(x, y)).find(|o| o.is_ne()).unwrap_or(Ordering::Equal)) + .then_with(|| a.dro.cmp(&b.dro)) +} /// Every `n`-th item, `n` chosen to keep at most [`PAIRS_PER_FILE`]. fn thinned(items: Vec) -> impl Iterator { @@ -330,24 +394,82 @@ impl Pool { let correction = crate::camera_preview::correspondence_correction(&raw, bytes); let lens = crate::camera_preview::lens_geometry(&raw.opcodes.list3); raw.opcodes.list3.retain(|op| !op.is_lens_correction()); - let Some(model) = raw.metadata.model.as_deref().map(str::trim).filter(|m| !m.is_empty()) else { return Ok(None) }; + let Some(model) = raw.metadata.model.as_deref().map(model_key).filter(|m| !m.is_empty()) else { return Ok(None) }; let Some(samples) = crate::camera_preview::profile_samples(&raw, bytes, lens.as_ref(), correction.as_ref()) else { return Ok(None) }; - let entry = self.models.entry(model.to_owned()).or_default(); - let colour = !samples.colour.is_empty(); - if colour { - entry.files += 1; - entry.pairs.extend(thinned(samples.colour)); - } else { - entry.tone_files += 1; - } - entry.tone.extend(thinned(samples.tone)); + let mut pairs: Vec<_> = thinned(samples.colour).map(single).collect(); + let f32_round = |x: f64| f64::from(x as f32); + let mut tone: Vec<_> = thinned(samples.tone).map(|(rgb, y)| (rgb.map(f32_round), f32_round(y))).collect(); + canonical_order(&mut pairs); + canonical_tone(&mut tone); + let colour = !pairs.is_empty(); + self.photos.push(PhotoPairs { + model: model.to_owned(), + id: lightcraft_preview::hash_bytes(bytes).to_string(), + dro: lightcraft_raw::embedded_preview_dynamic_range_optimized(bytes), + pairs, + tone, + }); Ok(Some(Added { model: model.to_owned(), colour })) } + /// Add photos read from a pairs file (their pairs put in [`canonical_order`]). + pub fn add_photos(&mut self, mut photos: Vec) { + for photo in &mut photos { + photo.model = model_key(&photo.model).to_owned(); + canonical_order(&mut photo.pairs); + canonical_tone(&mut photo.tone); + } + self.photos.extend(photos); + } + + /// The photos a pairs file can hold: all of [`Pool::photos`] but those with a camera model it refuses (too long, + /// control characters). Those still count in [`Pool::fit`]; one such raw must not cost the rest of the pool its export. + pub fn shareable_photos(&self) -> Vec<&PhotoPairs> { + let mut photos = self.photos(); + photos.retain(|p| crate::camera_pairs::shareable_model(&p.model)); + photos + } + + /// The pairs file ([`crate::camera_pairs`]) of the pool's [`Pool::shareable_photos`]. + pub fn pairs_file(&self) -> Result, String> { + crate::camera_pairs::write(&self.shareable_photos()) + } + + /// Add the photos of a pairs file; returns how many it held. The pool keeps one record of a photo (same model and + /// id), the first in [`photo_order`], so importing a file again changes nothing and files that disagree about a + /// photo give the same result in any order. Refuse an import that would leave more than + /// [`crate::camera_pairs::MAX_PHOTOS`] distinct photos; each holds at most [`PAIRS_PER_FILE`] pairs. + pub fn add_pairs_file(&mut self, bytes: &[u8], origin: &str) -> Result { + let photos = crate::camera_pairs::read(bytes, origin)?; + let n = photos.len(); + let seen: HashSet<(&str, &str)> = self.photos.iter().chain(&photos).map(|p| (p.model.as_str(), p.id.as_str())).collect(); + if seen.len() > crate::camera_pairs::MAX_PHOTOS { + return Err(format!("{origin}: {} photos is more than a pairs pool may hold ({})", seen.len(), crate::camera_pairs::MAX_PHOTOS)); + } + self.add_photos(photos); + self.photos.sort_by(photo_order); + self.photos.dedup_by(|a, b| a.model == b.model && a.id == b.id); + Ok(n) + } + + /// Photos contributing colour or tone, in stable model and id order. Tone-only photos do not count towards the colour fit minimum. + pub fn photos(&self) -> Vec<&PhotoPairs> { + let mut photos: Vec<&PhotoPairs> = self.photos.iter().filter(|p| !p.pairs.is_empty() || !p.tone.is_empty()).collect(); + photos.sort_by(|a, b| photo_order(a, b)); + photos.dedup_by(|a, b| a.model == b.model && a.id == b.id); + photos + } + /// Fit a profile per model with at least `min_files` photos. pub fn fit(&self, min_files: usize) -> Vec> { - let mut models: Vec<_> = self.models.iter().collect(); - models.sort_by(|a, b| a.0.cmp(b.0)); + let mut grouped = std::collections::BTreeMap::<&str, Model>::new(); + for photo in self.photos() { + let m = grouped.entry(&photo.model).or_default(); + m.files += usize::from(!photo.pairs.is_empty()); + m.pairs.extend_from_slice(&photo.pairs); + m.tone.extend_from_slice(&photo.tone); + } + let models = grouped; models .into_iter() .filter(|(_, m)| m.files >= min_files) @@ -361,19 +483,18 @@ impl Pool { /// Add another pool's photos and pairs (pools filled on separate threads). pub fn merge(&mut self, other: Pool) { - for (model, m) in other.models { - let entry = self.models.entry(model).or_default(); - entry.files += m.files; - entry.tone_files += m.tone_files; - entry.pairs.extend(m.pairs); - entry.tone.extend(m.tone); - } + self.photos.extend(other.photos); } /// Photos read per model. pub fn files(&self) -> Vec<(String, usize)> { - let mut v: Vec<_> = self.models.iter().map(|(name, m)| (name.clone(), m.files)).collect(); - v.sort(); + let mut v: Vec<(String, usize)> = Vec::new(); + for photo in self.photos().into_iter().filter(|p| !p.pairs.is_empty()) { + match v.last_mut() { + Some(last) if last.0 == photo.model => last.1 += 1, + _ => v.push((photo.model.clone(), 1)), + } + } v } } @@ -587,6 +708,29 @@ mod tests { assert_ne!(before_key, after_key, "a changed profile must not reuse the previous render cache"); } + #[test] + fn metadata_pairs_and_profile_lookup_share_model_keys() { + let model = BUNDLED[0].0; + let padded = format!(" \t{model}\r\n"); + assert_eq!(model_key(&padded), model); + assert_eq!(file_name(&padded), file_name(model)); + assert_eq!(get(&padded), get(model)); + assert!(get(model).is_some()); + let photos = synthetic(&padded, 5, 7); + let mut pool = Pool::default(); + pool.add_photos(photos.clone()); + assert_eq!(pool.files(), [(model.to_owned(), 5)]); + let bytes = crate::camera_pairs::write(&photos.iter().collect::>()).unwrap(); + let mut imported = Pool::default(); + imported.add_pairs_file(&bytes, "test").unwrap(); + assert_eq!(imported.files(), pool.files()); + assert_eq!(imported.photos(), pool.photos()); + assert_eq!(imported.add_pairs_file(&bytes, "repeat").unwrap(), 5); + assert_eq!(imported.files(), pool.files()); + assert_ne!(model_key("Model A"), model_key("model a")); + assert_ne!(model_key("Model A"), model_key("Model A")); + } + #[test] fn file_names_are_safe() { assert_eq!(file_name("ILCE-7M4"), "ILCE-7M4.json"); @@ -595,6 +739,85 @@ mod tests { assert_eq!(file_name("Ω 1/2"), "__1_2.json"); } + /// Synthetic photos of one model: pairs from a fixed colour mapping with a little structure. + fn synthetic(model: &str, n: usize, seed: u32) -> Vec { + let mut state = seed; + let mut next = move || { + state = state.wrapping_mul(1664525).wrapping_add(1013904223); + f64::from(state >> 8) / f64::from(1u32 << 24) + }; + (0..n) + .map(|k| PhotoPairs { + model: model.into(), + id: format!("{:032x}", u128::from(seed) * 1000 + k as u128 + 1), + dro: (k % 2 == 0).then_some(k % 4 == 0), + tone: Vec::new(), + pairs: (0..300) + .map(|_| { + let c = [next() * 0.8 + 0.02, next() * 0.8 + 0.02, next() * 0.8 + 0.02]; + let y = [c[0] * 1.5 - c[1] * 0.3 - c[2] * 0.1, c[1] * 1.3 - c[0] * 0.1, c[2] * 1.4 - c[1] * 0.2 + 0.05 * c[0]] + .map(|v| v.clamp(0.001, 1.0)); + single((c, y)) + }) + .collect(), + }) + .collect() + } + + #[test] + fn pairs_files_enforce_cumulative_photo_limit() { + let photo = |i: usize| PhotoPairs { + model: "ILCE-7M4".into(), + id: format!("{i:032x}"), + dro: None, + pairs: vec![([0.1; 3], [0.2; 3])], + tone: Vec::new(), + }; + let file = |i: usize| crate::camera_pairs::write(&[&photo(i)]).unwrap(); + let max = crate::camera_pairs::MAX_PHOTOS; + let mut pool = Pool::default(); + pool.add_photos((0..max - 1).map(photo).collect()); + // a photo the pool already holds is skipped, however often it's imported + for _ in 0..3 { + assert_eq!(pool.add_pairs_file(&file(0), "again").unwrap(), 1); + } + assert_eq!(pool.photos.len(), max - 1); + assert_eq!(pool.add_pairs_file(&file(max - 1), "at limit").unwrap(), 1); + assert_eq!(pool.photos.len(), max); + assert_eq!(pool.add_pairs_file(&file(0), "known at limit").unwrap(), 1, "a known photo still imports at the limit"); + let before = pool.photos.clone(); + let error = pool.add_pairs_file(&file(max), "over limit").unwrap_err(); + assert!(error.contains("over limit: 2001 photos is more than a pairs pool may hold (2000)"), "{error}"); + assert_eq!(pool.photos, before, "rejection must leave the stored pool unchanged"); + } + + #[test] + fn pairs_files_pool_to_the_same_profile_whatever_the_order_or_split() { + let photos = synthetic("ILCE-7M4", 8, 7); + let mut direct = Pool::default(); + direct.add_photos(photos.clone()); + let direct = direct.fit(5).remove(0).unwrap(); + assert_eq!((direct.files, direct.samples), (8, 2400)); + // two contributors' files, one of them listing a photo twice, pooled in the other order + let (first, second) = photos.split_at(3); + let write = |p: &[PhotoPairs]| crate::camera_pairs::write(&p.iter().collect::>()).unwrap(); + let (a, b) = (write(first), write(second)); + let mut pooled = Pool::default(); + assert_eq!(pooled.add_pairs_file(&b, "b").unwrap(), 5); + assert_eq!(pooled.add_pairs_file(&a, "a").unwrap(), 3); + assert_eq!(pooled.add_pairs_file(&a, "a again").unwrap(), 3); + assert_eq!(pooled.files(), vec![("ILCE-7M4".to_owned(), 8)]); + assert_eq!(pooled.fit(5).remove(0).unwrap(), direct); + // a pool re-exported as a pairs file holds each photo once + let again = pooled.pairs_file().unwrap(); + let mut reread = Pool::default(); + assert_eq!(reread.add_pairs_file(&again, "again").unwrap(), 8); + assert_eq!(reread.fit(5).remove(0).unwrap(), direct); + // too few photos of a model are left out + pooled.add_photos(synthetic("X-T4", 2, 9)); + assert_eq!(pooled.fit(5).len(), 1); + } + #[test] fn local_profile_lookup_uses_normalized_matching() { // Local profiles saved under one spelling should be found by another @@ -670,6 +893,147 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn pairs_files_keep_no_scan_order_and_fit_the_same() { + // pairs sampled in scan order over a 192x128 gradient preview: red follows the column, green the row + let (w, h) = (192, 128); + let scan: Vec = (0..w * h) + .step_by(7) + .map(|i| { + let (x, y) = ((i % w) as f64 / w as f64, (i / w) as f64 / h as f64); + let c = [0.05 + 0.8 * x, 0.05 + 0.8 * y, 0.4 - 0.3 * x * y]; + single((c, [c[0] * 1.4 - c[1] * 0.2, c[1] * 1.3 - c[2] * 0.1, c[2] * 1.2 + 0.05 * c[0]])) + }) + .collect(); + let rows = |p: &[Pair]| p.windows(2).filter(|w| w[1].0[1] < w[0].0[1]).count(); + assert_eq!(rows(&scan), 0, "in scan order the row channel never steps back"); + let tone: Vec = (1..512) + .map(|i| { + let x = f64::from(i) / 1024.0; + ([x; 3], f64::from((x * 1.3) as f32)) + }) + .collect(); + let mut photos: Vec = (0..5) + .map(|k| PhotoPairs { model: "ILCE-7M4".into(), id: format!("{:032x}", k + 1), dro: None, pairs: scan.clone(), tone: tone.clone() }) + .collect(); + photos.push(PhotoPairs { model: "ILCE-7M4".into(), id: format!("{:032x}", 6), dro: None, pairs: Vec::new(), tone }); + let mut pool = Pool::default(); + pool.add_photos(photos.clone()); + let fitted = pool.fit(5).remove(0).unwrap(); + assert!(fitted.tone.is_some(), "the fixture fits a pooled tone curve"); + assert_eq!(fitted.files, 5, "the sixth photo contributes tone only"); + // the written file holds each photo's pairs sorted by value, not in scan order + let written = crate::camera_pairs::write(&photos.iter().collect::>()).unwrap(); + assert_eq!(written, pool.pairs_file().unwrap()); + let reread = crate::camera_pairs::read(&written, "t").unwrap(); + assert_eq!(reread.len(), 6); + assert!(reread[5].pairs.is_empty() && !reread[5].tone.is_empty()); + for photo in &reread[..5] { + assert_eq!(photo.pairs.len(), scan.len()); + assert_ne!(photo.pairs, scan); + assert!(photo.pairs.is_sorted_by(|a, b| a.0[0] <= b.0[0]), "sorted by value"); + assert!(rows(&photo.pairs) >= w / 2, "the row channel no longer follows the scan"); + let mut a = photo.pairs.clone(); + let mut b = scan.clone(); + a.sort_by(|p, q| p.partial_cmp(q).unwrap()); + b.sort_by(|p, q| p.partial_cmp(q).unwrap()); + assert_eq!(a, b, "the same pairs"); + } + // a round trip, or the pairs arriving in any order, gives the same profile + let mut again = Pool::default(); + again.add_pairs_file(&written, "t").unwrap(); + assert_eq!(again.fit(5).remove(0).unwrap(), fitted); + let mut reversed = photos; + for photo in &mut reversed { + photo.pairs.reverse(); + photo.tone.reverse(); + } + let mut shuffled = Pool::default(); + shuffled.add_photos(reversed); + assert_eq!(shuffled.fit(5).remove(0).unwrap(), fitted); + } + + #[test] + fn photos_without_pairs_do_not_count() { + let mut pool = Pool::default(); + let empty = + |k: usize| PhotoPairs { model: "ILCE-7M4".into(), id: format!("{:032x}", k + 100), dro: None, pairs: Vec::new(), tone: Vec::new() }; + pool.add_photos(synthetic("ILCE-7M4", 1, 3)); + pool.add_photos((0..4).map(empty).collect()); + assert!(pool.fit(5).is_empty(), "one photo's pairs must not pass for five photos"); + assert_eq!(pool.files(), vec![("ILCE-7M4".to_owned(), 1)]); + pool.add_photos(synthetic("ILCE-7M4", 5, 3)); + let profile = pool.fit(5).remove(0).unwrap(); + assert_eq!((profile.files, profile.samples), (5, 1500)); + assert_eq!(crate::camera_pairs::read(&pool.pairs_file().unwrap(), "t").unwrap().len(), 5); + } + + /// Two records of one photo (files written by different builds, say) must not make the fit depend on the input order. + #[test] + fn conflicting_records_of_a_photo_resolve_the_same_in_any_order() { + let mut full = synthetic("ILCE-7M4", 6, 11); + for photo in &mut full { + canonical_order(&mut photo.pairs); + } + let mut fewer = full[0].clone(); + fewer.pairs.truncate(200); + let mut other_values = full[0].clone(); + other_values.pairs[0].0[0] = f64::from((other_values.pairs[0].0[0] + 0.25) as f32); + canonical_order(&mut other_values.pairs); + let mut other_flag = full[0].clone(); + other_flag.dro = None; + let mut empty = full[0].clone(); + empty.pairs.clear(); + for (variant, expected) in [ + (&fewer, &full[0]), + (&other_values, if full[0].pairs < other_values.pairs { &full[0] } else { &other_values }), + (&other_flag, if full[0].dro < other_flag.dro { &full[0] } else { &other_flag }), + (&empty, &full[0]), + ] { + let write = |p: &[&PhotoPairs]| crate::camera_pairs::write(p).unwrap(); + let rest: Vec<&PhotoPairs> = full[1..].iter().collect(); + let (a, b, rest) = (write(&[&full[0]]), write(&[variant]), write(&rest)); + let pooled = |files: [&[u8]; 3]| { + let mut pool = Pool::default(); + for file in files { + pool.add_pairs_file(file, "t").unwrap(); + } + pool + }; + let (first, second) = (pooled([&a, &b, &rest]), pooled([&b, &a, &rest])); + assert_eq!(first.photos.len(), 6, "each photo is held once"); + assert_eq!(first.photos()[0], expected); + assert_eq!(second.photos()[0], expected); + assert_eq!(first.fit(5), second.fit(5)); + assert_eq!(first.pairs_file().unwrap(), second.pairs_file().unwrap()); + // through add_photos (the raw route) and merge too, however the threads finished + let (mut third, mut other) = (Pool::default(), Pool::default()); + third.add_photos(vec![variant.clone()]); + other.add_photos(vec![full[0].clone()]); + third.merge(other); + assert_eq!(third.photos()[0], expected); + } + } + + /// A model a pairs file can't hold stays in the fit and only leaves the export, so one such raw can't fail `--pairs`. + #[test] + fn unshareable_models_stay_in_the_fit_and_leave_the_export() { + let long = "a".repeat(65); + let mut pool = Pool::default(); + pool.add_photos(synthetic("ILCE-7M4", 5, 3)); + pool.add_photos(synthetic(&long, 5, 5)); + pool.add_photos(synthetic( + "a +b", 5, 7, + )); + assert_eq!(pool.fit(5).iter().filter(|r| r.is_ok()).count(), 3); + assert_eq!(pool.files().len(), 3); + assert_eq!(pool.shareable_photos().len(), 5); + let shared = crate::camera_pairs::read(&pool.pairs_file().unwrap(), "t").unwrap(); + assert_eq!(shared.len(), 5); + assert!(shared.iter().all(|p| p.model == "ILCE-7M4")); + } + #[test] fn pool_skips_files_that_cannot_contribute() { let mut pool = Pool::default(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6042b51c8e8..096bb3ff55c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -20,6 +20,7 @@ pub mod aidefringe; #[cfg(not(target_arch = "wasm32"))] pub mod apple_photos; pub mod availability; +pub mod camera_pairs; pub(crate) mod camera_preview; pub mod camera_profiles; pub mod cmd; diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index 8d86976535e..fe236d25a1b 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -191,6 +191,17 @@ One photo can show too little of a colour for its own fit to learn it: in a seco Profiles are JSON files `.json` in `$LIGHTCRAFT_CAMERA_PROFILES`, else `/camera-profiles` (macOS `~/Library/Application Support/LightCraft/camera-profiles`); a local profile replaces a built-in one. Built-in profiles live in `assets/camera-profiles/` (listed in `assets/ATTRIBUTION.md`) and are compiled in, so the app, CLI and web build share them: ILCE-7M4, fitted to 597 photos (2.2 million colour pairs) shot in 2026, mostly with the Standard creative style and DRO Auto; ILCE-7CR, 125 photos, and ILCA-99M2, 144 photos (both below); ILCE-7RM5, 220 photos (Standard creative style); X-H2S, 201 photos; X-T4, 545 photos; NIKON Z 6_2, 296 photos; NIKON Z 8, 261 photos; NIKON D5300, 264 photos (below). They hold aggregate colour statistics only. A photo of a profiled model takes its colour from the profile and fits only its own tone and chroma curves (picture styles vary per shot; with Sony's DRO on, that tone curve is then lowered as described below); the acceptance gates still apply. A rejected profile fit retries the photo's own colour and tone fit; when no look fits at all, the photo keeps the profile's colour (below). Files are read once per process and validated (version, bounded invertible matrix, table shape and finite data); a damaged file is ignored with a warning. The profiles folder's contents are part of the render cache keys, so thumbnails rendered before a profile existed are redone; smart previews built before keep their colour until rebuilt. +#### Sharing colour pairs + +A profile is only as good as the variety of light and subjects behind it, and one photographer's library covers little of either. `lightcraft-cli calibrate --pairs FILE FOLDERS…` writes the sampled colour pairs and tone samples to a file that can be shared (without `--out` it only writes the file and installs no profile; with `--out DIR` it also fits). `lightcraft-cli calibrate --from-pairs FILE… [FOLDERS…]` pools such files, any number, with freshly sampled raws and fits as above, so profiles can be fitted on many photographers' cameras with no photo changing hands. To contribute a pairs file to the built-in profiles, open a "Share colour pairs" issue on GitHub with the file zipped and attached; LightCraft itself never sends it anywhere. + +What a pairs file discloses, said plainly on that form as well: it holds no image, but it is not only aggregate numbers either. Per photo it keeps up to 4,000 colour and 4,000 tone samples. Sorting them by value removes where in the frame each came from, but they still show which colours and brightness levels the photo contains, and there is no proof that a picture can't be partly reconstructed from them. The content `id` is stable: anyone holding the same raw can confirm it is in the file, and the same photo in two contributions can be matched up (which is what deduplication needs). The model and the DRO flag are there too. + +How an accepted file is recorded: the issue is the record of consent. The form requires the CC0 dedication and an acknowledgement of these disclosures, and the issue keeps the attached file. When pooled pairs files feed a bundled profile, that profile's row in `assets/ATTRIBUTION.md` names each contributor, the issue number, the photo count and the SHA-256 of the pairs file as attached, so the profile can be traced to the exact files it was fitted from. A file whose issue is withdrawn before the profile ships is left out. Once a profile has shipped, it stays as it is until it is next refitted. + +A pairs file is UTF-8 JSON (`format` `lightcraft-colour-pairs`, `version` 2; version 1 is read as colour-only). Per photo it holds `model` (Exif `Model`), `id` (a 128-bit hash of the raw file's bytes, only there so a photo listed in two files counts once; it is neither the file name nor any metadata), `dro` (Sony's Dynamic Range Optimizer on or off, left out when the file doesn't say), `pairs` (the count, at most 4000) and `data`: the pairs as little-endian `f32`, six values each (white-balanced camera RGB, then the camera JPEG's linear Rec.2020 RGB), split into four byte planes, zlib-compressed and base64-encoded. Version 2 also stores up to 4000 `tone_samples` per photo as four values each (white-balanced camera RGB, then JPEG luminance), sorted independently and encoded the same way in `tone_data`. Version 1 files supply no tone samples. There are no file names or paths, GPS, serial numbers, dates or images: each photo's pairs are sorted by their values, not kept in the order they were sampled across the preview, so they can't simply be laid back out as a small picture (what the samples still show is described above). The layout is also written into the file's `pair` field. Colour and tone samples are held at single precision and sorted the same way wherever they come from, and photos are fitted in model and id order, so the profile fitted from a version 2 pairs file is bit-for-bit the one fitted from the same raws; two files with the same photos in any order give the same profile. If two records of a photo differ, the one with the most pairs, then the lowest values, is used, whatever the order of the files. A tone-only photo contributes to the tone fit but does not count towards the minimum for a colour fit. A raw whose camera model a pairs file can't hold (over 64 characters or with control characters) is named on stderr and left out of the file; it still counts in a fit. A damaged or hostile file (bad ids, a pair count above the limit, non-finite values, data that doesn't match its count) is an error naming the file. + + ### Sony ILCE-7CR Fitted from 125 usable photos of 131 ILCE-7CR ARWs (one photographer, September 2025 to September 2026, Standard creative style with DRO off, Lv3 or Auto; 127 uncompressed, 2 compressed, 2 lossless compressed), 448,230 colour pairs. Measured as above: rendered at 1200 px with `lightcraft-cli render`, mean CIE76 ΔE against each file's embedded JPEG at 200 px.