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
6 changes: 3 additions & 3 deletions apps/lightcraft-web/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use lightcraft_engine::files::{load_bytes, probe_bytes};
use lightcraft_engine::files::{load_bytes_with, probe_bytes};
use lightcraft_engine::media::{FileLoader, FileProbe};

/// Prefix of the catalog paths of files kept in browser storage.
Expand Down Expand Up @@ -144,9 +144,9 @@ impl Originals {
/// Engine hooks that decode/probe from memory.
pub fn hooks(&self) -> (FileLoader, FileProbe) {
let s = self.clone();
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize| {
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, options| {
let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?;
load_bytes(&bytes, max_edge)
load_bytes_with(&bytes, max_edge, options)
});
let s = self.clone();
let probe: FileProbe = Arc::new(move |path: &str| {
Expand Down
44 changes: 38 additions & 6 deletions apps/lightcraft-web/src/wire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use std::sync::{Arc, Weak};

use lightcraft_engine::catalog::Source;
use lightcraft_engine::develop::{DevelopSettings, EmbeddedLens};
use lightcraft_engine::media::{DecodedSource, MediaCache, RenderJob, SourceLevel, SourceRef};
use lightcraft_engine::media::{DecodedSource, LoadOptions, MediaCache, RenderJob, SourceLevel, SourceRef};
use lightcraft_engine::pipeline::{Quality, RenderRequest, Rendered, SourceInfo, StageCache};
use lightcraft_preview::{Hash128, Lru, PreviewCache};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -126,10 +126,12 @@ impl WireJob {
}
}

/// Identifies the decoded source this job needs.
/// Identifies the decoded source this job needs (a file's includes the Camera colour it is decoded with).
fn source_key(&self) -> String {
match &self.origin {
Source::File { path } => format!("{}:{:?}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge),
Source::File { path } => {
format!("{}:{:?}:{}:{path}:{:?}", self.cache_generation, self.source_identity, self.max_edge, LoadOptions::of(&self.settings).colour)
}
Source::Demo { scene } => format!("{}:{:?}:{}:demo:{scene}", self.cache_generation, self.source_identity, self.max_edge),
}
}
Expand Down Expand Up @@ -181,11 +183,13 @@ impl WorkerCore {
None => {
let src = match (&job.origin, original) {
(Source::File { .. }, Some(bytes)) => {
let (image, info) = lightcraft_engine::files::load_bytes(bytes, job.max_edge)?;
DecodedSource::new(Arc::new(image), Some(info))
// (decoded for the settings it renders with, as the desktop's `SourceRef::File`)
let options = LoadOptions::of(&job.settings);
let (image, info) = lightcraft_engine::files::load_bytes_with(bytes, job.max_edge, options)?;
DecodedSource { options, ..DecodedSource::new(Arc::new(image), Some(info)) }
}
(Source::File { path }, None) => return Err(format!("{path}: original not found in browser storage")),
(origin @ Source::Demo { .. }, _) => self.media.origin_ref(origin, job.max_edge).load_source()?,
(origin @ Source::Demo { .. }, _) => self.media.origin_ref(origin, job.max_edge, LoadOptions::default()).load_source()?,
};
let cost = src.image.width * src.image.height * 12 + 64;
self.sources.insert(key, src.clone(), cost);
Expand Down Expand Up @@ -437,6 +441,34 @@ mod tests {
assert_eq!(old.request().window, None);
}

// A file is decoded with the Camera colour of the settings the job renders with, and a source decoded with one is
// not reused for a job with the other (as the desktop's `SourceRef::File`)
#[test]
fn a_file_source_is_decoded_for_the_jobs_camera_colour() {
use lightcraft_engine::develop::CameraColour;
// a 1 × 1 PNG
const PNG: &[u8] = &[
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01,
0x00, 0x00, 0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
];
let mut s = Session::with_demo();
let id = s.visible_cloned()[0];
let mut auto = WireJob::from_job(&s.thumb_job(id, 64).unwrap(), false, "Thumb");
auto.origin = Source::File { path: "web/hash/photo.png".into() };
let mut calibrated = auto.clone();
let mut d = (*auto.settings).clone();
d.profile.camera_colour = CameraColour::Colorimetric;
calibrated.settings = Arc::new(d);
assert_ne!(auto.source_key(), calibrated.source_key());

let mut core = WorkerCore::default();
core.render(&calibrated, Some(PNG)).unwrap();
assert_eq!(core.sources.get(&calibrated.source_key()).map(|s| s.options.colour), Some(CameraColour::Colorimetric));
assert!(core.needs_original(&auto).is_some(), "the Auto job decodes its own source");
assert!(core.needs_original(&calibrated).is_none());
}

#[test]
fn wire_job_renders_like_the_engine() {
let mut s = Session::with_demo();
Expand Down
40 changes: 40 additions & 0 deletions crates/develop/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,46 @@ mod tests {
use super::*;
use serde_json::json;

/// The Camera colour option is left out of the JSON while it is Auto (settings from before it keep their hash, and
/// every cached preview stays valid); Colorimetric is stored, read back, and changes the hash.
#[test]
fn camera_colour_is_stored_only_when_it_is_not_auto() {
let auto = DevelopSettings::default();
assert!(!auto.to_json().to_string().contains("camera_colour"));
let mut colorimetric = auto.clone();
colorimetric.profile.camera_colour = CameraColour::Colorimetric;
let v = colorimetric.to_json();
assert_eq!(v["profile"]["camera_colour"], json!("colorimetric"));
assert_eq!(DevelopSettings::from_json(&v).unwrap().profile.camera_colour, CameraColour::Colorimetric);
assert_ne!(colorimetric.hash64(), auto.hash64());
// a merge can set it back by name
let back: Profile = serde_json::from_value(json!({"camera_colour": "auto"})).unwrap();
assert!(back.camera_colour.is_auto());
}

/// A preset or sync of the Profile group carries the Camera colour both ways: Colorimetric onto an Auto photo,
/// and Auto back onto a Colorimetric one.
#[test]
fn the_profile_group_carries_the_camera_colour_both_ways() {
let auto = DevelopSettings::default();
let mut colorimetric = auto.clone();
colorimetric.profile.camera_colour = CameraColour::Colorimetric;
let on = extract_groups(&colorimetric, &[SettingsGroup::Profile]);
let off = extract_groups(&auto, &[SettingsGroup::Profile]);
assert_eq!(apply_partial(&auto, &on, 1.0).profile.camera_colour, CameraColour::Colorimetric);
assert_eq!(apply_partial(&colorimetric, &off, 1.0).profile.camera_colour, CameraColour::Auto);
// and a preset of the group still applies below the halfway amount (where discrete fields keep their value)
let mut lighter = colorimetric.clone();
lighter.light.exposure = 1.0;
let both = extract_groups(&lighter, &[SettingsGroup::Light, SettingsGroup::Profile]);
let weak = apply_partial(&auto, &both, 0.3);
assert!((weak.light.exposure - 0.3).abs() < 1e-9, "the preset applied: exposure {}", weak.light.exposure);
assert_eq!(weak.profile.camera_colour, CameraColour::Auto, "below the halfway amount the option keeps its value");
// other groups leave it alone
let light = extract_groups(&auto, &[SettingsGroup::Light]);
assert_eq!(apply_partial(&colorimetric, &light, 1.0).profile.camera_colour, CameraColour::Colorimetric);
}

#[test]
fn serde_roundtrip_default_and_edited() {
let mut s = DevelopSettings::default();
Expand Down
13 changes: 12 additions & 1 deletion crates/develop/src/presets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,11 @@ pub fn extract_groups(s: &DevelopSettings, groups: &[SettingsGroup]) -> Value {
}
}
}
// the Camera colour is left out of the settings while it is Auto; a preset or a sync of the Profile group still
// carries it, so that applying it turns a Colorimetric photo back to Auto
if let Some(Value::Object(profile)) = out.get_mut("profile") {
profile.entry("camera_colour").or_insert_with(|| serde_json::to_value(s.profile.camera_colour).unwrap_or(Value::Null));
}
Value::Object(out)
}

Expand Down Expand Up @@ -163,7 +168,13 @@ fn scale_patch(base: &Value, patch: &Value, t: f64) -> Value {
let mut out = Map::new();
for (k, pv) in p {
let bv = b.get(k).unwrap_or(&Value::Null);
out.insert(k.clone(), scale_patch(bv, pv, t));
let v = scale_patch(bv, pv, t);
// a field the settings leave out while it has its default (`camera_colour`, `camera_local_tone`) keeps
// it below the halfway amount: a `null` would not deserialize, and the whole preset would not apply
if v.is_null() && !b.contains_key(k) {
continue;
}
out.insert(k.clone(), v);
}
Value::Object(out)
}
Expand Down
26 changes: 25 additions & 1 deletion crates/develop/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,35 @@ pub struct Profile {
/// settings without it keep their JSON (and hash).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub camera_local_tone: bool,
/// Where a raw without colour matrices of its own takes its starting colour from
/// (`docs/camera-preview-colour.md`). Omitted when [`CameraColour::Auto`], so settings without
/// it keep their JSON (and hash).
#[serde(skip_serializing_if = "CameraColour::is_auto")]
pub camera_colour: CameraColour,
}

impl Default for Profile {
fn default() -> Self {
Self { id: "lc.color".into(), amount: 100.0, camera_local_tone: false }
Self { id: "lc.color".into(), amount: 100.0, camera_local_tone: false, camera_colour: CameraColour::Auto }
}
}

/// The starting colour of a raw that carries no colour matrices (NEF, ARW, CR3, …).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CameraColour {
/// The first available of: a camera profile with tone fitted to the file's JPEG, a look fitted
/// to the file's JPEG, the model's spectral matrices, the neutral fallback.
#[default]
Auto,
/// The model's matrices from measured spectral sensitivities with LightCraft's default tone
/// curve, never the embedded JPEG; [`CameraColour::Auto`] for a model without them.
Colorimetric,
}

impl CameraColour {
pub fn is_auto(&self) -> bool {
*self == CameraColour::Auto
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/engine/examples/render_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ fn benchmark_load(args: &[String], n: usize, only: &str) {
}
println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load"))));
let (loader, _) = lightcraft_engine::files::fs_hooks();
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560).expect("load"))));
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560, Default::default()).expect("load"))));
}
}

