Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
fade8e7
LR-PROF-CAMERACOLOR: align lens-corrected camera JPEG training pairs
r3d42-git Oct 23, 2026
46e809f
LR-PROF-CAMERACOLOR: merge current main and preserve geometry alignment
r3d42-git Oct 28, 2026
3f969c2
LR-PROF-CAMERACOLOR: synchronize external geometry with main
r3d42-git Nov 1, 2026
1424afa
LR-PROF-CAMERACOLOR: reject gains from dropped correspondence edges
r3d42-git Nov 1, 2026
04f8c67
LR-PROF-CAMERACOLOR: preserve lens dependencies in colour fits
r3d42-git Nov 2, 2026
d305b7b
LR-PROF-CAMERACOLOR: require original provenance for proxy repairs
r3d42-git Nov 2, 2026
20b954f
LR-PROF-CAMERACOLOR: reconcile current upstream integration
r3d42-git Nov 4, 2026
1fc885f
LR-PROF-CAMERACOLOR: reconcile runtime lens database integration
r3d42-git Nov 4, 2026
fbc601a
LR-PROF-CAMERACOLOR: reconcile DCP and display rendering integration
r3d42-git Nov 5, 2026
968c23b
LR-PROF-CAMERACOLOR: integrate upstream dither test follow-up
r3d42-git Nov 5, 2026
d593ba5
LR-PROF-CAMERACOLOR: integrate prepared culling previews
r3d42-git Nov 5, 2026
d1ab8b7
LR-PROF-CAMERACOLOR: preserve raw decode options in fresh smart previews
r3d42-git Nov 5, 2026
d505f21
LR-PROF-CAMERACOLOR: integrate current main and retain geometry regre…
r3d42-git Nov 5, 2026
fbb318a
LR-PROF-CAMERACOLOR: publish known activity totals before worker disp…
r3d42-git Nov 5, 2026
bd3ee7e
LR-PROF-CAMERACOLOR: narrow standalone color geometry scope
r3d42-git Nov 6, 2026
8d45e43
LR-PROF-CAMERACOLOR: keep DNG colour fits in stored sample space
r3d42-git Nov 16, 2026
1e27473
LR-PROF-CAMERACOLOR: align TIFF fixtures with current main
r3d42-git Nov 16, 2026
37c68e3
LR-PROF-CAMERACOLOR: record proposed geometry in the tracker row
r3d42-git Nov 17, 2026
aa54dd7
LR-PROF-CAMERACOLOR: merge current main and preserve correspondence s…
r3d42-git Nov 18, 2026
20c0943
Merge upstream main and retain camera profile cache invalidation
r3d42-git Nov 19, 2026
de8e20b
Keep the loaded camera profile fingerprint across lens reloads
r3d42-git Nov 19, 2026
1fd4a49
Merge upstream main and preserve Smart Preview provenance
r3d42-git Nov 25, 2026
344ac41
Keep Smart Preview scans valid across LensDB changes
r3d42-git Nov 25, 2026
fd17163
Merge main and preserve non-CR3 correspondence geometry
r3d42-git Nov 26, 2026
25a4377
Keep exact correspondence samples at invalid borders
r3d42-git Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/engine/src/camera_preview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights};
/// 13: the sensor proxy of every per-file fit gets the embedded vignetting correction the render applies (Fujifilm
/// RAF; other makes with a lens database), so the render no longer applies it twice, at the position a lens warp samples;
/// the warped candidate's alignment leaves out the pixels outside the sensor instead of reading them as black.
pub const LOOK_VERSION: u32 = 13;
/// 14: geometry-gated external lens and camera framing for JPEG calibration correspondences.
pub const LOOK_VERSION: u32 = 14;

#[derive(Clone, Debug)]
pub(crate) struct CameraLook {
Expand Down
11 changes: 10 additions & 1 deletion crates/engine/src/camera_preview/colour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,11 +131,20 @@ pub(crate) fn starting_colour_tags(raw: &mut RawImage, bytes: &[u8]) -> Option<C
if lightcraft_raw::color::has_matrix(&raw.color) {
return None;
}
let correction = crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(bytes));
starting_colour_tags_with_correction(raw, bytes, correction.as_ref())
Comment thread
r3d42-git marked this conversation as resolved.
Resolved
}

pub(super) fn starting_colour_tags_with_correction(
raw: &mut RawImage,
bytes: &[u8],
correction: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<ColorData> {
// the white the source shows, decided before `starting_colour` may fill in measured matrices
let 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));
// (a merge frame arrives without its lens warp: `lightcraft_merge` removes it before calling)
let (_, t, look) = starting_colour(raw, bytes, None, None);
let (_, t, look) = starting_colour(raw, bytes, None, correction);
dng_colour(&raw.color, &white, &t, look.as_ref())
}

