|
| 1 | +//! Bake per-film-simulation camera profiles into a look file (`assets/camera-looks/<model>.json`, |
| 2 | +//! `lightcraft_pipeline::looks`), as the starting point of `tools/fit_look.py`. A profile is JSON with the `matrix` and |
| 3 | +//! `hue_sat` of a `lightcraft-cli calibrate` profile, fitted to raws shot in one film simulation, and a `tone` |
| 4 | +//! (`CameraTone`: tone curve knots and chroma curve) pooled over them; the X-T5 file started from such profiles. |
| 5 | +//! |
| 6 | +//! A look is the whole rendering from white-balanced camera RGB: each grid node (CIELAB through the forward matrix) |
| 7 | +//! is rendered the way the finishing stage renders a starting look (matrix, hue/saturation table, tone map on |
| 8 | +//! luminance, chroma curve, highlights desaturated to white) and stored as Adobe RGB. A look takes camera RGB with |
| 9 | +//! only the dynamic range gain, so the tone curve is placed for raw exposure bias `BIAS` (the curves are pooled on |
| 10 | +//! the bias-corrected scale): -1.72 for an X-T5 at DR100 from ISO 250. |
| 11 | +//! |
| 12 | +//! usage: cargo run --release -p lightcraft-engine --example bake_look -- OUT.json MODEL GROUP BIAS ID=NAME=PROFILE.json… |
| 13 | +//! Prints, per look, how far the baked grid is from rendering the profile directly (CIE76 dE over camera colours). |
| 14 | +use lightcraft_color::{ADOBE_RGB, D50, D65, Mat3, REC2020, bradford, luminance_2020}; |
| 15 | +use lightcraft_pipeline::hue_sat::HueSat; |
| 16 | +use lightcraft_pipeline::looks::{Axis, Look}; |
| 17 | +use lightcraft_pipeline::tone::{CameraTone, ToneMap}; |
| 18 | +use lightcraft_raw::profile::HsvTable; |
| 19 | + |
| 20 | +const ADOBE_GAMMA: f32 = 563.0 / 256.0; |
| 21 | +/// The grid and node encoding of the X-T4 file, so both read alike. |
| 22 | +const LIGHTNESS: (f64, f64, usize) = (0.0, 100.0, 17); |
| 23 | +const AB: (f64, f64, usize) = (-168.0, 168.0, 29); |
| 24 | +const NODE_OFFSET: f64 = -4.0; |
| 25 | +const NODE_STEP: f64 = 1.0 / 8192.0; |
| 26 | +const WHITE: [f64; 3] = [0.96422, 1.0, 0.82521]; |
| 27 | + |
| 28 | +#[derive(serde::Deserialize)] |
| 29 | +struct Profile { |
| 30 | + matrix: [[f64; 3]; 3], |
| 31 | + hue_sat: Option<HsvTable>, |
| 32 | + tone: CameraTone, |
| 33 | +} |
| 34 | + |
| 35 | +/// One profile as the finishing stage renders it from white-balanced camera RGB. |
| 36 | +struct Render<'a> { |
| 37 | + matrix: [[f32; 3]; 3], |
| 38 | + hue_sat: Option<HueSat<'a>>, |
| 39 | + tone: ToneMap, |
| 40 | +} |
| 41 | + |
| 42 | +impl Render<'_> { |
| 43 | + /// Display-linear Rec.2020 of camera RGB `cam` (as `finish.rs`' `base_render`, peak 1). |
| 44 | + fn apply(&self, cam: [f32; 3]) -> [f32; 3] { |
| 45 | + let m = &self.matrix; |
| 46 | + let mut c: [f32; 3] = std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2]); |
| 47 | + if let Some(h) = &self.hue_sat { |
| 48 | + c = h.apply(c); |
| 49 | + } |
| 50 | + let yl = luminance_2020(c); |
| 51 | + let o = self.tone.apply(yl); |
| 52 | + let mut d = if yl > 1e-9 { c.map(|v| v * o / yl) } else { [0.0; 3] }; |
| 53 | + let k = self.tone.chroma_scale(o); |
| 54 | + if k != 1.0 { |
| 55 | + d = d.map(|v| o + (v - o) * k); |
| 56 | + } |
| 57 | + let mx = d[0].max(d[1]).max(d[2]); |
| 58 | + if mx > 1.0 { |
| 59 | + let t = ((mx - 1.0) / (mx - o).max(1e-6)).clamp(0.0, 1.0); |
| 60 | + d = d.map(|v| v + (o - v) * t); |
| 61 | + } |
| 62 | + d |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +fn mul(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] { |
| 67 | + std::array::from_fn(|i| m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2]) |
| 68 | +} |
| 69 | + |
| 70 | +fn lab_to_xyz(lab: [f64; 3]) -> [f64; 3] { |
| 71 | + let fy = (lab[0] + 16.0) / 116.0; |
| 72 | + let (fx, fz) = (fy + lab[1] / 500.0, fy - lab[2] / 200.0); |
| 73 | + let inv = |f: f64| if f > 6.0 / 29.0 { f * f * f } else { 3.0 * (6.0f64 / 29.0).powi(2) * (f - 4.0 / 29.0) }; |
| 74 | + [inv(fx) * WHITE[0], inv(fy) * WHITE[1], inv(fz) * WHITE[2]] |
| 75 | +} |
| 76 | + |
| 77 | +/// CIELAB (D65 white) of display-linear Rec.2020 `c`, for comparing renders. |
| 78 | +fn lab_of(c: [f32; 3]) -> [f64; 3] { |
| 79 | + let xyz = REC2020.to_xyz().apply(c.map(f64::from)); |
| 80 | + let w = lightcraft_color::D65.to_xyz(); |
| 81 | + let f = |t: f64| if t > (6.0f64 / 29.0).powi(3) { t.cbrt() } else { t / (3.0 * (6.0f64 / 29.0).powi(2)) + 4.0 / 29.0 }; |
| 82 | + let [fx, fy, fz] = std::array::from_fn(|i| f(xyz[i] / w[i])); |
| 83 | + [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)] |
| 84 | +} |
| 85 | + |
| 86 | +fn main() -> Result<(), String> { |
| 87 | + let args: Vec<String> = std::env::args().skip(1).collect(); |
| 88 | + let [out, model, group, bias, entries @ ..] = args.as_slice() else { |
| 89 | + return Err("usage: bake_look OUT.json MODEL GROUP BIAS ID=NAME=PROFILE.json…".into()); |
| 90 | + }; |
| 91 | + let bias: f32 = bias.parse().map_err(|_| "BIAS is a number of EV")?; |
| 92 | + let to_adobe = REC2020.to_space(&ADOBE_RGB).to_f32(); |
| 93 | + let mut profiles = Vec::new(); |
| 94 | + for entry in entries { |
| 95 | + let mut parts = entry.splitn(3, '='); |
| 96 | + let (Some(id), Some(name), Some(path)) = (parts.next(), parts.next(), parts.next()) else { |
| 97 | + return Err(format!("`{entry}` is not ID=NAME=PROFILE.json")); |
| 98 | + }; |
| 99 | + let json = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?; |
| 100 | + let p: Profile = serde_json::from_str(&json).map_err(|e| format!("{path}: {e}"))?; |
| 101 | + profiles.push((id, name, path, p)); |
| 102 | + } |
| 103 | + // one forward matrix for the file (its format has one): the first profile's colour, so its greys sit on the grid's |
| 104 | + // neutral axis; every node is rendered through its own profile's matrix whatever it is |
| 105 | + let first = profiles.first().ok_or("no profiles given")?; |
| 106 | + let forward = bradford(D65, D50).mul(&REC2020.to_xyz()).mul(&Mat3(first.3.matrix)); |
| 107 | + let back = forward.inverse().ok_or("the first profile's matrix is not invertible")?; |
| 108 | + let mut looks = Vec::new(); |
| 109 | + for (id, name, path, p) in &profiles { |
| 110 | + // the curve takes the raw with its bias undone; a look's camera RGB keeps it |
| 111 | + let scale = bias.exp2(); |
| 112 | + let curve = CameraTone::new(p.tone.knots().map(|[x, y]| [x * scale, y])) |
| 113 | + .and_then(|t| t.with_chroma(*p.tone.chroma())) |
| 114 | + .ok_or(format!("{path}: the curve doesn't scale by {scale}"))?; |
| 115 | + let render = Render { |
| 116 | + matrix: Mat3(p.matrix).to_f32(), |
| 117 | + hue_sat: p.hue_sat.as_ref().and_then(HueSat::new), |
| 118 | + tone: ToneMap::camera(&curve, 0.0, 0.0, 0.0), |
| 119 | + }; |
| 120 | + let node = |l: usize, a: usize, b: usize| { |
| 121 | + let at = |(lo, hi, n): (f64, f64, usize), i: usize| lo + (hi - lo) * i as f64 / (n - 1) as f64; |
| 122 | + let cam = back.apply(lab_to_xyz([at(LIGHTNESS, l), at(AB, a), at(AB, b)])).map(|v| v as f32); |
| 123 | + let d = render.apply(cam.map(|v| v.max(0.0))); |
| 124 | + mul(&to_adobe, d).map(|v| v.clamp(0.0, 1.0).powf(1.0 / ADOBE_GAMMA)) |
| 125 | + }; |
| 126 | + let (nl, nab) = (LIGHTNESS.2, AB.2); |
| 127 | + let mut nodes = Vec::with_capacity(nl * nab * nab); |
| 128 | + let mut hex = String::with_capacity(nl * nab * nab * 12); |
| 129 | + for l in 0..nl { |
| 130 | + for a in 0..nab { |
| 131 | + for b in 0..nab { |
| 132 | + let v = node(l, a, b); |
| 133 | + let q = v.map(|c| ((f64::from(c) - NODE_OFFSET) / NODE_STEP).round().clamp(0.0, 65535.0) as u16); |
| 134 | + for c in q { |
| 135 | + hex.push_str(&format!("{c:04x}")); |
| 136 | + } |
| 137 | + nodes.push(q.map(|c| (f64::from(c) * NODE_STEP + NODE_OFFSET) as f32)); |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | + // how much the grid loses against rendering the profile itself, over camera colours of photos |
| 142 | + let axis = |(lo, hi, n): (f64, f64, usize)| Axis { min: lo as f32, max: hi as f32, n }; |
| 143 | + let look = Look::new(&format!("look:{id}"), model, name, group, "", forward.0, WHITE, axis(LIGHTNESS), axis(AB), nodes)?; |
| 144 | + let mut des = Vec::new(); |
| 145 | + let mut seed = 0x2545_f491u32; |
| 146 | + let mut rnd = || { |
| 147 | + seed ^= seed << 13; |
| 148 | + seed ^= seed >> 17; |
| 149 | + seed ^= seed << 5; |
| 150 | + seed as f32 / u32::MAX as f32 |
| 151 | + }; |
| 152 | + for _ in 0..20000 { |
| 153 | + let y = 0.002 * (9.0f32 * rnd()).exp2(); |
| 154 | + let cam = [y * (0.3 + 1.4 * rnd()), y, y * (0.3 + 1.4 * rnd())]; |
| 155 | + let (a, b) = (lab_of(look.apply(cam)), lab_of(render.apply(cam))); |
| 156 | + des.push(((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()); |
| 157 | + } |
| 158 | + des.sort_by(f64::total_cmp); |
| 159 | + let mean = des.iter().sum::<f64>() / des.len() as f64; |
| 160 | + eprintln!("{id}: baked vs direct dE mean {mean:.2}, median {:.2}, 95th {:.2}", des[des.len() / 2], des[des.len() * 95 / 100]); |
| 161 | + looks.push(serde_json::json!({ |
| 162 | + "id": id, |
| 163 | + "name": name, |
| 164 | + "description": format!("Fitted to the {model}'s own {name} conversions. Not made or endorsed by Fujifilm."), |
| 165 | + "nodes": hex, |
| 166 | + })); |
| 167 | + } |
| 168 | + let file = serde_json::json!({ |
| 169 | + "version": 1, |
| 170 | + "model": model, |
| 171 | + "group": group, |
| 172 | + "input": { |
| 173 | + "forward_matrix": forward.0, |
| 174 | + "white": WHITE, |
| 175 | + "lightness": LIGHTNESS, |
| 176 | + "ab": AB, |
| 177 | + }, |
| 178 | + "output": "Adobe RGB (1998), encoded with gamma 563/256", |
| 179 | + "node_offset": NODE_OFFSET, |
| 180 | + "node_step": NODE_STEP, |
| 181 | + // the bias the curves were placed for: a raw with another bias is brightened by the difference |
| 182 | + "raw_exposure_bias": bias, |
| 183 | + "looks": looks, |
| 184 | + }); |
| 185 | + std::fs::write(out, serde_json::to_string(&file).map_err(|e| e.to_string())?).map_err(|e| format!("{out}: {e}"))?; |
| 186 | + Ok(()) |
| 187 | +} |
0 commit comments