Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 8 additions & 2 deletions crates/develop/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,23 @@ pub enum Process {
/// Highlights and Shadows keep the local contrast of the tones they move: their edge-aware base
/// is taken of a fine median of log luminance (issue #632).
V2,
/// Bright saturated colours keep their saturation: a colour past the output gamut or past
/// white keeps its luminance and its lowest channel, and leans towards the nearest secondary
/// instead of being desaturated towards grey, so a sunset's orange halo no longer bleaches
/// (`lightcraft_pipeline::finish::GamutMap`).
V3,
}

impl Process {
/// Every process, oldest first.
pub const ALL: [Process; 2] = [Process::V1, Process::V2];
pub const LATEST: Process = Process::V2;
pub const ALL: [Process; 3] = [Process::V1, Process::V2, Process::V3];
pub const LATEST: Process = Process::V3;

pub const fn version(self) -> ProcessVersion {
match self {
Process::V1 => ProcessVersion(1),
Process::V2 => ProcessVersion(2),
Process::V3 => ProcessVersion(3),
}
}
}
Expand Down
57 changes: 51 additions & 6 deletions crates/engine/src/camera_preview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
//! A global matrix can't follow the camera's hue-dependent rendering (the best matrix rendered a
//! lime shirt olive that the camera kept lime): a hue/saturation table fitted to the residuals
//! (applied like a DNG `ProfileHueSatMap`) corrects that when it also improves the held-out pixels.
use lightcraft_color::{D50, D65, Mat3, PROPHOTO, REC2020, Xy, bradford, luminance_2020};
use lightcraft_color::{D50, D65, Mat3, PROPHOTO, REC2020, SRGB, Xy, bradford, luminance_2020};
use lightcraft_pipeline::finish::GamutMap;
use lightcraft_pipeline::output::OutputSpace;
use lightcraft_pipeline::tone::{CameraTone, ToneMap};
use lightcraft_raster::{
Rgb32f,
Expand Down Expand Up @@ -34,7 +36,8 @@ use lightcraft_raw::{
/// 7: the sensor proxy follows the file's lens warp when the camera JPEG is lens-corrected.
/// 8: the bundled NIKON Z 6_2 profile.
/// 9: the bundled NIKON Z 8 and NIKON D5300 profiles.
pub const LOOK_VERSION: u32 = 9;
/// 10: the chroma curve fitted on predictions gamut mapped into sRGB, as the JPEG holds them.
pub const LOOK_VERSION: u32 = 10;

#[derive(Clone, Debug)]
pub(crate) struct CameraLook {
Expand Down Expand Up @@ -956,6 +959,18 @@ fn displayed(scene: [f64; 3], tone: &ToneMap) -> [f64; 3] {
scene.map(|v| o + (v * o / y - o) * k)
}

/// [`displayed`] as a camera JPEG can hold it: brought into sRGB by the finish stage's gamut map
/// (V3, [`GamutMap::KeepSaturation`]). The chroma curve is fitted on this, so it learns how the
/// camera bleaches colours, not how far the prediction lies outside the JPEG's gamut: compared
/// unmapped, a sunset's saturated orange (past sRGB, in range in the JPEG) taught the curve to
/// desaturate every bright colour. Camera JPEGs in Adobe RGB are mapped into sRGB too.
fn displayed_in_gamut(scene: [f64; 3], tone: &ToneMap) -> [f64; 3] {
let d = displayed(scene, tone);
let (to, back) = (REC2020.to_space(&SRGB), SRGB.to_space(&REC2020));
let (r, _) = GamutMap::KeepSaturation.apply(to.apply(d).map(|v| v as f32), OutputSpace::Srgb.luma(), 1.0);
back.apply(r.map(f64::from))
}

#[cfg(test)]
fn fit_pairs(sensor: &Rgb32f, reference: &Rgb32f) -> Option<CameraLook> {
fit_pairs_with(sensor, reference, None)
Expand Down Expand Up @@ -1713,7 +1728,7 @@ fn fit_chroma(pairs: &[([f64; 3], [f64; 3])], look: &CameraLook) -> Option<Camer
correction.as_ref().map_or(p, |c| c.apply(p.map(|v| v as f32)).map(f64::from))
};
let tone = ToneMap::camera(&look.tone, 0.0, 0.0, 0.0);
let predict = |x: &[f64; 3]| displayed(scene(x), &tone);
let predict = |x: &[f64; 3]| displayed_in_gamut(scene(x), &tone);
let chroma = |p: [f64; 3]| {
let y = luma(p);
(y > 0.0).then(|| p.iter().map(|v| (v / y - 1.0).powi(2)).sum::<f64>().sqrt())
Expand Down Expand Up @@ -1749,7 +1764,7 @@ fn fit_chroma(pairs: &[([f64; 3], [f64; 3])], look: &CameraLook) -> Option<Camer
.iter()
.step_by(3)
.map(|(x, y)| {
let p = displayed(scene(x), map);
let p = displayed_in_gamut(scene(x), map);
(0..3).map(|c| (p[c] - y[c]).powi(2)).sum::<f64>()
})
.sum()
Expand Down Expand Up @@ -2213,7 +2228,9 @@ mod tests {
let fit = fit_pairs(&sensor, &reference).unwrap();
// relative to the matrix, which already carries the average colourfulness
let chroma = fit.tone.chroma();
assert!(chroma[6] < 0.5 * chroma[1], "highlights bleach relative to shadows: {chroma:?}");
// about half (0.51): the fit predicts through the V3 output map, which takes a share of the
// bleaching right below white itself (`gamut_map_keep_to`), so the curve needs a little less
assert!(chroma[6] < 0.55 * chroma[1], "highlights bleach relative to shadows: {chroma:?}");
// and the rendered highlights land on the camera's, far closer than without the curve
let with = ToneMap::camera(&fit.tone, 0.0, 0.0, 0.0);
let without = ToneMap::camera(&fit.tone.with_chroma([1.0; lightcraft_pipeline::tone::CHROMA_N]).unwrap(), 0.0, 0.0, 0.0);
Expand All @@ -2233,6 +2250,34 @@ mod tests {
assert!(b < 0.5 * a, "highlight error {a:.4} -> {b:.4}");
}

/// A camera that doesn't bleach, but whose JPEG holds a bright saturated orange within sRGB (red
/// clipped, blue kept low): the chroma curve must not read the gamut limit as bleaching. Fitted
/// on unmapped predictions it desaturated every bright colour, a sunset's orange halo among them.
#[test]
fn chroma_curve_does_not_learn_the_jpeg_gamut() {
let known = Mat3([[1.8, -0.4, -0.1], [-0.2, 1.5, -0.1], [-0.05, -0.3, 1.7]]);
let (to, back) = (REC2020.to_space(&SRGB), SRGB.to_space(&REC2020));
let mut sensor = Rgb32f::new(96, 64);
let mut reference = sensor.clone();
for (i, (src, dst)) in sensor.data.iter_mut().zip(&mut reference.data).enumerate() {
let ev = 0.02 + (i % 37) as f32 * 0.03;
*src = if i % 3 == 0 {
[ev * 1.25, ev * 0.5, ev * 0.12]
} else {
[ev * (0.75 + (i % 11) as f32 * 0.05), ev, ev * (0.7 + (i % 13) as f32 * 0.05)]
};
let p = known.apply_f32(*src);
let y = luminance_2020(p);
let o = 1.0 - (-2.5 * y).exp();
let d = p.map(|v| v * o / y);
let (r, _) = GamutMap::KeepSaturation.apply(to.apply_f32(d), OutputSpace::Srgb.luma(), 1.0);
*dst = back.apply_f32(r).map(|v| v.clamp(0.0, 0.999));
}
let fit = fit_pairs(&sensor, &reference).unwrap();
let chroma = fit.tone.chroma();
assert!(chroma.iter().all(|k| *k > 0.9), "no bleaching to learn: {chroma:?}");
}

/// Pooled pairs of several "photos" recover the camera's matrix, and a photo given that
/// colour model (a camera profile) keeps it, fitting only its own tone.
#[test]
Expand Down Expand Up @@ -3480,7 +3525,7 @@ mod tests {
let new_ratio =
(colourfulness_ratio(&new, &sensor, &reference, &clipped, mid), colourfulness_ratio(&new, &sensor, &reference, &clipped, bright));
// with the clipped sky in the pairs, the bright colours lose much of their colour
assert!(old_ratio.1 < 0.8, "earlier fit: colourfulness vs camera {old_ratio:?}, chroma {:?}", old.tone.chroma());
assert!(old_ratio.1 < 0.85, "earlier fit: colourfulness vs camera {old_ratio:?}, chroma {:?}", old.tone.chroma());
// without it, the render keeps the camera's colourfulness at every brightness
for r in [new_ratio.0, new_ratio.1] {
assert!((0.9..1.1).contains(&r), "colourfulness vs camera {new_ratio:?}, chroma {:?}", new.tone.chroma());
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/media.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl SettingsHashes {
}

/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
pub const RENDER_CACHE_VERSION: u64 = 64;
pub const RENDER_CACHE_VERSION: u64 = 65;

/// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache).
pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512];
Expand Down
6 changes: 6 additions & 0 deletions crates/gpu/src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, srgb_lut};
pub const CURVE_N: u32 = 1024;

/// Field name and number of 32-bit words.
// `finish.wgsl`'s `gamut_keep` takes the share of `gamut_desat` as `y2 * y2 * y`.
const _: () = assert!(lightcraft_pipeline::finish::KEEP_DESATURATE_POWER == 6, "update gamut_keep in finish.wgsl");

const FIELDS: &[(&str, usize)] = &[
("W", 1),
("H", 1),
Expand Down Expand Up @@ -73,6 +76,8 @@ const FIELDS: &[(&str, usize)] = &[
("OUT_Y", 3),
("OUT_TRC", 1),
("OUT_GAMMA", 1),
// `GamutMap::KeepSaturation` (V3) instead of desaturating towards luminance
("GAMUT_KEEP", 1),
// first row of a band dispatch (the kernel runs over rows Y0.., see `render`)
("Y0", 1),
];
Expand Down Expand Up @@ -233,6 +238,7 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
let (trc, gamma) = fp.out_trc.code();
p.u("OUT_TRC", trc);
p.f("OUT_GAMMA", gamma);
p.b("GAMUT_KEEP", fp.gamut == lightcraft_pipeline::finish::GamutMap::KeepSaturation);
if let Some((amt, cell, rough, seed)) = fp.grain {
p.b("GRAIN", true);
p.f("GRAIN_AMT", amt);
Expand Down
111 changes: 96 additions & 15 deletions crates/gpu/src/wgsl/finish.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,90 @@ fn chroma_scale(o: f32) -> f32 {
return a + (b - a) * t;
}

// `lightcraft_pipeline::finish::gamut_map_to` into 0..1: desaturate towards luminance until in range.
fn gamut_desat(r: vec3<f32>, luma: vec3<f32>) -> vec3<f32> {
let yy = clamp(dot(luma, r), 0.0, 1.0);
var tg = 1.0;
for (var k = 0u; k < 3u; k++) {
let cc = r[k];
if (cc < 0.0) {
tg = min(tg, yy / max(yy - cc, 1e-9));
} else if (cc > 1.0) {
tg = min(tg, (1.0 - yy) / max(cc - yy, 1e-9));
}
}
if (tg < 1.0) {
return yy + (r - yy) * tg;
}
return r;
}

// `lightcraft_pipeline::finish::gamut_keep_saturation` into 0..1: keep luminance (weights `luma`)
// and saturation; clipped luminance goes to the channels above the lowest first, then towards white.
fn gamut_keep_saturation(r0: vec3<f32>, luma: vec3<f32>) -> vec3<f32> {
let yy = clamp(dot(luma, r0), 0.0, 1.0);
var t = 1.0;
for (var k = 0u; k < 3u; k++) {
if (r0[k] < 0.0) {
t = min(t, yy / max(yy - r0[k], 1e-9));
}
}
var r = r0;
if (t < 1.0) {
r = yy + (r0 - yy) * t;
}
let lo = min(r.x, min(r.y, r.z));
let hi = max(r.x, max(r.y, r.z));
if (!(hi > 1.0)) {
return r;
}
var q = min(r, vec3<f32>(1.0));
var w = vec3<f32>(1.0);
if (hi - lo > 1e-9) {
w = (r - lo) / (hi - lo);
}
let room = dot(luma, w * (1.0 - q));
let need = yy - dot(luma, q);
if (room > 1e-9 && need > 0.0) {
q = q + min(need / room, 1.0) * w * (1.0 - q);
}
let need2 = yy - dot(luma, q);
let room2 = dot(luma, 1.0 - q);
if (room2 > 1e-9 && need2 > 0.0) {
q = q + (1.0 - q) * clamp(need2 / room2, 0.0, 1.0);
}
return q;
}

// `lightcraft_pipeline::finish::gamut_map_keep_to` into 0..1: `gamut_keep_saturation`, then, for a
// colour past white, a share Y^5 (`KEEP_DESATURATE_POWER`) of `gamut_desat`'s colour.
fn gamut_keep(r0: vec3<f32>, luma: vec3<f32>) -> vec3<f32> {
let q = gamut_keep_saturation(r0, luma);
// past white once a channel below 0 is brought in, as `gamut_keep_saturation` decides
let yy = clamp(dot(luma, r0), 0.0, 1.0);
var t = 1.0;
for (var k = 0u; k < 3u; k++) {
if (r0[k] < 0.0) {
t = min(t, yy / max(yy - r0[k], 1e-9));
}
}
var r = r0;
if (t < 1.0) {
r = yy + (r0 - yy) * t;
}
if (!(max(r.x, max(r.y, r.z)) > 1.0)) {
return q;
}
let d = gamut_desat(r0, luma);
let y = clamp(dot(luma, d), 0.0, 1.0);
let y2 = y * y;
let f = y2 * y2 * y2;
if (f > 0.0) {
return q + (d - q) * f;
}
return q;
}

fn encode_srgb(v: f32) -> f32 {
let o = pu(F_SRGB_OFF);
let f = clamp(v, 0.0, 1.0) * f32(SRGB_N);
Expand Down Expand Up @@ -419,8 +503,12 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
}
let mx = max(d.x, max(d.y, d.z));
if (mx > 1.0) {
let t = clamp((mx - 1.0) / max(mx - o, 1e-6), 0.0, 1.0);
d = d + (o - d) * t;
if (pu(F_GAMUT_KEEP) != 0u) {
d = gamut_keep_saturation(d, vec3<f32>(0.2627, 0.6780, 0.0593));
} else {
let t = clamp((mx - 1.0) / max(mx - o, 1e-6), 0.0, 1.0);
d = d + (o - d) * t;
}
}

// --- colour
Expand Down Expand Up @@ -467,25 +555,18 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
}
}

// --- gamut map to the output space (desaturate towards luminance until in range)
// --- gamut map to the output space (`GamutMap`: by process)
let om = array<vec3<f32>, 3>(
vec3<f32>(pf(F_OUT_M), pf(F_OUT_M + 1u), pf(F_OUT_M + 2u)),
vec3<f32>(pf(F_OUT_M + 3u), pf(F_OUT_M + 4u), pf(F_OUT_M + 5u)),
vec3<f32>(pf(F_OUT_M + 6u), pf(F_OUT_M + 7u), pf(F_OUT_M + 8u)),
);
var r = mul3(om, d);
let yy = clamp(pf(F_OUT_Y) * r.x + pf(F_OUT_Y + 1u) * r.y + pf(F_OUT_Y + 2u) * r.z, 0.0, 1.0);
var tg = 1.0;
for (var k = 0u; k < 3u; k++) {
let cc = r[k];
if (cc < 0.0) {
tg = min(tg, yy / max(yy - cc, 1e-9));
} else if (cc > 1.0) {
tg = min(tg, (1.0 - yy) / max(cc - yy, 1e-9));
}
}
if (tg < 1.0) {
r = yy + (r - yy) * tg;
let out_y = vec3<f32>(pf(F_OUT_Y), pf(F_OUT_Y + 1u), pf(F_OUT_Y + 2u));
if (pu(F_GAMUT_KEEP) != 0u) {
r = gamut_keep(r, out_y);
} else {
r = gamut_desat(r, out_y);
}

// --- encode, curves, grain
Expand Down
Loading