Expand Down
108 changes: 97 additions & 11 deletions crates/engine/src/camera_preview/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,23 @@ pub(super) fn proxies(
.and_then(|l| Some((into_lens_geometry(&sensor, raw, k, l)?, into_lens_geometry(&clipped, raw, k, l)?)));
let gain = 2f32.powf(transform.baseline_exposure as f32);
let to_working = |p: [f32; 3]| transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * gain));
// External profiles describe the developed default crop, unlike OpcodeList3's active-area warp.
// Keep the established CR3/in-file routes; only an uncalibrated file with no in-file warp
// may propose this additional correspondence geometry. Its acceptance uses edges, never RGB error.
let aligned_external = embedded
.filter(|correction| {
raw.format != RawFormat::Cr3 && file_local_look(raw.format) && transform.matrix_is_fallback && lens.is_none() && correction.warp.is_some()
})
.and_then(|correction| {
let mut working = sensor.clone();
working.map_in_place(to_working);
align_profile_geometry(&working, &clipped, &reference, correction, raw.orientation)
});
let external_applied = aligned_external.is_some();
if let Some((aligned, mask)) = aligned_external {
sensor = aligned;
clipped = mask;
}
if raw.format == RawFormat::Cr3 {
// Orient the camera JPEG and the sensor identically before collecting pixel correspondences.
sensor = sensor.into_oriented(raw.orientation);
Expand All @@ -160,7 +177,7 @@ pub(super) fn proxies(
// NaN: those pixels are left out of the pairs anyway). Resized to exactly the proxy's size, like
// the reference, so the mask pairs pixel for pixel.
let clipped: Vec<bool> = resize(&clipped, sensor.width, sensor.height, Filter::Box).data.iter().map(|p| p[0] > 0.0).collect();
if raw.format != RawFormat::Cr3 {
if raw.format != RawFormat::Cr3 && !external_applied {
sensor.map_in_place(to_working);
}
Some((sensor, reference, clipped))
Expand All @@ -183,7 +200,7 @@ pub(super) struct Cr3Framing {
}

impl Cr3Framing {
const IDENTITY: Self = Self { scale: 1.0, offset: [0.0; 2] };
pub(super) const IDENTITY: Self = Self { scale: 1.0, offset: [0.0; 2] };

pub(super) fn source(self, x: f32, y: f32, w: usize, h: usize) -> (f32, f32) {
let (w, h) = (w as f32, h as f32);
Expand All @@ -196,6 +213,12 @@ impl Cr3Framing {
/// A separate third of the edges must confirm a substantial improvement and a close match.
/// A weak, flat or unrelated preview leaves the sensor framing unchanged.
pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option<Cr3Framing> {
estimate_framing_against(sensor, reference, sensor)
}

/// Score both a proposed lens geometry and its bounded framing against the original sensor.
/// The identity framing is a valid candidate: lens correction alone may already align the JPEG.
fn estimate_framing_against(sensor: &Rgb32f, reference: &Rgb32f, original: &Rgb32f) -> Option<Cr3Framing> {
if sensor.width.checked_mul(sensor.height)? != sensor.data.len() || reference.width.checked_mul(reference.height)? != reference.data.len() {
return None;
}
Expand All @@ -208,7 +231,12 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
if (reference.width, reference.height) != (w, h) {
return None;
}
let original = fit(original, PROXY, PROXY, Filter::Box);
if (original.width, original.height) != (w, h) || original.data.len() != sensor.data.len() {
return None;
}
let mut gradients = Rgb32f::new(w, h);
let mut original_gradients = Rgb32f::new(w, h);
let mut edges = Vec::new();
for y in 1..h - 1 {
for x in 1..w - 1 {
Expand All @@ -220,6 +248,8 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
};
let d = derivative(&sensor);
gradients.data[y * w + x] = [d[0], d[1], 0.0];
let d = derivative(&original);
original_gradients.data[y * w + x] = [d[0], d[1], 0.0];
let d = derivative(&reference);
let magnitude = d[0].hypot(d[1]);
let value = luminance_2020(reference.data[y * w + x]);
Expand All @@ -231,7 +261,7 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
if edges.len() < 192 {
return None;
}
let score = |framing: Cr3Framing, held_out: bool| -> Option<f64> {
let score = |gradients: &Rgb32f, framing: Cr3Framing, held_out: bool| -> Option<f64> {
let (mut agreement, mut weight, mut valid, mut total) = (0.0, 0.0, 0usize, 0usize);
for &(x, y, target, magnitude, holdout) in &edges {
if holdout != held_out {
Expand All @@ -254,15 +284,15 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
}
(valid >= 64 && valid * 5 >= total * 4 && weight > 0.0).then_some(agreement / weight)
};
let before = score(Cr3Framing::IDENTITY, false)?;
let mut best = (before, Cr3Framing::IDENTITY);
let before = score(&original_gradients, Cr3Framing::IDENTITY, false)?;
let mut best = (score(&gradients, Cr3Framing::IDENTITY, false).unwrap_or(-1.0), Cr3Framing::IDENTITY);
// At most 10% zoom and two proxy pixels of translation; a coarse search followed by one
// local refinement prevents unbounded optimisation on the photograph's contents.
for s in -10..=10 {
for tx in -4..=4 {
for ty in -4..=4 {
let framing = Cr3Framing { scale: 1.0 + s as f32 * 0.01, offset: [tx as f32 * 0.5 / w as f32, ty as f32 * 0.5 / h as f32] };
if let Some(value) = score(framing, false)
if let Some(value) = score(&gradients, framing, false)
&& value > best.0
{
best = (value, framing);
Expand All @@ -281,20 +311,20 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
if !(0.9..=1.1).contains(&framing.scale) || framing.offset[0].abs() > 2.0 / w as f32 || framing.offset[1].abs() > 2.0 / h as f32 {
continue;
}
if let Some(value) = score(framing, false)
if let Some(value) = score(&gradients, framing, false)
&& value > best.0
{
best = (value, framing);
}
}
}
}
let (held_before, held_after) = (score(Cr3Framing::IDENTITY, true)?, score(best.1, true)?);
let (held_before, held_after) = (score(&original_gradients, Cr3Framing::IDENTITY, true)?, score(&gradients, best.1, true)?);
if best.0 < 0.9 || best.0 < before + 0.04 || held_after < 0.9 || held_after < held_before + 0.04 {
return None;
}
if lightcraft_pipeline::profiling() {
eprintln!("[profile] CR3 JPEG framing {:?}, held-out edge agreement {held_before:.4} -> {held_after:.4}", best.1);
eprintln!("[profile] camera JPEG framing {:?}, held-out edge agreement {held_before:.4} -> {held_after:.4}", best.1);
}
Some(best.1)
}
Expand All @@ -314,15 +344,71 @@ fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rg
(apply(&sensor), apply(&clipped))
}

/// Resample a correspondence image with a common source map. Nonfinite/outside coordinates
/// become NaN so they cannot contribute colour or tone training pairs. A nonnegative clip mask
/// uses the same bilinear map: any clipped contributing sample remains strictly positive.
pub(super) fn resample_correspondence(image: &Rgb32f, source: impl Fn(f64, f64) -> lightcraft_geom::Point) -> Rgb32f {
let (w, h) = (image.width, image.height);
let mut out = Rgb32f::new(w, h);
if w == 0 || h == 0 {
return out;
}
for (i, pixel) in out.data.iter_mut().enumerate() {
let p = source((i % w) as f64 + 0.5, (i / w) as f64 + 0.5);
*pixel = if p.x.is_finite() && p.y.is_finite() && p.x >= 0.5 && p.y >= 0.5 && p.x <= w as f64 - 0.5 && p.y <= h as f64 - 0.5 {
image.sample_bilinear(p.x as f32, p.y as f32)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else {
[f32::NAN; 3]
};
}
out
}

/// A resolved profile is a proposal for camera-JPEG geometry, never an instruction to change
/// the rendered RAW's optics. The lens is already relative to the oriented default crop;
/// re-express it in this un-oriented sensor proxy's frame before using its green-plane warp.
/// Candidate and original are judged on the same fixed edges, with independent held-out edges.
pub(super) fn align_profile_geometry(
sensor: &Rgb32f,
clipped: &Rgb32f,
reference: &Rgb32f,
correction: &lightcraft_develop::EmbeddedLens,
orientation: lightcraft_geom::Orientation,
) -> Option<(Rgb32f, Rgb32f)> {
if correction.warp.is_none() || (sensor.width, sensor.height) != (clipped.width, clipped.height) {
return None;
}
let (w, h) = (sensor.width as f64, sensor.height as f64);
let (ow, oh) = if orientation.swaps_axes() { (h, w) } else { (w, h) };
let correction = lightcraft_pipeline::optics::reorient_lens(correction, orientation.inverse(), ow, oh);
let mut warp = lightcraft_pipeline::optics::Warp::identity(w, h);
warp.lens = Some(correction);
warp.lens_dist = 1.0;
let source = |x, y| warp.corrected_to_source(lightcraft_geom::Point::new(x, y), 1);
let candidate = resample_correspondence(sensor, source);
let framing = estimate_framing_against(&candidate, reference, sensor)?;
let mask = resample_correspondence(clipped, source);
let frame = |x: f64, y: f64| {
let (x, y) = framing.source(x as f32, y as f32, sensor.width, sensor.height);
lightcraft_geom::Point::new(f64::from(x), f64::from(y))
};
Some((resample_correspondence(&candidate, frame), resample_correspondence(&mask, frame)))
}

/// Colour training pairs of one raw for a camera profile: white-balanced camera RGB (with the
/// baseline exposure) → its camera JPEG (linear Rec.2020). `None` for formats with their own
/// colour matrices, other files or unusable previews.
pub(crate) fn profile_pairs(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option<Vec<([f64; 3], [f64; 3])>> {
pub(crate) fn profile_pairs(
raw: &RawImage,
bytes: &[u8],
lens: Option<&LensGeometry>,
correction: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<Vec<([f64; 3], [f64; 3])>> {
if !file_local_look(raw.format) || lightcraft_raw::color::has_matrix(&raw.color) {
return 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, lens, None)?;
let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens, correction)?;
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);
Expand Down
Loading