Skip to content
8 changes: 5 additions & 3 deletions crates/engine/src/camera_preview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ use hue_sat::{MIN_LUMINANCE_KEPT, NO_LUMINANCE_KEPT, fit_hue_sat, hue_saturation
pub(crate) use look_fit::fit_preview;
#[cfg(test)]
use look_fit::{
FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, at_most, clips_more, correct_vignetting, fit_look, fit_look_with, sony_dro_off_tone, with_dro_off_tone,
without_clipped,
FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, at_most, clips_more, correct_vignetting, fit_look, fit_look_with, fit_preview_with, measured_colour,
sony_dro_off_tone, with_dro_off_tone, without_clipped,
};
#[cfg(test)]
use mono::{fit_dark_tone, fit_tone_only, monochrome, monochrome_look, to_prophoto};
Expand Down Expand Up @@ -84,7 +84,9 @@ 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: a partial look of a model with measured spectral matrices takes their colour instead of the generic one.
/// 15: a partial look of a model with a camera profile takes the profile's colour (matrix and hue/saturation table).
pub const LOOK_VERSION: u32 = 15;

#[derive(Clone, Debug)]
pub(crate) struct CameraLook {
Expand Down
53 changes: 43 additions & 10 deletions crates/engine/src/camera_preview/look_fit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@ pub(crate) fn fit_preview(
transform: &CameraTransform,
lens: Option<&LensGeometry>,
embedded: Option<&lightcraft_develop::EmbeddedLens>,
) -> (Option<CameraLook>, bool) {
let profile = raw.metadata.model.as_deref().and_then(crate::camera_profiles::get);
fit_preview_with(raw, bytes, transform, lens, embedded, profile.as_deref())
}

/// [`fit_preview`] with the model's camera profile given (`None`: none), so tests don't depend on
/// the profiles folder of the machine they run on.
pub(super) fn fit_preview_with(
raw: &RawImage,
bytes: &[u8],
transform: &CameraTransform,
lens: Option<&LensGeometry>,
embedded: Option<&lightcraft_develop::EmbeddedLens>,
profile: Option<&crate::camera_profiles::CameraProfile>,
) -> (Option<CameraLook>, bool) {
if !transform.matrix_is_fallback || !file_local_look(raw.format) {
return (None, false);
Expand All @@ -21,12 +35,14 @@ pub(crate) fn fit_preview(
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).
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 colour = profile.and_then(|p| Some((p.matrix().mul(&transform.matrix.inverse()?), p.hue_sat.clone())));
// Sony's Dynamic Range Optimizer (on by default) brightens the camera JPEG's darker regions,
// not the raw: keep the colour fitted to the JPEG, take the tone curve without DRO.
let dro = lightcraft_raw::embedded_preview_dynamic_range_optimized(bytes) == Some(true);
let look = match fit_look_with(&sensor, &reference, &clipped, colour.clone(), dro) {
// When the full fit fails, the partial look (`fit_partial`) takes the camera profile's colour, matrix and table;
// without a profile, the colour of the model's measured spectral matrices.
let measured = if colour.is_some() { colour.clone() } else { measured_colour(raw, transform).map(|m| (m, None)) };
let look = match fit_look_with(&sensor, &reference, &clipped, colour.clone(), dro, measured) {
Some(look) => look,
// A black-and-white JPEG has no colour to fit: the profile's colour and the JPEG's tone curve
// (`monochrome_look` does it without a profile).
Expand All @@ -52,14 +68,30 @@ pub(crate) fn fit_preview(
(Some(look), black_and_white)
}

/// The colour of the camera model's measured spectral matrices ([`lightcraft_raw::spectral`]) in the space of the
/// sensor proxy developed with `transform` (the generic colour of a raw without matrices): white-balanced camera RGB
/// through the matrices, at the file's as-shot white. Like a camera profile's colour it keeps white white, so the
/// look's tone curve sets the brightness. `None` for a model without them or a file with matrices of its own.
pub(super) fn measured_colour(raw: &RawImage, transform: &CameraTransform) -> Option<Mat3> {
let camera = lightcraft_raw::spectral::find(raw.metadata.make.as_deref(), raw.metadata.model.as_deref()?)?;
let mut color = raw.color.clone();
if !camera.fill(&mut color) {
return None;
}
let white = lightcraft_raw::color::as_shot_white_of(&color, raw.wb_multipliers);
let measured = lightcraft_raw::color::camera_transform_of(&color, white).matrix;
let colour = measured.mul(&transform.matrix.inverse()?);
colour.0.iter().flatten().all(|v| v.is_finite()).then_some(colour)
}

/// Sensor level (normalised, white = 1) at or above which a raw channel counts as clipped, as in
/// the render's highlight reconstruction.
pub(super) const SENSOR_CLIP: f32 = 0.99;

/// [`fit_look_with`] for a photo without Sony's DRO.
#[cfg(test)]
pub(super) fn fit_look(sensor: &Rgb32f, reference: &Rgb32f, clipped: &[bool], colour: Option<(Mat3, Option<HsvTable>)>) -> Option<CameraLook> {
fit_look_with(sensor, reference, clipped, colour, false)
fit_look_with(sensor, reference, clipped, colour, false, None)
}

/// The photo's look, refitted without the proxy pixels whose sensor values are clipped.
Expand All @@ -79,23 +111,24 @@ pub(super) fn fit_look(sensor: &Rgb32f, reference: &Rgb32f, clipped: &[bool], co
/// its look and none switches attempt (a refit that just clears the gate on all pixels must not
/// replace a look fitted away from edges). A photo that had no look gets one when the search
/// without the clipped pixels finds it, and otherwise the [`fit_partial`] look when that is clearly
/// closer to the camera JPEG than the neutral fallback.
/// closer to the camera JPEG than the neutral fallback: in the `measured` colour when the model has
/// one and that passes, else in the generic colour, so a measured colour never costs a photo its look.
pub(super) fn fit_look_with(
sensor: &Rgb32f,
reference: &Rgb32f,
clipped: &[bool],
colour: Option<(Mat3, Option<HsvTable>)>,
dro: bool,
measured: Option<(Mat3, Option<HsvTable>)>,
) -> 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 Some((look, attempt)) = search_ordered(sensor, reference, colour.clone(), TONE_FITS, &bright) else {
return unclipped
.as_ref()
.and_then(|u| search_ordered(u, reference, colour, TONE_FITS, &bright))
.map(|(look, _)| look)
.or_else(|| fit_partial(unclipped.as_ref().unwrap_or(sensor), reference, &bright));
return unclipped.as_ref().and_then(|u| search_ordered(u, reference, colour, TONE_FITS, &bright)).map(|(look, _)| look).or_else(|| {
let fit_on = unclipped.as_ref().unwrap_or(sensor);
measured.as_ref().and_then(|m| fit_partial(fit_on, reference, &bright, Some(m))).or_else(|| fit_partial(fit_on, reference, &bright, None))
});
};
let Some(unclipped) = unclipped else { return Some(look) };
let refit = fit_attempt(&unclipped, reference, &colour, attempt, &bright);
Expand Down
56 changes: 44 additions & 12 deletions crates/engine/src/camera_preview/pairs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,11 +440,28 @@ 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.
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))
///
/// `measured`: the colour of the camera model's measured spectral matrices, in the sensor proxy's space, when it has
/// them. The look then takes that colour instead of the generic one (no matrix of the photo's own): a scene whose
/// full look fails is one whose colour the photo can't teach, and the generic colour is furthest from the camera's
/// on the saturated light that makes it fail (the blue LED wall of a Canon EOS R50 photo came out blue-violet
/// where the camera rendered it magenta).
pub(super) fn fit_partial(
sensor: &Rgb32f,
reference: &Rgb32f,
highlights: &HighlightCheck,
measured: Option<&(Mat3, Option<HsvTable>)>,
) -> Option<CameraLook> {
[None, Some(EDGE_CONTRAST)].into_iter().find_map(|edge_limit| fit_partial_on(sensor, reference, edge_limit, highlights, measured))
}

fn fit_partial_on(sensor: &Rgb32f, reference: &Rgb32f, edge_limit: Option<f32>, highlights: &HighlightCheck) -> Option<CameraLook> {
fn fit_partial_on(
sensor: &Rgb32f,
reference: &Rgb32f,
edge_limit: Option<f32>,
highlights: &HighlightCheck,
measured: Option<&(Mat3, Option<HsvTable>)>,
) -> 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 related = rank_correlation(&pairs);
Expand All @@ -456,25 +473,34 @@ fn fit_partial_on(sensor: &Rgb32f, reference: &Rgb32f, edge_limit: Option<f32>,
}
let spread = |y: &[f64; 3]| y.iter().copied().fold(f64::NEG_INFINITY, f64::max) - y.iter().copied().fold(f64::INFINITY, f64::min);
let colourful = pairs.iter().filter(|(_, y)| spread(y) > 0.05).count() >= pairs.len() / 20;
let matrix = match colourful.then(|| fit_matrix(&pairs)).flatten() {
Some(own) => Mat3(std::array::from_fn(|r| {
let damped = |own: Mat3| {
Mat3(std::array::from_fn(|r| {
std::array::from_fn(|c| Mat3::IDENTITY.0[r][c] + PARTIAL_MATRIX_WEIGHT * (own.0[r][c] - Mat3::IDENTITY.0[r][c]))
})),
None => Mat3::IDENTITY,
}))
};
let (matrix, hue_sat) = match measured {
Some((measured, table)) => (*measured, table.clone()),
None => (colourful.then(|| fit_matrix(&pairs)).flatten().map_or(Mat3::IDENTITY, damped), None),
};
// a camera profile's colour brings its hue/saturation table, applied after the matrix as in a full look
let correction = hue_sat.as_ref().and_then(HueSat::new);
let colour = |x: [f64; 3]| {
let p = matrix.apply(x);
correction.as_ref().map_or(p, |c| c.apply(p.map(|v| v as f32)).map(f64::from))
};
let tone = fit_tone_with_shadows(ToneFit::Quantile, &pairs, sensor, reference, edge_limit, |x| matrix.apply(x))?;
let mut look = CameraLook { matrix, tone, hue_sat: None };
let tone = fit_tone_with_shadows(ToneFit::Quantile, &pairs, sensor, reference, edge_limit, colour)?;
let mut look = CameraLook { matrix, tone, hue_sat: hue_sat.clone() };
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)) {
if !highlights_hold(&look.tone, highlights, colour) {
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) {
let (fallback, partial) = (displayed(*x, &neutral), displayed(matrix.apply(*x), &tone));
let (fallback, partial) = (displayed(*x, &neutral), displayed(colour(*x), &tone));
for c in 0..3 {
before += (fallback[c] - target[c]).powi(2);
after += (partial[c] - target[c]).powi(2);
Expand All @@ -487,7 +513,13 @@ fn fit_partial_on(sensor: &Rgb32f, reference: &Rgb32f, edge_limit: Option<f32>,
eprintln!(
"[profile] camera look partial (tone{}{}) holdout RMS {:.5} -> {:.5} ({samples} channels{})",
if look.tone.chroma().iter().any(|k| *k != 1.0) { ", chroma" } else { "" },
if matrix != Mat3::IDENTITY { ", damped matrix" } else { "" },
if measured.is_some() {
", measured colour"
} else if matrix != Mat3::IDENTITY {
", damped matrix"
} else {
""
},
(before / samples.max(1) as f64).sqrt(),
(after / samples.max(1) as f64).sqrt(),
if edge_limit.is_some() { ", away from edges" } else { "" }
Expand Down
Loading
Loading