Skip to content
Merged
Show file tree
Hide file tree
Changes from 23 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
5 changes: 3 additions & 2 deletions crates/engine/src/camera_preview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ mod tone;
pub(crate) use colour::{PROFILE_PROXY, dng_colour, dng_tone_eligible};
#[cfg(test)]
use colour::{PROXY, starting_colour_with};
pub(crate) use colour::{file_local_look, starting_colour, starting_colour_tags, with_starting_colour};
pub(crate) use colour::{correspondence_correction, file_local_look, starting_colour, starting_colour_tags, with_starting_colour};
pub(crate) use hue_sat::HueSat;
#[cfg(test)]
use hue_sat::{MIN_LUMINANCE_KEPT, NO_LUMINANCE_KEPT, fit_hue_sat, hue_saturation, restore_weight};
Expand Down Expand Up @@ -86,7 +86,8 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights};
/// the warped candidate's alignment leaves out the pixels outside the sensor instead of reading them as black.
/// 14: bundled camera profiles also match the Nikon model spellings that differ in case, spacing or the Z8 alias,
/// so previews made without the profile are rebuilt.
pub const LOOK_VERSION: u32 = 14;
/// 15: geometry-gated external lens and camera framing for JPEG calibration correspondences.
pub const LOOK_VERSION: u32 = 15;

#[derive(Clone, Debug)]
pub(crate) struct CameraLook {
Expand Down
35 changes: 30 additions & 5 deletions crates/engine/src/camera_preview/colour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,18 +126,46 @@ pub(super) fn starting_colour_with(
(xy, t, look.or_else(|| dark(raw, &t)))
}

/// Additional profile resolution for this proposal's pooled/DNG routes; CR3 keeps Main's route.
pub(crate) fn correspondence_correction(raw: &RawImage, bytes: &[u8]) -> Option<lightcraft_develop::EmbeddedLens> {
if raw.format == RawFormat::Cr3 {
return None;
}
crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(bytes))
}

/// The colour a raw starts from ([`starting_colour`]) as DNG colour tags, for a DNG of the raw's camera RGB (Photo
/// Merge, issue #965): without them a merge of CR2s, whose colour comes from a look fitted to their JPEG, rendered
/// green and dark. `None` when the file has colour matrices of its own (a DNG keeps them).
pub(crate) fn starting_colour_tags(raw: &mut RawImage, bytes: &[u8]) -> Option<ColorData> {
if lightcraft_raw::color::has_matrix(&raw.color) {
return None;
}
let correction = correspondence_correction(raw, bytes);
starting_colour_tags_with_correction(raw, bytes, correction.as_ref())
}

/// Fit DNG colour in the stored sample space. Only a vignette owned by the file's
/// retained opcodes may enter the fit; external profile geometry still aligns the pairs.
pub(super) fn starting_colour_tags_with_correction(
raw: &mut RawImage,
bytes: &[u8],
correction: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<ColorData> {
let correction = correction.filter(|_| raw.format != RawFormat::Cr3).map(|correction| lightcraft_develop::EmbeddedLens {
vignette: crate::files::embedded_lens(&raw.info()).and_then(|lens| lens.vignette),
..*correction
});
// 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);
// Resolve the file warp before removing lens opcodes, just as opening the RAW does.
// The fit needs uncorrected sensor samples; the caller still owns the original opcodes.
let lens = super::lens_geometry(&raw.opcodes.list3);
let list3 = std::mem::take(&mut raw.opcodes.list3);
raw.opcodes.list3 = list3.iter().filter(|op| !op.is_lens_correction()).cloned().collect();
let (_, t, look) = starting_colour(raw, bytes, lens.as_ref(), correction.as_ref());
raw.opcodes.list3 = list3;
dng_colour(&raw.color, &white, &t, look.as_ref())
}

Expand All @@ -149,10 +177,7 @@ pub(crate) fn with_starting_colour(raw: &mut RawImage, bytes: &[u8]) {
if lightcraft_raw::color::has_matrix(&raw.color) {
return;
}
let list3 = raw.opcodes.list3.clone();
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
let tags = starting_colour_tags(raw, bytes);
raw.opcodes.list3 = list3;
if let Some(tags) = tags {
raw.color = tags;
}
Expand Down
152 changes: 138 additions & 14 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,9 +213,17 @@ 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, None)
}

