LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Merge PR #1586 (rebased)
Brandon Thomas99eba2e0692e
diff --cc crates/engine/src/camera_preview.rsindex e01116b45,75d07d508..fbf4e04a8--- a/crates/engine/src/camera_preview.rs+++ b/crates/engine/src/camera_preview.rs@@@ -76,38 -77,10 +77,43 @@@ pub(crate) fn file_local_look(format: R/// white (a monochrome picture style) has no colour to fit, but still gives its tone curve: with the camera profile's/// colour in [`fit_preview`], else on top of the spectral matrices or the fallback ([`monochrome_look`]). Returns the/// as-shot white, the camera transform at it and the fitted look.+ /// `lens` is the file's own lens-correction warp ([`lens_geometry`], read before the caller removes it from+ /// `OpcodeList3`): the camera applied it to its JPEG, so the sensor proxy is warped the same way before pairing.-pub(crate) fn starting_colour(raw: &mut RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> (Xy, CameraTransform, Option<CameraLook>) {- starting_colour_with(raw, |raw, t| fit_preview(raw, bytes, t, lens), |raw, t| monochrome_look(raw, bytes, t, lens))++/// `embedded` is the file's embedded lens vignetting, for the DNG tone fit.+pub(crate) fn starting_colour(+ raw: &mut RawImage,+ bytes: &[u8],- lens: Option<&lightcraft_develop::EmbeddedLens>,++ lens: Option<&LensGeometry>,++ embedded: Option<&lightcraft_develop::EmbeddedLens>,+) -> (Xy, CameraTransform, Option<CameraLook>) {- let (xy, t, look) = starting_colour_with(raw, |raw, t| fit_preview(raw, bytes, t), |raw, t| monochrome_look(raw, bytes, t));++ let (xy, t, look) =++ starting_colour_with(raw, |raw, t| fit_preview(raw, bytes, t, lens), |raw, t| monochrome_look(raw, bytes, t, lens));+ if look.is_none() && dng_tone_eligible(raw, &t) {- let look = fit_dng_tone(raw, bytes, &t, lens);++ let look = fit_dng_tone(raw, bytes, &t, embedded);+ return (xy, t, look);+ }+ (xy, t, look)+}++/// Whether the profile's tone curve is absent or the identity (within 0.005 over the range).+fn identity_tone_curve(curve: Option<&lightcraft_raw::profile::ToneCurve>) -> bool {+ curve.is_none_or(|c| {+ (0..=32).all(|i| {+ let x = i as f32 / 32.0;+ (c.eval(x) - x).abs() < 0.005+ })+ })+}++/// A DNG with its own colour model whose tone is not (yet) defined by the file: a matrix, no+/// non-identity `ProfileToneCurve`, no `LookTable` (a look table is the file's own rendering).+pub(crate) fn dng_tone_eligible(raw: &RawImage, t: &CameraTransform) -> bool {+ let p = &raw.color.profile;+ raw.format == RawFormat::Dng+ && !t.matrix_is_fallback+ && identity_tone_curve(p.tone_curve.as_ref())+ && p.look_table.is_none()+ && p.gain_table_map.is_none()}/// [`starting_colour`] with the JPEG fit (the look, and whether the JPEG is black and white) and the black-and-white@@@ -154,7 -127,8 +160,8 @@@ pub(crate) fn starting_colour_tags(raw// the white the source shows, decided before `starting_colour` may fill in measured matriceslet scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata);let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(raw));- let (_, t, look) = starting_colour(raw, bytes, None);+ // (a merge frame arrives without its lens warp: `lightcraft_merge` removes it before calling)- let (_, t, look) = starting_colour(raw, bytes, None);++ let (_, t, look) = starting_colour(raw, bytes, None, None);dng_colour(&raw.color, &white, &t, look.as_ref())}@@@ -256,7 -230,7 +263,7 @@@ pub(crate) fn fit_preview(raw: &RawImagif !transform.matrix_is_fallback || !file_local_look(raw.format) {return (None, false);}- let Some((sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, 0.0) else { return (None, false) };- let Some((sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, lens) else { return (None, false) };++ let Some((sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, 0.0, lens) else { return (None, false) };let black_and_white = monochrome(&reference);// A camera profile pooled from many photos knows colours this photo shows too little of;// try its colour first and fit tone/chroma per photo (picture styles vary).@@@ -413,163 -387,16 +420,170 @@@ fn at_most(a: &CameraTone, b: &CameraTo/// decodes at full size, so a 66.5 MP full-frame ILCE-7RM6 JPEG transiently needs ~200 MB (3 B/px);/// 128 MP also admits 100 MP medium-format previews.const FIT_PREVIEW_MAX_PIXELS: u64 = 128_000_000;++/// A DNG's tone and chroma curves fitted to its own camera JPEG ([`dng_tone_eligible`]); the file's colour model+/// (matrix, profile tables, white balance) stays as it is: the proxy goes through the file's tables and the given+/// colour of the search is the identity. Same held-out acceptance gates as [`fit_look`]; the preview must be near+/// the raw's size, show the same picture ([`structure_agrees`]), and the curve must not clip more highlights than+/// the plain render ([`clips_more`]).+fn fit_dng_tone(raw: &RawImage, bytes: &[u8], transform: &CameraTransform, lens: Option<&lightcraft_develop::EmbeddedLens>) -> Option<CameraLook> {+ // Logged under LIGHTCRAFT_PROFILE so a corpus run can count the outcome per gate.+ let refuse = |why: &str| {+ if std::env::var_os("LIGHTCRAFT_PROFILE").is_some() {+ eprintln!("DNGTONE refused {why}");+ }+ None+ };- let Some((mut sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, MIN_PREVIEW_FRACTION) else { return refuse("preview") };++ let Some((mut sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, MIN_PREVIEW_FRACTION, None) else { return refuse("preview") };+ // As the loader renders it: the profile's tables around the baseline exposure.+ let xy = lightcraft_raw::color::as_shot_white_xy(raw);+ if let Some(tables) = lightcraft_raw::profile::ProfileTables::new(&raw.color.profile, lightcraft_raw::color::illuminant_weight(&raw.color, xy)) {+ let gain = 2f32.powf(transform.baseline_exposure as f32);+ sensor.map_in_place(|p| tables.apply(p.map(|v| v / gain), gain));+ }+ correct_vignetting(&mut sensor, lens, raw.orientation);+ if (sensor.width, sensor.height) != (reference.width, reference.height) {+ return refuse("preview");+ }+ if !structure_agrees(&sensor, &reference) {+ return refuse("structure");+ }+ let unclipped = without_clipped(&sensor, &clipped);+ let fit_on = unclipped.as_ref().unwrap_or(&sensor);+ let colour = Some((Mat3::IDENTITY, None));+ let look = TONE_FITS.iter().find_map(|&tone| {+ [false, true]+ .into_iter()+ .find_map(|away_from_edges| fit_attempt(fit_on, &reference, &colour, Attempt { tone, profile: true, away_from_edges, dark: true }))+ });+ let Some(look) = look else { return refuse("fit") };+ let plain = match raw.color.profile.tone_curve.as_ref().and_then(crate::files::dng_tone_curve) {+ Some(curve) => ToneMap::camera(&curve, 0.0, 0.0, 0.0),+ None => ToneMap::new(0.0, 0.0, 0.0),+ };+ let fitted = ToneMap::camera(&look.tone, 0.0, 0.0, 0.0);+ if clips_more(&sensor, &reference, &fitted, &plain) {+ return refuse("clip");+ }+ if std::env::var_os("LIGHTCRAFT_PROFILE").is_some() {+ eprintln!("DNGTONE accepted");+ }+ Some(look)+}++/// Whether the fitted tone map puts clearly more of the photo's proxy pixels at or near white than both the plain+/// render and the camera's own preview do ([`CLIP_TOLERANCE`]): a fit that clips what the camera clips too is the+/// camera's look, one that clips what neither does loses highlight detail.+fn clips_more(sensor: &Rgb32f, reference: &Rgb32f, fitted: &ToneMap, plain: &ToneMap) -> bool {+ let near_white = |tone: &ToneMap| {+ let n = sensor.data.iter().filter(|p| p.iter().all(|v| v.is_finite()) && tone.apply(luminance_2020(p.map(|v| v.max(0.0)))) >= 0.98).count();+ n as f64 / sensor.data.len().max(1) as f64+ };+ let preview = reference.data.iter().filter(|p| luminance_2020(**p) >= 0.98).count() as f64 / reference.data.len().max(1) as f64;+ near_white(fitted) > near_white(plain).max(preview) + CLIP_TOLERANCE+}++/// Multiply the sensor proxy (sensor orientation, default crop) by the embedded vignetting correction, the gain the+/// pipeline applies to the render (`optics::embedded_vignette_gain`; `lens` is in the oriented, cropped frame): the+/// camera JPEG has it applied, so a tone fitted without it brightens the render's corners twice.+fn correct_vignetting(sensor: &mut Rgb32f, lens: Option<&lightcraft_develop::EmbeddedLens>, orientation: lightcraft_geom::Orientation) {+ let Some(vignette) = lens.and_then(|l| l.vignette) else { return };+ let (w, h) = (sensor.width as f64, sensor.height as f64);+ let (ow, oh) = if orientation.swaps_axes() { (h, w) } else { (w, h) };+ let width = sensor.width.max(1);+ for (i, p) in sensor.data.iter_mut().enumerate() {+ let (x, y) = orientation.map((i % width) as f64 + 0.5, (i / width) as f64 + 0.5, w, h);+ let gain = lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, lightcraft_geom::Point::new(x, y), ow, oh) as f32;+ *p = p.map(|v| v * gain);+ }+}++/// The embedded preview's long edge must be at least this share of the raw's (and 384 px): a DNG whose preview is a+/// small thumbnail is not fitted.+const MIN_PREVIEW_FRACTION: f64 = 0.9;++/// Lowest preview luminance and channel value a tone-only fit trains on (the other fits use 0.015 and 0.004): a dark+/// night scene has most of its pixels below 0.015, and a curve fitted without them overshoots its shadows.+const DARK_FLOOR: (f32, f32) = (0.004, 0.001);++/// Share of the proxy by which the fitted curve may clip more highlights than the plain render and the camera's+/// preview (chosen on the CC0 and user DNGs from the clipped share of their 1440 px renders: it refuses the fits+/// that clip about 1% more than the camera does and passes the ones that clip like the camera).+const CLIP_TOLERANCE: f64 = 0.001;++/// Log-luminance correlation (5 × 5 box blurred) the unshifted proxies must reach.+const MIN_STRUCTURE: f64 = 0.85;++/// Whether the sensor proxy and the camera JPEG proxy show the same picture in the same place: their log luminance+/// correlates by at least [`MIN_STRUCTURE`] unshifted, and no shift of more than one proxy pixel (within ±3)+/// correlates better.+fn structure_agrees(sensor: &Rgb32f, reference: &Rgb32f) -> bool {+ let (w, h) = (sensor.width, sensor.height);+ if (w, h) != (reference.width, reference.height) || w < 16 || h < 16 || sensor.data.len() != w * h || reference.data.len() != w * h {+ return false;+ }+ let log = |img: &Rgb32f| -> Vec<f64> {+ let l: Vec<f64> =+ img.data.iter().map(|p| f64::from(luminance_2020(p.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 }))).max(1e-4).ln()).collect();+ (0..w * h)+ .map(|i| {+ let (x, y) = (i % w, i / w);+ let (mut sum, mut n) = (0.0, 0.0);+ for yy in y.saturating_sub(2)..(y + 3).min(h) {+ for xx in x.saturating_sub(2)..(x + 3).min(w) {+ if let Some(v) = l.get(yy * w + xx) {+ sum += v;+ n += 1.0;+ }+ }+ }+ sum / f64::max(n, 1.0)+ })+ .collect()+ };+ let (a, b) = (log(sensor), log(reference));+ const M: usize = 3;+ let corr = |dx: isize, dy: isize| -> f64 {+ let (mut n, mut sa, mut sb, mut saa, mut sbb, mut sab) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);+ for y in M..h - M {+ for x in M..w - M {+ let (xx, yy) = (x.saturating_add_signed(dx), y.saturating_add_signed(dy));+ let (Some(&u), Some(&v)) = (a.get(y * w + x), b.get(yy * w + xx)) else { continue };+ n += 1.0;+ sa += u;+ sb += v;+ saa += u * u;+ sbb += v * v;+ sab += u * v;+ }+ }+ let var = (saa - sa * sa / n) * (sbb - sb * sb / n);+ if n < 2.0 || var <= 1e-12 { 0.0 } else { (sab - sa * sb / n) / var.sqrt() }+ };+ let at_zero = corr(0, 0);+ let (mut best, mut shift) = (at_zero, (0isize, 0isize));+ for dy in -(M as isize)..=M as isize {+ for dx in -(M as isize)..=M as isize {+ let c = corr(dx, dy);+ if c > best + 1e-9 {+ (best, shift) = (c, (dx, dy));+ }+ }+ }+ at_zero >= MIN_STRUCTURE && shift.0.abs() <= 1 && shift.1.abs() <= 1+}+/// Same-size proxies of the sensor (white-balanced, baseline exposure, through `transform`'s/// matrix: the generic camera ≈ sRGB model) and of the file's embedded camera JPEG (linear Rec.2020),/// and per proxy pixel whether any sensor sample it covers is clipped.- fn proxies(raw: &RawImage, bytes: &[u8], transform: &CameraTransform, size: usize, min_fraction: f64) -> Option<(Rgb32f, Rgb32f, Vec<bool>)> {+ fn proxies(+ raw: &RawImage,+ bytes: &[u8],+ transform: &CameraTransform,+ size: usize,++ min_fraction: f64,+ lens: Option<&LensGeometry>,+ ) -> Option<(Rgb32f, Rgb32f, Vec<bool>)> {let edge = (2 * size).max(384) as u32;let decoded = crate::files::decode_raw_preview(bytes,@@@ -784,7 -620,7 +812,7 @@@ pub(crate) fn profile_pairs(raw: &RawImreturn None;}let transform = lightcraft_raw::color::camera_transform(raw, lightcraft_raw::color::as_shot_white_xy(raw));- let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0)?;- let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, lens)?;++ let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens)?;let to_camera = transform.matrix.inverse()?;// clipped sensor pixels don't record the scene's colour (see `fit_look`)let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor);@@@ -1300,7 -1222,7 +1424,7 @@@ fn monochrome_look(raw: &RawImage, byteif !file_local_look(raw.format) {return None;}- let (sensor, reference, clipped) = proxies(raw, bytes, transform, PROXY, 0.0)?;- let (sensor, reference, clipped) = proxies(raw, bytes, transform, PROXY, lens)?;++ let (sensor, reference, clipped) = proxies(raw, bytes, transform, PROXY, 0.0, lens)?;if !monochrome(&reference) {return None;}@@@ -2334,6 -2171,93 +2458,93 @@@ mod tests}}+ /// The lens warp the colour fit follows is the first `WarpRectilinear`'s green plane; no warp, a DNG 1.6 chain+ /// (phone DNGs, which carry colour matrices), a centre outside the area or a non-finite term give none.+ #[test]+ fn lens_geometry_reads_the_first_rectilinear_warp() {+ use lightcraft_raw::Opcode;+ let warp = |k0: f64, c: [f64; 2]| Opcode::WarpRectilinear {+ planes: vec![[9.0, 0.0, 0.0, 0.0, 0.0, 0.0], [k0, 0.1, -0.02, 0.003, 0.0, 0.0], [9.0, 0.0, 0.0, 0.0, 0.0, 0.0]],+ center: c,+ };+ assert_eq!(lens_geometry(&[warp(0.97, [0.5, 0.4])]), Some(LensGeometry { k: [0.97, 0.1, -0.02, 0.003], center: [0.5, 0.4] }));+ let single = Opcode::WarpRectilinear { planes: vec![[1.02, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] };+ assert_eq!(lens_geometry(std::slice::from_ref(&single)).map(|g| g.k[0]), Some(1.02));+ assert!(lens_geometry(&[]).is_none());+ assert!(lens_geometry(&[warp(1.0, [1.5, 0.5])]).is_none());+ assert!(lens_geometry(&[warp(f64::NAN, [0.5, 0.5])]).is_none());+ let mut p = [0.0; lightcraft_raw::opcodes::WR2_LEN];+ p[0] = 1.0;+ p[18] = 1e6;+ let chain = Opcode::WarpRectilinear2 { planes: vec![p], center: [0.5, 0.5], reciprocal: false, optional: false };+ assert!(lens_geometry(&[chain, single]).is_none());+ }++ /// A binned sensor proxy moved into the camera JPEG's geometry: the identity warp leaves it as it is, a warp+ /// whose source radius is 0.8 of the output's samples nearer the centre, output pixels whose source falls outside+ /// the proxy are NaN (left out of the pairs), and a proxy of another size is left alone.+ #[test]+ fn the_sensor_proxy_follows_the_cameras_lens_warp() {+ let mut raw = raw_of(RawFormat::Nef, "NIKON CORPORATION", "NIKON Z 6_2", Default::default());+ raw.active_area = lightcraft_raw::Rect::new(0, 0, 64, 48);+ raw.crop = raw.active_area;+ // a 1/4 proxy whose pixels hold their own coordinates+ let mut img = Rgb32f::new(16, 12);+ for (i, p) in img.data.iter_mut().enumerate() {+ *p = [(i % 16) as f32, (i / 16) as f32, 1.0];+ }+ let geometry = |k0: f64| LensGeometry { k: [k0, 0.0, 0.0, 0.0], center: [0.5, 0.5] };+ let same = into_lens_geometry(&img, &raw, 4, &geometry(1.0)).unwrap();+ assert!(same.data.iter().zip(&img.data).all(|(a, b)| (0..3).all(|c| (a[c] - b[c]).abs() < 1e-4)));+ // the corner pixel's centre (1.5, 1.5) maps to (31.5 - 0.8 * 30, 23.5 - 0.8 * 22) = (7.5, 5.9) on the sensor+ let zoomed = into_lens_geometry(&img, &raw, 4, &geometry(0.8)).unwrap();+ assert!((zoomed.data[0][0] - 1.5).abs() < 1e-4 && (zoomed.data[0][1] - 1.1).abs() < 1e-4, "{:?}", zoomed.data[0]);+ let outside = into_lens_geometry(&img, &raw, 4, &geometry(1.3)).unwrap();+ assert!(outside.data[0][0].is_nan() && outside.data[6 * 16 + 8][0].is_finite());+ assert!(into_lens_geometry(&Rgb32f::new(15, 12), &raw, 4, &geometry(1.0)).is_none());+ }++ /// A raw with an in-file lens correction (Fujifilm, Panasonic, the A7R IVA, Nikon) may have a lens-corrected+ /// camera JPEG: the proxies the fit pairs line up with it at least as well as the uncorrected sensor, on every+ /// corpus file the colour fit uses that carries such a warp, and better on those whose JPEG is corrected.+ #[test]+ fn corpus_lens_corrected_jpegs_pair_with_the_warped_sensor() {+ let dir = std::env::var_os("LIGHTCRAFT_CORPUS")+ .map(std::path::PathBuf::from)+ .unwrap_or_else(|| std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"))+ .join("raw");+ let Ok(entries) = std::fs::read_dir(&dir) else {+ eprintln!("skip: no corpus at {}", dir.display());+ return;+ };+ let mut paths: Vec<_> = entries.flatten().map(|e| e.path()).collect();+ paths.sort();+ let (mut checked, mut gain) = (0, 0.0);+ for path in paths {+ let Ok(bytes) = std::fs::read(&path) else { continue };+ let Ok(mut raw) = lightcraft_raw::decode(&bytes) else { continue };+ let Some(lens) = lens_geometry(&raw.opcodes.list3) else { continue };+ if !file_local_look(raw.format) || lightcraft_raw::color::has_matrix(&raw.color) {+ continue;+ }+ raw.opcodes.list3.retain(|op| !op.is_lens_correction());+ let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw));+ let (Some((plain, reference, _)), Some((chosen, chosen_reference, _))) =- (proxies(&raw, &bytes, &t, PROXY, None), proxies(&raw, &bytes, &t, PROXY, Some(&lens)))++ (proxies(&raw, &bytes, &t, PROXY, 0.0, None), proxies(&raw, &bytes, &t, PROXY, 0.0, Some(&lens)))+ else {+ continue;+ };+ let (before, after) = (alignment(&plain, &reference), alignment(&chosen, &chosen_reference));+ eprintln!("{}: alignment {before:.3} -> {after:.3}", path.display());+ // (chosen on camera RGB, measured after the colour transform: a near tie may flip by a little)+ assert!(after >= before - 0.01, "{}: {before:.3} -> {after:.3}", path.display());+ gain += after - before;+ checked += 1;+ }+ eprintln!("{checked} corpus raws with an in-file lens warp, mean gain {:.3}", gain / checked.max(1) as f64);+ assert!(checked == 0 || gain > 0.0);+ }+/// Step 1: a file's own colour matrices win over everything, including a spectral row for its model; no JPEG fit/// is tried.#[test]@@@ -2381,7 -2305,7 +2592,7 @@@assert!(crate::camera_profiles::get("ILCE-7M4").is_some());let camera = lightcraft_raw::spectral::find(Some("SONY"), "ILCE-7M4").unwrap();let mut raw = raw_of(RawFormat::Arw, "SONY", "ILCE-7M4", Default::default());-- let (_, t, look) = starting_colour(&mut raw, &[], None);++ let (_, t, look) = starting_colour(&mut raw, &[], None, None);assert!(look.is_none());assert_eq!(raw.color.color_matrix, camera.color_matrix.map(Some));assert!(!t.matrix_is_fallback);@@@ -2440,13 -2364,13 +2651,13 @@@#[test]fn a_camera_outside_the_table_keeps_the_fallback() {let mut raw = raw_of(RawFormat::Cr2, "Canon", "Canon EOS 7D", Default::default());-- let (_, t, look) = starting_colour(&mut raw, &[], None);++ let (_, t, look) = starting_colour(&mut raw, &[], None, None);assert!(look.is_none() && t.matrix_is_fallback);assert_eq!(raw.color, lightcraft_raw::ColorData::default());// without a model there is no table rowlet mut raw = raw_of(RawFormat::Cr2, "Canon", "", Default::default());raw.metadata.model = None;-- assert!(starting_colour(&mut raw, &[], None).1.matrix_is_fallback);++ assert!(starting_colour(&mut raw, &[], None, None).1.matrix_is_fallback);}/// The colour precedence on public raws (each skipped without its corpus file): a photo whose JPEG fit is@@@ -2471,7 -2396,7 +2683,7 @@@let measured = lightcraft_raw::spectral::find(make, model).is_some();let covered = measured || lightcraft_raw::kelvin_presets::covers(make, model);let before = raw.color.clone();- let (_, t, fitted) = starting_colour(&mut raw, &bytes, None);- let (_, t, fitted) = starting_colour(&mut raw, &bytes, lens.as_ref());++ let (_, t, fitted) = starting_colour(&mut raw, &bytes, lens.as_ref(), None);let spectral = !own && fitted.is_none() && measured;eprintln!("{name}: own matrices {own}, JPEG fit {}, spectral {spectral}", fitted.is_some());assert_eq!(raw.color != before, spectral, "{name}");@@@ -2981,9 -2876,9 +3193,9 @@@let mut raw = lightcraft_raw::decode(&bytes).unwrap();raw.opcodes.list3.retain(|op| !op.is_lens_correction());let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw));- let look = fit_preview(&raw, &bytes, &transform).0.expect("a camera look");+ let look = fit_preview(&raw, &bytes, &transform, None).0.expect("a camera look");// the look fitted to the JPEG, as before this change- let (sensor, reference, clipped) = proxies(&raw, &bytes, &transform, PROXY, 0.0).unwrap();- let (sensor, reference, clipped) = proxies(&raw, &bytes, &transform, PROXY, None).unwrap();++ let (sensor, reference, clipped) = proxies(&raw, &bytes, &transform, PROXY, 0.0, None).unwrap();let profile = raw.metadata.model.as_deref().and_then(crate::camera_profiles::get);let colour = profile.as_ref().and_then(|p| Some((p.matrix().mul(&transform.matrix.inverse()?), p.hue_sat.clone())));let fitted = fit_look(&sensor, &reference, &clipped, colour).unwrap();diff --cc crates/engine/src/files.rsindex 534025206,2c3c85341..dd246cf84--- a/crates/engine/src/files.rs+++ b/crates/engine/src/files.rs@@@ -429,8 -408,8 +431,10 @@@ fn load_bytes_now// the camera's measured matrices (`Photo::relative_wb` decides the same from the catalog's camera)let scale = WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata);// the source's segmentation mattes (DNG semantic masks), read while the starting colour is fitted-- let ((xy, t, camera_look), mattes) =- rayon::join(|| crate::camera_preview::starting_colour(&mut raw, &bytes, lens.as_ref()), || dng_mattes(&bytes, &info));- rayon::join(|| crate::camera_preview::starting_colour(&mut raw, &bytes, lens_geometry.as_ref()), || dng_mattes(&bytes, &info));++ let ((xy, t, camera_look), mattes) = rayon::join(++ || crate::camera_preview::starting_colour(&mut raw, &bytes, lens_geometry.as_ref(), lens.as_ref()),++ || dng_mattes(&bytes, &info),++ );drop(bytes);// Previews and thumbnails bin the mosaic straight to (about) the size they need; only// larger levels (exports, 1:1) demosaic the whole sensor.diff --cc crates/engine/src/tests_xmp.rsindex c5f2b05c0,6921a6f8c..231a7bee3--- a/crates/engine/src/tests_xmp.rs+++ b/crates/engine/src/tests_xmp.rs@@@ -975,7 -973,7 +975,7 @@@ fn dngs_of_raws_without_colour_matricesstd::fs::write(&path, &bytes).unwrap();let mut opened = lightcraft_raw::decode(&bytes).unwrap();assert!(!has_matrix(&opened.color));-- let (_, want, look) = crate::camera_preview::starting_colour(&mut opened, &bytes, None);++ let (_, want, look) = crate::camera_preview::starting_colour(&mut opened, &bytes, None, None);assert_eq!((want.matrix_is_fallback, look.is_none()), (!measured, true), "{model}");let mut s = Session::new().with_fs();diff --cc docs/whats-new.mdindex 20bde58af,7bd55c810..70bfe4076--- a/docs/whats-new.md+++ b/docs/whats-new.md@@@ -20,6 -24,13 +20,11 @@@#1447), or keeps the photo you had when the folder holds it. Before, the photo from the previous view stayed active:Photo Grid marked nothing, and Detail, the histogram and the photo info showed a photo that isn't in the folder.-## 2026-10-14-+ ### Closer camera colour for lens-corrected raws+ - Raws from cameras that correct their own JPEG for lens distortion (Panasonic and Fujifilm with that setting on, the+ Sony A7R IVA) now start from colours closer to the camera's. The starting look was being fitted against a JPEG that+ didn't line up with the raw near the edges. Photos you already imported pick this up when their previews are rebuilt.+### HDR merges of moving lights, and many brackets at once- A star, the moon or a light that moves between the photos of a bracket (a night bracket on a tripod) no longerleaves a black hole where the middle photo had it clipped. With Deghost, the brightest photo's copy of it in a