diff --git a/README.md b/README.md index 280eb72..44968a7 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,47 @@ itself after the last export or a quit; a browser that refuses says so on the page instead. Leave the framing untouched in the app; any adjustment there reintroduces the resample. +## Lend an export its RAW's detail + +A photograph smaller than the delivery width, such as an edit exported at +2048, can take the detail it lacks from its RAW. ig-prep looks for a RAW with +the same stem (RAF, DNG, ARW, CR2, CR3, NEF and the rest the macOS RAW engine +reads) in the photograph's folder, then in each `--raw` folder: + +```sh +ig-prep --raw /Volumes/CARD/DCIM/100_FUJI -o ig ~/Pictures/exports +``` + +The photograph stays the authority on the look. A cubic fitted on thumbnails +maps the RAW's rendering onto the photograph's colour. The photograph is +enlarged whole, and the mapped RAW adds only detail above the photograph's +sample rate, tile by tile, in proportion to how well the RAW's next octave +down agrees with the photograph's. Each pixel stays inside the photograph's +local range. A camera file that already covers the width is delivered byte for +byte as before, and its RAW is never decoded, because Apple's RAW render +carries a fifth of a Fujifilm HIF's fine-detail energy and would only swap +the camera's sharpening for its own. + +In November 2026, five X-T50 HIFs were exported at 2048, rebuilt at 3072 from +their RAFs, and scored against each HIF's own 3072 output. Scores are +SSIMULACRA2 / Butteraugli max norm, from fast-ssim2 0.9.0 and imazen's +butteraugli 0.9.3: + +| Film simulation | Enlarged | With the RAW | +| --------------- | ----------- | ------------ | +| Nostalgic Neg | 74.9 / 4.33 | 77.6 / 3.15 | +| Nostalgic Neg | 76.1 / 2.64 | 76.4 / 2.55 | +| Classic Chrome | 83.5 / 3.17 | 83.5 / 2.36 | +| Provia | 66.7 / 4.34 | 75.9 / 4.82 | +| Eterna | 80.6 / 3.47 | 79.5 / 4.34 | + +Eterna loses because its glitter comes out of Apple's demosaic as different +sparkles, so the RAW is worth a try on an export and worth a look after. A RAW +is refused when its capture time, its frame shape or its fine structure +disagrees with the photograph's, so a cropped edit is delivered from the +export alone, and the line says why. `--no-raw` turns the search off. +`--pick`, `--variants` and `diagnose` do not use RAWs yet. + ## JPEG encoder The encoder is **ZenJPEG 0.8.4**, using the site's JPEG stack with a diff --git a/src/decode.rs b/src/decode.rs index a0ac3ba..798f5c6 100644 --- a/src/decode.rs +++ b/src/decode.rs @@ -17,6 +17,15 @@ pub struct Decoded { } pub fn open(path: &Path) -> Result { + // A RAW goes by extension: DNG, NEF and ARW are TIFF inside and CR3 is + // ISO BMFF, so their magic would send them down the wrong branch. sips + // renders them through the macOS RAW engine and leaves orientation alone. + if crate::raw::is_raw(path) { + return Ok(Decoded { + img: via_converter(path, false)?, + orientation_applied: false, + }); + } let bytes = std::fs::read(path).map_err(|e| e.to_string())?; let (img, orientation_applied) = if bytes.starts_with(&[0xff, 0xd8]) { (jpeg(&bytes)?, false) diff --git a/src/image.rs b/src/image.rs index 34d9e00..7ae6cef 100644 --- a/src/image.rs +++ b/src/image.rs @@ -80,11 +80,18 @@ impl Rgb { /// Lanczos3 operates directly on linear-light samples, without an intermediate copy. pub fn resize(src: &Rgb, w: u32, h: u32) -> Result { - use fast_image_resize::images::{Image, ImageRef}; - use fast_image_resize::{FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer}; if (src.w, src.h) == (w, h) { return Ok(Rgb::new(w, h, src.px.clone())); } + resize_window(src, [0.0, 0.0, src.w as f64, src.h as f64], w, h) +} + +/// Resize the window `[left, top, width, height]` of `src`, in fractional +/// source pixels, so a window drawn on one frame lands exactly on another of +/// a different size instead of rounding to the nearer whole pixel. +pub fn resize_window(src: &Rgb, window: [f64; 4], w: u32, h: u32) -> Result { + use fast_image_resize::images::{Image, ImageRef}; + use fast_image_resize::{FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer}; let source = ImageRef::new( src.w, src.h, @@ -104,7 +111,9 @@ pub fn resize(src: &Rgb, w: u32, h: u32) -> Result { .resize( &source, &mut target, - &ResizeOptions::new().resize_alg(ResizeAlg::Convolution(FilterType::Lanczos3)), + &ResizeOptions::new() + .resize_alg(ResizeAlg::Convolution(FilterType::Lanczos3)) + .crop(window[0], window[1], window[2], window[3]), ) .map_err(|e| format!("resize: {e}"))?; Ok(Rgb::new(w, h, pixels)) diff --git a/src/main.rs b/src/main.rs index 90b9f28..1c73b61 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,6 +13,7 @@ mod heif; mod image; mod mcp; mod pick; +mod raw; mod simulate; use encode::Chroma; @@ -50,6 +51,18 @@ OPTIONS about half the bytes, faster, and slightly ahead of q99 after the servers in local models. Cannot combine with -q, the chroma flags or --dither. + --raw also look in for each photograph's RAW (same + stem, any RAW extension). Repeatable. Its own folder + is always searched first. + --no-raw never use a RAW + +RAW + A photograph smaller than the delivery width, such as an edit exported + at 2048, takes the detail it lacks from its RAW: the photograph keeps + every frequency it holds and the RAW, mapped onto its look, fills in + above them. A camera file that already covers the width is delivered as + before and its RAW is never decoded. A RAW is refused when its capture + time, its frame or its structure disagrees with the photograph's. --variants write eight variants (1080/1440, q95/99, 444/420), references and a manifest to a NEW --out directory; use --crop or --pad for out-of-band sources @@ -161,6 +174,8 @@ fn main() { let mut match_tables = false; let mut out_dir = PathBuf::from("ig"); let mut pad = [255u8, 255, 255]; + let mut raw_dirs = Vec::new(); + let mut no_raw = false; while let Some(a) = args.next() { match a.as_str() { @@ -187,6 +202,18 @@ fn main() { "-w" | "--width" => width = args.next().and_then(|v| v.parse().ok()).unwrap_or(width), "-q" => quality = args.next().and_then(|v| v.parse().ok()).unwrap_or(quality), "-o" | "--out" => out_dir = args.next().map(PathBuf::from).unwrap_or(out_dir), + "--no-raw" => no_raw = true, + "--raw" => match args.next() { + Some(d) if Path::new(&d).is_dir() => raw_dirs.push(PathBuf::from(d)), + Some(d) => { + eprintln!("ig-prep: --raw needs a directory, got {d}"); + std::process::exit(2); + } + None => { + eprintln!("ig-prep: --raw needs a directory"); + std::process::exit(2); + } + }, "--pad-color" => { if let Some(h) = args.next() { let h = h.trim_start_matches('#'); @@ -237,6 +264,12 @@ fn main() { eprintln!("ig-prep: {MATCH_CONFLICT}"); std::process::exit(2); } + if !raw_dirs.is_empty() && (no_raw || pick || variants || check) { + eprintln!( + "ig-prep: --raw applies to an ordinary conversion; it cannot combine with --no-raw, --pick, --variants or --check" + ); + std::process::exit(2); + } if pick && (check || dry || variants) { eprintln!( "ig-prep: --pick chooses the framing interactively; it cannot combine with --check, --dry-run or --variants" @@ -270,6 +303,11 @@ fn main() { dry, pad, out_dir: out_dir.clone(), + raw: if no_raw { + Raw::Off + } else { + Raw::Search(raw_dirs) + }, }; if pick { @@ -543,6 +581,16 @@ pub struct Opts { pub dry: bool, pad: [u8; 3], pub out_dir: PathBuf, + pub raw: Raw, +} + +/// Whether a camera RAW may lend a photograph the detail it lacks at the +/// delivery size. +#[derive(Clone)] +pub enum Raw { + Off, + /// Look beside each photograph, then in these folders. + Search(Vec), } impl Opts { @@ -560,6 +608,7 @@ impl Opts { dry: false, pad: [255, 255, 255], out_dir: PathBuf::from("ig"), + raw: Raw::Search(Vec::new()), } } @@ -606,6 +655,9 @@ pub struct Report { pub chroma: &'static str, pub error: Option, note: &'static str, + /// What a RAW found beside the photograph did, or why it did nothing. + /// Absent when no RAW was found or the search was off. + pub raw: Option, } impl Report { @@ -621,6 +673,7 @@ impl Report { chroma: "", error: Some(e), note: "", + raw: None, } } @@ -632,7 +685,10 @@ impl Report { } let (fw, fh) = self.from.unwrap_or((0, 0)); let (tw, th) = self.to.unwrap_or((0, 0)); - let summary = format!("{}: {fw}x{fh} -> {tw}x{th}{}", self.name, self.note); + let mut summary = format!("{}: {fw}x{fh} -> {tw}x{th}{}", self.name, self.note); + if let Some(raw) = &self.raw { + summary.push_str(&format!(" [{raw}]")); + } match self.bytes { Some(b) => format!("{summary} {} {} KB", self.chroma, b / 1024), None => summary, @@ -652,7 +708,16 @@ pub fn one(path: &Path, o: &Opts) -> Report { Err(e) => return Report::failed(path, name, e), }; - let plan = geometry::plan(img.w, img.h, o.fit, o.gravity, o.width); + let own = geometry::plan(img.w, img.h, o.fit, o.gravity, o.width); + let raw_path = match &o.raw { + Raw::Off => None, + Raw::Search(dirs) => raw::find(path, dirs), + }; + let (lent, raw_note) = match &raw_path { + Some(rp) => lend(&img, &own, path, rp, o), + None => (None, None), + }; + let plan = lent.as_ref().map_or(own, |l| l.plan); let note = if plan.outside_band { match o.fit { Fit::Full => " (outside Instagram's band, crop it in the app)", @@ -673,12 +738,18 @@ pub fn one(path: &Path, o: &Opts) -> Report { chroma: o.encode_label(), error: None, note, + raw: raw_note, }; if o.dry { return report; } - let final_img = match render(&img, &plan, o.pad) { + let rendered = match &lent { + Some(l) => raw::merge(&img, &l.img, &l.look, plan.crop, plan.scale) + .map(|scaled| padded(scaled, &plan, o.pad)), + None => render(&img, &plan, o.pad), + }; + let final_img = match rendered { Ok(img) => img, Err(e) => return Report::failed(path, report.name, e), }; @@ -700,6 +771,46 @@ pub fn one(path: &Path, o: &Opts) -> Report { } } +/// A RAW that passed every check, and the plan its larger frame allows. +struct Lent { + img: image::Rgb, + look: raw::Look, + plan: geometry::Plan, +} + +/// Decide whether the RAW at `rp` lends the photograph detail, and say why +/// in the report either way. The checks run cheapest first, so a full-size +/// camera file never pays for decoding its RAW. +fn lend( + img: &image::Rgb, + own: &geometry::Plan, + path: &Path, + rp: &Path, + o: &Opts, +) -> (Option, Option) { + let rname = rp.file_name().unwrap_or_default().to_string_lossy(); + // A photograph that is downscaled already holds every frequency the + // output can show, so the RAW would only replace the camera's detail + // with the RAW engine's. + if own.scale.0 < own.crop.2 { + return (None, Some(format!("{rname} not needed"))); + } + if let Some(why) = raw::mismatch(path, rp) { + return (None, Some(format!("{rname} not used: {why}"))); + } + let paired = load_oriented(rp).and_then(|r| raw::pair(img, &r).map(|look| (r, look))); + let (r, look) = match paired { + Ok(p) => p, + Err(why) => return (None, Some(format!("{rname} not used: {why}"))), + }; + let plan = geometry::plan(r.w, r.h, o.fit, o.gravity, o.width); + if plan.scale.0 <= own.scale.0 { + return (None, Some(format!("{rname} not needed"))); + } + let note = format!("detail above {}x{} from {rname}", own.scale.0, own.scale.1); + (Some(Lent { img: r, look, plan }), Some(note)) +} + fn load_oriented(path: &Path) -> Result { // Orientation comes from the metadata reader rather than from the decoder, // because a HEIF's rotation lives in its EXIF and sips does not apply it. @@ -745,7 +856,11 @@ fn render(img: &image::Rgb, plan: &geometry::Plan, pad: [u8; 3]) -> Result image::Rgb { + if plan.canvas != plan.scale { scaled.pad_onto( plan.canvas.0, plan.canvas.1, @@ -755,7 +870,7 @@ fn render(img: &image::Rgb, plan: &geometry::Plan, pad: [u8; 3]) -> Result Value { let mut plan_props = Map::new(); plan_props.insert("paths".into(), paths_schema("inspect")); geometry_props(&mut plan_props); + plan_props.insert( + "raw".into(), + json!({ + "type": "boolean", + "default": true, + "description": "Let a camera RAW with the photograph's stem lend it the detail it \ + lacks when it is smaller than the delivery width, such as an edit \ + exported at 2048. The photograph keeps every frequency it holds. \ + A camera file that covers the width is unaffected. A RAW whose \ + capture time, frame or structure disagrees is refused.", + }), + ); + plan_props.insert( + "raw_dirs".into(), + json!({ + "type": "array", + "items": { "type": "string" }, + "description": "Folders to search for RAWs after each photograph's own, such as \ + a memory card or a RAW archive. Each must be under the root.", + }), + ); let mut convert_props = plan_props.clone(); convert_props.insert( @@ -457,6 +478,11 @@ fn file_props(converted: bool) -> Value { Instagram will crop it unless fit=crop or fit=pad handled it here.", }, "error": { "type": "string", "description": "Present only if this file failed." }, + "raw": { + "type": "string", + "description": "What a RAW found beside the photograph did, or why it did nothing. \ + Absent when none was found.", + }, }); if converted { p["output"] = json!({ "type": "string", "description": "Path of the written JPEG." }); @@ -555,6 +581,10 @@ fn call(id: Value, params: &Value, root: Option<&Path>) -> Value { Err(e) => return tool_error(id, e), }; opts.dry = true; + opts.raw = match raw_opts(&args, root) { + Ok(r) => r, + Err(e) => return tool_error(id, e), + }; let reports = crate::run_all(&files, &opts); let failed = reports.iter().filter(|r| r.error.is_some()).count(); let mut text = lines(&reports); @@ -690,6 +720,9 @@ fn report_json_plan(r: &Report) -> Value { if let Some(e) = &r.error { m["error"] = json!(e); } + if let Some(raw) = &r.raw { + m["raw"] = json!(raw); + } m } @@ -770,9 +803,39 @@ fn convert_opts(args: &Value, root: Option<&Path>) -> Result { } let dir = args.get("out_dir").and_then(Value::as_str).unwrap_or("ig"); o.out_dir = under_root(Path::new(dir), root, false)?; + o.raw = raw_opts(args, root)?; Ok(o) } +fn raw_opts(args: &Value, root: Option<&Path>) -> Result { + let on = match args.get("raw") { + None => true, + Some(v) => v.as_bool().ok_or("raw must be a boolean")?, + }; + let dirs = match args.get("raw_dirs") { + None => Vec::new(), + Some(v) => v + .as_array() + .ok_or("raw_dirs must be an array of strings")? + .iter() + .map(|d| { + let d = d.as_str().ok_or("raw_dirs must be an array of strings")?; + let dir = under_root(Path::new(d), root, true)?; + if dir.is_dir() { + Ok(dir) + } else { + Err(format!("{} is not a directory", dir.display())) + } + }) + .collect::>()?, + }; + match (on, dirs.is_empty()) { + (true, _) => Ok(Raw::Search(dirs)), + (false, true) => Ok(Raw::Off), + (false, false) => Err("raw_dirs names folders to search, so it needs raw left on".into()), + } +} + fn inputs(args: &Value, root: Option<&Path>) -> Result<(Vec, usize), String> { let list = args .get("paths") @@ -1043,6 +1106,30 @@ mod tests { assert!(convert_opts(&json!({ "pad_color": "fff" }), None).is_err()); } + /// A RAW folder is read from, so `--root` bounds it like every other path. + #[test] + fn raw_folders_stay_under_the_root_and_need_raw_left_on() { + let root = tempfile::tempdir().unwrap(); + let root = root.path().canonicalize().unwrap(); + let card = root.join("card"); + std::fs::create_dir(&card).unwrap(); + let outside = tempfile::tempdir().unwrap(); + + assert!(matches!(raw_opts(&json!({}), Some(&root)), Ok(Raw::Search(d)) if d.is_empty())); + assert!(matches!( + raw_opts(&json!({ "raw": false }), Some(&root)), + Ok(Raw::Off) + )); + assert!(matches!( + raw_opts(&json!({ "raw_dirs": [card] }), Some(&root)), + Ok(Raw::Search(d)) if d == vec![card.clone()] + )); + let escaped = raw_opts(&json!({ "raw_dirs": [outside.path()] }), Some(&root)); + assert!(escaped.is_err_and(|e| e.contains("outside the root"))); + assert!(raw_opts(&json!({ "raw": false, "raw_dirs": [card] }), Some(&root)).is_err()); + assert!(raw_opts(&json!({ "raw": "yes" }), None).is_err()); + } + /// `match` replaces quality, chroma and dither, so naming any of them /// alongside it is refused rather than quietly overridden. #[test] diff --git a/src/raw.rs b/src/raw.rs new file mode 100644 index 0000000..204562c --- /dev/null +++ b/src/raw.rs @@ -0,0 +1,609 @@ +//! A camera RAW beside a photograph, used for the detail the photograph no +//! longer holds at the delivery size. +//! +//! The photograph, whether a camera JPEG or HIF or an edit exported from one, +//! stays the authority on how the picture looks. The RAW only fills the +//! frequencies above what the photograph itself samples across the output. +//! A full-size camera file is therefore delivered exactly as before, and its +//! RAW is never decoded. +//! +//! Measured 2026-11-01 on five X-T50 RAFs, each HIF exported at 2048 and +//! rebuilt at 3072, scored against the HIF's own 3072 output. Scores are +//! SSIMULACRA2 / Butteraugli max norm, from fast-ssim2 0.9.0 and imazen's +//! butteraugli 0.9.3 (the site's photo-metrics), Lanczos enlargement first: +//! +//! | Film simulation | Enlarged | With the RAW | +//! |--------------------|-------------|--------------| +//! | Nostalgic Neg | 74.9 / 4.33 | 77.6 / 3.15 | +//! | Nostalgic Neg | 76.1 / 2.64 | 76.4 / 2.55 | +//! | Classic Chrome | 83.5 / 3.17 | 83.5 / 2.36 | +//! | Provia | 66.7 / 4.34 | 75.9 / 4.82 | +//! | Eterna | 80.6 / 3.47 | 79.5 / 4.34 | +//! +//! Eterna's loss is glitter the RAW engine demosaics into different sparkles. +//! The same work measured that Apple's RAW render carries a fifth of the HIF's +//! fine-detail energy, which is why the RAW never replaces detail the +//! photograph has. + +use crate::color::{linear_to_srgb, srgb_to_linear}; +use crate::image::{Rgb, resize, resize_window}; +use std::path::{Path, PathBuf}; + +/// RAW formats the macOS RAW engine behind `sips` decodes. +pub const EXTS: [&str; 14] = [ + "raf", "dng", "arw", "cr2", "cr3", "nef", "nrw", "orf", "rw2", "pef", "srw", "3fr", "iiq", + "rwl", +]; + +/// Below this, the photograph and the RAW are not the same exposure. A true +/// pair measured 0.970; mirrored, shifted by 3% and rotated 180 degrees it +/// measured 0.016 or less. +const MIN_STRUCTURE: f32 = 0.5; + +/// Width of the thumbnails the colour map and the pairing check are fitted on. +const THUMB: u32 = 480; + +/// How far the two frames' aspect ratios may differ, as a fraction. An export +/// rounds each edge to a whole pixel; a crop in the edit moves it much further. +const ASPECT_SLACK: f64 = 0.003; + +/// Side of the output tiles the RAW's detail is trusted over. 32 and 128 +/// scored within 0.1 SSIMULACRA2 of 64 on every frame above. +const TILE: u32 = 64; + +pub fn is_raw(path: &Path) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| EXTS.contains(&e.to_ascii_lowercase().as_str())) +} + +/// The first RAW sharing the photograph's stem, in its own folder and then in +/// each of `dirs`. Stems compare without case because cameras write upper case +/// and exporters often do not. Only named folders are searched: camera +/// counters wrap at 9999, so a drive-wide search finds somebody's DSCF0001. +/// A symlink is never a match, so the MCP server's --root, which vouches for +/// the folders, also bounds every RAW read out of them. +pub fn find(photo: &Path, dirs: &[PathBuf]) -> Option { + let stem = photo.file_stem()?.to_str()?; + let own = photo.parent().map(|p| { + if p.as_os_str().is_empty() { + PathBuf::from(".") + } else { + p.to_path_buf() + } + }); + own.iter().chain(dirs).find_map(|dir| { + let mut hits: Vec = std::fs::read_dir(dir) + .ok()? + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_file())) + .map(|e| e.path()) + .filter(|p| { + is_raw(p) + && p.file_stem() + .and_then(|s| s.to_str()) + .is_some_and(|s| s.eq_ignore_ascii_case(stem)) + }) + .collect(); + hits.sort(); + hits.into_iter().next() + }) +} + +/// When the shutter fired, to the hundredth where the camera records it. +fn captured(path: &Path) -> Option { + let p = exif_sooc::read(path).ok()?; + let at = p.get("DateTimeOriginal")?.value.as_str()?.to_owned(); + let sub = p + .get("SubSecTimeOriginal") + .and_then(|t| t.value.as_str()) + .unwrap_or_default(); + Some(format!("{at}.{sub}")) +} + +/// Why a RAW found beside the photograph cannot lend it detail. Each check +/// runs before the RAW is trusted with a single pixel. +pub fn mismatch(photo_path: &Path, raw_path: &Path) -> Option { + match (captured(photo_path), captured(raw_path)) { + (Some(a), Some(b)) if a != b => Some(format!("captured at {b}, the photograph at {a}")), + _ => None, + } +} + +pub fn shape_mismatch(photo: &Rgb, raw: &Rgb) -> Option { + let a = photo.w as f64 / photo.h as f64; + let b = raw.w as f64 / raw.h as f64; + ((a / b - 1.0).abs() > ASPECT_SLACK).then(|| { + format!( + "its frame is {}x{} and the photograph's {}x{}, so the edit cropped it", + raw.w, raw.h, photo.w, photo.h + ) + }) +} + +/// Gamma-encoded copy, so fitting and band splitting happen on perceptual +/// steps rather than on light, where shadows would count for nothing. +fn encoded(img: &Rgb) -> Rgb { + Rgb::new( + img.w, + img.h, + img.px.iter().map(|&c| linear_to_srgb(c)).collect(), + ) +} + +fn thumbs(photo: &Rgb, raw: &Rgb) -> Result<(Rgb, Rgb), String> { + let h = ((THUMB as f64) * photo.h as f64 / photo.w as f64) + .round() + .max(1.0) as u32; + Ok(( + encoded(&resize(photo, THUMB, h)?), + encoded(&resize(raw, THUMB, h)?), + )) +} + +/// Correlation of the two frames' fine luma structure. Tone, colour and film +/// simulation drop out under the normalisation, so an edit scores like the +/// camera file and only a different exposure or framing scores low. +fn structure(a: &Rgb, b: &Rgb) -> Result { + let high = |img: &Rgb| -> Result, String> { + let blur = resize( + &resize(img, (img.w / 4).max(1), (img.h / 4).max(1))?, + img.w, + img.h, + )?; + let luma = |p: &[f32]| 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]; + let d: Vec = img + .px + .as_chunks::<3>() + .0 + .iter() + .zip(blur.px.as_chunks::<3>().0.iter()) + .map(|(p, q)| luma(p) - luma(q)) + .collect(); + let n = d.len() as f32; + let mean = d.iter().sum::() / n; + let sd = (d.iter().map(|v| (v - mean).powi(2)).sum::() / n).sqrt(); + Ok(d.iter().map(|v| (v - mean) / sd.max(1e-9)).collect()) + }; + let (x, y) = (high(a)?, high(b)?); + Ok(x.iter().zip(&y).map(|(p, q)| p * q).sum::() / x.len() as f32) +} + +/// A cubic in gamma-encoded RGB from the RAW's rendering to the photograph's +/// look. Fitted 3.2 levels RMS on the Nostalgic Neg pair, against 11.5 with +/// no map; what it misses at low frequencies the merge takes from the +/// photograph anyway, so it only has to be right about fine detail. +pub struct Look([[f64; 20]; 3]); + +fn terms([r, g, b]: [f64; 3]) -> [f64; 20] { + [ + 1.0, + r, + g, + b, + r * r, + g * g, + b * b, + r * g, + r * b, + g * b, + r * r * r, + g * g * g, + b * b * b, + r * r * g, + r * r * b, + g * g * r, + g * g * b, + b * b * r, + b * b * g, + r * g * b, + ] +} + +impl Look { + /// Least squares through the normal equations, with a ridge small enough + /// to leave a real fit alone and large enough that a RAW with no colour in + /// some region cannot make the system singular. + fn fit(raw: &Rgb, photo: &Rgb) -> Look { + let mut ata = [[0.0f64; 20]; 20]; + let mut atb = [[0.0f64; 3]; 20]; + for (p, q) in raw + .px + .as_chunks::<3>() + .0 + .iter() + .zip(photo.px.as_chunks::<3>().0.iter()) + { + let t = terms([p[0], p[1], p[2]].map(|c| c.clamp(0.0, 1.0) as f64)); + for i in 0..20 { + for j in 0..20 { + ata[i][j] += t[i] * t[j]; + } + for c in 0..3 { + atb[i][c] += t[i] * q[c] as f64; + } + } + } + let ridge = 1e-9 * (0..20).map(|i| ata[i][i]).sum::(); + for (i, row) in ata.iter_mut().enumerate() { + row[i] += ridge; + } + let mut coef = [[0.0; 20]; 3]; + for c in 0..3 { + let x = solve(ata, std::array::from_fn(|i| atb[i][c])); + coef[c] = x; + } + Look(coef) + } + + fn apply(&self, img: &Rgb) -> Rgb { + let mut px = Vec::with_capacity(img.px.len()); + for p in img.px.as_chunks::<3>().0.iter() { + let t = terms([p[0], p[1], p[2]].map(|c| c.clamp(0.0, 1.0) as f64)); + for c in 0..3 { + px.push(self.0[c].iter().zip(&t).map(|(k, v)| k * v).sum::() as f32); + } + } + Rgb::new(img.w, img.h, px) + } +} + +/// Gaussian elimination with partial pivoting; the ridge keeps it regular. +fn solve(mut a: [[f64; 20]; 20], mut b: [f64; 20]) -> [f64; 20] { + for col in 0..20 { + let pivot = (col..20) + .max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs())) + .unwrap_or(col); + a.swap(col, pivot); + b.swap(col, pivot); + let p = a[col]; + for row in col + 1..20 { + let f = a[row][col] / p[col]; + for (x, y) in a[row][col..].iter_mut().zip(&p[col..]) { + *x -= f * y; + } + b[row] -= f * b[col]; + } + } + let mut x = [0.0; 20]; + for row in (0..20).rev() { + let s: f64 = (row + 1..20).map(|k| a[row][k] * x[k]).sum(); + x[row] = (b[row] - s) / a[row][row]; + } + x +} + +/// Fit the RAW to the photograph, or say why it is not the same picture. +pub fn pair(photo: &Rgb, raw: &Rgb) -> Result { + if let Some(why) = shape_mismatch(photo, raw) { + return Err(why); + } + let (p, r) = thumbs(photo, raw)?; + let s = structure(&p, &r)?; + if s < MIN_STRUCTURE { + return Err(format!( + "its structure correlates {s:.2} with the photograph's, under {MIN_STRUCTURE}" + )); + } + Ok(Look::fit(&r, &p)) +} + +/// The photograph wherever it has samples, and the RAW's detail above them. +/// +/// `crop` is a window in RAW pixels and `out` the size it is delivered at. The +/// photograph is enlarged whole, and the mapped RAW adds only what survives +/// subtracting its own copy resampled through the photograph's sample count, +/// scaled by [`trust`]. Each sum is held within the photograph's range over +/// one of its samples, so a RAW highlight the map extrapolates cannot become +/// a white ring: replacing the photograph's band with the RAW's and leaving +/// the result unbounded scored Butteraugli 13.6 on the Eterna frame above. +pub fn merge( + photo: &Rgb, + raw: &Rgb, + look: &Look, + crop: (u32, u32, u32, u32), + out: (u32, u32), +) -> Result { + let sx = photo.w as f64 / raw.w as f64; + let sy = photo.h as f64 / raw.h as f64; + let window = [ + crop.0 as f64 * sx, + crop.1 as f64 * sy, + crop.2 as f64 * sx, + crop.3 as f64 * sy, + ]; + let held = ( + (window[2].round() as u32).clamp(1, out.0), + (window[3].round() as u32).clamp(1, out.1), + ); + let mapped = look.apply(&encoded(&resize( + &raw.crop(crop.0, crop.1, crop.2, crop.3), + out.0, + out.1, + )?)); + let shown = encoded(&resize_window(photo, window, out.0, out.1)?); + let low = resize(&resize(&mapped, held.0, held.1)?, out.0, out.1)?; + let gain = trust(&shown, &mapped, held)?; + let reach = (out.0 as f64 / held.0 as f64).ceil() as usize; + let (w, h) = (out.0 as usize, out.1 as usize); + let floor = spread(&shown.px, w, h, reach, f32::min); + let ceiling = spread(&shown.px, w, h, reach, f32::max); + let px = mapped + .px + .iter() + .zip(&low.px) + .zip(floor.iter().zip(&ceiling)) + .zip(shown.px.iter().zip(&gain.px)) + .map(|(((m, l), (lo, hi)), (s, g))| { + srgb_to_linear((s + g * (m - l)).clamp(*lo, *hi).clamp(0.0, 1.0)) + }) + .collect(); + Ok(Rgb::new(out.0, out.1, px)) +} + +/// How far to trust the RAW's detail around each pixel: per tile and channel, +/// the least-squares gain from the RAW's octave just below the photograph's +/// Nyquist to the photograph's own, kept within [0, 1]. Where the RAW's fine +/// texture is noise the photograph does not share, it lends nothing. +fn trust(shown: &Rgb, mapped: &Rgb, held: (u32, u32)) -> Result { + let half = ((held.0 / 2).max(1), (held.1 / 2).max(1)); + let octave = |img: &Rgb| -> Result, String> { + let a = resize(&resize(img, held.0, held.1)?, img.w, img.h)?; + let b = resize(&resize(img, half.0, half.1)?, img.w, img.h)?; + Ok(a.px.iter().zip(&b.px).map(|(x, y)| x - y).collect()) + }; + let (s, m) = (octave(shown)?, octave(mapped)?); + let (w, tw, th) = ( + shown.w as usize, + shown.w.div_ceil(TILE) as usize, + shown.h.div_ceil(TILE) as usize, + ); + let mut cross = vec![0.0f64; tw * th * 3]; + let mut power = vec![0.0f64; tw * th * 3]; + for (i, (a, b)) in s.iter().zip(&m).enumerate() { + let (p, c) = (i / 3, i % 3); + let t = ((p / w) / TILE as usize * tw + (p % w) / TILE as usize) * 3 + c; + cross[t] += (a * b) as f64; + power[t] += (b * b) as f64; + } + let tiles = cross + .iter() + .zip(&power) + .map(|(x, p)| { + if *p > 0.0 { + (x / p).clamp(0.0, 1.0) as f32 + } else { + 0.0 + } + }) + .collect(); + let mut gain = resize(&Rgb::new(tw as u32, th as u32, tiles), shown.w, shown.h)?; + gain.px.iter_mut().for_each(|g| *g = g.clamp(0.0, 1.0)); + Ok(gain) +} + +/// Each channel's `pick` (least or greatest) within `r` pixels of each pixel. +fn spread(px: &[f32], w: usize, h: usize, r: usize, pick: fn(f32, f32) -> f32) -> Vec { + let at = |x: usize, y: usize, c: usize| (y * w + x) * 3 + c; + let mut across = vec![0.0; px.len()]; + let mut out = vec![0.0; px.len()]; + for y in 0..h { + for x in 0..w { + for c in 0..3 { + across[at(x, y, c)] = (x.saturating_sub(r)..=(x + r).min(w - 1)) + .map(|i| px[at(i, y, c)]) + .fold(px[at(x, y, c)], pick); + } + } + } + for y in 0..h { + for x in 0..w { + for c in 0..3 { + out[at(x, y, c)] = (y.saturating_sub(r)..=(y + r).min(h - 1)) + .map(|j| across[at(x, j, c)]) + .fold(across[at(x, y, c)], pick); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A frame with structure at every scale, so the pairing check has + /// something to correlate and a band split has something to split. + fn scene(w: u32, h: u32) -> Rgb { + let px = (0..w * h) + .flat_map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + // The last term, about 4 pixels a period, is finer than a + // third-size export can hold. + let v = 0.5 + + 0.2 * (x * 0.31).sin() * (y * 0.17).cos() + + 0.1 * (x * 0.07).sin() + + 0.06 * (x * 1.6).sin() * (y * 1.4).cos(); + [v * 0.9, v, v * 0.8].map(srgb_to_linear) + }) + .collect(); + Rgb::new(w, h, px) + } + + #[test] + fn finds_a_raw_by_stem_without_case_and_skips_other_stems() { + let dir = tempfile::tempdir().unwrap(); + for f in ["DSCF0001.RAF", "dscf0002.dng", "DSCF0001.xmp"] { + std::fs::write(dir.path().join(f), b"").unwrap(); + } + let photo = dir.path().join("dscf0001.jpg"); + assert_eq!(find(&photo, &[]), Some(dir.path().join("DSCF0001.RAF"))); + assert_eq!(find(&dir.path().join("DSCF0003.jpg"), &[]), None); + } + + #[test] + fn a_named_folder_is_searched_after_the_photographs_own() { + let (here, card) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + std::fs::write(card.path().join("XT500078.RAF"), b"").unwrap(); + let photo = here.path().join("XT500078.jpg"); + assert_eq!(find(&photo, &[]), None); + assert_eq!( + find(&photo, &[card.path().to_path_buf()]), + Some(card.path().join("XT500078.RAF")) + ); + } + + #[test] + fn a_cropped_edit_is_refused_and_a_rounded_export_is_not() { + let raw = Rgb::new(7728, 5152, vec![0.0; 7728 * 5152 * 3]); + let rounded = Rgb::new(2048, 1365, vec![0.0; 2048 * 1365 * 3]); + let cropped = Rgb::new(2048, 1536, vec![0.0; 2048 * 1536 * 3]); + assert_eq!(shape_mismatch(&rounded, &raw), None); + assert_eq!( + shape_mismatch(&cropped, &raw).as_deref(), + Some("its frame is 7728x5152 and the photograph's 2048x1536, so the edit cropped it") + ); + } + + #[test] + fn a_mirrored_raw_fails_the_pairing_check_and_the_true_one_passes() { + let raw = scene(960, 640); + let mirrored = Rgb::new( + 960, + 640, + raw.px + .as_chunks::<{ 960 * 3 }>() + .0 + .iter() + .flat_map(|row| { + row.as_chunks::<3>() + .0 + .iter() + .rev() + .flatten() + .copied() + .collect::>() + }) + .collect(), + ); + assert!(pair(&raw, &raw).is_ok()); + assert_eq!( + pair(&raw, &mirrored) + .err() + .map(|e| e.ends_with("under 0.5")), + Some(true) + ); + } + + #[test] + fn the_look_reproduces_a_global_tone_and_colour_change() { + // A grade inside the cubic's span, crossing channels the way a film + // simulation does, so any error left is the solver's. + let raw = encoded(&scene(64, 64)); + let graded = Rgb::new( + 64, + 64, + raw.px + .as_chunks::<3>() + .0 + .iter() + .flat_map(|p| { + let [r, g, b] = [p[0], p[1], p[2]]; + [ + r * r, + 0.1 + 0.8 * g - 0.2 * g * g * g, + 0.9 * b + 0.1 * r * g, + ] + }) + .collect(), + ); + let got = Look::fit(&raw, &graded).apply(&raw); + let worst = got + .px + .iter() + .zip(&graded.px) + .map(|(a, b)| (a - b).abs()) + .fold(0.0, f32::max); + assert!(worst < 1.0 / 255.0, "worst error {worst}"); + } + + #[test] + fn a_photograph_at_full_size_comes_through_the_merge_unchanged() { + let photo = scene(120, 80); + let look = Look::fit(&encoded(&photo), &encoded(&photo)); + let out = merge(&photo, &scene(120, 80), &look, (0, 0, 120, 80), (120, 80)).unwrap(); + let worst = out + .px + .iter() + .zip(&photo.px) + .map(|(a, b)| (linear_to_srgb(*a) - linear_to_srgb(*b)).abs()) + .fold(0.0, f32::max); + assert!(worst < 0.5 / 255.0, "worst error {worst}"); + } + + #[test] + fn a_small_export_gains_the_raws_fine_detail() { + // The export is the RAW at a third of the size: its fine detail is gone, + // and the merge should bring it back nearer than enlarging does. + let raw = scene(360, 240); + let export = resize(&raw, 120, 80).unwrap(); + let look = Look::fit(&encoded(&resize(&raw, 120, 80).unwrap()), &encoded(&export)); + let merged = merge(&export, &raw, &look, (0, 0, 360, 240), (360, 240)).unwrap(); + let enlarged = resize(&export, 360, 240).unwrap(); + let err = |img: &Rgb| -> f32 { + let e: f32 = img + .px + .iter() + .zip(&raw.px) + .map(|(a, b)| (linear_to_srgb(*a) - linear_to_srgb(*b)).powi(2)) + .sum(); + (e / img.px.len() as f32).sqrt() * 255.0 + }; + let (m, e) = (err(&merged), err(&enlarged)); + assert!(m < e / 4.0, "merged {m:.2} levels, enlarged {e:.2}"); + } + + #[test] + fn a_raws_noise_the_photograph_does_not_share_is_held_back() { + // Same scene as above, but the RAW also carries grain at every scale + // that the export never had: its octave below the export's Nyquist + // disagrees with the export's, so the merge should stay near the + // enlargement. Ungated, it would sit where the RAW does. + let clean = scene(360, 240); + let raw = Rgb::new( + 360, + 240, + clean + .px + .iter() + .enumerate() + .map(|(i, v)| { + // murmur3's finalizer, so the grain is white. + let mut n = i as u32; + n = (n ^ (n >> 16)).wrapping_mul(0x85eb_ca6b); + n = (n ^ (n >> 13)).wrapping_mul(0xc2b2_ae35); + n ^= n >> 16; + v + 0.2 * (n as f32 / u32::MAX as f32 - 0.5) + }) + .collect(), + ); + let export = resize(&clean, 120, 80).unwrap(); + let look = Look::fit(&encoded(&export), &encoded(&export)); + let merged = merge(&export, &raw, &look, (0, 0, 360, 240), (360, 240)).unwrap(); + let enlarged = resize(&export, 360, 240).unwrap(); + let apart = |img: &Rgb| -> f32 { + let e: f32 = img + .px + .iter() + .zip(&enlarged.px) + .map(|(a, b)| (linear_to_srgb(*a) - linear_to_srgb(*b)).powi(2)) + .sum(); + (e / img.px.len() as f32).sqrt() * 255.0 + }; + let (m, r) = (apart(&merged), apart(&raw)); + assert!( + m < r / 5.0, + "merge moved {m:.2} levels from the enlargement, the RAW sits {r:.2}" + ); + } +} diff --git a/src/simulate.rs b/src/simulate.rs index 174b9bc..f6b73b1 100644 --- a/src/simulate.rs +++ b/src/simulate.rs @@ -161,7 +161,12 @@ pub fn encode(w: u32, h: u32, rgb: &[u8]) -> Result, String> { fn ycbcr_box420(w: u32, h: u32, rgb: &[u8]) -> Vec { let (w, h) = (w as usize, h as usize); let mut ycc = vec![0u8; w * h * 3]; - for (p, o) in rgb.chunks_exact(3).zip(ycc.chunks_exact_mut(3)) { + for (p, o) in rgb + .as_chunks::<3>() + .0 + .iter() + .zip(ycc.as_chunks_mut::<3>().0) + { let (r, g, b) = (p[0] as f32, p[1] as f32, p[2] as f32); let to_u8 = |v: f32| v.round().clamp(0.0, 255.0) as u8; o[0] = to_u8(0.299 * r + 0.587 * g + 0.114 * b);