/// 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: Option<&Rgb32f>) -> Option<Cr3Framing> {
if sensor.width.checked_mul(sensor.height)? != sensor.data.len() || reference.width.checked_mul(reference.height)? != reference.data.len() {
return None;
}
let proposal = original.is_some();
let original = original.unwrap_or(sensor);
let sensor = fit(sensor, PROXY, PROXY, Filter::Box);
let (w, h) = (sensor.width, sensor.height);
if w < 16 || h < 16 {
Expand All @@ -208,7 +233,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 +250,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 +263,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, support: Option<(&Rgb32f, Cr3Framing)>| -> 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 @@ -247,25 +279,49 @@ pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Optio
if !length.is_finite() || length <= 0.01 {
continue;
}
// Pairwise comparisons use exactly the same valid edges on both sides,
// including the same reference weights.
if let Some((other, map)) = support {
let (ox, oy) = map.source(x, y, w, h);
if ox < 1.5 || oy < 1.5 || ox > w as f32 - 1.5 || oy > h as f32 - 1.5 {
continue;
}
let p = other.sample_bilinear(ox, oy);
let length = p[0].hypot(p[1]);
if !length.is_finite() || length <= 0.01 {
continue;
}
}
let k = f64::from(magnitude.min(0.25));
agreement += k * f64::from((sample[0] * target[0] + sample[1] * target[1]) / (length * magnitude));
weight += k;
valid += 1;
}
(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);
// Only profile proposals use common-support improvement during candidate selection.
// The public CR3 framing fallback retains its original independent-support search.
let before = score(&original_gradients, Cr3Framing::IDENTITY, false, None)?;
let training = |framing| -> Option<(f64, f64)> {
let after = score(&gradients, framing, false, proposal.then_some((&original_gradients, Cr3Framing::IDENTITY)))?;
if proposal && after < 0.9 {
return None;
}
let before = if proposal { score(&original_gradients, Cr3Framing::IDENTITY, false, Some((&gradients, framing)))? } else { before };
(!proposal || after >= before + 0.04).then_some((before, after))
};
let initial = training(Cr3Framing::IDENTITY);
let mut best = (initial.map_or(-1.0, |v| v.1), Cr3Framing::IDENTITY, initial.map_or(before, |v| v.0));
// 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((before, value)) = training(framing)
&& value > best.0
{
best = (value, framing);
best = (value, framing, before);
}
}
}
Expand All @@ -281,24 +337,36 @@ 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((before, value)) = training(framing)
&& value > best.0
{
best = (value, framing);
best = (value, framing, before);
}
}
}
}
let (held_before, held_after) = (score(Cr3Framing::IDENTITY, true)?, score(best.1, true)?);
if best.0 < 0.9 || best.0 < before + 0.04 || held_after < 0.9 || held_after < held_before + 0.04 {
if proposal && best.0 < 0.9 {
return None;
}
let (held_before, held_after) = (
score(&original_gradients, Cr3Framing::IDENTITY, true, proposal.then_some((&gradients, best.1)))?,
score(&gradients, best.1, true, proposal.then_some((&original_gradients, Cr3Framing::IDENTITY)))?,
);
if best.0 < 0.9 || best.0 < best.2 + 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)
}

/// Exercise the proposal gate independently of lens-map construction in regressions.
#[cfg(test)]
pub(super) fn estimate_profile_framing(candidate: &Rgb32f, reference: &Rgb32f, original: &Rgb32f) -> Option<Cr3Framing> {
estimate_framing_against(candidate, reference, Some(original))
}

/// The sensor proxy and its clip mask (same size), both moved to the camera JPEG's framing.
fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rgb32f, Rgb32f) {
let Some(framing) = estimate_cr3_framing(&sensor, reference) else { return (sensor, clipped) };
Expand All @@ -314,15 +382,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, Some(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
Loading