Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
c7e8c5f
LR-PROF-CAMERACOLOR: a partial look from the bright pairs for mostly-…
AlexChambers Oct 10, 2026
4ac5576
LR-PROF-CAMERACOLOR: wire bright-fit helpers into the split modules
AlexChambers Oct 28, 2026
9de0650
LR-PROF-CAMERACOLOR: merge current main and retain bright-tone cache …
AlexChambers Oct 30, 2026
cc373c2
631: preserve bright camera fits on current main
AlexChambers Oct 31, 2026
056aa08
LC-CAMERACOLOR: use effective JPEG primaries for bright tone pairs
AlexChambers Oct 31, 2026
6ee32f6
LC-CAMERACOLOR: keep bright retry holdouts out of chroma training
AlexChambers Oct 31, 2026
df5f2c2
LC-CAMERACOLOR: honor every known preview colour space
AlexChambers Oct 31, 2026
db8624e
LR-PROF-CAMERACOLOR: merge current main (CRW decoder, 0.18.0)
AlexChambers Nov 3, 2026
3480e88
LR-PROF-CAMERACOLOR: merge current main (lens database download, mask…
AlexChambers Nov 4, 2026
2f26347
LR-PROF-CAMERACOLOR: merge current main (GPU render, process V3 and V…
AlexChambers Nov 5, 2026
1992af5
LR-PROF-CAMERACOLOR: merge current main eaef01e98 (light tests allow …
AlexChambers Nov 5, 2026
f3dd5fb
LR-PROF-CAMERACOLOR: refresh the parity summary after the merge
AlexChambers Nov 5, 2026
268358c
LR-PROF-CAMERACOLOR: merge current main 5b4eb6924 (BM3D denoise, Remo…
AlexChambers Nov 5, 2026
e3156be
LR-PROF-CAMERACOLOR: merge current main eab130ece (doc headers keep n…
AlexChambers Nov 5, 2026
c7caa3e
LR-PROF-CAMERACOLOR: refresh the parity summary after the merge
AlexChambers Nov 5, 2026
f40d859
LR-PROF-CAMERACOLOR: merge current main ba282d363 (ORF decoder, exact…
AlexChambers Nov 5, 2026
36f2624
LR-PROF-CAMERACOLOR: refresh the parity summary after the merge
AlexChambers Nov 5, 2026
3d58358
LR-PROF-CAMERACOLOR: merge current main fe632e05f (CR3 white level, p…
AlexChambers Nov 5, 2026
3398e85
LR-PROF-CAMERACOLOR: merge current main e9c29e2c5 (crystal grain proc…
AlexChambers Nov 10, 2026
f4354eb
LR-PROF-CAMERACOLOR: merge current main c4b899f9d (craft-libs and cra…
AlexChambers Nov 14, 2026
07977d3
Merge remote-tracking branch 'origin/main' into camera-look-bright-tone
AlexChambers Nov 18, 2026
d2df0f1
LR-PROF-CAMERACOLOR: cover bright retry rejections (#631)
AlexChambers Nov 22, 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 @@ -44,7 +44,7 @@ use mono::{fit_dark_tone, fit_tone_only, monochrome, monochrome_look, to_prophot
#[cfg(test)]
use pairs::{
Attempt, Pairs, TONE_FITS, collect_pairs, colour_pair, displayed, fit_attempt, fit_pairs, fit_pairs_ordered, fit_pairs_with, fit_partial,
fit_tone_with_shadows, luma, rank_correlation_ties, search_ordered,
fit_partial_on, fit_tone_with_shadows, jpeg_clipped, luma, rank_correlation_ties, search_ordered,
};
#[cfg(test)]
pub(crate) use proxy::LensGeometry;
Expand Down Expand Up @@ -79,7 +79,8 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights};
/// a tone-only fallback for near-black scenes with too few colour pairs (#1587); DNG tone fitting uses a
/// lens-corrected proxy when the file carries lens opcodes; validated A7CR distortion, including the lens data
/// stored with each smart preview.
pub const LOOK_VERSION: u32 = 12;
/// 13: the partial look's second attempt with the bright pairs (#631's bird).
pub const LOOK_VERSION: u32 = 13;

#[derive(Clone, Debug)]
pub(crate) struct CameraLook {
Expand Down
18 changes: 14 additions & 4 deletions crates/engine/src/camera_preview/look_fit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::colour::{PROXY, file_local_look};
use super::mono::{fit_tone_only_with, monochrome};
use super::pairs::{Attempt, TONE_FITS, fit_attempt, fit_partial, search_ordered};
use super::proxy::{CLIP_TOLERANCE, LensGeometry, MIN_PREVIEW_FRACTION, proxies, structure_agrees};
use super::tone::{HighlightCheck, highlights};
use super::tone::{HighlightCheck, clipped_highlights, highlights};
use super::{CameraLook, CameraTone, CameraTransform, HsvTable, Mat3, RawImage, Rgb32f, ToneMap, luminance_2020};

/// The look fitted to the file's camera JPEG, and whether that JPEG is black and white ([`monochrome`]).
Expand All @@ -25,7 +25,12 @@ pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransf
// (`monochrome_look` does it without a profile).
None if colour.is_some() && black_and_white => {
let unclipped = without_clipped(&sensor, &clipped);
let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro, grey: true };
let bright = HighlightCheck {
pairs: highlights(&sensor, &reference),
clipped: clipped_highlights(&sensor, &reference, &clipped),
dro,
grey: true,
};
let Some(look) = fit_tone_only_with(unclipped.as_ref().unwrap_or(&sensor), &reference, colour, &bright) else { return (None, true) };
look
}
Expand Down Expand Up @@ -82,7 +87,7 @@ pub(super) fn fit_look_with(
) -> Option<CameraLook> {
let unclipped = without_clipped(sensor, clipped);
// from the proxies as they are: the retries' filters (clipped pixels, edges) don't remove them
let bright = HighlightCheck { pairs: highlights(sensor, reference), dro, grey: false };
let bright = HighlightCheck { pairs: highlights(sensor, reference), clipped: clipped_highlights(sensor, reference, clipped), dro, grey: false };
let Some((look, attempt)) = search_ordered(sensor, reference, colour.clone(), TONE_FITS, &bright) else {
return unclipped
.as_ref()
Expand Down Expand Up @@ -224,7 +229,12 @@ pub(super) fn fit_dng_tone(
let unclipped = without_clipped(&sensor, &clipped);
let fit_on = unclipped.as_ref().unwrap_or(&sensor);
let colour = Some((Mat3::IDENTITY, None));
let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro: false, grey: false };
let bright = HighlightCheck {
pairs: highlights(&sensor, &reference),
clipped: clipped_highlights(&sensor, &reference, &clipped),
dro: false,
grey: false,
};
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 }, &bright)
Expand Down
16 changes: 11 additions & 5 deletions crates/engine/src/camera_preview/mono.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use super::pairs::{
rank_correlation_ties,
};
use super::proxy::{LensGeometry, proxies};
use super::tone::{HighlightCheck, ToneFit, fit_tone, highlights, highlights_hold};
use super::tone::{HighlightCheck, ToneFit, clipped_highlights, fit_tone, highlights, highlights_hold};
use super::{CameraLook, CameraTransform, D50, D65, HsvTable, Mat3, PROPHOTO, REC2020, RawImage, Rgb32f, ToneMap, bradford, luminance_2020};

/// A camera JPEG pixel's channels may differ by this much (linear) and still count as grey.
Expand Down Expand Up @@ -45,7 +45,8 @@ pub(super) fn monochrome_look(raw: &RawImage, bytes: &[u8], transform: &CameraTr
// Sony's Dynamic Range Optimizer brightens a B/W JPEG as much as a colour one
let dro = lightcraft_raw::embedded_preview_dynamic_range_optimized(bytes) == Some(true);
let unclipped = without_clipped(&sensor, &clipped);
let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro, grey: true };
let bright =
HighlightCheck { pairs: highlights(&sensor, &reference), clipped: clipped_highlights(&sensor, &reference, &clipped), dro, grey: true };
let look = fit_tone_only_with(unclipped.as_ref().unwrap_or(&sensor), &reference, None, &bright)?;
let look = if dro { with_dro_off_tone(look) } else { look };
if lightcraft_pipeline::profiling() {
Expand Down Expand Up @@ -77,7 +78,12 @@ pub(super) fn fit_tone_only_with(
/// [`fit_tone_only_with`] for a photo without Sony's DRO, checked against its own bright areas.
#[cfg(test)]
pub(super) fn fit_tone_only(sensor: &Rgb32f, reference: &Rgb32f, colour: Option<(Mat3, Option<HsvTable>)>) -> Option<CameraLook> {
fit_tone_only_with(sensor, reference, colour, &HighlightCheck { pairs: highlights(sensor, reference), dro: false, grey: true })
fit_tone_only_with(
sensor,
reference,
colour,
&HighlightCheck { pairs: highlights(sensor, reference), clipped: Vec::new(), dro: false, grey: true },
)
}

fn fit_tone_only_on(
Expand Down Expand Up @@ -111,7 +117,7 @@ pub(super) fn fit_dark_tone(sensor: &Rgb32f, reference: &Rgb32f, clipped: &[bool
return None;
}
// no JPEG pixel reaches 0.85 here, so the bright-area check has nothing to hold
let bright = HighlightCheck { pairs: highlights(sensor, reference), dro: false, grey: true };
let bright = HighlightCheck { pairs: highlights(sensor, reference), clipped: Vec::new(), dro: false, grey: true };
[None, Some(EDGE_CONTRAST)].into_iter().find_map(|edge_limit| {
let pairs: Pairs = sensor
.data
Expand Down Expand Up @@ -176,7 +182,7 @@ fn fit_tone_only_pairs(
pairs.iter().enumerate().filter(|(i, _)| i % 3 != 0).map(|(_, (x, y))| (luma(coloured(*x).map(|v| v.max(0.0))), luma(*y))).collect(),
)?
} else {
fit_tone_with_shadows(ToneFit::Quantile, pairs, sensor, reference, edge_limit, coloured)?
fit_tone_with_shadows(ToneFit::Quantile, pairs, &[], sensor, reference, edge_limit, coloured)?
};
let look = CameraLook { matrix, tone, hue_sat: hue_sat.clone() };
if !highlights_hold(&look.tone, highlights, coloured) {
Expand Down
109 changes: 93 additions & 16 deletions crates/engine/src/camera_preview/pairs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ use super::hue_sat::{HueSat, fit_chroma, fit_hue_sat};
use super::proxy::DARK_FLOOR;
#[cfg(test)]
use super::tone::highlights;
use super::tone::{HighlightCheck, ToneFit, highlights_hold};
use super::{CameraLook, CameraTone, HsvTable, Mat3, Rgb32f, ToneMap, luminance_2020};
use super::tone::{HighlightCheck, ToneFit, highlights_hold, keeps, keeps_highlights};
use super::{CameraLook, CameraTone, HsvTable, Mat3, REC2020, Rgb32f, ToneMap, luminance_2020};
use lightcraft_color::{ADOBE_RGB, SRGB};

/// A fit must cut the held-out squared error to below this share of the fallback's.
pub(super) const MIN_IMPROVEMENT: f64 = 0.7;
Expand Down Expand Up @@ -110,16 +111,22 @@ fn colour_pair_above(input: [f32; 3], output: [f32; 3], (ylo, clo): (f32, f32))
/// The original pairs and their split still own the colour fit and its acceptance gates.
/// Luminance needs no channel ratios, so the binned proxy can use a lower sensor floor and
/// keep JPEG pixels with a channel near black. Quantile medians limit the effect of noise.
/// `tone_only` pairs train the tone curve and nothing else ([`fit_partial`]'s bright pairs, above
/// the dark set's range): the two thirds that the caller doesn't hold out, by their own index,
/// join the training of both curves.
pub(super) fn fit_tone_with_shadows(
fit: ToneFit,
pairs: &[([f64; 3], [f64; 3])],
tone_only: &[Pair],
sensor: &Rgb32f,
reference: &Rgb32f,
edge_limit: Option<f32>,
colour: impl Fn([f64; 3]) -> [f64; 3],
) -> Option<CameraTone> {
let luminances = |x: [f64; 3], y: [f64; 3]| (luma(colour(x).map(|v| v.max(0.0))), luma(y));
let original = fit.fit(pairs.iter().enumerate().filter(|(i, _)| i % 3 != 0).map(|(_, (x, y))| luminances(*x, *y)).collect());
let tone_only_training = || tone_only.iter().enumerate().filter(|(i, _)| i % 3 != 0).map(|(_, (x, y))| luminances(*x, *y));
let original =
fit.fit(pairs.iter().enumerate().filter(|(i, _)| i % 3 != 0).map(|(_, (x, y))| luminances(*x, *y)).chain(tone_only_training()).collect());
let mut eligible = Vec::new();
let (mut colour_index, mut extra_index) = (0, 0);
for (i, (input, output)) in sensor.data.iter().zip(&reference.data).enumerate() {
Expand Down Expand Up @@ -151,7 +158,7 @@ pub(super) fn fit_tone_with_shadows(
if dark < 96 || held.len() < 32 || rank_correlation_ties(&held) < PARTIAL_MIN_RANK_CORRELATION {
return original;
}
let training = eligible.iter().filter(|(_, _, held)| !held).map(|(x, y, _)| (*x, *y)).collect();
let training = eligible.iter().filter(|(_, _, held)| !held).map(|(x, y, _)| (*x, *y)).chain(tone_only_training()).collect();
let Some(candidate) = fit.fit(training) else { return original };
let error = |tone: &CameraTone| -> f64 {
held.iter().map(|(x, y)| (f64::from(tone.apply(x[0] as f32)).powf(1.0 / 2.2) - y[0].powf(1.0 / 2.2)).powi(2)).sum()
Expand Down Expand Up @@ -228,8 +235,14 @@ pub(super) fn fit_pairs_ordered(
colour: Option<(Mat3, Option<HsvTable>)>,
order: &[ToneFit],
) -> Option<CameraLook> {
search_ordered(sensor, reference, colour, order, &HighlightCheck { pairs: highlights(sensor, reference), dro: false, grey: false })
.map(|(look, _)| look)
search_ordered(
sensor,
reference,
colour,
order,
&HighlightCheck { pairs: highlights(sensor, reference), clipped: Vec::new(), dro: false, grey: false },
)
.map(|(look, _)| look)
}

/// The tone fits the search tries, in order: the first whose look passes the acceptance gates is
Expand Down Expand Up @@ -317,7 +330,7 @@ fn fit_pairs_on(
let p = matrix.apply(x);
correction.as_ref().map_or(p, |c| c.apply(p.map(|v| v as f32)).map(f64::from))
};
let Some(curve) = fit_tone_with_shadows(tone_fit, &pairs, sensor, reference, edge_limit, colour) else { continue };
let Some(curve) = fit_tone_with_shadows(tone_fit, &pairs, &[], sensor, reference, edge_limit, colour) else { continue };
let mut look = CameraLook { matrix, tone: curve, hue_sat: hue_sat.clone() };
if let Some(tone) = fit_chroma(&bright, &look) {
look.tone = tone;
Expand Down Expand Up @@ -440,13 +453,51 @@ pub(super) fn rank_correlation_ties(pairs: &[([f64; 3], [f64; 3])]) -> f64 {
/// and in gamma-encoded display values, and when the JPEG shows the same picture
/// ([`PARTIAL_MIN_RANK_CORRELATION`]). There is no limit on its own error: it only has to be clearly
/// closer to the camera JPEG than what the photo would get otherwise.
///
/// When that fails, it is tried once more with the frame's bright, unclipped pixels in the tone fit
/// and in the held-out check ([`bright_tone_pairs`]). The fits leave out camera JPEG luminance 0.85
/// and up, where the camera bleaches colour; for tone alone those pixels are good evidence, and a
/// frame that is mostly bright overcast sky has too few midtones to fit a curve that matches its sky
/// (issue #631: a bird against cloud, 92% of the frame above the cut, 473 midtone pairs). Only a
/// photo that would otherwise get no look at all gets this one.
pub(super) fn fit_partial(sensor: &Rgb32f, reference: &Rgb32f, highlights: &HighlightCheck) -> Option<CameraLook> {
[None, Some(EDGE_CONTRAST)].into_iter().find_map(|edge_limit| fit_partial_on(sensor, reference, edge_limit, highlights))
let attempt = |bright_tone: bool| {
[None, Some(EDGE_CONTRAST)].into_iter().find_map(|edge_limit| fit_partial_on(sensor, reference, edge_limit, highlights, bright_tone))
};
attempt(false).or_else(|| attempt(true))
}

/// The bright pairs [`fit_partial`]'s second attempt adds to its tone fit: camera JPEG luminance 0.85
/// and up, not clipped in the JPEG ([`jpeg_clipped`]: a clipped JPEG pixel only bounds the curve),
/// from `bright`, which has no clipped sensor pixels when the clipped ones were left out of the
/// proxy.
fn bright_tone_pairs(bright: &[Pair]) -> Vec<Pair> {
bright.iter().filter(|(_, y)| luma(*y) >= 0.85 && !jpeg_clipped(*y)).copied().collect()
}

/// Whether a camera JPEG pixel (linear Rec.2020, as the reference proxy holds it) has a channel at
/// or near its maximum in the JPEG's own encoding, sRGB or Adobe RGB (camera JPEGs are one or the
/// other). Such a channel no longer shows the scene's level, while in Rec.2020 it can read as
/// little as 0.96 (a red channel clipped in sRGB, Codex review of #631's bird).
pub(super) fn jpeg_clipped(y: [f64; 3]) -> bool {
static SPACES: std::sync::OnceLock<[Mat3; 2]> = std::sync::OnceLock::new();
let spaces = SPACES.get_or_init(|| [SRGB.from_xyz().mul(&REC2020.to_xyz()), ADOBE_RGB.from_xyz().mul(&REC2020.to_xyz())]);
spaces.iter().any(|m| m.apply(y).iter().any(|v| *v >= 0.98))
}

fn fit_partial_on(sensor: &Rgb32f, reference: &Rgb32f, edge_limit: Option<f32>, highlights: &HighlightCheck) -> Option<CameraLook> {
pub(super) fn fit_partial_on(
sensor: &Rgb32f,
reference: &Rgb32f,
edge_limit: Option<f32>,
highlights: &HighlightCheck,
bright_tone: bool,
) -> Option<CameraLook> {
// as for a known colour model: enough signal for the tone, but no monochrome reference
let (pairs, bright) = collect_pairs(sensor, reference, 0.005, edge_limit, false)?;
let extra = if bright_tone { bright_tone_pairs(&bright) } else { Vec::new() };
if bright_tone && extra.is_empty() {
return None;
}
let related = rank_correlation(&pairs);
if related < PARTIAL_MIN_RANK_CORRELATION {
if lightcraft_pipeline::profiling() {
Expand All @@ -462,30 +513,44 @@ fn fit_partial_on(sensor: &Rgb32f, reference: &Rgb32f, edge_limit: Option<f32>,
})),
None => Mat3::IDENTITY,
};
let tone = fit_tone_with_shadows(ToneFit::Quantile, &pairs, sensor, reference, edge_limit, |x| matrix.apply(x))?;
let tone = fit_tone_with_shadows(ToneFit::Quantile, &pairs, &extra, sensor, reference, edge_limit, |x| matrix.apply(x))?;
let mut look = CameraLook { matrix, tone, hue_sat: None };
if let Some(tone) = fit_chroma(&bright, &look) {
look.tone = tone;
}
let (tone, neutral) = (ToneMap::camera(&look.tone, 0.0, 0.0, 0.0), ToneMap::new(0.0, 0.0, 0.0));
if !highlights_hold(&look.tone, highlights, |x| matrix.apply(x)) {
let kept = if bright_tone {
let colour = |x: [f64; 3]| matrix.apply(x);
keeps_highlights(&look.tone, highlights, colour) && keeps(&look.tone, highlights, &highlights.clipped, colour)
} else {
highlights_hold(&look.tone, highlights, |x| matrix.apply(x))
};
if !kept {
return None;
}
let encoded = |v: f64| v.max(0.0).powf(1.0 / 2.2);
let (mut before, mut after, mut before_encoded, mut after_encoded, mut samples) = (0.0, 0.0, 0.0, 0.0, 0);
for (x, target) in pairs.iter().step_by(3) {
// the held-out midtones alone (gamma-encoded): the second attempt mustn't buy its sky with them
let (mut mid_before, mut mid_after, mut mid_samples) = (0.0, 0.0, 0usize);
let midtones = pairs.len().div_ceil(3);
for (n, (x, target)) in pairs.iter().step_by(3).chain(extra.iter().step_by(3)).enumerate() {
let (fallback, partial) = (displayed(*x, &neutral), displayed(matrix.apply(*x), &tone));
for c in 0..3 {
before += (fallback[c] - target[c]).powi(2);
after += (partial[c] - target[c]).powi(2);
before_encoded += (encoded(fallback[c]) - encoded(target[c])).powi(2);
after_encoded += (encoded(partial[c]) - encoded(target[c])).powi(2);
let (b, a) = ((encoded(fallback[c]) - encoded(target[c])).powi(2), (encoded(partial[c]) - encoded(target[c])).powi(2));
before_encoded += b;
after_encoded += a;
samples += 1;
if n < midtones {
(mid_before, mid_after, mid_samples) = (mid_before + b, mid_after + a, mid_samples + 1);
}
}
}
if lightcraft_pipeline::profiling() {
eprintln!(
"[profile] camera look partial (tone{}{}) holdout RMS {:.5} -> {:.5} ({samples} channels{})",
"[profile] camera look partial (tone{}{}{}) holdout RMS {:.5} -> {:.5} ({samples} channels{})",
if bright_tone { " with bright pairs" } else { "" },
if look.tone.chroma().iter().any(|k| *k != 1.0) { ", chroma" } else { "" },
if matrix != Mat3::IDENTITY { ", damped matrix" } else { "" },
(before / samples.max(1) as f64).sqrt(),
Expand All @@ -495,5 +560,17 @@ fn fit_partial_on(sensor: &Rgb32f, reference: &Rgb32f, edge_limit: Option<f32>,
}
let better =
after.is_finite() && after_encoded.is_finite() && after < before * MIN_IMPROVEMENT && after_encoded < before_encoded * MIN_IMPROVEMENT;
(samples > 0 && better).then_some(look)
let rms = |e: f64| (e / mid_samples.max(1) as f64).sqrt();
let midtones_kept = !bright_tone || rms(mid_after) <= rms(mid_before) + MAX_MIDTONE_LOSS;
if bright_tone && lightcraft_pipeline::profiling() {
eprintln!("[profile] camera look partial with bright pairs: midtones (encoded) RMS {:.5} -> {:.5}", rms(mid_before), rms(mid_after));
}
(samples > 0 && better && midtones_kept).then_some(look)
}

/// How much further from the camera JPEG than the neutral fallback (gamma-encoded RMS over the
/// held-out midtones) [`fit_partial`]'s second attempt may leave them: its bright pairs can make the
/// sky alone meet the gates, and the midtones must not pay for it. A small allowance, not none,
/// because on a frame the fallback already renders right in the midtones a curve through the sky
/// moves them a little.
pub(super) const MAX_MIDTONE_LOSS: f64 = 0.02;
Loading
Loading