Expand Down
2 changes: 1 addition & 1 deletion 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::{colorimetric_camera, 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
31 changes: 30 additions & 1 deletion crates/engine/src/camera_preview/colour.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use super::look_fit::{fit_dng_tone, fit_preview, look_proxies};
use super::mono::{fit_dark_tone, monochrome_look};
use super::proxy::LensGeometry;
use lightcraft_develop::CameraColour;

use super::{CameraLook, CameraTone, CameraTransform, ColorData, D50, D65, Mat3, ProfileLook, REC2020, RawFormat, RawImage, ToneCurve, Xy, bradford};

/// Long edge of the sensor/JPEG proxy a single photo's look is fitted on (the acceptance gates
Expand Down Expand Up @@ -44,14 +46,19 @@ pub(crate) fn file_local_look(format: RawFormat) -> bool {
/// `OpcodeList3`): the camera applied it to its JPEG, so the sensor proxy is warped the same way before pairing.
/// `embedded` is the file's embedded lens correction: its vignetting is applied to the sensor proxy of every fit, as
/// the render applies it.
/// `colour` is the photo's Profile option: [`CameraColour::Colorimetric`] skips the JPEG (the fit, the black-and-white
/// tone and the near-black tone) for a model with spectral matrices, which then give the colour with LightCraft's
/// default tone curve.
pub(crate) fn starting_colour(
raw: &mut RawImage,
bytes: &[u8],
lens: Option<&LensGeometry>,
embedded: Option<&lightcraft_develop::EmbeddedLens>,
colour: CameraColour,
) -> (Xy, CameraTransform, Option<CameraLook>) {
let (xy, t, look) = starting_colour_with(
raw,
colour,
|raw, t| fit_preview(raw, bytes, t, lens, embedded),
|raw, t| monochrome_look(raw, bytes, t, lens, embedded),
|raw, t| {
Expand Down Expand Up @@ -89,10 +96,21 @@ pub(crate) fn dng_tone_eligible(raw: &RawImage, t: &CameraTransform) -> bool {
raw.format == RawFormat::Dng && !t.matrix_is_fallback && identity_tone_curve(p.tone_curve.as_ref()) && p.gain_table_map.is_none()
}

/// Matrices from measured spectral sensitivities for the raw's camera model, when it has no colour matrices of its own
/// and its starting look is otherwise fitted to its JPEG ([`file_local_look`]): what [`CameraColour::Colorimetric`]
/// starts from.
pub(crate) fn colorimetric_camera(raw: &RawImage) -> Option<&'static lightcraft_raw::spectral::Camera> {
if lightcraft_raw::color::has_matrix(&raw.color) || !file_local_look(raw.format) {
return None;
}
lightcraft_raw::spectral::find(raw.metadata.make.as_deref(), raw.metadata.model.as_deref()?)
}

/// [`starting_colour`] with the JPEG fit (the look, and whether the JPEG is black and white) and the black-and-white
/// JPEG's tone fit and the near-black tone fallback passed in (tests pin the order with them).
pub(super) fn starting_colour_with(
raw: &mut RawImage,
colour: CameraColour,
fit: impl FnOnce(&RawImage, &CameraTransform) -> (Option<CameraLook>, bool),
monochrome: impl FnOnce(&RawImage, &CameraTransform) -> Option<CameraLook>,
dark: impl FnOnce(&RawImage, &CameraTransform) -> Option<CameraLook>,
Expand All @@ -105,6 +123,17 @@ pub(super) fn starting_colour_with(
if !t.matrix_is_fallback {
return (xy, t, None);
}
// Colorimetric: the measured matrices, never the JPEG (a model without them starts as Auto does)
if colour == CameraColour::Colorimetric
&& let Some(camera) = colorimetric_camera(raw)
{
camera.fill(&mut raw.color);
if lightcraft_pipeline::profiling() {
eprintln!("[profile] {:?} camera colour from spectral sensitivities (Colorimetric): {} {}", raw.format, camera.make, camera.model);
}
let (xy, t) = start(raw);
return (xy, t, None);
}
let (look, black_and_white) = fit(raw, &t);
if let Some(look) = look {
return (xy, t, Some(look));
Expand Down Expand Up @@ -135,7 +164,7 @@ pub(crate) fn starting_colour_tags(raw: &mut RawImage, bytes: &[u8]) -> Option<C
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);
let (_, t, look) = starting_colour(raw, bytes, None, None, CameraColour::Auto);
dng_colour(&raw.color, &white, &t, look.as_ref())
}

Expand Down
Loading