LR-META-EXIF-FULL: merge current main (GPU render, process V3 and V4, imported DCP camera profiles, Auto Sync white balance) (#693)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alex ChambersandClaude Opus 5.5 committed 2026-11-05 07:54:28 +01:00
commit 032cb95302
174 files changed
+15486 -782

No files matched your search

+1
View File
@@ -85,3 +85,4 @@ jobs:
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
+3
View File
@@ -14,3 +14,6 @@ plan/
# model weights are never committed (SAM 3: docs/ai-masks.md)
*.safetensors
*.safetensors.part
# Python tools import their public operator family.
__pycache__/
Generated
+60 -5
View File
@@ -1688,6 +1688,19 @@ dependencies = [
"winit",
]
[[package]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"ahash",
"egui",
"enum-map",
"itertools 0.15.0",
"log",
"profiling",
]
[[package]]
name = "egui_glow"
version = "0.37.0"
@@ -1774,6 +1787,26 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "enum-map"
version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06"
dependencies = [
"enum-map-derive",
]
[[package]]
name = "enum-map-derive"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "enumflags2"
version = "0.7.12"
@@ -3732,6 +3765,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"unicode-normalization",
"unicode-segmentation",
"web-time",
]
@@ -3762,6 +3796,13 @@ dependencies = [
"webpki-roots",
]
[[package]]
name = "lightcraft-film"
version = "0.18.0"
dependencies = [
"libm",
]
[[package]]
name = "lightcraft-geocode"
version = "0.18.0"
@@ -3991,6 +4032,7 @@ dependencies = [
"craft-update",
"craft-window",
"egui",
"egui_extras",
"egui_kittest",
"lightcraft-catalog",
"lightcraft-codecs",
@@ -4008,6 +4050,7 @@ dependencies = [
"lightcraft-slideshow",
"lightcraft-testkit",
"log",
"pollster 1.0.1",
"serde",
"serde_json",
"toml",
@@ -4023,9 +4066,11 @@ dependencies = [
"egui",
"js-sys",
"lightcraft-codecs",
"lightcraft-color",
"lightcraft-engine",
"lightcraft-preview",
"lightcraft-raster",
"lightcraft-raw",
"lightcraft-ui-egui",
"log",
"serde",
@@ -6608,6 +6653,12 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "tokio"
version = "1.53.1"
@@ -6814,6 +6865,15 @@ version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "unicode-normalization"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-properties"
version = "0.1.4"
@@ -8221,11 +8281,6 @@ name = "egui_demo_lib"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
[[patch.unused]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
+2
View File
@@ -30,6 +30,7 @@ lightcraft-raw = { path = "crates/raw" }
lightcraft-codecs = { path = "crates/codecs" }
lightcraft-meta = { path = "crates/meta" }
lightcraft-develop = { path = "crates/develop" }
lightcraft-film = { path = "crates/film" }
lightcraft-lensdb = { path = "crates/lensdb" }
lightcraft-inpaint = { path = "crates/inpaint" }
lightcraft-scenes = { path = "crates/scenes" }
@@ -62,6 +63,7 @@ proptest = "1"
bytemuck = { version = "1", features = ["derive"] }
crc32fast = "1"
siphasher = "1"
libm = "0.2" # pure-Rust maths for lightcraft-film (target-independent results)
libc = "0.2" # dev-only: process CPU time in benches
dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds
+2
View File
@@ -80,3 +80,5 @@ heif = ["lightcraft-codecs/heif"]
[dev-dependencies]
egui = { workspace = true }
lightcraft-color = { workspace = true }
lightcraft-raw = { workspace = true }
+63 -3
View File
@@ -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.
@@ -144,9 +144,11 @@ 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| {
// (an imported camera profile is not applied on the web, as in the render worker: a raw keeps its own colour,
// whether it decodes in a worker or inline when workers are unavailable)
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, _dcp: Option<&lightcraft_engine::media::DcpProfile>| {
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, None)
});
let s = self.clone();
let probe: FileProbe = Arc::new(move |path: &str| {
@@ -237,6 +239,64 @@ mod tests {
assert_eq!(out.image.width, 20);
}
/// CodeRabbit on #1063: without web workers a render runs inline and handed the selected camera profile to this
/// loader, which applied it, so the picture differed from the worker's (which keeps the raw's own colour, the
/// documented web behaviour). The loader now ignores it.
#[test]
fn the_web_loader_keeps_a_raws_own_colour_with_a_camera_profile() {
use lightcraft_raw::*;
let (w, h) = (32usize, 24usize);
let raw = RawImage {
format: RawFormat::Dng,
width: w,
height: h,
cpp: 1,
data: RawData::U16((0..w * h).map(|i| 256 + ((i % w) * 300 + (i / w) * 200) as u16).collect()),
cfa: Cfa::bayer("RGGB"),
bits: 14,
black: BlackLevel::uniform(256.0),
white: vec![16000.0],
active_area: Rect::new(0, 0, w, h),
crop: Rect::new(0, 0, w, h),
orientation: Orientation::Normal,
color: ColorData {
illuminant: [21, 0],
color_matrix: [Some(lightcraft_color::Mat3([[0.9, 0.2, -0.15], [-0.3, 1.25, 0.08], [0.02, -0.12, 0.85]])), None],
as_shot_neutral: Some([0.5, 1.0, 0.7]),
..Default::default()
},
wb_multipliers: None,
linearized: false,
pixel_aspect: 1.0,
opcodes: OpcodeLists::default(),
metadata: Default::default(),
lens_metadata: Default::default(),
};
let dng = write_dng(&raw, &DngWriteOptions::default()).unwrap();
// our own numbers: a matrix that swaps the camera's red and blue
let swap = lightcraft_color::Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]).mul(&lightcraft_color::Mat3([
[3.2406, -1.5372, -0.4986],
[-0.9689, 1.8758, 0.0415],
[0.0557, -0.2040, 1.0570],
]));
let profile = dcp::DcpProfile {
name: "Swap".into(),
camera_model: "LightCraft Test Camera".into(),
color: ColorData { illuminant: [21, 0], color_matrix: [Some(swap), None], ..Default::default() },
};
assert_ne!(
load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data,
load_bytes_with(&dng, 64, None).unwrap().0.data,
"the profile changes a raw's colour where it is applied"
);
let store = Originals::default();
store.insert("h1", Arc::from(dng));
let (loader, _) = store.hooks();
let with = loader("web/h1/a.dng", 64, Some(&profile)).unwrap();
let without = loader("web/h1/a.dng", 64, None).unwrap();
assert_eq!(with.0.data, without.0.data, "the web loader leaves it out");
}
#[test]
fn download_names() {
assert_eq!(download_name("dir/x-lightcraft.png"), "x-lightcraft.png");
+3
View File
@@ -318,6 +318,7 @@ impl Workers {
loaded: None,
quick: None,
display: None,
frame: None,
};
g.done.push((b.slot, r, 0.0));
}
@@ -409,6 +410,7 @@ impl Workers {
loaded: None,
quick: None,
display: None,
frame: None,
},
ms,
));
@@ -463,6 +465,7 @@ impl RenderOffload for Workers {
loaded: None,
quick: None,
display: None,
frame: None,
};
g.done.push((slot, r, 0.0));
return None;
+76 -2
View File
@@ -79,7 +79,67 @@ fn app_icon() -> egui::IconData {
eframe::icon_data::from_png_bytes(png).unwrap_or_default()
}
struct App(LightcraftApp, PrefsWriter, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
struct App(LightcraftApp, PrefsWriter, Option<WindowTextures>, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
/// Draws renders that stayed on the GPU: registers their textures with the window's egui-wgpu
/// renderer (the GPU renderer runs on the window's device, see [`adopt_window_device`]).
struct WindowTextures {
device: eframe::wgpu::Device,
queue: eframe::wgpu::Queue,
renderer: std::sync::Arc<egui::mutex::RwLock<eframe::egui_wgpu::Renderer>>,
}
impl lightcraft_ui_egui::render::ScreenTextures for WindowTextures {
fn show(&mut self, frame: &lightcraft_engine::media::ScreenFrame, id: Option<egui::TextureId>) -> Option<egui::TextureId> {
let view = frame.texture.create_view(&Default::default());
let mut r = self.renderer.write();
let filter = eframe::wgpu::FilterMode::Linear;
Some(match id {
Some(id) => {
r.update_egui_texture_from_wgpu_texture(&self.device, &view, filter, id);
id
}
None => r.register_native_texture(&self.device, &view, filter),
})
}
fn free(&mut self, id: egui::TextureId) {
self.renderer.write().free_texture(&id);
}
fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option<egui::ColorImage> {
match lightcraft_engine::gpu::read_texture(&self.device, &self.queue, &frame.texture, frame.width, frame.height) {
Ok(img) => Some(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], img.data.as_flattened())),
Err(e) => {
log::warn!("gpu: a view can't be read back for the screenshot: {e}");
None
}
}
}
}
/// Render on the window's device (off the UI thread: building the kernels takes a moment), so the
/// loupe's drafts are drawn straight from the GPU; the textures they leave are shown through
/// [`WindowTextures`] once that worked. Otherwise the GPU renderer makes a device of its own, as
/// before, and every render comes back as pixels.
fn adopt_window_device(rs: &eframe::egui_wgpu::RenderState, ctx: &egui::Context) -> WindowTextures {
let (device, queue, info) = (rs.device.clone(), rs.queue.clone(), rs.adapter.get_info());
let ctx = ctx.clone();
// before the first frame's GPU warm-up can start a device of its own
lightcraft_engine::gpu::set_window_device_pending(true);
let spawned = std::thread::Builder::new().name("lc-gpu-window".into()).spawn(move || {
match lightcraft_engine::gpu::adopt_window_device(device, queue, info) {
Ok(()) => log::info!("gpu: rendering on the window's device"),
Err(e) => log::info!("gpu: renders come back as pixels: {e}"),
}
ctx.request_repaint();
});
if let Err(e) = spawned {
log::warn!("gpu: {e}");
lightcraft_engine::gpu::set_window_device_pending(false);
}
WindowTextures { device: rs.device.clone(), queue: rs.queue.clone(), renderer: rs.renderer.clone() }
}
impl eframe::App for App {
fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
@@ -89,7 +149,7 @@ impl eframe::App for App {
}
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
if let Some(m) = self.2.as_mut()
if let Some(m) = self.3.as_mut()
&& m.update(&mut self.0, ctx)
&& lightcraft_ui_egui::panels::notices::may_close(&mut self.0)
{
@@ -109,6 +169,13 @@ impl eframe::App for App {
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
self.0.perf.host_frame_ms = frame.info().cpu_usage.map(|s| f64::from(s) * 1000.0);
// the GPU renderer adopted the window's device: its renders can be drawn as they are
if self.2.is_some()
&& lightcraft_engine::gpu::on_window_device()
&& let Some(t) = self.2.take()
{
self.0.renderer.set_screen_textures(Box::new(t));
}
self.0.ui(ui);
}
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
@@ -358,9 +425,16 @@ fn main() -> eframe::Result {
#[cfg(target_os = "macos")]
let menu =
(std::env::var_os("LIGHTCRAFT_NO_NATIVE_MENU").is_none()).then(|| native_menu::NativeMenu::install(&mut app, &cc.egui_ctx));
// the GPU renderer on the window's device, when GPU rendering is on
// (LIGHTCRAFT_GPU_WINDOW=0: a device of its own, renders read back - for comparison or a driver
// that misbehaves with compute and drawing on one device)
let window_device = std::env::var_os("LIGHTCRAFT_GPU_WINDOW").is_none_or(|v| v != "0");
let window_textures =
cc.wgpu_render_state.as_ref().filter(|_| gpu_on && window_device).map(|rs| adopt_window_device(rs, &cc.egui_ctx));
Ok(Box::new(App(
app,
writer,
window_textures,
#[cfg(target_os = "macos")]
menu,
)))
+3
View File
@@ -5,6 +5,7 @@ fn desktop_clear_color_stays_opaque_with_a_modal_open() {
let mut app = App(
LightcraftApp::new(Session::new(), Services::default()),
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
@@ -566,6 +567,7 @@ fn on_exit_ends_the_process_on_macos() {
let mut app = App(
app,
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
@@ -598,6 +600,7 @@ fn on_exit_removes_the_lock_owner_note() {
let mut app = App(
LightcraftApp::new(session, Services::default()),
PrefsWriter::default(),
None,
#[cfg(target_os = "macos")]
None,
);
+11 -1
View File
@@ -154,6 +154,15 @@ pub fn base_options() -> WgpuConfiguration {
n.instance_descriptor.backend_options = backend::backend_options();
// no indirect-call validation pipeline: Intel Metal fails to compile it and the window never opens (#250)
n.instance_descriptor.flags = backend::instance_flags_from_env(n.instance_descriptor.flags);
// the GPU renderer may run on this device (`adopt_window_device`): it needs the adapter's
// buffer limits (a 24 MP photo is a 275 MiB buffer), not wgpu's defaults
let default = n.device_descriptor.clone();
n.device_descriptor = std::sync::Arc::new(move |adapter| {
if adapter.get_info().backend == wgpu::Backend::Gl {
return default(adapter);
}
wgpu::DeviceDescriptor { label: Some("lightcraft window"), required_limits: adapter.limits(), ..Default::default() }
});
}
c
}
@@ -192,7 +201,8 @@ fn probe(backends: Backends, compose_window: bool) -> Result<WgpuSetupExisting,
..Default::default()
}))
.map_err(|e| format!("no adapter: {e}"))?;
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() };
// (not GL: the adapter's own limits, which the GPU renderer needs when it adopts this device)
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { adapter.limits() };
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("egui wgpu device"),
required_limits: wgpu::Limits { max_texture_dimension_2d: 8192, ..base },
+70
View File
@@ -0,0 +1,70 @@
//! Fault injection for the catalog log's writer thread (tests only: nothing in the product
//! installs a hook, and with none installed a check is one uncontended lock of an empty list).
//!
//! A test makes the drive under one library directory slow (a hook that sleeps) or failing (a
//! hook that returns an error) and proves that a flag never waits for it and that nothing handed
//! over is lost: `crates/catalog/src/tests_log_thread.rs`, `crates/engine/src/tests/slow_drive.rs`.
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
/// Where the log thread is about to touch the drive.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step {
/// Writing bytes to the log (or to the file that replaces it).
Write,
/// Syncing them.
Sync,
}
/// Runs before each [`Step`] in the hooked directory: an error fails that step.
pub type Hook = Arc<dyn Fn(Step) -> io::Result<()> + Send + Sync>;
static HOOKS: Mutex<Vec<(PathBuf, Hook)>> = Mutex::new(Vec::new());
/// Run `hook` before every write and sync of the catalog log in `dir` (replacing an earlier one).
#[doc(hidden)]
pub fn install(dir: &Path, hook: Hook) {
let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
hooks.retain(|(d, _)| d != dir);
hooks.push((dir.to_path_buf(), hook));
}
/// Remove the hook of `dir`.
#[doc(hidden)]
pub fn remove(dir: &Path) {
HOOKS.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| d != dir);
}
static ON_CALLER: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Write the log in `dir` on the caller's thread, syncing before each append returns, as builds
/// before PERF-STEP-STALL did: a test's "before" (stores opened afterwards; the hooks run there too).
#[doc(hidden)]
pub fn write_on_caller(dir: &Path, on: bool) {
let mut dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
dirs.retain(|d| d != dir);
if on {
dirs.push(dir.to_path_buf());
}
}
pub(crate) fn on_caller(dir: &Path) -> bool {
let dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
!dirs.is_empty() && dirs.iter().any(|d| d == dir)
}
pub(crate) fn check(dir: &Path, step: Step) -> io::Result<()> {
let hook = {
let hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
if hooks.is_empty() {
return Ok(());
}
hooks.iter().find(|(d, _)| d == dir).map(|(_, h)| h.clone())
};
match hook {
Some(h) => h(step),
None => Ok(()),
}
}
+32 -2
View File
@@ -6,7 +6,10 @@
//! rename).
//! - `catalog.log` — JSON lines, one per op applied after the snapshot:
//! `{"seq":N,"crc":C,"op":{…}}` where `C` is the CRC-32 of the op's JSON text. Appends are
//! fsynced before [`Journal::append`] returns.
//! fsynced before [`Journal::append`] returns, except natively: [`crate::FsStore`] hands them to
//! a thread of its own that writes and syncs them in order right after (so a flag never waits
//! for the drive), holds and retries whatever fails ([`Journal::unwritten`]) and refuses later
//! appends meanwhile, so the log never has a gap and nothing handed over is dropped.
//!
//! Loading = snapshot + replay of the records with `seq > snapshot seq`. Recovery rules:
//! - a **torn final record** (crash mid-append: truncated line or bad CRC at the end) is dropped
@@ -195,6 +198,10 @@ pub struct Journal {
/// A failed append may have left part of its records after `log_bytes`, and cutting them off
/// failed too: the next append cuts the log back to `log_bytes` first.
tail_dirty: bool,
/// An append failed (natively that can be the store's own log thread failing to write records
/// handed over before, which it holds and retries): the next chance writes a snapshot, a fresh
/// file holding everything, in case only the log's file is broken.
snapshot_due: bool,
}
/// A background snapshot in flight.
@@ -383,6 +390,7 @@ impl Journal {
pending: None,
retry_at_records: 0,
tail_dirty: false,
snapshot_due: false,
};
let log = log.unwrap_or_default();
@@ -516,6 +524,7 @@ impl Journal {
self.tail_dirty = false;
}
if let Err(e) = self.store.append(LOG, buf.as_bytes()) {
self.snapshot_due = true;
// Part of the batch may be in the file. Cut it back to the last whole record, so the
// retry (same seqs) starts on a clean line instead of after a fragment that would
// read back as damage.
@@ -678,6 +687,7 @@ impl Journal {
}
fn record_snapshot(&mut self, t: SnapshotTiming) {
self.snapshot_due = false;
self.stats.snapshots += 1;
self.stats.last_snapshot = t;
self.stats.max_snapshot_ms = self.stats.max_snapshot_ms.max(t.total_ms);
@@ -697,6 +707,23 @@ impl Journal {
}
}
/// Wait until every appended record is in the file and synced (natively the store writes the
/// log on a thread of its own, [`crate::FsStore`]): before the files are read or copied from
/// outside. An error says why some aren't yet: they are held and retried, never dropped.
pub fn flush(&mut self) -> Result<()> {
self.store.flush().map_err(io)
}
/// Appended records the store holds because writing them failed (retried), and why; `None`
/// when nothing is held back. Never waits for the drive.
pub fn unwritten(&self) -> Option<(usize, String)> {
// a snapshot that holds every op holds whatever the log's thread still holds
if self.snapshot_seq >= self.seq && self.pending.is_none() {
return None;
}
self.store.unwritten()
}
/// Where persistence time went so far.
pub fn stats(&self) -> PersistStats {
PersistStats { snapshot_running: self.pending.is_some(), ..self.stats }
@@ -706,7 +733,10 @@ impl Journal {
pub fn wants_snapshot(&self) -> bool {
self.pending.is_none()
&& self.log_records >= self.retry_at_records
&& (self.log_records >= self.policy.max_records || self.log_bytes >= self.policy.max_bytes)
&& (self.snapshot_due
|| self.unwritten().is_some()
|| self.log_records >= self.policy.max_records
|| self.log_bytes >= self.policy.max_bytes)
}
pub fn seq(&self) -> u64 {
+7
View File
@@ -14,12 +14,17 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod dates;
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub mod fault;
pub mod folders;
mod index;
pub mod journal;
pub mod keywords;
pub mod local;
pub mod lock;
#[cfg(not(target_arch = "wasm32"))]
mod log_writer;
pub mod model;
pub mod query;
pub mod rules;
@@ -1490,6 +1495,8 @@ mod tests_journal;
mod tests_local;
#[cfg(test)]
mod tests_lock;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests_log_thread;
#[cfg(test)]
mod tests_repair;
#[cfg(test)]
+377
View File
@@ -0,0 +1,377 @@
//! The thread that writes the catalog log for [`crate::FsStore`] (natively).
//!
//! An append hands its bytes over and returns; the thread writes them in order and makes each batch
//! durable (`sync_data`) before the next. The caller (the UI thread, for the app) never waits for
//! the drive: on Windows a write to a file waits for a sync of that file in flight, so with the log
//! written and synced on the UI thread every flag, rating and step waited for the drive, 30–90 ms
//! on a busy disk in a test and over a second on a photographer's machine while previews were
//! written.
//!
//! **Nothing handed over is ever dropped.** The store's log is the file's first `good` bytes (written
//! and synced) followed by `held`, the bytes handed over and not yet synced. A write or sync that
//! fails keeps `held` and retries it (on every later message, and every [`RETRY`] meanwhile), first
//! cutting the file back to `good` so a fragment of the failed write never stays in it. While a
//! failure stands, [`LogWriter::append`] refuses new bytes with the failure (the journal keeps those
//! records queued, as for any failed append) and [`LogWriter::unwritten`] says how many records are
//! held, so the app counts them as not saved and its quit prompt warns before anything could be
//! lost. Cutting the log back, replacing it and reading it act on that logical content, after
//! everything handed over before; the caller waits for them. Dropping the writer waits for
//! everything handed over and tries a last time.
use std::io::{self, Seek, Write};
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
/// How long a caller waits for the thread at most (a cut, a replace, a read, a flush).
const WAIT: Duration = Duration::from_secs(60);
/// How often held bytes are retried while a failure stands and nothing else arrives.
pub(crate) const RETRY: Duration = Duration::from_millis(500);
enum Msg {
Append(Vec<u8>),
Truncate(u64, Sender<io::Result<()>>),
Replace(Vec<u8>, Sender<io::Result<()>>),
Read(Sender<io::Result<Option<Vec<u8>>>>),
/// Reply once everything before is written and synced (or why it isn't).
Flush(Sender<io::Result<()>>),
}
/// What the caller can see without waiting.
#[derive(Default)]
struct Shared {
/// Why the held bytes couldn't be written (until they are, or the log is cut or replaced).
failed: Option<String>,
/// Records (lines) handed over and not yet written and synced, while `failed` stands.
held_records: usize,
}
pub(crate) struct LogWriter {
pub(crate) name: String,
tx: Option<Sender<Msg>>,
shared: Arc<Mutex<Shared>>,
thread: Option<std::thread::JoinHandle<()>>,
}
fn stopped() -> io::Error {
io::Error::other("the catalog log writer stopped")
}
fn not_written(why: &str) -> io::Error {
io::Error::other(format!("the catalog log could not be written: {why}"))
}
impl LogWriter {
/// A writer for `dir/name` (`None` when no thread can start: the store then writes itself).
pub(crate) fn start(dir: PathBuf, name: &str) -> Option<LogWriter> {
let (tx, rx) = channel::<Msg>();
let shared = Arc::new(Mutex::new(Shared::default()));
let sh = shared.clone();
let mut w = Writer::new(dir, name);
let thread = std::thread::Builder::new().name("catalog-log".into()).spawn(move || w.run(&rx, &sh)).ok()?;
Some(LogWriter { name: name.to_string(), tx: Some(tx), shared, thread: Some(thread) })
}
fn send(&self, m: Msg) -> io::Result<()> {
self.tx.as_ref().ok_or_else(stopped)?.send(m).map_err(|_| stopped())
}
fn ask<T>(&self, make: impl FnOnce(Sender<io::Result<T>>) -> Msg) -> io::Result<T> {
let (tx, rx) = channel();
self.send(make(tx))?;
rx.recv_timeout(WAIT).map_err(|e| match e {
RecvTimeoutError::Timeout => io::Error::new(io::ErrorKind::TimedOut, "the drive took over a minute to write the catalog log"),
RecvTimeoutError::Disconnected => stopped(),
})?
}
/// Hand `data` over (never waits for the drive). Refused while bytes handed over before can't
/// be written: the caller keeps `data` and appends it again later.
pub(crate) fn append(&self, data: &[u8]) -> io::Result<()> {
if let Some(why) = self.shared.lock().unwrap_or_else(PoisonError::into_inner).failed.clone() {
return Err(not_written(&why));
}
self.send(Msg::Append(data.to_vec()))
}
/// Cut the log to `len` bytes, after everything handed over; waits for it.
pub(crate) fn truncate(&self, len: u64) -> io::Result<()> {
self.ask(|r| Msg::Truncate(len, r))
}
/// Replace the log with `data` (atomically, durably), after everything handed over; waits.
pub(crate) fn replace(&self, data: &[u8]) -> io::Result<()> {
self.ask(|r| Msg::Replace(data.to_vec(), r))
}
/// The log as appended so far (written or still held), after everything handed over.
pub(crate) fn read(&self) -> io::Result<Option<Vec<u8>>> {
self.ask(Msg::Read)
}
/// Wait until everything handed over is written and synced; an error says why it isn't (the
/// bytes are still held and retried).
pub(crate) fn flush(&self) -> io::Result<()> {
self.ask(Msg::Flush)
}
/// Records handed over that can't be written yet, and why (`None`: nothing is held back by a
/// failure). Never waits.
pub(crate) fn unwritten(&self) -> Option<(usize, String)> {
let sh = self.shared.lock().unwrap_or_else(PoisonError::into_inner);
sh.failed.clone().map(|why| (sh.held_records.max(1), why))
}
}
impl Drop for LogWriter {
fn drop(&mut self) {
drop(self.tx.take());
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
/// The thread's side: the file and what is held for it.
struct Writer {
dir: PathBuf,
path: PathBuf,
tmp: PathBuf,
file: Option<std::fs::File>,
/// Bytes of the file written whole and synced (`None` until the file was first opened).
good: Option<u64>,
/// Handed over, not yet written and synced.
held: Vec<u8>,
failed: Option<String>,
}
fn lines(b: &[u8]) -> usize {
b.iter().filter(|c| **c == b'\n').count()
}
impl Writer {
fn new(dir: PathBuf, name: &str) -> Writer {
let path = dir.join(name);
let tmp = dir.join(format!("{name}.tmp"));
Writer { dir, path, tmp, file: None, good: None, held: Vec::new(), failed: None }
}
fn hook(&self, step: crate::fault::Step) -> io::Result<()> {
crate::fault::check(&self.dir, step)
}
/// Open the file positioned at `good` (a fragment past it, from a write that failed, is cut).
fn open(&mut self) -> io::Result<u64> {
if let (Some(_), Some(g)) = (&self.file, self.good) {
return Ok(g);
}
// (a link or a device planted at the name meanwhile is refused, as at the first append)
crate::store::check_regular_directory_entry(&self.path)?;
let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(&self.path)?;
let len = f.metadata()?.len();
let good = match self.good {
None => len,
Some(g) if len > g => {
f.set_len(g)?;
g
}
Some(g) if len < g => {
// shorter than what was synced: someone else cut it; continue at its end
log::error!("catalog: {} is {len} bytes, {g} were written", self.path.display());
len
}
Some(g) => g,
};
f.seek(io::SeekFrom::Start(good))?;
self.good = Some(good);
self.file = Some(f);
Ok(good)
}
/// Write and sync what is held.
fn write_held(&mut self) -> io::Result<()> {
if self.held.is_empty() {
return Ok(());
}
let r = (|| {
self.hook(crate::fault::Step::Write)?;
self.open()?;
let f = self.file.as_mut().ok_or_else(|| io::Error::other("catalog log not open"))?;
f.write_all(&self.held)?;
self.hook(crate::fault::Step::Sync)?;
self.file.as_ref().ok_or_else(|| io::Error::other("catalog log not open"))?.sync_data()
})();
match r {
Ok(()) => {
let n = self.held.len() as u64;
self.good = Some(self.good.unwrap_or(0).saturating_add(n));
self.held.clear();
Ok(())
}
Err(e) => {
// the handle may be dead (a network share that reconnected, a removed volume): the
// retry opens the file again and cuts what this attempt left past `good`
self.file = None;
Err(e)
}
}
}
/// Cut the logical log (file then held) to `len` bytes.
fn truncate(&mut self, len: u64) -> io::Result<()> {
let good = match self.good {
Some(g) => g,
None => match self.open() {
Ok(g) => g,
Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
Err(e) => return Err(e),
},
};
// (to exactly `good` with bytes held: the file is cut, since a write that failed may have
// left some of them past `good`)
if len > good || (len == good && self.held.is_empty()) {
// within what is held: nothing on the drive changes (what a failed write left past
// `good` is cut before the next write)
let keep = usize::try_from(len - good).unwrap_or(usize::MAX).min(self.held.len());
self.held.truncate(keep);
return Ok(());
}
self.file = None;
let f = match std::fs::OpenOptions::new().write(true).open(&self.path) {
Ok(f) => f,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
self.good = None;
self.held.clear();
return Ok(());
}
Err(e) => return Err(e),
};
f.set_len(len)?;
f.sync_all()?;
self.good = Some(len);
self.held.clear();
Ok(())
}
fn replace(&mut self, data: &[u8]) -> io::Result<()> {
self.file = None;
let written = (|| {
self.hook(crate::fault::Step::Write)?;
let mut f = crate::store::create_staging(&self.tmp)?;
f.write_all(data)?;
self.hook(crate::fault::Step::Sync)?;
f.sync_all()?;
drop(f);
std::fs::rename(&self.tmp, &self.path)
})();
match written {
Ok(()) => {
// what was held is part of what the caller replaced the log with (a snapshot holds
// the records before it, `data` the ones after)
self.good = Some(data.len() as u64);
self.held.clear();
self.failed = None;
Ok(())
}
Err(e) => {
let _ = std::fs::remove_file(&self.tmp);
Err(e)
}
}
}
fn read(&mut self) -> io::Result<Option<Vec<u8>>> {
let mut bytes = match std::fs::read(&self.path) {
Ok(b) => b,
Err(e) if e.kind() == io::ErrorKind::NotFound && self.held.is_empty() => return Ok(None),
Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
Err(e) => return Err(e),
};
if let Some(g) = self.good {
bytes.truncate(usize::try_from(g).unwrap_or(usize::MAX));
}
bytes.extend_from_slice(&self.held);
Ok(Some(bytes))
}
fn publish(&self, shared: &Mutex<Shared>) {
let mut sh = shared.lock().unwrap_or_else(PoisonError::into_inner);
sh.failed = self.failed.clone().filter(|_| !self.held.is_empty());
sh.held_records = if sh.failed.is_some() { lines(&self.held) } else { 0 };
}
fn run(&mut self, rx: &Receiver<Msg>, shared: &Mutex<Shared>) {
loop {
let first = if self.failed.is_some() && !self.held.is_empty() {
match rx.recv_timeout(RETRY) {
Ok(m) => Some(m),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => break,
}
} else {
match rx.recv() {
Ok(m) => Some(m),
Err(_) => break,
}
};
let mut batch: Vec<Msg> = first.into_iter().collect();
while let Ok(m) = rx.try_recv() {
batch.push(m);
}
let mut flushes = Vec::new();
for m in batch {
match m {
Msg::Append(data) => self.held.extend_from_slice(&data),
// (published before the reply: the caller reads what it left at once)
Msg::Truncate(len, reply) => {
let r = self.truncate(len);
self.publish(shared);
let _ = reply.send(r);
}
Msg::Replace(data, reply) => {
let r = self.replace(&data);
self.publish(shared);
let _ = reply.send(r);
}
Msg::Read(reply) => {
let _ = reply.send(self.read());
}
Msg::Flush(reply) => flushes.push(reply),
}
}
self.step();
self.publish(shared);
for r in flushes {
let _ = r.send(match &self.failed {
Some(why) if !self.held.is_empty() => Err(not_written(why)),
_ => Ok(()),
});
}
}
// the store is closing: everything handed over gets one more try
self.step();
self.publish(shared);
if !self.held.is_empty() {
log::error!("catalog: {} record(s) could not be written to {} (the closing snapshot holds them)", lines(&self.held), self.path.display());
}
}
/// Write what is held; a failure is kept (and logged when it is new).
fn step(&mut self) {
match self.write_held() {
Ok(()) => {
if self.failed.take().is_some() {
log::info!("catalog: {} written again", self.path.display());
}
}
Err(e) => {
let why = e.to_string();
if self.failed.as_deref() != Some(why.as_str()) {
log::error!("catalog: {}: {why} ({} record(s) held, retried)", self.path.display(), lines(&self.held));
}
self.failed = Some(why);
}
}
}
}
+100 -6
View File
@@ -28,7 +28,9 @@ pub trait Store: Send {
self.write_atomic(name, &buf)?;
Ok(buf.len() as u64)
}
/// Append and make durable (fsync) before returning. On an error, part of `data` may have
/// Append and make durable (fsync): before returning, or, natively, by the store's own log
/// thread right after ([`FsStore`]: a write that fails is returned by a later append, and a
/// read through the store sees every byte handed over). On an error, part of `data` may have
/// been written (a full disk, a dropped network share): the journal cuts the file back to its
/// previous length with [`Store::truncate`] before appending again.
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()>;
@@ -43,12 +45,23 @@ pub trait Store: Send {
fn background_writer(&self) -> Option<Box<dyn Store>> {
None
}
/// Wait until every append handed over is in the file and synced ([`FsStore`] writes them on a
/// thread of its own; the default has nothing to wait for). An error says why some aren't: they
/// are still held and retried, never dropped.
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
/// Records handed over by [`Store::append`] that can't be written yet (a write or sync on the
/// store's own thread failed: they are held and retried), and why. `None`: nothing held back.
fn unwritten(&self) -> Option<(usize, String)> {
None
}
}
/// Appends and truncates open the name's own file, so anything else at the name is the library's
/// problem: a link planted there redirects the write outside the directory (CWE-59), and a device
/// hangs the open. Refused with an error the open can show, before anything is written through.
fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
pub(crate) fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(md) if md.is_file() => Ok(()),
Ok(md) => Err(io::Error::other(format!("{} is a {:?}, not a regular file", path.display(), md.file_type()))),
@@ -60,15 +73,24 @@ fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
/// Files in a directory.
pub struct FsStore {
dir: PathBuf,
/// Open append handle (kept between appends; dropped on rewrite/truncate).
/// Open append handle (kept between appends; dropped on rewrite/truncate). Used when no thread
/// writes the log (the browser build, or one that couldn't start).
appender: Option<(String, std::fs::File)>,
/// The thread that writes the log (natively; started by the first append).
#[cfg(not(target_arch = "wasm32"))]
log: Option<crate::log_writer::LogWriter>,
}
impl FsStore {
/// Use `dir` (created if missing).
pub fn open(dir: impl AsRef<Path>) -> io::Result<FsStore> {
std::fs::create_dir_all(dir.as_ref())?;
Ok(FsStore { dir: dir.as_ref().to_path_buf(), appender: None })
Ok(FsStore {
dir: dir.as_ref().to_path_buf(),
appender: None,
#[cfg(not(target_arch = "wasm32"))]
log: None,
})
}
pub fn dir(&self) -> &Path {
&self.dir
@@ -76,6 +98,21 @@ impl FsStore {
fn path(&self, name: &str) -> PathBuf {
self.dir.join(name)
}
/// The log thread, when it writes `name`.
#[cfg(not(target_arch = "wasm32"))]
fn log_for(&self, name: &str) -> Option<&crate::log_writer::LogWriter> {
self.log.as_ref().filter(|w| w.name == name)
}
/// Wait until the log thread has written and synced everything handed to it.
pub fn flush_log(&self) -> io::Result<()> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = &self.log {
return w.flush();
}
Ok(())
}
fn sync_dir(&self) {
// Makes the rename durable on POSIX; opening a directory fails on Windows (where
// `rename` is already journaled by NTFS), so errors are ignored.
@@ -97,6 +134,11 @@ pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result<std::fs::File>
impl Store for FsStore {
fn read(&mut self, name: &str) -> io::Result<Option<Vec<u8>>> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// what was handed over, written or still held
return w.read();
}
match std::fs::read(self.path(name)) {
Ok(b) => Ok(Some(b)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
@@ -106,6 +148,13 @@ impl Store for FsStore {
fn write_atomic(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// (after the appends handed over before)
w.replace(data)?;
self.sync_dir();
return Ok(());
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -122,6 +171,15 @@ impl Store for FsStore {
fn write_atomic_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result<u64> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
// (the log is small: buffered, and replaced by its thread after the appends before)
let mut buf = Vec::new();
fill(&mut buf)?;
w.replace(&buf)?;
self.sync_dir();
return Ok(buf.len() as u64);
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -148,6 +206,23 @@ impl Store for FsStore {
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
use std::io::Write;
#[cfg(not(target_arch = "wasm32"))]
{
if self.log.is_none() && !crate::fault::on_caller(&self.dir) {
check_regular_directory_entry(&self.path(name))?;
if !self.path(name).exists() {
// created here, so the open's errors are this append's and its entry is durable
std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?;
self.sync_dir();
}
self.appender = None;
self.log = crate::log_writer::LogWriter::start(self.dir.clone(), name);
}
// (another name than the log's is written here, as without a thread)
if let Some(w) = self.log_for(name) {
return w.append(data);
}
}
if self.appender.as_ref().is_none_or(|(n, _)| n != name) {
check_regular_directory_entry(&self.path(name))?;
let existed = self.path(name).exists();
@@ -158,6 +233,12 @@ impl Store for FsStore {
self.appender = Some((name.to_string(), f));
}
let Some((_, f)) = self.appender.as_mut() else { return Err(io::Error::other("appender not open")) };
#[cfg(not(target_arch = "wasm32"))]
let written = crate::fault::check(&self.dir, crate::fault::Step::Write)
.and_then(|()| f.write_all(data))
.and_then(|()| crate::fault::check(&self.dir, crate::fault::Step::Sync))
.and_then(|()| f.sync_data());
#[cfg(target_arch = "wasm32")]
let written = f.write_all(data).and_then(|()| f.sync_data());
if written.is_err() {
// The handle may be dead (a network share that reconnected, a removed volume): the next
@@ -169,6 +250,10 @@ impl Store for FsStore {
}
fn truncate(&mut self, name: &str, len: u64) -> io::Result<()> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(w) = self.log_for(name) {
return w.truncate(len);
}
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
@@ -189,7 +274,16 @@ impl Store for FsStore {
#[cfg(not(target_arch = "wasm32"))]
fn background_writer(&self) -> Option<Box<dyn Store>> {
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None }))
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None, log: None }))
}
fn flush(&mut self) -> io::Result<()> {
self.flush_log()
}
#[cfg(not(target_arch = "wasm32"))]
fn unwritten(&self) -> Option<(usize, String)> {
self.log.as_ref().and_then(|w| w.unwritten())
}
}
@@ -256,13 +350,13 @@ impl Store for MemStore {
}
}
// (its one test plants a symlink, so the module is Unix-only: elsewhere `use super::*` would be unused)
#[cfg(all(test, unix))]
mod tests_staging {
use super::*;
/// A link planted at a staging name (`<name>.tmp`) is removed, never followed: the file it points to keeps its
/// bytes and the save still lands (issue #1502).
#[cfg(unix)]
#[test]
fn a_link_at_the_staging_name_is_never_written_through() {
let dir = std::env::temp_dir().join(format!("lc-staging-link-{}", std::process::id()));
+2 -1
View File
@@ -269,9 +269,10 @@ fn fs_store_background_snapshot() {
}
// a previous crash mid-snapshot left a partial temp file
std::fs::write(dir.join(format!("{SNAPSHOT}.tmp")), b"{\"format\":\"lightcraft-catal").unwrap();
// (closed first: its log thread writes what was handed over)
drop(j);
let (mut j2, c2, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
assert_eq!((c2.to_snapshot(), r.snapshot_seq), (live.to_snapshot(), 0));
drop(j);
let n = j2.seq();
j2.snapshot_in_background(&live).unwrap();
for k in 200..260 {
+232
View File
@@ -0,0 +1,232 @@
//! PERF-STEP-STALL: the catalog log's own thread ([`crate::log_writer`]). Appends return at once
//! however slow the drive is; everything handed over is written in order; a write that fails is
//! held, reported and retried, never dropped, and the log never has a gap.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use crate::fault::{self, Step};
use crate::store::{FsStore, Store};
const LOG: &str = "catalog.log";
fn temp_dir(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lc-log-thread-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
d
}
fn wait_until(what: &str, mut done: impl FnMut() -> bool) {
let t = Instant::now();
while !done() {
assert!(t.elapsed() < Duration::from_secs(20), "{what}");
std::thread::sleep(Duration::from_millis(10));
}
}
/// Appends are written by the thread in order; a read through the store sees every one; a cut
/// and a replace come after the appends before them; dropping the store writes what is left.
#[test]
fn appends_are_written_in_order_and_cuts_and_replaces_come_after_them() {
let dir = temp_dir("order");
let mut store = FsStore::open(&dir).unwrap();
let mut want = Vec::new();
for i in 0..200u32 {
let line = format!("{i}\n");
store.append(LOG, line.as_bytes()).unwrap();
want.extend_from_slice(line.as_bytes());
if i % 50 == 0 {
assert_eq!(store.read(LOG).unwrap().unwrap(), want, "all of it, through the store");
}
}
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want, "all of it, in the file");
store.truncate(LOG, 4).unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
// never longer than it is
store.truncate(LOG, 400).unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
store.append(LOG, b"x\n").unwrap();
store.write_atomic(LOG, b"tail\n").unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n");
store.append(LOG, b"more\n").unwrap();
drop(store);
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\nmore\n");
let _ = std::fs::remove_dir_all(&dir);
}
/// (a) Each sync takes 300 ms: 100 appends still return at once, and a flush then finds all of
/// them in the file (before, each append waited for its own sync: 30 s for these).
#[test]
fn an_append_never_waits_for_a_slow_sync() {
let dir = temp_dir("slow");
let mut store = FsStore::open(&dir).unwrap();
store.append(LOG, b"first\n").unwrap();
let syncs = Arc::new(AtomicUsize::new(0));
let n = syncs.clone();
fault::install(
&dir,
Arc::new(move |step| {
if step == Step::Sync {
n.fetch_add(1, Ordering::SeqCst);
std::thread::sleep(Duration::from_millis(300));
}
Ok(())
}),
);
let mut want = b"first\n".to_vec();
let mut slowest = Duration::ZERO;
for i in 0..100u32 {
let line = format!("{i}\n");
let t = Instant::now();
store.append(LOG, line.as_bytes()).unwrap();
slowest = slowest.max(t.elapsed());
want.extend_from_slice(line.as_bytes());
std::thread::sleep(Duration::from_millis(2));
}
assert!(slowest < Duration::from_millis(50), "an append waited {slowest:?}");
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want);
// batched: far fewer syncs than appends
assert!(syncs.load(Ordering::SeqCst) < 50, "{} syncs", syncs.load(Ordering::SeqCst));
fault::remove(&dir);
let _ = std::fs::remove_dir_all(&dir);
}
/// (c) Writes fail for a while: what was handed over is held (reported, with the reason), later
/// appends are refused so the caller keeps them, and once writes work again the held bytes land,
/// in order, with no fragment of the failed attempts and no gap.
#[test]
fn a_failed_write_is_held_reported_and_retried() {
let dir = temp_dir("fail");
let mut store = FsStore::open(&dir).unwrap();
store.append(LOG, b"0\n").unwrap();
store.flush().unwrap();
let fail = Arc::new(AtomicBool::new(true));
let f = fail.clone();
fault::install(&dir, Arc::new(move |_| if f.load(Ordering::SeqCst) { Err(std::io::Error::other("disk full (test)")) } else { Ok(()) }));
// (one append: the log thread can fail the first before a second arrives, and then refuses it)
store.append(LOG, b"1\n2\n").unwrap();
wait_until("the failure is published", || store.unwritten().is_some());
let (held, why) = store.unwritten().unwrap();
assert!(why.contains("disk full"), "{why}");
assert!(held >= 1, "{held}");
let refused = store.append(LOG, b"3\n");
assert!(refused.is_err(), "refused while held");
assert!(store.flush().is_err(), "a flush says it isn't written");
// a read through the store still sees what was handed over
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
// a cut within what is held keeps it (the journal cuts back to its own length on an error)
store.truncate(LOG, 6).unwrap();
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
// a fragment of a failed write left in the file is cut before the retry
{
use std::io::Write;
let mut file = std::fs::OpenOptions::new().append(true).open(dir.join(LOG)).unwrap();
file.write_all(b"{\"seq\":").unwrap();
}
fail.store(false, Ordering::SeqCst);
wait_until("retried on its own", || store.unwritten().is_none());
store.append(LOG, b"3\n").unwrap();
store.flush().unwrap();
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n2\n3\n");
fault::remove(&dir);
let _ = std::fs::remove_dir_all(&dir);
}
/// (b, c) Through the journal: ops appended while the drive is slow or failing all reopen, and a
/// journal over a log that failed has no gap (no damage on load).
#[test]
fn the_journal_reopens_every_op_after_a_slow_then_failing_drive() {
use crate::{Catalog, Journal, Op, Photo, PhotoId, Source};
let dir = temp_dir("journal");
let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
let fail = Arc::new(AtomicBool::new(false));
let f = fail.clone();
fault::install(
&dir,
Arc::new(move |step| {
if f.load(Ordering::SeqCst) {
return Err(std::io::Error::other("network share dropped (test)"));
}
if step == Step::Sync {
std::thread::sleep(Duration::from_millis(40));
}
Ok(())
}),
);
let mut queued: Vec<Op> = Vec::new();
for id in 1..=60u64 {
if id == 20 {
fail.store(true, Ordering::SeqCst);
}
if id == 40 {
fail.store(false, Ordering::SeqCst);
}
let p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 4, 3, "2026-11-02");
let op = Op::AddPhoto { photo: Box::new(p) };
c.apply(op.clone()).unwrap();
queued.push(op);
// as the engine does: a failed append keeps its ops queued for the next one
if j.append(&queued).is_ok() {
queued.clear();
}
std::thread::sleep(Duration::from_millis(5));
}
wait_until("everything written", || {
if !queued.is_empty() && j.append(&queued).is_ok() {
queued.clear();
}
queued.is_empty() && j.unwritten().is_none()
});
j.flush().unwrap();
let expect = c.to_snapshot();
drop(j);
fault::remove(&dir);
let (_, again, report): (_, Catalog, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
assert!(report.damaged.is_none(), "{report:?}");
assert_eq!(again.to_snapshot(), expect);
assert_eq!(again.len(), 60);
let _ = std::fs::remove_dir_all(&dir);
}
/// A sync that fails leaves the written bytes past the synced length in the file; a cut to exactly
/// that length removes them from the file too, so they never come back on the next open (review
/// of #3557).
#[test]
fn a_cut_to_the_synced_length_removes_bytes_a_failed_sync_left() {
let dir = temp_dir("cut-synced");
let mut store = FsStore::open(&dir).unwrap();
store
.append(
LOG, b"0
",
)
.unwrap();
store.flush().unwrap();
fault::install(&dir, Arc::new(|step| if step == Step::Sync { Err(std::io::Error::other("sync failed (test)")) } else { Ok(()) }));
store
.append(
LOG, b"1
",
)
.unwrap();
wait_until("the failure is published", || store.unwritten().is_some());
assert_eq!(
std::fs::read(dir.join(LOG)).unwrap(),
b"0
1
",
"written, not synced"
);
store.truncate(LOG, 2).unwrap();
fault::remove(&dir);
drop(store);
assert_eq!(
std::fs::read(dir.join(LOG)).unwrap(),
b"0
"
);
let _ = std::fs::remove_dir_all(&dir);
}
+3
View File
@@ -88,6 +88,9 @@ fn partial_append_then_retry_loads_cleanly() {
assert!(j.append(&batch).is_err(), "tear at {tear}");
// cut back to the last whole record
assert_eq!(t.files.get(LOG).unwrap().len(), good_len, "tear at {tear}");
// and a snapshot is due (records handed over before may be missing from a log written
// by a thread of its own: note 2 of 2026-10-25)
assert!(j.wants_snapshot(), "tear at {tear}");
j.append(&batch).unwrap();
let more = apply(&mut c, vec![Op::SetLabel { id, label: Some(ColorLabel::ALL[0]) }]);
j.append(&more).unwrap();
+4 -1
View File
@@ -55,5 +55,8 @@ fn a_file_path_rule_allocates_nothing_per_photo() {
}
let blocks = dhat::HeapStats::get().total_blocks - before;
assert!(hits > 0, "the rules matched nothing: the test measures nothing");
assert_eq!(blocks, 0, "{blocks} heap blocks for {} rule tests", 100 * rules.len() * photos.len());
// dhat counts every thread, and the test harness's own thread can allocate a few blocks while this
// runs. An allocation per photo would be thousands, two per rule test.
let tests = 100 * rules.len() * photos.len();
assert!(blocks < 64, "{blocks} heap blocks for {tests} rule tests");
}
+10 -2
View File
@@ -84,17 +84,25 @@ 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,
/// Pixel-scale sharpening with working Radius and Detail controls.
V3,
/// V3, with Contrast and Blacks on a raw's camera look calibrated to Lightroom: the
/// camera curve keeps V2 Whites and fitted pointwise operators follow it
/// (`lightcraft_pipeline::light_v3`, `docs/light-v3.md`).
V4,
}
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; 4] = [Process::V1, Process::V2, Process::V3, Process::V4];
pub const LATEST: Process = Process::V4;
pub const fn version(self) -> ProcessVersion {
match self {
Process::V1 => ProcessVersion(1),
Process::V2 => ProcessVersion(2),
Process::V3 => ProcessVersion(3),
Process::V4 => ProcessVersion(4),
}
}
}
+1
View File
@@ -40,6 +40,7 @@ log = { workspace = true }
ab_glyph = { workspace = true }
# Apply the font’s vertical substitutions and origins to Japanese watermarks.
harfrust = { version = "0.13", default-features = false, features = ["std"] }
unicode-normalization = "0.1"
unicode-segmentation = "1.13"
lightcraft-segment = { workspace = true, optional = true }
+1 -1
View File
@@ -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, None).expect("load"))));
}
}
+3
View File
@@ -11,6 +11,7 @@ mod color;
pub(crate) mod convert;
mod cull;
pub mod curves;
pub mod dcp_profiles;
pub(crate) mod denoise;
mod develop;
mod edit;
@@ -40,6 +41,7 @@ mod print;
mod query;
pub mod recheck;
pub mod reload;
pub mod similar;
mod slideshow;
mod sync;
mod xmp;
@@ -153,6 +155,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(manage::specs());
v.extend(previews::specs());
v.extend(lut_profiles::specs());
v.extend(dcp_profiles::specs());
v.extend(mask_effects::specs());
v.extend(cull::specs());
v.extend(convert::specs());
+3 -40
View File
@@ -105,43 +105,6 @@ fn burst_params(p: &Value) -> Result<(f64, f32)> {
Ok((num("burstGap", BURST_GAP, MAX_GAP)?, num("similarity", SAME, 1.0)? as f32))
}
/// Find Similar: photos that look like `id` (signatures from thumbnail-level sources, cached by
/// content), most similar first; the view is filtered to them.
fn find_similar(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "library.findSimilar";
let id = super::photo_id(p, C)?.or(s.active()).ok_or_else(|| super::bad(C, "no photo"))?;
let min = p.get("similarity").and_then(Value::as_f64).unwrap_or(0.8) as f32;
let all: Vec<PhotoId> = s.catalog.photos().filter(|q| q.in_library()).map(|q| q.id).collect();
let sig = |s: &mut Session, id: PhotoId| -> Option<[f32; 64]> {
let key = s.catalog.photo(id).map(|p| crate::media::content_key(p))?;
if let Some(v) = s.signatures.get(&key) {
return Some(*v);
}
let src = s.source_now(id, crate::media::SourceLevel::Thumb).ok()?;
let v = lightcraft_pipeline::cull::signature(&src);
s.signatures.insert(key, v);
Some(v)
};
let me = sig(s, id).ok_or_else(|| super::bad(C, "can't read the photo"))?;
let mut hits: Vec<(PhotoId, f32)> = Vec::new();
for q in all {
if let Some(v) = sig(s, q) {
let sim = lightcraft_pipeline::cull::similarity(&me, &v);
if sim >= min {
hits.push((q, sim.clamp(0.0, 1.0)));
}
}
}
hits.sort_by(|a, b| b.1.total_cmp(&a.1));
if p.get("filter").and_then(Value::as_bool).unwrap_or(true) {
s.shelved_filter = None;
s.filter.only = hits.iter().map(|h| h.0).collect();
// an empty `only` means "no constraint": no hits is its own state that shows no photos
s.filter.only_none = s.filter.only.is_empty();
}
Ok(json!({"photos": hits.iter().map(|(i, v)| json!({"id": i.0, "similarity": (v * 1000.0).round() / 1000.0})).collect::<Vec<_>>()}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -149,9 +112,9 @@ pub fn specs() -> Vec<CommandSpec> {
"Find Similar Photos",
["Photo"],
None,
"{id?, similarity?: 0..1 (0.8), filter?: bool (true)} — photos that look like the active one (composition and tones), most similar first; filters the view to them (Clear Filters to go back) → {photos: [{id, similarity}]}",
always,
find_similar
"{id?, similarity?: 0..1 (0.8), filter?: bool (true)} — photos that look like the active one (composition and tones), most similar first; filters the view to them (Clear Filters to go back) → {photos: [{id, similarity}]}. In the app the photos are read on a worker thread under an activity row: a control request is answered with this when the search ends, and from a menu the answer is {background: true, count}",
super::similar::no_search_running,
super::similar::run
),
cmd!(
"photo.analyze",
+212
View File
@@ -0,0 +1,212 @@
//! Imported camera profiles: the user's own DNG Camera Profiles (`.dcp`), chosen like any other
//! profile (`develop.profile {id: "dcp:…"}`). Unlike the built-in looks and LUT profiles, which
//! work on developed colour, a camera profile replaces the raw file's colour model when it is
//! decoded (its matrices and hue/saturation map; see [`lightcraft_raw::dcp`]), so the photo's
//! source is decoded again when it changes. Other photos (JPEG, TIFF…) ignore it.
//!
//! A library on disk keeps a copy of each file in its `Profiles/` folder; the list lives in the
//! library's prefs and the profiles are parsed again when the library opens.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use super::{CommandSpec, always, bad, cmd, str_param};
use crate::media::LoadedCameraProfile;
use crate::{Result, Session};
/// Profile id prefix of imported camera profiles.
pub const DCP_PREFIX: &str = "dcp:";
/// Profile browser group of imported camera profiles.
pub const DCP_GROUP: &str = "Camera Profiles";
/// One imported camera profile.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DcpEntry {
/// `dcp:<slug>`.
pub id: String,
/// `ProfileName`, else the file name.
pub name: String,
/// The camera it was made for (`UniqueCameraModel`).
#[serde(default)]
pub camera_model: String,
/// The `.dcp` file (the library's copy when there is a library on disk).
pub file: String,
}
/// Is `id` an imported camera profile id?
pub fn is_dcp_id(id: &str) -> bool {
id.starts_with(DCP_PREFIX)
}
fn profiles_dir(s: &Session) -> Option<PathBuf> {
s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Profiles"))
}
/// Parse every imported camera profile again and hand them to the decoder (missing or damaged
/// files are skipped: photos using them develop with the file's own colour, and the profile is not offered or
/// accepted by `develop.profile` until its file is back; the entry is kept).
///
/// A library's own copies are found in `profiles`, the `Profiles/` folder of the library being opened (`None`: not on
/// disk), wherever the saved path points: a library moved or restored elsewhere keeps its profiles (the saved path is
/// updated).
pub fn register_all(s: &mut Session, profiles: Option<&Path>) {
if let Some(dir) = profiles {
for p in &mut s.dcp_profiles {
if let Some(here) = library_copy(dir, &p.file) {
p.file = here.to_string_lossy().to_string();
}
}
}
let loaded: Vec<(String, LoadedCameraProfile)> = s
.dcp_profiles
.iter()
.filter_map(|p| {
lightcraft_raw::dcp::read_dcp(Path::new(&p.file)).ok().and_then(|b| LoadedCameraProfile::parse(&b).ok()).map(|d| (p.id.clone(), d))
})
.collect();
s.media.camera_profiles = loaded.into_iter().collect();
}
/// The copy of saved profile file `file` in the open library's profiles folder `dir`, when it is there under the
/// same name and `file` is not already it.
fn library_copy(dir: &Path, file: &str) -> Option<PathBuf> {
let saved = Path::new(file);
let here = dir.join(saved.file_name()?);
(here != saved && here.is_file()).then_some(here)
}
/// `.dcp` files under `paths` (folders searched).
pub fn dcp_files(paths: &[String]) -> Vec<PathBuf> {
let is_dcp = |f: &Path| f.extension().is_some_and(|x| x.eq_ignore_ascii_case("dcp"));
let mut out = Vec::new();
for p in paths {
let path = Path::new(p);
if path.is_dir() {
out.extend(crate::walk::files_in(path, None, crate::walk::Limits::default(), is_dcp).files);
} else if is_dcp(path) {
out.push(path.to_path_buf());
}
}
out
}
/// Import the `.dcp` files under `paths` → (imported `[{id, name, cameraModel}]`, failed `[[file, error]]`).
/// A profile already imported (same name, camera and bytes) is not added twice.
pub fn import_files(s: &mut Session, paths: &[String]) -> Result<(Vec<Value>, Vec<Value>)> {
const C: &str = "profile.import";
let dir = profiles_dir(s);
if let Some(d) = &dir {
std::fs::create_dir_all(d).map_err(|e| bad(C, format!("{}: {e}", d.display())))?;
}
let (mut imported, mut failed) = (Vec::new(), Vec::new());
for f in dcp_files(paths) {
let shown = f.display().to_string();
let bytes = match lightcraft_raw::dcp::read_dcp(&f) {
Ok(b) => b,
Err(e) => {
failed.push(json!([shown, e.to_string()]));
continue;
}
};
let loaded = match LoadedCameraProfile::parse(&bytes) {
Ok(p) => p,
Err(e) => {
failed.push(json!([shown, e.to_string()]));
continue;
}
};
let profile = loaded.profile.clone();
let stem = f.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Camera Profile".into());
let name = if profile.name.trim().is_empty() { stem.clone() } else { profile.name.trim().to_string() };
// the same profile imported again: keep the one there is
let same = s.dcp_profiles.iter().find(|p| {
p.name == name && p.camera_model == profile.camera_model && lightcraft_raw::dcp::read_dcp(Path::new(&p.file)).is_ok_and(|b| b == bytes)
});
if let Some(p) = same {
imported.push(json!({"id": p.id, "name": p.name, "cameraModel": p.camera_model, "existing": true}));
continue;
}
// (the file name keeps profiles with the same ProfileName apart, e.g. per-body copies)
let slug = crate::presets::slug(&format!("{}-{stem}", profile.camera_model));
let mut id = format!("{DCP_PREFIX}{slug}");
let mut n = 2;
while s.dcp_profiles.iter().any(|x| x.id == id) {
id = format!("{DCP_PREFIX}{slug}-{n}");
n += 1;
}
let file = match &dir {
Some(d) => {
let to = d.join(format!("{}.dcp", id.trim_start_matches(DCP_PREFIX)));
// a copy that fails (disk full, no access) fails this file only: the profiles
// copied before it stay imported, and nothing half-written is left behind
if let Err(e) = std::fs::write(&to, &bytes) {
if to.is_file() {
let _ = std::fs::remove_file(&to);
}
failed.push(json!([shown, format!("{}: {e}", to.display())]));
continue;
}
to.to_string_lossy().to_string()
}
// no library on disk: remember the original (the in-memory session ends with the app)
None => f.to_string_lossy().to_string(),
};
s.media.camera_profiles.insert(id.clone(), loaded);
s.dcp_profiles.push(DcpEntry { id: id.clone(), name: name.clone(), camera_model: profile.camera_model.clone(), file });
imported.push(json!({"id": id, "name": name, "cameraModel": profile.camera_model}));
}
Ok((imported, failed))
}
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "profile.deleteCamera";
let id = str_param(p, "id").ok_or_else(|| bad(C, "missing id"))?.to_string();
let Some(i) = s.dcp_profiles.iter().position(|x| x.id == id) else {
return Err(bad(C, format!("no imported camera profile `{id}`")));
};
// the library's copy goes first; a file outside the library is the user's and stays. A copy that can't be
// removed (in use, no access) keeps the profile, so the library never holds a file it no longer lists. A path
// with `..` in it is never the library's copy (it could lead out of the profiles folder).
if let Some(d) = profiles_dir(s)
&& let Some(entry) = s.dcp_profiles.get(i)
&& Path::new(&entry.file).starts_with(&d)
&& !Path::new(&entry.file).components().any(|c| c == std::path::Component::ParentDir)
{
match std::fs::remove_file(&entry.file) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(bad(C, format!("could not delete {}: {e}", entry.file))),
}
}
s.dcp_profiles.remove(i);
s.media.camera_profiles.remove(&id);
s.profile_favorites.retain(|f| f != &id);
s.profile_recent.retain(|f| f != &id);
s.save_prefs()?;
Ok(json!({"deleted": id}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "profiles.camera",
"Imported Camera Profiles",
[],
None,
"{} → {profiles: [{id, name, cameraModel, file}]}: the imported .dcp camera profiles (use with develop.profile)",
always,
|s, _| Ok(json!({"profiles": s.dcp_profiles}))
),
cmd!(
"profile.deleteCamera",
"Delete Imported Camera Profile",
[],
None,
"{id: dcp:…} — photos using it develop with their file's own colour again",
always,
delete
),
]
}
+10 -2
View File
@@ -557,9 +557,17 @@ pub fn specs() -> Vec<CommandSpec> {
}),
cmd!("develop.profile", "Set Profile", [], None, "{id: profile id (see profiles.list), amount?: 0..200}", has_active, |s, p| {
let id = str_param(p, "id").ok_or_else(|| bad("develop.profile", "missing id"))?.to_string();
if !crate::presets::PROFILES.iter().any(|x| x.id == id) && !s.lut_profiles.iter().any(|x| x.id == id) {
if !crate::presets::PROFILES.iter().any(|x| x.id == id)
&& !s.lut_profiles.iter().any(|x| x.id == id)
&& !s.dcp_profiles.iter().any(|x| x.id == id)
{
return Err(bad("develop.profile", format!("unknown profile `{id}`")));
}
// an imported camera profile whose file is missing or damaged: choosing it would develop with the
// file's own colour without saying so
if crate::cmd::dcp_profiles::is_dcp_id(&id) && !s.media.camera_profiles.contains_key(&id) {
return Err(bad("develop.profile", format!("camera profile `{id}` can't be used: its file is missing or damaged")));
}
edit(s, "develop.profile", "Profile", |d| {
d.profile.id = id.clone();
d.profile.amount = f64_or(p, "amount", d.profile.amount).clamp(0.0, 200.0);
@@ -570,7 +578,7 @@ pub fn specs() -> Vec<CommandSpec> {
}),
cmd!("profile.favorite", "Favorite Profile", [], None, "{id, favorite?: bool} (toggles when omitted)", always, |s, p| {
let id = str_param(p, "id").ok_or_else(|| bad("profile.favorite", "missing id"))?.to_string();
if crate::presets::profile(&id).is_none() && !s.lut_profiles.iter().any(|x| x.id == id) {
if crate::presets::profile(&id).is_none() && !s.lut_profiles.iter().any(|x| x.id == id) && !s.dcp_profiles.iter().any(|x| x.id == id) {
return Err(bad("profile.favorite", format!("unknown profile `{id}`")));
}
let on = s.profile_favorites.contains(&id);
+75 -10
View File
@@ -47,6 +47,10 @@ pub struct PlaceNames {
shared: Arc<Mutex<DownloadShared>>,
/// (cities file, its size, its modification time, the parsed names).
cache: Option<(PathBuf, u64, Option<SystemTime>, Arc<GeoNames>)>,
/// (folder, server) a download goes to instead of `<settings>/geonames` and GeoNames. Only
/// tests set it: no command can, so a client never chooses where the files land (#2575).
#[cfg(not(target_arch = "wasm32"))]
download_to: Option<(PathBuf, String)>,
}
impl PlaceNames {
@@ -188,10 +192,7 @@ mod download {
use lightcraft_geocode::{GEONAMES_BASE, GEONAMES_ZIP};
use super::{
Cancel, DownloadOutcome, GEONAMES_ATTRIBUTION, GEONAMES_FILES, GeoNames, PoisonError, Result, Session, Value, bad, dataset_dir, json,
str_param,
};
use super::{Cancel, DownloadOutcome, GEONAMES_ATTRIBUTION, GEONAMES_FILES, GeoNames, PoisonError, Result, Session, Value, bad, json};
use crate::activity::Unit;
const MAX_ZIP: u64 = 64 * 1024 * 1024;
@@ -218,7 +219,11 @@ mod download {
return Err("the downloaded place list is empty".into());
}
let _ = std::fs::remove_file(staging.join(GEONAMES_ZIP));
let write = |name: &str, data: &[u8]| std::fs::write(dir.join(name), data).map_err(|e| format!("could not save {name}: {e}"));
// a temp file renamed over the old one: never half-written, and a link in its place is
// replaced, not written through (#2575); not synced, as a download can always be repeated
let write = |name: &str, data: &[u8]| {
lightcraft_catalog::safe_file::write_atomic_nosync(&dir.join(name), data).map_err(|e| format!("could not save {name}: {e}"))
};
for name in &GEONAMES_FILES[1..] {
// optional: without them states stay blank and countries are ISO codes
match get(name, base, &staging, cancel, task).and_then(|()| std::fs::read(staging.join(name)).map_err(|e| e.to_string())) {
@@ -241,10 +246,21 @@ mod download {
}
/// `metadata.downloadPlaceNames`: starts a background download (shown in the activity stack, cancellable).
/// The files always go to `<settings>/geonames`, from GeoNames: a control or MCP client naming a
/// folder (`dataset`) or a server (`base`) could have written a server's bytes into any folder (#2575).
pub(super) fn start(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "metadata.downloadPlaceNames";
let dir = dataset_dir(p).ok_or_else(|| bad(C, "no settings folder: give `dataset`"))?;
let base = str_param(p, "base").unwrap_or(GEONAMES_BASE).to_string();
if p.get("dataset").is_some() || p.get("base").is_some() {
return Err(bad(C, "the place names always download from GeoNames into the settings folder: `dataset` and `base` are not accepted"));
}
let target = s.place_names.download_to.clone();
let (dir, base) = match target {
Some(t) => t,
None => (
crate::config::config_dir().ok_or_else(|| bad(C, "no settings folder to save the place names in"))?.join("geonames"),
GEONAMES_BASE.to_string(),
),
};
if !base_allowed(&base) {
return Err(bad(C, "`base` must be an https:// address"));
}
@@ -309,7 +325,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Download Place Names (GeoNames)",
["Photo"],
None,
"{dataset?: folder} → {started, path, attribution} — downloads the GeoNames cities list (CC-BY 4.0, ~3 MB, from download.geonames.org) in the background for Fill Location from GPS; no photo data is sent",
"{} → {started, path, attribution} — downloads the GeoNames cities list (CC-BY 4.0, ~3 MB, from download.geonames.org) in the background for Fill Location from GPS, always into `geonames` in the settings folder (a folder or server named by the caller is refused); no photo data is sent",
always,
download::start
));
@@ -468,7 +484,8 @@ mod tests {
#[cfg(not(target_arch = "wasm32"))]
fn download(s: &mut Session, base: &str, dir: &Path) -> DownloadOutcome {
s.execute("metadata.downloadPlaceNames", &json!({"dataset": dir, "base": base})).unwrap();
s.place_names.download_to = Some((dir.to_path_buf(), base.to_string()));
s.execute("metadata.downloadPlaceNames", &json!({})).unwrap();
assert!(s.place_names.downloading() || s.place_names.lock().unreported.is_some());
let started = std::time::Instant::now();
loop {
@@ -493,7 +510,8 @@ mod tests {
let base = serve();
let dir = std::env::temp_dir().join(format!("lightcraft-geocode-dl-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
assert!(s.execute("metadata.downloadPlaceNames", &json!({"dataset": dir, "base": "http://example.com/"})).is_err());
s.place_names.download_to = Some((dir.clone(), "http://example.com/".into()));
assert!(s.execute("metadata.downloadPlaceNames", &json!({})).is_err(), "plain http to another machine");
for bad in ["missing", "garbage", "short"] {
let o = download(&mut s, &format!("{base}/{bad}/"), &dir);
@@ -516,6 +534,53 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// Issue #2575: a control or MCP client named the folder (`dataset`) and the server (`base`),
/// so it could have a server's bytes written as `cities15000.txt`, `admin1CodesASCII.txt` and
/// `countryInfo.txt` into any folder. Both are refused now, before anything starts.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_client_cannot_choose_where_the_place_names_download_to() {
let mut s = Session::with_demo();
let dir = std::env::temp_dir().join(format!("lightcraft-geocode-elsewhere-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for p in [json!({"dataset": dir}), json!({"base": "https://example.com/"}), json!({"dataset": dir, "base": "https://example.com/"})] {
let e = s.execute("metadata.downloadPlaceNames", &p).unwrap_err().to_string();
assert!(e.contains("not accepted"), "{p}: {e}");
}
assert!(!s.place_names.downloading() && s.activity.list().is_empty(), "nothing started");
assert!(!dir.exists(), "nothing written");
}
/// The downloaded files replace what is there by renaming a complete temp file over it, so a
/// link planted under one of their names is replaced, not followed to the file it points at.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_download_replaces_a_planted_link_instead_of_writing_through_it() {
let mut s = Session::with_demo();
let base = serve();
let root = std::env::temp_dir().join(format!("lightcraft-geocode-link-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let dir = root.join("geonames");
std::fs::create_dir_all(&dir).unwrap();
let victim = root.join("victim.txt");
std::fs::write(&victim, "keep me").unwrap();
let link = dir.join("countryInfo.txt");
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(&victim, &link);
#[cfg(windows)]
let linked = std::os::windows::fs::symlink_file(&victim, &link);
if let Err(e) = linked {
lightcraft_testkit::skip!(System, "can't create a symbolic link here: {e}");
let _ = std::fs::remove_dir_all(&root);
return;
}
assert_eq!(download(&mut s, &format!("{base}/good/"), &dir), DownloadOutcome::Done(2));
assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me", "the link's target is untouched");
assert!(!std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link is now the downloaded file");
assert!(std::fs::read_to_string(&link).unwrap().contains("France"));
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn download_base_is_https_or_loopback_only() {
assert!(download::base_allowed("https://download.geonames.org/export/dump/"));
+13 -3
View File
@@ -77,11 +77,14 @@ fn cube_files(paths: &[String]) -> (Vec<(String, String, Option<String>)>, Vec<V
));
}
}
} else {
} else if path.extension().is_some_and(|x| x.eq_ignore_ascii_case("cube")) {
match std::fs::read_to_string(path) {
Ok(t) => out.push((stem(path), t, None)),
Err(e) => failed.push(json!([stem(path), e.to_string()])),
}
} else if !path.extension().is_some_and(|x| x.eq_ignore_ascii_case("dcp")) {
// (a .dcp is a camera profile: `dcp_profiles::import_files` takes it)
failed.push(json!([stem(path), "not a .cube, .dcp or .zip file"]));
}
}
(out, failed)
@@ -133,6 +136,10 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
s.lut_profiles.push(LutProfile { id: id.clone(), name: display.clone(), group: group.clone(), file });
imported.push(json!({"id": id, "name": display, "group": group}));
}
// camera profiles (.dcp) among them
let (cameras, camera_failed) = super::dcp_profiles::import_files(s, &paths)?;
imported.extend(cameras);
failed.extend(camera_failed);
s.save_prefs()?;
// presets that name these profiles use them now
crate::profile_refs::refresh(s);
@@ -146,12 +153,15 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Profiles",
[],
None,
"{paths: [.cube file, folder or .zip]} — 3D LUTs become creative profiles (Amount 0–200 %; rendered on the CPU) in the profile browser's groups (folder / zip name, else Imported) → {imported: [{id, name, group}], failed}",
"{paths: [.cube / .dcp file, folder or .zip]} — 3D LUTs become creative profiles (Amount 0–200 %; rendered on the CPU) in the profile browser's groups (folder / zip name, else Imported); DNG camera profiles (.dcp, the user's own) become camera profiles (dcp: ids, group Camera Profiles) that replace a raw file's colour model when it is decoded → {imported: [{id, name, group | cameraModel}], failed}",
always,
import
),
cmd!("profile.deleteImported", "Delete Imported Profile", [], None, "{id: lut:…}", always, |s, p| {
cmd!("profile.deleteImported", "Delete Imported Profile", [], None, "{id: lut:… | dcp:…}", always, |s, p| {
let id = str_param(p, "id").ok_or_else(|| bad("profile.deleteImported", "missing id"))?.to_string();
if super::dcp_profiles::is_dcp_id(&id) {
return s.execute("profile.deleteCamera", p);
}
let Some(i) = s.lut_profiles.iter().position(|x| x.id == id) else {
return Err(bad("profile.deleteImported", format!("no imported profile `{id}`")));
};
+14 -4
View File
@@ -360,8 +360,9 @@ struct SmartCounts {
fn original_only(source: crate::media::SourceRef) -> Option<crate::media::SourceRef> {
use crate::media::SourceRef;
match source {
// (a smart preview keeps the file's own colour: an imported camera profile is applied when the original is read)
SourceRef::File { path, max_edge, loader, denoise, .. } => {
Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, reduced: None })
Some(SourceRef::File { path, max_edge, loader, fallback: None, denoise, camera_profile: None, reduced: None })
}
SourceRef::Loaded(d) if d.info.is_some() && !d.from_proxy && !d.reduced => Some(SourceRef::Loaded(d)),
_ => None,
@@ -486,7 +487,9 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {
continue;
}
let path = crate::smart::sharded_file_path(&dir, &ph);
let source = (!discard).then(|| s.media.source_ref(&ph, crate::media::SourceLevel::Preview));
// (a smart preview keeps the file's own colour: never built with the photo's imported camera profile, nor
// from a cached source developed with it)
let source = (!discard).then(|| s.media.source_ref_without_profile(&ph, crate::media::SourceLevel::Preview));
jobs.push((id, path, source, preview_fitted_look(&ph)));
}
let custom = s.smart_previews_dir.is_some();
@@ -720,8 +723,15 @@ mod tests {
let mut jobs = jobs_for(&mut s, id, Some(512));
assert_eq!(jobs.len(), 2, "view and thumbnail");
assert!(jobs[0].view_cache.is_some(), "the view renders first");
jobs[1].source =
SourceRef::File { path: "/nonexistent/photo.arw".into(), max_edge: 512, loader: None, fallback: None, denoise: None, reduced: None };
jobs[1].source = SourceRef::File {
path: "/nonexistent/photo.arw".into(),
max_edge: 512,
loader: None,
fallback: None,
denoise: None,
camera_profile: None,
reduced: None,
};
assert!(run_photo(jobs), "the thumbnail rendered from the view's decoded source");
}
+399
View File
@@ -0,0 +1,399 @@
//! Find Similar (`library.findSimilar`), split so the app can read the photos on a worker thread: the
//! first search reads a thumbnail-level source of every photo in the library, and in a large
//! library that froze the window for as long as it took (issue #3468). [`plan`] lists what is to be
//! read (no file-system calls), [`measure`] reads it without the session (cancellable, with
//! progress), [`keep`] adds what it found to the session's signatures and [`apply`] answers from
//! those. The command itself (the CLI, MCP without an app) does all of them at once.
//!
//! A search keeps no decoded source and learns nothing from one: it only looks, and in a large library
//! it would push out of memory what the grid and the loupe are showing.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, PoisonError};
use lightcraft_catalog::PhotoId;
use serde_json::{Value, json};
use super::bad;
use crate::media::{SourceLevel, SourceRef, content_key};
use crate::{Result, Session};
const C: &str = "library.findSimilar";
/// The kind of the row in the activity stack that a search on a worker thread holds.
pub const KIND: &str = "similar";
/// A content key and that content's look-alike signature.
pub type Signature = (String, [f32; 64]);
/// Whether a search can start (the command's `enabled`): one at a time, for what a second one would
/// read the first is reading.
pub fn no_search_running(s: &Session) -> std::result::Result<(), String> {
if s.activity.list().iter().any(|r| r.kind == KIND) { Err("a search for similar photos is already running".to_string()) } else { Ok(()) }
}
/// What a search asks.
#[derive(Debug)]
pub struct Search {
id: PhotoId,
min: f32,
filter: bool,
}
/// A content whose signature isn't known yet, and how to read it: from the first of its photos that
/// can be read (a copy that is offline gives way to the next).
struct Content {
key: String,
sources: Vec<SourceRef>,
}
/// What a search has to read: the searched photo first, as nothing can be compared without it.
pub struct Reads {
me: Option<Content>,
rest: Vec<Content>,
}
impl Reads {
/// How many contents are to be read.
pub fn len(&self) -> usize {
self.rest.len().saturating_add(usize::from(self.me.is_some()))
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
/// The search `p` asks for and what it has to read, once for each content not known yet. No
/// file-system calls.
pub fn plan(s: &mut Session, p: &Value) -> Result<(Search, Reads)> {
let id = super::photo_id(p, C)?.or(s.active()).ok_or_else(|| bad(C, "no photo"))?;
let min = p.get("similarity").and_then(Value::as_f64).unwrap_or(0.8) as f32;
let filter = p.get("filter").and_then(Value::as_bool).unwrap_or(true);
let photo = s.catalog.photo(id).ok_or_else(|| bad(C, "can't read the photo"))?;
let my_key = content_key(photo);
let me =
(!s.signatures.contains_key(&my_key)).then(|| Content { sources: vec![s.media.source_ref(photo, SourceLevel::Thumb)], key: my_key.clone() });
let mut rest: Vec<Content> = Vec::new();
let mut at = std::collections::HashMap::new();
for q in s.catalog.photos().filter(|q| q.in_library()) {
let key = content_key(q);
// (the searched photo's content is known by the time these are read, or the search has ended)
if key == my_key || s.signatures.contains_key(&key) {
continue;
}
let source = s.media.source_ref(q, SourceLevel::Thumb);
match at.get(&key).and_then(|i: &usize| rest.get_mut(*i)) {
Some(content) => content.sources.push(source),
None => {
at.insert(key.clone(), rest.len());
rest.push(Content { key, sources: vec![source] });
}
}
}
Ok((Search { id, min, filter }, Reads { me, rest }))
}
/// `content`'s signature, or `None` when none of its photos can be read or `cancel` is set first. A
/// decoder's panic is that photo's failure, not the search's.
fn signature_of(content: &Content, cancel: &AtomicBool) -> Option<[f32; 64]> {
content.sources.iter().find_map(|source| {
if cancel.load(Ordering::Relaxed) {
return None;
}
crate::guard::catch("Find Similar", || {
crate::memory::in_background(|| source.load_source()).ok().map(|decoded| lightcraft_pipeline::cull::signature(&decoded.image))
})
.ok()
.flatten()
})
}
/// Read what [`plan`] listed, several photos at once. Doesn't touch the session. `progress(done)` is
/// called from the threads doing the reading; once `cancel` is set no further file is started, and
/// what was read until then comes back. A searched photo that can't be read ends it there.
pub fn measure(reads: Reads, cancel: &AtomicBool, progress: &(dyn Fn(usize) + Sync)) -> Vec<Signature> {
let found = Mutex::new(Vec::with_capacity(reads.len().min(4096)));
let done = AtomicUsize::new(0);
let keep = |key: String, v: [f32; 64]| found.lock().unwrap_or_else(PoisonError::into_inner).push((key, v));
if let Some(me) = reads.me {
let Some(v) = signature_of(&me, cancel) else { return Vec::new() };
keep(me.key, v);
done.store(1, Ordering::Relaxed);
progress(1);
}
let lanes = crate::export::export_parallelism(reads.rest.len());
let queue = Mutex::new(reads.rest.into_iter());
let work = || {
while !cancel.load(Ordering::Relaxed) {
let next = queue.lock().unwrap_or_else(PoisonError::into_inner).next();
let Some(content) = next else { break };
if let Some(v) = signature_of(&content, cancel) {
keep(content.key, v);
}
progress(done.fetch_add(1, Ordering::Relaxed).saturating_add(1));
}
};
#[cfg(not(target_arch = "wasm32"))]
std::thread::scope(|sc| {
for k in 1..lanes.max(1) {
// a lane that can't start leaves its photos to the others (and to this thread)
if std::thread::Builder::new().name(format!("similar-{k}")).spawn_scoped(sc, work).is_err() {
break;
}
}
work();
});
#[cfg(target_arch = "wasm32")]
{
let _ = lanes;
work();
}
found.into_inner().unwrap_or_else(PoisonError::into_inner)
}
/// Add what [`measure`] found to the signatures, also when the search was stopped: they hold for the
/// contents they were read from, and the next search doesn't read those again.
pub fn keep(s: &mut Session, found: Vec<Signature>) {
s.signatures.extend(found);
}
/// Answer `search` from the signatures known now, most similar first, and filter the view to the
/// photos found. A photo with none (it can't be read, or came after the [`plan`]) isn't compared.
pub fn apply(s: &mut Session, search: &Search) -> Result<Value> {
let known = s.catalog.photo(search.id).and_then(|photo| s.signatures.get(&content_key(photo)));
let me = *known.ok_or_else(|| bad(C, "can't read the photo"))?;
let mut hits: Vec<(PhotoId, f32)> = Vec::new();
for q in s.catalog.photos().filter(|q| q.in_library()) {
if let Some(v) = s.signatures.get(&content_key(q)) {
let sim = lightcraft_pipeline::cull::similarity(&me, v);
if sim >= search.min {
hits.push((q.id, sim.clamp(0.0, 1.0)));
}
}
}
hits.sort_by(|a, b| b.1.total_cmp(&a.1));
if search.filter {
s.shelved_filter = None;
s.filter.only = hits.iter().map(|h| h.0).collect();
// an empty `only` means "no constraint": no hits is its own state that shows no photos
s.filter.only_none = s.filter.only.is_empty();
}
Ok(json!({"photos": hits.iter().map(|(i, v)| json!({"id": i.0, "similarity": (v * 1000.0).round() / 1000.0})).collect::<Vec<_>>()}))
}
/// Find Similar: photos that look like `id` (signatures from thumbnail-level sources, cached by
/// content), most similar first; the view is filtered to them.
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let (search, reads) = plan(s, p)?;
let found = measure(reads, &AtomicBool::new(false), &|_| {});
keep(s, found);
apply(s, &search)
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::Arc;
use lightcraft_catalog::{Op, Photo, Source};
use lightcraft_raster::Rgb32f;
use super::*;
/// Reads per file, the files that can't be read and the file whose decoder panics.
#[derive(Default)]
struct Files {
reads: Mutex<HashMap<String, usize>>,
unreadable: Mutex<Vec<String>>,
panics: Mutex<Option<String>>,
/// Set once this many reads have started.
cancel_after: Option<(usize, Arc<AtomicBool>)>,
}
impl Files {
fn reads_of(&self, path: &str) -> usize {
self.reads.lock().unwrap().get(path).copied().unwrap_or(0)
}
fn reads(&self) -> usize {
self.reads.lock().unwrap().values().sum()
}
}
/// A session of photos `/p/<name>.jpg`, each with its content hash when it has one. Odd numbers
/// in a name mean a picture that gets brighter to the right, others one that does downwards.
fn session(photos: &[(&str, Option<&str>)], files: Files) -> (Session, Arc<Files>) {
let files = Arc::new(files);
let mut s = Session::new();
for (i, (name, hash)) in photos.iter().enumerate() {
let source = Source::File { path: format!("/p/{name}.jpg") };
let mut p = Photo::new(PhotoId(i as u64 + 1), source, &format!("{name}.jpg"), "JPEG", 64, 64, "2026-01-01T00:00:00");
p.content_hash = hash.map(str::to_string);
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
}
let seen = files.clone();
s.media.file_loader = Some(Arc::new(move |path: &str, _, _| {
let started = {
let mut reads = seen.reads.lock().unwrap();
*reads.entry(path.to_string()).or_default() += 1;
reads.values().sum::<usize>()
};
if let Some((after, cancel)) = &seen.cancel_after
&& started >= *after
{
cancel.store(true, Ordering::SeqCst);
}
if seen.panics.lock().unwrap().as_deref() == Some(path) {
panic!("a decoder fails on {path}");
}
if seen.unreadable.lock().unwrap().iter().any(|f| f == path) {
return Err(format!("{path}: gone"));
}
let across = path.bytes().filter(u8::is_ascii_digit).any(|b| b % 2 == 1);
let image = Rgb32f::from_fn(64, 64, |x, y| {
let v = if across { x } else { y };
[v as f32 / 64.0; 3]
});
Ok((image, Default::default()))
}));
(s, files)
}
fn ids(r: &Value) -> Vec<u64> {
r["photos"].as_array().unwrap().iter().map(|h| h["id"].as_u64().unwrap()).collect()
}
/// A search on a worker thread holds a row of its kind: the command is off until the row goes.
#[test]
fn a_running_search_turns_the_command_off() {
let (mut s, files) = session(&[("a1", None), ("b2", None)], Files::default());
let row = s.activity.start(KIND, "Find Similar Photos", crate::activity::Cancel::No);
let off = s.commands().into_iter().find(|c| c.id == C).is_some_and(|c| !c.enabled);
assert!(off, "the menu shows it off");
assert!(matches!(s.execute(C, &json!({"id": 1})), Err(crate::EngineError::Disabled(..))));
assert_eq!(files.reads(), 0);
drop(row);
assert!(s.execute(C, &json!({"id": 1})).is_ok());
}
#[test]
fn making_the_plan_reads_no_file() {
let (mut s, files) = session(&[("a1", None), ("b2", None), ("c1", None)], Files::default());
let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap();
assert_eq!(reads.len(), 3);
assert_eq!(files.reads(), 0);
}
#[test]
fn the_command_reads_each_photo_and_finds_the_ones_alike() {
let names: Vec<String> = (0..40).map(|i| format!("p{i}")).collect();
let photos: Vec<(&str, Option<&str>)> = names.iter().map(|n| (n.as_str(), None)).collect();
let (mut s, files) = session(&photos, Files::default());
let r = s.execute("library.findSimilar", &json!({"id": 1})).unwrap();
assert_eq!(files.reads(), 40, "each once");
assert!(ids(&r).contains(&1) && ids(&r).len() < 40, "{r}");
// known now: no file is read again
let again = s.execute("library.findSimilar", &json!({"id": 1})).unwrap();
assert_eq!(files.reads(), 40);
assert_eq!(ids(&again), ids(&r));
}
#[test]
fn a_content_is_read_once_and_an_unreadable_copy_gives_way_to_the_next() {
let files = Files::default();
files.unreadable.lock().unwrap().push("/p/copy2.jpg".into());
let photos = [("me1", None), ("copy2", Some("h")), ("copy4", Some("h")), ("copy6", Some("h"))];
let (mut s, files) = session(&photos, files);
let r = s.execute("library.findSimilar", &json!({"id": 1, "similarity": -1.0})).unwrap();
assert_eq!(files.reads_of("/p/copy2.jpg"), 1);
assert_eq!(files.reads_of("/p/copy4.jpg"), 1, "the next copy stands in");
assert_eq!(files.reads_of("/p/copy6.jpg"), 0, "its content is known by then");
assert_eq!(ids(&r).len(), 4, "every copy is compared: {r}");
}
#[test]
fn a_searched_photo_that_cannot_be_read_ends_the_search_before_any_other_is_read() {
let files = Files::default();
files.unreadable.lock().unwrap().push("/p/me1.jpg".into());
let (mut s, files) = session(&[("me1", None), ("b2", None), ("c1", None)], files);
let e = s.execute("library.findSimilar", &json!({"id": 1})).unwrap_err();
assert!(e.to_string().contains("can't read the photo"), "{e}");
assert_eq!(files.reads(), 1, "only the searched photo");
assert!(s.signatures.is_empty());
assert_eq!(s.filter, Default::default(), "the view stays as it was");
}
#[test]
fn a_photo_nobody_has_is_refused_at_once() {
let (mut s, files) = session(&[("a1", None)], Files::default());
assert!(matches!(plan(&mut s, &json!({"id": 99})), Err(crate::EngineError::BadParams { .. })));
assert_eq!(files.reads(), 0);
}
#[test]
fn a_photo_whose_decoder_panics_is_left_out_and_the_search_goes_on() {
let files = Files::default();
*files.panics.lock().unwrap() = Some("/p/bad3.jpg".into());
let (mut s, _) = session(&[("me1", None), ("bad3", None), ("ok1", None), ("ok5", None)], files);
let r = s.execute("library.findSimilar", &json!({"id": 1, "similarity": -1.0})).unwrap();
assert_eq!(ids(&r).len(), 3, "{r}");
assert!(!ids(&r).contains(&2), "{r}");
}
/// Stopped after some reads: what was read is kept, the view is left alone, and the next search
/// reads only the rest.
#[test]
fn a_stopped_search_keeps_what_it_read_and_the_next_reads_the_rest() {
let cancel = Arc::new(AtomicBool::new(false));
let files = Files { cancel_after: Some((5, cancel.clone())), ..Default::default() };
let names: Vec<String> = (0..64).map(|i| format!("p{i}")).collect();
let photos: Vec<(&str, Option<&str>)> = names.iter().map(|n| (n.as_str(), None)).collect();
let (mut s, _) = session(&photos, files);
let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap();
let found = measure(reads, &cancel, &|_| {});
let read = found.len();
assert!((1..64).contains(&read), "stopped along the way: {read}");
keep(&mut s, found);
assert_eq!(s.filter, Default::default());
let (_, rest) = plan(&mut s, &json!({"id": 1})).unwrap();
assert_eq!(rest.len(), 64 - read);
}
#[test]
fn a_stopped_search_reads_nothing_more() {
let (mut s, files) = session(&[("a1", None), ("b2", None), ("c1", None)], Files::default());
let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap();
assert!(measure(reads, &AtomicBool::new(true), &|_| {}).is_empty());
assert_eq!(files.reads(), 0);
}
/// What changed while the files were read: a photo deleted since isn't an answer, and one added
/// since has no signature to compare.
#[test]
fn photos_that_changed_during_the_search_are_answered_as_they_are_now() {
let (mut s, _) = session(&[("a1", None), ("b1", None), ("c1", None)], Files::default());
let (search, reads) = plan(&mut s, &json!({"id": 1, "similarity": -1.0})).unwrap();
let found = measure(reads, &AtomicBool::new(false), &|_| {});
s.catalog.apply(Op::RemovePhoto { id: PhotoId(2) }).unwrap();
let added = Photo::new(PhotoId(9), Source::File { path: "/p/new1.jpg".into() }, "new1.jpg", "JPEG", 64, 64, "2026-01-01T00:00:00");
s.catalog.apply(Op::AddPhoto { photo: Box::new(added) }).unwrap();
keep(&mut s, found);
let mut answer = ids(&apply(&mut s, &search).unwrap());
answer.sort_unstable();
assert_eq!(answer, [1, 3]);
}
#[test]
fn progress_counts_every_content_read_or_not() {
let files = Files::default();
files.unreadable.lock().unwrap().push("/p/b2.jpg".into());
let (mut s, _) = session(&[("a1", None), ("b2", None), ("c1", None), ("d2", None)], files);
let (_, reads) = plan(&mut s, &json!({"id": 1})).unwrap();
let top = AtomicUsize::new(0);
let found = measure(reads, &AtomicBool::new(false), &|done| {
top.fetch_max(done, Ordering::SeqCst);
});
assert_eq!(top.load(Ordering::SeqCst), 4);
assert_eq!(found.len(), 3);
}
}
+2 -1
View File
@@ -1,4 +1,5 @@
use super::options::{Conflict, DestinationMode, ExportFormat, HdrCurve, MetadataPolicy, Resize, ResizeMode, SharpenAmount, SharpenFor};
use super::place::clean_subfolder;
use super::prepare::DngCompression;
use super::watermark::{Anchor, Watermark};
use super::{ExportOptions, JxlColour, JxlEffort, JxlOptions, OutputDepth, OutputSpace, TiffCompression};
@@ -429,7 +430,7 @@ impl ExportOptions {
naming: s("naming").map_or(d.naming, str::to_string),
start_number: u("startNumber").map_or(d.start_number, |v| v.min(999_999) as u32),
destination_mode: s("destinationMode").and_then(DestinationMode::parse).unwrap_or(d.destination_mode),
subfolder: s("subfolder").map_or(d.subfolder, |v| v.trim().replace(['\\', ':', '\0'], "_")),
subfolder: s("subfolder").map_or(d.subfolder, clean_subfolder),
conflict: s("conflict").and_then(Conflict::parse).unwrap_or(d.conflict),
tiff_compression: match s("tiffCompression").map(str::to_ascii_lowercase).as_deref() {
Some("none") => TiffCompression::None,
+10 -1
View File
@@ -60,6 +60,14 @@ fn join_path(a: &str, b: &str) -> String {
if a.is_empty() { b.to_string() } else { format!("{}/{b}", a.trim_end_matches('/')) }
}
/// A subfolder that stays inside the destination folder (issue #2571): `\`, `:` and NUL become `_`
/// (so no drive, root or Windows separator), and empty, `.` and `..` parts are dropped; `a/b` still
/// nests. Applied where the folder is used, so presets and the Export dialog's field are covered too.
pub(super) fn clean_subfolder(s: &str) -> String {
let s = s.trim().replace(['\\', ':', '\0'], "_");
s.split('/').map(str::trim).filter(|p| !p.is_empty() && *p != "." && *p != "..").collect::<Vec<_>>().join("/")
}
impl<'a> Placer<'a> {
pub(super) fn new(
o: &'a ExportOptions,
@@ -89,7 +97,8 @@ impl<'a> Placer<'a> {
d.to_string()
}
};
Ok(if self.o.subfolder.is_empty() { base } else { join_path(&base, &self.o.subfolder) })
let sub = clean_subfolder(&self.o.subfolder);
Ok(if sub.is_empty() { base } else { join_path(&base, &sub) })
}
/// Place photo `photo`'s export result (file `name`, its original in `source_dir`): write it
+2
View File
@@ -912,6 +912,8 @@ fn ramp(depth: OutputDepth, space: OutputSpace) -> lightcraft_pipeline::Rendered
fn distinct_levels(bytes: &[u8]) -> (usize, lightcraft_codecs::Decoded) {
let d = lightcraft_codecs::decode(bytes, Default::default()).expect("decodes");
let mut v: Vec<u32> = (0..d.image.width).map(|x| d.image.get(x, 1)[1].to_bits()).collect();
// sorted first: 8-bit output is dithered, so equal levels aren't all side by side
v.sort_unstable();
v.dedup();
(v.len(), d)
}
+3 -1
View File
@@ -11,6 +11,8 @@ use lightcraft_pipeline::SourceInfo;
use lightcraft_raster::Rgb32f;
use lightcraft_raster::resample::{Filter, fit};
use lightcraft_raw::dcp::DcpProfile;
use crate::media::{DenoiseSpec, FileLoader, FileProbe, PairLoader, PreviewLoader, ProbeInfo, ReducedLoader};
mod colour;
@@ -25,7 +27,7 @@ pub(crate) use colour::clipped_white;
use fs::quick_image_srgb;
pub use fs::{fs_hooks, fs_pair_loader, fs_reduced_loader};
pub(crate) use load::{DngWhite, WbScaleOf, dng_tone_curve};
pub use load::{load_bytes, load_vec, load_vec_pair, load_vec_reduced};
pub use load::{load_bytes, load_bytes_with, load_vec, load_vec_pair, load_vec_reduced};
#[cfg(test)]
use preview::PLAN_PREFIX;
pub(crate) use preview::decode_raw_preview;
+6 -5
View File
@@ -1,7 +1,7 @@
use super::load::{load_vec, load_vec_pair, load_vec_reduced};
use super::preview::{fit_box, fs_preview_loader, preview_orientation};
use super::probe::probe_bytes;
use super::{Arc, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit};
use super::{Arc, DcpProfile, DenoiseSpec, FileLoader, FileProbe, Filter, PairLoader, ReducedLoader, fit};
/// The file's first [`lightcraft_raw::PREVIEW_PREFIX`] bytes (or the whole file when it is shorter),
/// which is what every format [`lightcraft_raw::bounded_preview`] covers keeps its pointer in.
@@ -54,13 +54,13 @@ pub(super) fn quick_image_srgb(header: &[u8], window: &[u8], adobe_rgb: bool, ma
/// The filesystem-backed [`PairLoader`]: the file is read and decoded once, and developed as usual and from the photo's
/// denoised picture. It holds two pictures at once, so it counts for more at the memory gate than a plain load.
pub fn fs_pair_loader() -> PairLoader {
Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec| {
Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec, dcp: Option<&DcpProfile>| {
let len = std::fs::metadata(path).map(|m| m.len() as usize).unwrap_or(0);
let weight = len * if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 4 } else { 10 };
let gate = crate::memory::work_gate();
let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) };
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
let r = load_vec_pair(bytes, max_edge, spec);
let r = load_vec_pair(bytes, max_edge, spec, dcp);
crate::memory::release();
r
})
@@ -74,7 +74,8 @@ pub fn fs_pair_loader() -> PairLoader {
/// interactive loads (the loupe, exports) never wait — they are counted, so background work
/// yields to them.
pub fn fs_hooks() -> (FileLoader, FileProbe) {
let loader: FileLoader = Arc::new(|path: &str, max_edge: usize| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge)));
let loader: FileLoader =
Arc::new(|path: &str, max_edge: usize, dcp: Option<&DcpProfile>| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge, dcp)));
let probe: FileProbe = Arc::new(|path: &str| {
use std::io::Read;
// one open, then everything from the open file: its size and modification time are not
@@ -94,7 +95,7 @@ pub fn fs_hooks() -> (FileLoader, FileProbe) {
/// The filesystem [`ReducedLoader`]: [`load_vec_reduced`] of the file, gated like [`fs_hooks`]' loader.
pub fn fs_reduced_loader() -> ReducedLoader {
Arc::new(|path: &str, max_edge: usize| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge)))
Arc::new(|path: &str, max_edge: usize, dcp: Option<&DcpProfile>| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge, dcp)))
}
/// Read `path` and `load` it, waiting on [`crate::memory::work_gate`] as [`fs_hooks`] explains.
+172 -17
View File
@@ -1,7 +1,7 @@
use super::colour::bin_factor;
use super::preview::{fit_box, load_embedded_preview};
use super::probe::preview_reason;
use super::{Arc, CameraColourModel, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orientation, Rgb32f, SourceInfo, fit, xy_to_temp_tint};
use super::{Arc, CameraColourModel, DcpProfile, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orientation, Rgb32f, SourceInfo, fit, xy_to_temp_tint};
/// Decode a file into a linear Rec.2020 image no larger than `max_edge`, oriented.
///
@@ -9,27 +9,41 @@ use super::{Arc, CameraColourModel, DenoiseSpec, Filter, HIGHLIGHT_CLIP, Orienta
/// instead of each one waking the pool from outside and waiting for it (which costs more than the
/// loops themselves when the machine is busy).
pub fn load_bytes(bytes: &[u8], max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false).map(|(img, _, info, _)| (img, info)))
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, None).map(|(img, _, info, _)| (img, info)))
}
/// [`load_bytes`] developing a raw file with an imported camera profile (`dcp`) in place of its own colour model.
pub fn load_bytes_with(bytes: &[u8], max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false, dcp).map(|(img, _, info, _)| (img, info)))
}
/// [`load_bytes`] taking the file's bytes: a raw file's bytes are freed as soon as it is decoded
/// (less memory held while it is developed).
pub fn load_vec(bytes: Vec<u8>, max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false).map(|(img, _, info, _)| (img, info)))
pub fn load_vec(bytes: Vec<u8>, max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false, dcp).map(|(img, _, info, _)| (img, info)))
}
/// [`load_vec`] for a thumbnail: a DNG that keeps reduced-resolution copies of its raw image (Lightroom's HDR and
/// panorama merges) develops the smallest that covers `max_edge` instead of the whole image. The flag says whether
/// it did: such a picture is not the full image, and an export never renders from it.
pub fn load_vec_reduced(bytes: Vec<u8>, max_edge: usize) -> Result<(Rgb32f, SourceInfo, bool), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true).map(|(img, _, info, reduced)| (img, info, reduced)))
pub fn load_vec_reduced(bytes: Vec<u8>, max_edge: usize, dcp: Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo, bool), String> {
rayon::scope(move |_| {
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true, dcp).map(|(img, _, info, reduced)| (img, info, reduced))
})
}
/// [`load_vec`] that also develops the photo's cached denoised picture (`spec`) from the same decode: the plain
/// picture, the denoised one (`None` when it cannot be read or does not fit this raw: the plain one is then all
/// there is) and the source facts. Both pictures are the same size.
pub fn load_vec_pair(bytes: Vec<u8>, max_edge: usize, spec: &DenoiseSpec) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> {
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false).map(|(img, twin, info, _)| (img, twin, info)))
pub fn load_vec_pair(
bytes: Vec<u8>,
max_edge: usize,
spec: &DenoiseSpec,
dcp: Option<&DcpProfile>,
) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> {
rayon::scope(move |_| {
load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false, dcp).map(|(img, twin, info, _)| (img, twin, info))
})
}
/// The denoised camera RGB of `raw` from its cached product, as the plain development would have it: the default
@@ -59,6 +73,7 @@ fn load_bytes_now(
max_edge: usize,
denoise: Option<&DenoiseSpec>,
allow_reduced: bool,
dcp: Option<&DcpProfile>,
) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo, bool), String> {
if lightcraft_raw::probe(&bytes).is_some() {
// a thumbnail (`allow_reduced`, never an export) of a DNG that keeps smaller copies of its raw image
@@ -92,20 +107,46 @@ fn load_bytes_now(
let dng_lens_ops = (raw.format == lightcraft_raw::RawFormat::Dng && raw.opcodes.list3.iter().any(|op| op.is_lens_correction()))
.then(|| raw.opcodes.list3.clone());
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
// A camera profile without a tone curve of its own (most chart-made ones: a matrix, maybe a hue/saturation map)
// keeps the contrast the photo has without it: the file's own DNG tone curve, else the tone of the look fitted
// to its camera JPEG. (A chart pins colour, not a rendering: its curve would be a choice, and this one is the
// camera's.)
let kept_tone = match dcp {
Some(p) if p.color.profile.tone_curve.is_none() => raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve).or_else(|| {
let own = raw.color.clone();
// the same proxy as the starting colour's fit below: the DNG's lens opcodes back in, no embedded lens
let tone = with_dng_lens_ops(&mut raw, dng_lens_ops.as_ref(), lens.as_ref(), list3, |raw, embedded| {
crate::camera_preview::starting_colour(raw, &bytes, lens_geometry.as_ref(), embedded)
})
.2
.map(|look| look.tone);
raw.color = own;
tone
}),
_ => None,
};
// An imported camera profile replaces the file's colour model (its matrices and look; the shot's white stays), so
// the starting colour and the white balance scale below come from it, not from a fitted or built-in look.
// (the white balance stays on the scale the file and its camera give, the one the catalog's
// `Photo::relative_wb` and the quick previews use: a profile's matrices must not turn a relative white balance
// into Kelvin, which would read existing edits as absolute temperatures)
let own_scale = dcp.map(|_| WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata));
if let Some(p) = dcp {
raw.color = p.applied_to(&raw.color);
}
// Which scale white balance is edited on, and the as-shot white on it, from the file's own colour tags or
// the camera's measured matrices (`Photo::relative_wb` decides the same from the catalog's camera)
let scale = WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata);
let scale = match &own_scale {
Some(own) => scale.keeping_classification_of(own),
None => scale,
};
// the source's segmentation mattes (DNG semantic masks), read while the starting colour is fitted
let ((xy, t, camera_look), mattes) = rayon::join(
|| {
let removed = dng_lens_ops.map(|ops| std::mem::replace(&mut raw.opcodes.list3, ops));
// With the opcodes restored, the proxy already includes vignetting; do not apply it twice.
let embedded = if removed.is_some() { None } else { lens.as_ref() };
let colour = crate::camera_preview::starting_colour(&mut raw, &bytes, lens_geometry.as_ref(), embedded);
if let Some(ops) = removed {
raw.opcodes.list3 = ops;
}
colour
with_dng_lens_ops(&mut raw, dng_lens_ops.as_ref(), lens.as_ref(), list3, |raw, embedded| {
crate::camera_preview::starting_colour(raw, &bytes, lens_geometry.as_ref(), embedded)
})
},
|| dng_mattes(&bytes, &info),
);
@@ -183,7 +224,12 @@ fn load_bytes_now(
let tags = lightcraft_raw::ColorData { profile: Default::default(), ..raw.color.clone() };
Arc::new(lightcraft_pipeline::CameraColor { tags, developed_for: xy })
});
let camera_tone = camera_look.as_ref().map(|p| p.tone).or_else(|| raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve));
let camera_tone = camera_tone_of(
dcp.is_some(),
camera_look.as_ref().map(|p| p.tone),
raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve),
kept_tone,
);
let local_tone = local_tone(&raw);
let (temp, tint) = scale.as_shot(xy);
return Ok((
@@ -262,6 +308,13 @@ impl WbScaleOf {
WbScaleOf { own_matrix, relative: fitted && !covered, legacy_relative: fitted && covered, scale_white, camera }
}
/// This scale (a raw's, with an imported camera profile's colour model) on the white-balance scale `own` (the
/// same raw's with its own colour) gives: relative, or Kelvin edited on the relative scale before. The matrices,
/// and so the colour and the as-shot reading, stay this scale's.
pub(super) fn keeping_classification_of(self, own: &WbScaleOf) -> Self {
WbScaleOf { relative: own.relative, legacy_relative: own.legacy_relative, ..self }
}
/// What a DNG of this raw's camera RGB declares so that it shows the white balance as this scale does: the
/// camera's measured matrices when they give the scale, else the white the scale shows at As Shot (the presets'
/// reading; 6500 K / 0 on the relative scale; else `own`, the white the file's tags give).
@@ -348,3 +401,105 @@ pub(crate) fn dng_tone_curve(curve: &lightcraft_raw::profile::ToneCurve) -> Opti
});
lightcraft_pipeline::tone::CameraTone::new(knots)
}
/// A raw's `OpcodeList3`.
fn list3(raw: &mut lightcraft_raw::RawImage) -> &mut Vec<lightcraft_raw::Opcode> {
&mut raw.opcodes.list3
}
/// `fit(raw, embedded)` with a DNG's lens opcodes `ops` back in `raw`'s `OpcodeList3` (`list3`), as its preview has
/// them applied, and the list as it was afterwards. With the opcodes restored the proxy already includes the
/// vignetting, so `embedded` is `None` then (else `lens`): every tone fit of one photo sees the same proxy.
fn with_dng_lens_ops<R, L, T>(
raw: &mut R,
ops: Option<&Vec<lightcraft_raw::Opcode>>,
lens: Option<&L>,
list3: fn(&mut R) -> &mut Vec<lightcraft_raw::Opcode>,
fit: impl FnOnce(&mut R, Option<&L>) -> T,
) -> T {
let removed = ops.map(|ops| std::mem::replace(list3(raw), ops.clone()));
let embedded = if removed.is_some() { None } else { lens };
let out = fit(raw, embedded);
if let Some(ops) = removed {
*list3(raw) = ops;
}
out
}
/// The tone a raw's starting look gets from its camera: `look` (the tone of the look fitted to the camera JPEG),
/// `curve` (the colour model's own tone curve: the file's, or with an imported camera profile, the profile's) and
/// `kept` (the photo's own tone, kept for a profile without a curve). With a camera profile (`profile`), its curve
/// comes first, then the kept tone, and the fitted look's only last: the look was fitted without the profile, so it
/// must not replace the profile's curve or the contrast kept for it. Without one, the fitted look leads as before.
fn camera_tone_of<T>(profile: bool, look: Option<T>, curve: Option<T>, kept: Option<T>) -> Option<T> {
if profile { curve.or(kept).or(look) } else { look.or(curve).or(kept) }
}
#[cfg(test)]
mod camera_tone_tests {
use super::camera_tone_of;
/// CodeRabbit on #1063: with an imported camera profile, a fitted camera look's tone replaced the profile's own
/// tone curve and the tone kept for a profile without one. Without a profile the order is unchanged.
#[test]
fn a_camera_profiles_curve_and_kept_tone_come_before_the_fitted_look() {
assert_eq!(camera_tone_of(true, Some("look"), Some("profile"), Some("kept")), Some("profile"));
assert_eq!(camera_tone_of(true, Some("look"), None, Some("kept")), Some("kept"));
assert_eq!(camera_tone_of(true, Some("look"), None, None), Some("look"));
assert_eq!(camera_tone_of(false, Some("look"), Some("file"), Some("kept")), Some("look"));
assert_eq!(camera_tone_of(false, None, Some("file"), Some("kept")), Some("file"));
assert_eq!(camera_tone_of::<&str>(false, None, None, None), None);
}
}
#[cfg(test)]
mod wb_scale_tests {
use super::WbScaleOf;
/// CodeRabbit on #1063: a raw edited on the relative white-balance scale (no colour matrices, none measured for
/// its camera) turned to Kelvin once an imported camera profile's matrices replaced its colour, so its existing
/// edits (6500 K / 0 = as shot) were read as absolute temperatures, and the catalog and quick previews still
/// used the relative scale. The profile's matrices stay; the scale is the file's.
#[test]
fn a_camera_profile_keeps_a_relative_white_balance_relative() {
let format = lightcraft_raw::RawFormat::Cr3;
let meta = lightcraft_meta::Metadata::default();
let own_color = lightcraft_raw::ColorData::default();
let own = WbScaleOf::new(format, &own_color, Some([2.0, 1.0, 1.5]), &meta);
assert!(own.relative && !own.own_matrix, "a matrix-less raw of an unmeasured camera is relative");
let m = lightcraft_color::Mat3([[0.9, 0.1, 0.0], [0.1, 0.8, 0.1], [0.0, 0.2, 0.8]]);
let profiled = lightcraft_raw::ColorData { illuminant: [21, 0], color_matrix: [Some(m), None], ..Default::default() };
let with = WbScaleOf::new(format, &profiled, Some([2.0, 1.0, 1.5]), &meta);
assert!(!with.relative, "the profile's matrices alone would make it Kelvin");
let kept = with.keeping_classification_of(&own);
assert!(kept.relative && !kept.legacy_relative && kept.own_matrix, "relative, with the profile's matrices");
assert_eq!(kept.as_shot(lightcraft_color::Xy { x: 0.3127, y: 0.329 }), (6500.0, 0.0));
}
}
#[cfg(test)]
mod lens_ops_tests {
use lightcraft_raw::Opcode;
use super::with_dng_lens_ops;
fn same(v: &mut Vec<Opcode>) -> &mut Vec<Opcode> {
v
}
/// Both tone fits of a DNG (the kept tone for a camera profile without a curve, and the starting colour) see its
/// lens opcodes restored and no embedded lens; the list is as it was afterwards (CodeRabbit on #1063: the
/// kept-tone fit ran without the opcodes and with the embedded lens).
#[test]
fn a_dngs_tone_fit_sees_its_lens_opcodes_and_no_embedded_lens() {
let vignette = Opcode::FixVignetteRadial { k: [0.1, 0.0, 0.0, 0.0, 0.0], center: [0.5, 0.5] };
let ops = vec![vignette.clone()];
let mut list: Vec<Opcode> = Vec::new();
let lens = 7;
let seen = with_dng_lens_ops(&mut list, Some(&ops), Some(&lens), same, |l, embedded| (l.clone(), embedded.copied()));
assert_eq!(seen, (vec![vignette], None), "the opcodes are in, the embedded lens is not");
assert!(list.is_empty(), "the list is as it was");
let seen = with_dng_lens_ops(&mut list, None, Some(&lens), same, |l, embedded| (l.len(), embedded.copied()));
assert_eq!(seen, (0, Some(7)), "without DNG lens opcodes the embedded lens is used");
}
}
+4 -4
View File
@@ -591,7 +591,7 @@ fn cached_denoise_uses_the_same_white_balance_profile_and_orientation_as_plain_r
product::write(&path, &camera_rgb, key).unwrap();
let spec = DenoiseSpec { product: path, key: key.into(), make: None };
let (ordinary, _) = load_bytes(&bytes, 2048).unwrap();
let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec).unwrap();
let (plain, cached, _) = load_vec_pair(bytes, 2048, &spec, None).unwrap();
assert_eq!(plain.data, ordinary.data, "requesting a twin must not change the ordinary path");
let cached = cached.unwrap();
assert_eq!((plain.width, plain.height), (24, 32));
@@ -1255,10 +1255,10 @@ fn exports_never_develop_a_dngs_reduced_copy() {
let mean = |img: &lightcraft_raster::Rgba8| img.data.iter().map(|p| p[1] as f64).sum::<f64>() / img.data.len().max(1) as f64;
// the loaders: only the thumbnail's develops the copy, and only when it covers the size
let (copy, _, used) = load_vec_reduced(bytes.clone(), 512).unwrap();
let (copy, _, used) = load_vec_reduced(bytes.clone(), 512, None).unwrap();
assert!(used, "a thumbnail develops the copy");
assert!(!load_vec_reduced(bytes.clone(), 1024).unwrap().2, "no copy covers 1024 px");
let (full, _) = load_vec(bytes.clone(), 512).unwrap();
assert!(!load_vec_reduced(bytes.clone(), 1024, None).unwrap().2, "no copy covers 1024 px");
let (full, _) = load_vec(bytes.clone(), 512, None).unwrap();
assert!(g(&copy) > 4.0 * g(&full), "the fixture's copy is much brighter: {} vs {}", g(&copy), g(&full));
let dir = std::env::temp_dir().join(format!("lc-reduced-export-{}", std::process::id()));
+1
View File
@@ -512,6 +512,7 @@ impl Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut: None,
display_fit: None,
+1 -1
View File
@@ -14,7 +14,7 @@ fn fixture(preview_edge: Option<usize>, renderable: bool, preview_only: bool) ->
let mut session = Session::new();
let reads = Arc::new(AtomicUsize::new(0));
let count = reads.clone();
session.media.file_loader = Some(Arc::new(move |_, edge| {
session.media.file_loader = Some(Arc::new(move |_, edge, _| {
count.fetch_add(1, Ordering::SeqCst);
if !renderable {
return Err("synthetic raw cannot be rendered".into());
+32 -10
View File
@@ -80,6 +80,7 @@ pub mod slideshow;
pub mod slideshow_export;
pub mod smart;
pub mod sync;
mod sync_same;
pub mod text;
mod view;
pub mod walk;
@@ -359,6 +360,8 @@ pub struct Session {
/// The user's point-curve presets (`curve.*`; built-ins: [`cmd::curves::builtin_presets`]),
/// persisted in prefs.json.
pub curve_presets: Vec<cmd::curves::CurvePreset>,
/// Imported camera profiles (`.dcp`).
pub dcp_profiles: Vec<cmd::dcp_profiles::DcpEntry>,
/// Mask effect presets (the Masking panel's Effect menu).
pub mask_effects: Vec<cmd::mask_effects::MaskEffect>,
/// The effect a new mask of each kind (`brush`, `linear`…) starts with: the one last applied
@@ -518,6 +521,7 @@ impl Session {
metadata_presets: Vec::new(),
filter_presets: Vec::new(),
curve_presets: Vec::new(),
dcp_profiles: Vec::new(),
mask_effects: Vec::new(),
mask_tool_effects: Default::default(),
label_sets: Vec::new(),
@@ -614,7 +618,8 @@ impl Session {
}
}
if self.depth == 0 && self.library.is_some() {
// Make the command durable before reporting success. When the command's own records
// Make the command durable before reporting success (natively: handed to the catalog
// log's own thread, which syncs it right after and holds it until it can). When the command's own records
// can't be appended, it fails with `NotSaved`: the change stays applied in memory and
// queued, and the next save (any later command, or the frame loop) retries it. Other
// persistence trouble (a failed compaction, an older queued change still unwritten by
@@ -946,8 +951,9 @@ impl Session {
i.crop_edited |= crop_edited;
return self.apply_silent(Op::SetDevelop { id, settings, label: label.into(), edited: Some(now) });
}
let own_auto = self.own_auto_wb(id, &requested, label);
let mut ops = vec![self.develop_op(id, (*settings).clone(), label).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?];
ops.extend(self.auto_sync_ops(id, &requested, label));
ops.extend(self.auto_sync_ops(id, &requested, label, &own_auto));
let op = if ops.len() == 1 { ops.remove(0) } else { Op::Batch { ops } };
self.commit(label, op)
}
@@ -988,13 +994,12 @@ impl Session {
/// never spot removal or red eye (they belong to one photo's pixels), nor the rendering process
/// (Sync doesn't carry it either), nor history / snapshot restores. Constrain Crop then fits each
/// photo's own crop: the active photo's fitted crop is never copied over another's.
fn auto_sync_ops(&self, id: PhotoId, new: &DevelopSettings, label: &str) -> Vec<Op> {
if !self.auto_sync
|| self.active() != Some(id)
|| self.selection.ids.len() < 2
|| label.starts_with("History:")
|| label.starts_with("Restore ")
{
///
/// White balance goes on each photo as the active photo's mode or value on the photo's own
/// scale ([`sync_same`]): As Shot its own camera white, Auto its own (`own_auto`, worked out on
/// its pixels), a Temp or Tint the same number, only the slider that moved.
fn auto_sync_ops(&self, id: PhotoId, new: &DevelopSettings, label: &str, own_auto: &std::collections::HashMap<PhotoId, (f64, f64)>) -> Vec<Op> {
if !self.auto_sync_applies(id, label) {
return Vec::new();
}
let Some(old) = self.develop_of(id) else { return Vec::new() };
@@ -1016,18 +1021,35 @@ impl Session {
return Vec::new();
}
}
let ainfo = self.source_info(id);
let wb_changed = old.wb != new.wb;
self.selection
.ids
.iter()
.filter(|x| **x != id)
.filter_map(|x| self.develop_of(*x).map(|d| (*x, d)))
.filter_map(|(x, d)| {
let synced = self.fit_constrained_crop(x, lightcraft_develop::apply_partial(&d, &delta, 1.0));
let mut synced = lightcraft_develop::apply_partial(&d, &delta, 1.0);
if wb_changed {
sync_same::synced_wb(&ainfo, &old, new, &self.source_info(x), &d, own_auto.get(&x).copied(), &mut synced);
}
let synced = self.fit_constrained_crop(x, synced);
(synced != *d).then(|| self.develop_op(x, synced, label)).flatten()
})
.collect()
}
/// Auto Sync carries an edit of photo `id` labelled `label` to the other selected photos: it is
/// on, `id` is the active photo of a selection of two or more, and the edit is not a History or
/// snapshot restore.
fn auto_sync_applies(&self, id: PhotoId, label: &str) -> bool {
self.auto_sync
&& self.active() == Some(id)
&& self.selection.ids.len() >= 2
&& !label.starts_with("History:")
&& !label.starts_with("Restore ")
}
/// The op that sets a photo's develop settings and appends a History entry (for batches).
pub fn develop_op(&self, id: PhotoId, settings: DevelopSettings, label: &str) -> Option<Op> {
self.catalog.photo(id)?;
+74 -13
View File
@@ -13,8 +13,12 @@
//! The files live in [`Store`]s: a directory ([`FsStore`]) natively, or any other implementation
//! via [`Session::open_library_in`] (the browser build keeps them in OPFS or IndexedDB).
//!
//! Every top-level [`Session::execute`] persists the ops it produced (fsynced) before returning,
//! so a crash loses at most the command in flight. When that write fails the command returns
//! Every top-level [`Session::execute`] persists the ops it produced before returning: fsynced
//! there, or natively handed to the catalog log's own thread, which writes and syncs them right
//! after (the UI thread never waits for the drive), so a crash or power cut loses at most the
//! batch in flight (what arrived during one sync). A write that thread
//! can't make is held and retried, counts as unsaved ([`Session::unsaved`]) and makes a snapshot
//! due. When that write fails the command returns
//! [`EngineError::NotSaved`]: its change stays applied in memory and queued, and every later save
//! retries the queue ([`Session::unsaved`] reports it meanwhile), so nothing is lost once the
//! disk is writable again. The log is compacted into a snapshot when it
@@ -134,6 +138,10 @@ pub struct Library {
/// Why the last write of presets.json failed; `None` once it is written. While set, the preset
/// changes exist only in memory and count as unsaved ([`Session::unsaved`], issue #2266).
presets_error: Option<String>,
/// Records the catalog log's own thread holds because writing them failed (it retries them),
/// and why; refreshed by every persist and every frame ([`Session::persist_if_dirty`]). While
/// set they count as unsaved ([`Session::unsaved`]), so quitting asks first.
log_held: Option<(usize, String)>,
/// When the frame loop may retry a failed append ([`Session::persist_if_dirty`] backs off).
retry_at: Option<web_time::Instant>,
/// What forgetting untouched Local records did when the library opened.
@@ -277,6 +285,8 @@ struct PrefsFile {
label_sets: Vec<crate::cmd::manage::LabelSet>,
/// Imported LUT profiles.
lut_profiles: Vec<crate::cmd::lut_profiles::LutProfile>,
/// Imported camera profiles (`.dcp`).
dcp_profiles: Vec<crate::cmd::dcp_profiles::DcpEntry>,
/// Keyword sets, the one in use, recent keywords.
keyword_sets: Vec<crate::cmd::keywords::KeywordSet>,
keyword_set: Option<String>,
@@ -322,6 +332,8 @@ fn poll_compaction(lib: &mut Library) {
log::error!("library: compaction: {e}");
lib.last_error = Some(format!("compaction: {e}"));
}
// (never waits: the log's thread publishes what it holds)
lib.log_held = lib.journal.unwritten();
}
/// How long the frame loop waits before retrying a failed append (commands retry at once).
@@ -501,13 +513,24 @@ impl Session {
/// Open `stores`; the new library takes `lock` once nothing can fail any more.
fn open_stores(&mut self, stores: LibraryStores, seed_demo: bool, lock: &mut Option<LibraryLock>) -> Result<()> {
let LibraryStores { dir, catalog, mut files, on_disk } = stores;
self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir));
// the current library may be these same files: let its background snapshot land first
if let Some(old) = self.library.as_mut()
&& let Err(e) = old.journal.wait()
{
log::error!("library: {e}");
// the current library may be these same files: let its background snapshot land first, and
// what its log's thread was handed reach the file before the new journal reads it. When
// that can't be written, the open fails and the current library stays open with what its
// thread holds (retried): read now, the files would miss it (review of #3557).
if let Some(old) = self.library.as_mut() {
if let Err(e) = old.journal.wait() {
log::error!("library: {e}");
}
if let Err(e) = old.journal.flush() {
old.log_held = old.journal.unwritten();
// a snapshot that holds every op leaves nothing for the files to miss
if old.journal.snapshot_seq() < old.journal.seq() {
return Err(EngineError::NotSaved(format!("the open library's changes aren't on disk yet, so it stays open: {e}")));
}
log::error!("library: {e} (every change is in its snapshot)");
}
}
self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir));
// Photo ids belong to one library; denoise work must not carry into the next.
self.denoise.library_changed();
self.media.denoise.clear();
@@ -555,6 +578,8 @@ impl Session {
self.label_sets = prefs.label_sets;
self.lut_profiles = prefs.lut_profiles;
crate::cmd::lut_profiles::register_all(self);
self.dcp_profiles = prefs.dcp_profiles;
crate::cmd::dcp_profiles::register_all(self, on_disk.then(|| dir.join("Profiles")).as_deref());
self.keyword_sets = prefs.keyword_sets;
self.keyword_set = prefs.keyword_set;
self.recent_keywords = prefs.recent_keywords;
@@ -582,7 +607,11 @@ impl Session {
self.presets.push(u);
}
}
let known = |id: &String| crate::presets::profile(id).is_some() || self.lut_profiles.iter().any(|p| &p.id == id);
let known = |id: &String| {
crate::presets::profile(id).is_some()
|| self.lut_profiles.iter().any(|p| &p.id == id)
|| self.dcp_profiles.iter().any(|p| &p.id == id)
};
self.profile_favorites = f.profile_favorites.into_iter().filter(known).collect();
self.profile_recent = f.profile_recent.into_iter().filter(known).take(crate::presets::RECENT_PROFILES).collect();
}
@@ -631,6 +660,7 @@ impl Session {
last_error: None,
unsaved_error: None,
presets_error: None,
log_held: None,
retry_at: None,
forgot_local: None,
presets_saved,
@@ -661,7 +691,7 @@ impl Session {
Ok(())
}
/// Write pending ops to the log (fsynced), compact when due, and save changed presets.
/// Write pending ops to the log (fsynced, or handed to the log's own thread natively), compact when due, and save changed presets.
/// Called after every top-level command; cheap when nothing changed. Fails (with
/// [`EngineError::NotSaved`]) only when the queued ops couldn't be written; they stay queued.
pub fn persist(&mut self) -> Result<()> {
@@ -726,13 +756,40 @@ impl Session {
pub fn persist_if_dirty(&mut self) {
let backing_off = self.library.as_ref().and_then(|l| l.retry_at).is_some_and(|t| web_time::Instant::now() < t);
let presets_unsaved = self.library.as_ref().is_some_and(|l| l.presets_error.is_some());
if self.library.is_some() && (!self.pending_log.is_empty() || presets_unsaved) && !backing_off {
// records the log's thread can't write: a snapshot (a fresh file holding everything) is due
let log_held = self.library.as_ref().is_some_and(|l| l.log_held.is_some());
if self.library.is_some() && (!self.pending_log.is_empty() || presets_unsaved || log_held) && !backing_off {
let _ = self.persist();
} else if let Some(lib) = self.library.as_mut() {
poll_compaction(lib);
}
}
/// Read again what the catalog log's own thread holds because writing it failed (never waits):
/// before a check of [`Session::unsaved`] that must be current, such as the quit prompt's.
pub fn refresh_unsaved(&mut self) {
if let Some(lib) = self.library.as_mut() {
lib.log_held = lib.journal.unwritten();
}
}
/// Every change applied is in the library's last snapshot (a closing snapshot landed), whatever
/// the catalog log's thread still holds or failed to reset. `false` without a library.
pub fn snapshot_holds_everything(&self) -> bool {
self.pending_log.is_empty() && self.library.as_ref().is_some_and(|l| l.journal.snapshot_seq() >= l.journal.seq())
}
/// Wait until what the catalog log's thread was handed is on disk, then read again what it
/// holds ([`Session::refresh_unsaved`]). Before the quit check: a change the thread accepted
/// but hasn't written yet is in no count of [`Session::unsaved`]. An error (a write failed, or
/// the drive took over a minute) means some changes may not be on disk yet.
pub fn flush_log(&mut self) -> Result<()> {
let Some(lib) = self.library.as_mut() else { return Ok(()) };
let flushed = lib.journal.flush();
lib.log_held = lib.journal.unwritten();
Ok(flushed?)
}
/// Changes applied in memory but not yet written to disk because saving failed: the number of
/// queued ops (plus one for presets.json) and why (`None` when everything is saved, or no library
/// is open). Retried by every command and by [`Session::persist_if_dirty`].
@@ -740,8 +797,9 @@ impl Session {
let lib = self.library.as_ref()?;
let ops = lib.unsaved_error.as_deref().filter(|_| !self.pending_log.is_empty());
let presets = lib.presets_error.as_deref();
let n = ops.map_or(0, |_| self.pending_log.len()) + usize::from(presets.is_some());
ops.or(presets).map(|why| (n, why))
let held = lib.log_held.as_ref().map(|(n, why)| (*n, why.as_str()));
let n = ops.map_or(0, |_| self.pending_log.len()) + held.map_or(0, |(n, _)| n) + usize::from(presets.is_some());
ops.or(held.map(|(_, why)| why)).or(presets).map(|why| (n, why))
}
/// Flush everything and write a snapshot (on quit). Ends an open interaction first.
@@ -760,6 +818,8 @@ impl Session {
let Some(lib) = self.library.as_mut() else { return Ok(()) };
let before = lib.journal.seq();
let snapshot = lib.journal.snapshot_with_unlogged(&self.catalog, unlogged);
// (a snapshot that landed holds what the log's thread held)
lib.log_held = lib.journal.unwritten();
if unlogged > 0 && lib.journal.seq() == before + unlogged {
// the snapshot holds the queued ops: they are saved, never append them again
log::info!("library: {unlogged} queued change(s) saved in the closing snapshot");
@@ -834,6 +894,7 @@ impl Session {
mask_tool_effects: self.mask_tool_effects.clone(),
label_sets: self.label_sets.clone(),
lut_profiles: self.lut_profiles.clone(),
dcp_profiles: self.dcp_profiles.clone(),
keyword_sets: self.keyword_sets.clone(),
keyword_set: self.keyword_set.clone(),
recent_keywords: self.recent_keywords.clone(),
+22 -1
View File
@@ -24,6 +24,7 @@ use lightcraft_develop::DevelopSettings;
use lightcraft_pipeline::{Quality, RenderRequest, Rendered, SourceInfo, StageCache};
use lightcraft_preview::{Hash128, Hasher128, Lru, PreviewCache};
use lightcraft_raster::{Histogram, Rgb32f, Rgba8};
pub use lightcraft_raw::dcp::DcpProfile;
use serde::{Deserialize, Serialize};
mod cache;
@@ -35,7 +36,7 @@ mod source;
pub use cache::DenoiseIndex;
pub use quick::{QuickJob, QuickSource, content_key, source_info};
pub use render::{RenderJob, RenderResult, develop, develop_reporting, fit_for_display};
pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_for_display};
#[cfg(test)]
use settings_hash::SETTINGS_HASH_ENTRIES;
use settings_hash::SettingsHashes;
@@ -79,6 +80,26 @@ pub struct MediaCache {
pub rendered: Arc<PreviewCache>,
/// Which photos have a cached denoised picture, and how to read it.
pub denoise: DenoiseIndex,
/// Imported camera profiles by id ([`crate::cmd::dcp_profiles`]), handed to the decoder of photos using them.
pub camera_profiles: std::collections::HashMap<String, LoadedCameraProfile>,
}
/// An imported camera profile ready for the decoder, with a fingerprint of its file: decoded sources and cached renders
/// made with it carry the fingerprint, so a profile deleted, or replaced by another under the same id, never has
/// its old pictures stand in.
#[derive(Clone, Debug)]
pub struct LoadedCameraProfile {
pub profile: Arc<DcpProfile>,
/// Never 0 (0 is "no camera profile" in a render key).
pub fingerprint: u64,
}
impl LoadedCameraProfile {
/// Parse a `.dcp` file's bytes.
pub fn parse(bytes: &[u8]) -> Result<Self, lightcraft_raw::dcp::DcpError> {
let profile = lightcraft_raw::dcp::parse_dcp(bytes)?;
Ok(LoadedCameraProfile { profile: Arc::new(profile), fingerprint: Hasher128::new().update(bytes).finish().0 as u64 | 1 })
}
}
#[cfg(test)]
+86 -14
View File
@@ -1,6 +1,6 @@
use super::settings_hash::SettingsHashes;
use super::source::{DecodedSource, DenoiseSpec, PairLoader, RENDERED_MEM_BYTES, SourceLevel, SourceRef, THUMB_SOURCE_BYTES};
use super::{Arc, DevelopSettings, Hasher128, Lru, MediaCache, Photo, PhotoId, PreviewCache, Rgb32f, Source, SourceInfo};
use super::{Arc, DcpProfile, DevelopSettings, HashMap, Hasher128, Lru, MediaCache, Photo, PhotoId, PreviewCache, Rgb32f, Source, SourceInfo};
/// The photos that have a cached denoised picture for the denoise model in use. Only memory: nothing here touches the
/// file system, so it can be asked on the UI thread.
@@ -70,6 +70,7 @@ impl Default for MediaCache {
scenes: Vec::new(),
rendered: Arc::new(PreviewCache::memory(rendered_budget(budget))),
denoise: DenoiseIndex::default(),
camera_profiles: HashMap::new(),
}
}
}
@@ -202,14 +203,16 @@ impl MediaCache {
}
/// The facts of photo `id`'s cached sources: the decoder's when one has them, else `header`
/// (with a smart preview's stored camera tone curve).
pub(super) fn source_facts(&self, id: PhotoId, header: SourceInfo) -> SourceInfo {
/// (with a smart preview's stored camera tone curve). Only sources developed with `profile` (the photo's imported
/// camera profile tag, [`Self::camera_profile_of`], or none) count: one made with another profile has its facts.
pub(super) fn source_facts(&self, id: PhotoId, header: SourceInfo, profile: Option<&str>) -> SourceInfo {
let cached = || {
self.thumbs
.peek(&id)
.into_iter()
.chain(self.previews.iter().filter(|e| e.0 == id).map(|e| &e.1))
.chain(self.full.iter().filter(|e| e.0 == id).map(|e| &e.1))
.filter(|s| s.camera_profile.as_deref() == profile)
};
match cached().find(|s| s.info.is_some()).or_else(|| cached().next()) {
Some(s) => s.info_or(header),
@@ -221,7 +224,13 @@ impl MediaCache {
self.insert_source(id, level, DecodedSource::new(img, None));
}
pub(super) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) {
/// A decoded source with what the decoder reported about it (tests: photos of another as-shot white).
#[cfg(test)]
pub(crate) fn insert_with_info(&mut self, id: PhotoId, level: SourceLevel, img: Arc<Rgb32f>, info: lightcraft_pipeline::SourceInfo) {
self.insert_source(id, level, DecodedSource::new(img, Some(info)));
}
pub(crate) fn insert_source(&mut self, id: PhotoId, level: SourceLevel, img: DecodedSource) {
let tick = lightcraft_preview::next_tick();
match level {
SourceLevel::Thumb => {
@@ -296,24 +305,49 @@ impl MediaCache {
self.source_ref_with(p, level, false)
}
/// [`Self::source_ref`] without the photo's imported camera profile (keeping its denoised picture): a smart
/// preview keeps the file's own colour, and a cached source developed with the profile doesn't stand in for it.
#[cfg(not(target_arch = "wasm32"))]
pub fn source_ref_without_profile(&mut self, p: &Photo, level: SourceLevel) -> SourceRef {
self.source_ref_for(p, level, true, None)
}
fn source_ref_with(&mut self, p: &Photo, level: SourceLevel, cached: bool) -> SourceRef {
let mut r = self.source_ref_plain(p, level, cached);
let wanted = self.camera_profile_of(p);
self.source_ref_for(p, level, cached, wanted)
}
/// [`Self::source_ref_with`] developed with camera profile `wanted` (none: the file's own colour).
fn source_ref_for(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc<DcpProfile>)>) -> SourceRef {
let mut r = self.source_ref_plain(p, level, cached, wanted);
if let (SourceRef::File { denoise, .. }, Some((spec, loader))) = (&mut r, self.denoise.get(p.id)) {
*denoise = Some((spec.clone(), loader.clone()));
}
r
}
fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool) -> SourceRef {
if cached && let Some(a) = self.get_source(p.id, level) {
/// Is photo `p`'s original known to be missing (cached answer only)?
fn original_offline(&self, p: &Photo) -> bool {
matches!(&p.source, Source::File { path } if self.availability.is_offline(path))
}
fn source_ref_plain(&mut self, p: &Photo, level: SourceLevel, cached: bool, wanted: Option<(String, Arc<DcpProfile>)>) -> SourceRef {
// (a source developed with another camera profile, or none, doesn't stand in; a smart preview
// has no camera profile, and decoding it again gives the same picture, so it stands in while the
// original is offline)
if cached
&& let Some(a) = self.get_source(p.id, level)
&& (a.camera_profile == wanted.as_ref().map(|(id, _)| id.clone()) || (a.from_proxy && self.original_offline(p)))
{
return SourceRef::Loaded(Box::new(a));
}
// a thumbnail of a photo whose preview is decoded (the one in the loupe) is cut from it; not
// with a denoised picture, which the thumbnail would lose
// with a denoised picture, which the thumbnail would lose, nor from one decoded with another camera profile
if cached
&& level == SourceLevel::Thumb
&& self.denoise.spec(p.id).is_none()
&& let Some(big) = self.get_source(p.id, SourceLevel::Preview)
&& (big.camera_profile == wanted.as_ref().map(|(tag, _)| tag.clone()) || (big.from_proxy && self.original_offline(p)))
{
return SourceRef::Fit { from: Box::new(big), max_edge: level.max_edge() };
}
@@ -336,12 +370,36 @@ impl MediaCache {
return SourceRef::Smart { path: sp };
}
let mut r = self.origin_ref(&p.source, max_edge);
if let SourceRef::File { fallback, .. } = &mut r {
if let SourceRef::File { fallback, camera_profile, .. } = &mut r {
*fallback = Some(sp);
*camera_profile = wanted;
}
return r;
}
self.origin_ref(&p.source, max_edge)
let mut r = self.origin_ref(&p.source, max_edge);
if let SourceRef::File { camera_profile, .. } = &mut r {
*camera_profile = wanted;
}
r
}
/// The imported camera profile photo `p` develops with, when its profile setting names one this library has: what a
/// source decoded with it is tagged with (its id and the file's fingerprint), and the profile.
pub fn camera_profile_of(&self, p: &Photo) -> Option<(String, Arc<DcpProfile>)> {
let id = &p.develop.profile.id;
if !crate::cmd::dcp_profiles::is_dcp_id(id) {
return None;
}
self.camera_profiles.get(id).map(|d| (format!("{id}#{:016x}", d.fingerprint), d.profile.clone()))
}
/// What a render with profile `profile_id` adds to its cache keys: the imported camera profile's fingerprint, 0
/// for any other profile and for a camera profile this library no longer has (it renders without it).
pub fn camera_profile_salt(&self, profile_id: &str) -> u64 {
if !crate::cmd::dcp_profiles::is_dcp_id(profile_id) {
return 0;
}
self.camera_profiles.get(profile_id).map_or(0, |d| d.fingerprint)
}
/// How to load `origin` at most `max_edge` pixels long, ignoring decoded sources in memory (a
@@ -354,12 +412,26 @@ impl MediaCache {
}
match self.scenes.iter().find(|s| s.id == *scene) {
Some(s) => SourceRef::Demo { scene: Box::new(s.clone()), max_edge },
None => SourceRef::File { path: format!("demo:{scene}"), max_edge, loader: None, fallback: None, denoise: None, reduced: None },
None => SourceRef::File {
path: format!("demo:{scene}"),
max_edge,
loader: None,
fallback: None,
denoise: None,
camera_profile: None,
reduced: None,
},
}
}
Source::File { path } => {
SourceRef::File { path: path.clone(), max_edge, loader: self.file_loader.clone(), fallback: None, denoise: None, reduced: None }
}
Source::File { path } => SourceRef::File {
path: path.clone(),
max_edge,
loader: self.file_loader.clone(),
fallback: None,
denoise: None,
camera_profile: None,
reduced: None,
},
}
}
}
+2
View File
@@ -49,6 +49,7 @@ impl QuickJob {
loaded: None,
quick: None,
display: None,
frame: None,
})
}
@@ -66,6 +67,7 @@ impl QuickJob {
loaded: None,
quick,
display: None,
frame: None,
};
let rendered = |image: Rgba8| {
let histogram = Histogram::of_srgb8(&image);
+95 -10
View File
@@ -32,6 +32,9 @@ pub struct RenderJob {
pub view_cache: Option<(Arc<PreviewCache>, Hash128)>,
/// Render for this monitor profile ([`Self::with_display`]).
pub display: Option<Arc<crate::display::Display>>,
/// Shown on screen at once and not kept: the result may stay on the GPU as a texture
/// ([`Self::on_screen`]).
pub on_screen: bool,
/// Compose the render into a slideshow slide ([`Self::with_slide`]).
pub slide: Option<Arc<crate::slide::SlideCompose>>,
/// A face tile that can be cut from the raw's embedded preview, tried before `source`
@@ -57,6 +60,17 @@ pub fn fit_for_display(img: &Rgba8, max_w: usize, max_h: usize) -> Rgba8 {
Rgba8 { width: small.width, height: small.height, data: small.data.iter().map(|p| [c(p[0]), c(p[1]), c(p[2]), c(p[3])]).collect() }
}
/// A render left on the GPU for the window to draw ([`RenderResult::frame`]).
#[cfg(not(target_arch = "wasm32"))]
pub type ScreenFrame = lightcraft_gpu::DisplayFrame;
/// A render left on the GPU for the window to draw (never, in the browser build).
#[cfg(target_arch = "wasm32")]
#[derive(Clone, Debug)]
pub struct ScreenFrame {
pub width: usize,
pub height: usize,
}
pub struct RenderResult {
pub request_id: u64,
pub source_key: Option<Hash128>,
@@ -74,6 +88,9 @@ pub struct RenderResult {
/// The display profile (id) the image is encoded for; `None`: sRGB (see
/// [`crate::display::present`]).
pub display: Option<u64>,
/// The result as a texture on the window's GPU device ([`RenderJob::on_screen`]); `rendered`
/// then holds its histogram and an empty image.
pub frame: Option<ScreenFrame>,
}
impl RenderJob {
@@ -123,6 +140,15 @@ impl RenderJob {
self
}
/// The result is only drawn (an interactive draft of a view): when the GPU renderer runs on the
/// window's device it may hand back a texture ([`RenderResult::frame`]) instead of reading the
/// pixels back. Ignored where pixels are needed: thumbnails (cached), a full-quality render
/// kept as the view preview, and a monitor profile (corrected on the CPU).
pub fn on_screen(mut self) -> Self {
self.on_screen = true;
self
}
/// Render with some colour grading wheels (shadows, midtones, highlights) switched off for
/// viewing (the wheel eyes in the Edit panel). The photo's settings are untouched; the result
/// gets its own key and is never cached as the photo's preview or thumbnail.
@@ -189,6 +215,7 @@ impl RenderJob {
loaded: None,
quick: None,
display: None,
frame: None,
}
}
@@ -232,6 +259,7 @@ impl RenderJob {
loaded: None,
quick: None,
display: None,
frame: None,
};
}
// a face tile of an unedited raw: cut from the camera's embedded preview when it is big enough
@@ -252,6 +280,7 @@ impl RenderJob {
loaded: None,
quick: None,
display: None,
frame: None,
};
}
let was_loaded = matches!(self.source, SourceRef::Loaded(_));
@@ -267,14 +296,43 @@ impl RenderJob {
// the plain picture, or (Denoise amount above 0 and a denoised picture cached) the mix the amount asks for
let src = &source.image_for(self.settings.denoise_amount());
let info = source.info_or(self.info);
// Thumbnails (many small jobs side by side) stay on the CPU; views and exports use
// the GPU when there is one.
let gpu = self.cache.is_none();
// Views and exports use the GPU when there is one (waiting for the device if it is
// still being created). Thumbnails (grid, filmstrip, preset and profile previews)
// use it once it is ready - ~20-30 % faster than the CPU at 256 px with six jobs
// side by side (`crates/gpu/tests/it/thumbs_bench.rs`), and the cores stay free for
// decoding - but never wait for it: at startup they render on the CPU.
let gpu = self.cache.is_none() || lightcraft_gpu::ready();
// a clipping preview tests sRGB values, like the histogram: rendered in sRGB, then
// converted for the display below
let clip_view = self.request.overlay.is_clipping();
let request = if clip_view { RenderRequest { display: None, ..self.request } } else { self.request };
let (mut rendered, gpu_fallback) = develop_reporting(src, &info, &self.settings, &request, self.stages.as_deref(), gpu);
let pixels_needed =
self.cache.is_some() || self.display.is_some() || (self.view_cache.is_some() && self.request.quality == Quality::Full);
let frame = (self.on_screen && !pixels_needed && gpu)
.then(|| develop_on_screen(src, &info, &self.settings, &request, self.stages.as_deref()));
let (mut rendered, gpu_fallback) = match frame {
Some(OnScreen::Frame(frame, histogram)) => {
return RenderResult {
request_id: self.request_id,
source_key: self.source_key,
photo: self.photo,
level: self.level,
key: self.key,
rendered: Ok(Rendered {
image: lightcraft_raster::Rgba8 { width: 0, height: 0, data: Vec::new() },
histogram,
deep: None,
}),
gpu_fallback: None,
loaded: (!was_loaded).then_some(source),
quick: None,
display: None,
frame: Some(frame),
};
}
Some(OnScreen::Pixels(r)) => (r, None),
None => develop_reporting(src, &info, &self.settings, &request, self.stages.as_deref(), gpu),
};
// for a display profile: the image goes to the display's values, the histogram
// and the cached view preview stay sRGB
let mut srgb = None;
@@ -329,6 +387,7 @@ impl RenderJob {
loaded: (!was_loaded).then_some(source),
quick: None,
display,
frame: None,
}
}
Err(e) => self.failed(e),
@@ -370,12 +429,8 @@ fn develop_image(
stages: Option<&StageCache>,
gpu: bool,
) -> (Rendered, Option<String>) {
// LUT profiles have no GPU stage: they render on the CPU
let fallback = if gpu
&& !lightcraft_pipeline::lut::is_lut_profile(&s.profile.id)
&& !s.masks.iter().any(|m| m.visible && m.refine > 0.0)
&& req.proof.is_none()
{
// (LUT profiles, Refine Edges and soft proofs render on the GPU too)
let fallback = if gpu {
match lightcraft_gpu::try_render(src, info, s, req, stages) {
Ok(r) => return (r, None),
Err(lightcraft_gpu::Fallback::Failed(why)) => Some(why),
@@ -390,3 +445,33 @@ fn develop_image(
};
(rendered, fallback)
}
/// What [`develop_on_screen`] made.
enum OnScreen {
/// A texture on the window's device, and the histogram (never in the browser build).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
Frame(ScreenFrame, Histogram),
/// Pixels (GPU or CPU).
Pixels(Rendered),
}
/// [`develop`] for a render that is only drawn: a texture on the window's device when the GPU
/// renderer can hand one over, else the pixels.
fn develop_on_screen(src: &Arc<Rgb32f>, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, stages: Option<&StageCache>) -> OnScreen {
#[cfg(not(target_arch = "wasm32"))]
match lightcraft_gpu::render_display(src, info, s, req, stages) {
// an HDR edit's histogram shows the HDR range, as `develop_reporting` gives it
Some(lightcraft_gpu::Output::Display { frame, histogram }) => {
OnScreen::Frame(frame, lightcraft_pipeline::hdr_histogram(src, info, s, req).unwrap_or(histogram))
}
Some(lightcraft_gpu::Output::Image(mut r)) => {
if let Some(h) = lightcraft_pipeline::hdr_histogram(src, info, s, req) {
r.histogram = h;
}
OnScreen::Pixels(r)
}
None => OnScreen::Pixels(develop(src, info, s, req, stages, false)),
}
#[cfg(target_arch = "wasm32")]
OnScreen::Pixels(develop(src, info, s, req, stages, false))
}
+94 -27
View File
@@ -1,5 +1,6 @@
use super::quick::{QuickJob, content_key, source_info};
use super::render::{RenderJob, RenderResult};
use super::settings_hash::with_process;
use super::source::{PreviewLoader, RENDER_CACHE_VERSION, SourceLevel, SourceRef, THUMB_SIZES, face_edge, source_edge_needed, thumb_bucket};
use super::{Arc, DevelopSettings, Hash128, Hasher128, MediaKind, Op, Photo, PhotoId, RenderRequest, Rendered, Rgb32f, Source, SourceInfo};
@@ -41,7 +42,14 @@ impl crate::Session {
} else {
source_edge_needed(&p, &settings, apply_crop, max_w.max(max_h))
});
let source = self.media.source_ref(&p, level);
// the Before side develops with the Before settings' camera profile (or none), not the edit's
let source = if before {
let mut q = (*p).clone();
q.develop = settings.clone();
self.media.source_ref(&q, level)
} else {
self.media.source_ref(&p, level)
};
let request = RenderRequest { apply_crop, ..RenderRequest::fit(max_w, max_h) };
// the photo id is part of the key: two photos with the same settings and size must not
// share a result (a view slot showing photo A would otherwise look current for photo B)
@@ -52,6 +60,7 @@ impl crate::Session {
// Temporary "before" settings must not replace the photo's cached develop hash.
let settings_hash = if before { settings.hash64() } else { self.media.settings_hashes.get(id, &settings) };
let salt = self.media.denoise_salt(id, &settings);
let profile_salt = self.media.camera_profile_salt(&settings.profile.id);
let lens = super::quick::lens_key(&p);
let key = settings_hash
^ ((max_w as u64) << 40)
@@ -61,14 +70,20 @@ impl crate::Session {
^ id.0.wrapping_mul(0x9e37_79b9_7f4a_7c15)
^ content.rotate_left(17)
^ salt
^ lens.rotate_left(29);
^ profile_salt.rotate_left(29)
^ lens.rotate_left(37);
let cache = thumb_bucket.map(|b| {
let mut k = Hasher128::new();
k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key());
k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION);
with_process(&mut k, &settings).u64(crate::camera_profiles::cache_key());
// (only a render that uses a denoised picture has it in its key, so every other thumbnail stays valid)
if salt != 0 {
k.u64(salt);
}
// (likewise an imported camera profile's file: deleted or replaced, the thumbnail renders afresh)
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
}
// (likewise a database lens profile: thumbnails of every other photo keep their keys)
if lens != 0 {
k.u64(lens);
@@ -91,6 +106,7 @@ impl crate::Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut: None,
display_fit: None,
@@ -101,7 +117,17 @@ impl crate::Session {
/// temporary preview while hovering a preset or profile; nothing is committed or cached).
pub fn preview_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool, settings: &DevelopSettings) -> Option<RenderJob> {
let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?;
// the source as these settings develop it: another camera profile (or none) decodes anew
let mut p = (**self.catalog.photo(id)?).clone();
let own_profile = self.media.camera_profile_of(&p).map(|c| c.0);
p.develop = Arc::new(settings.clone());
if self.media.camera_profile_of(&p).map(|c| c.0) != own_profile {
job.source = self.media.source_ref(&p, job.level);
}
job.settings = Arc::new(settings.clone());
// (the imported camera profile's file is in the key, as in `render_job`'s: a profile file replaced under the
// same id is a new picture)
let profile_salt = self.media.camera_profile_salt(&settings.profile.id);
// (the photo's database lens profile stays part of it: a profile looked up again renders afresh)
let lens = self.catalog.photo(id).map_or(0, |p| super::quick::lens_key(p));
job.key = settings.hash64()
@@ -109,19 +135,20 @@ impl crate::Session {
^ ((max_h as u64) << 20)
^ (apply_crop as u64)
^ (job.level as u64) << 60
^ lens.rotate_left(29);
^ profile_salt.rotate_left(29)
^ lens.rotate_left(37);
Some(job)
}
/// Cache key of a variant thumbnail ([`Self::variant_job`]).
pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize) -> Hash128 {
/// `profile_salt`: [`MediaCache::camera_profile_salt`] of `settings`' profile.
pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize, profile_salt: u64) -> Hash128 {
let mut k = Hasher128::new();
k.str(&content_key(p))
.str("variant")
.u64(settings.hash64())
.u64(edge as u64)
.u64(RENDER_CACHE_VERSION)
.u64(crate::camera_profiles::cache_key());
k.str(&content_key(p)).str("variant").u64(settings.hash64()).u64(edge as u64).u64(RENDER_CACHE_VERSION);
with_process(&mut k, settings).u64(crate::camera_profiles::cache_key());
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
}
let lens = super::quick::lens_key(p);
if lens != 0 {
k.u64(lens);
@@ -135,11 +162,13 @@ impl crate::Session {
/// hash, so a variant renders once; `key` is derived from the same hash, so a frontend can
/// keep one texture per variant.
pub fn variant_job(&mut self, id: PhotoId, settings: &DevelopSettings, edge: usize) -> Option<RenderJob> {
let p = self.catalog.photo(id)?.clone();
let mut p = (**self.catalog.photo(id)?).clone();
let edge = edge.clamp(16, SourceLevel::Thumb.max_edge());
let level = SourceLevel::Thumb;
// decoded as these settings develop it (their camera profile, or none)
p.develop = Arc::new(settings.clone());
let source = self.media.source_ref(&p, level);
let ck = Self::variant_key(&p, settings, edge);
let ck = Self::variant_key(&p, settings, edge, self.media.camera_profile_salt(&settings.profile.id));
Some(RenderJob {
request_id: 0,
cache_generation: self.media.rendered.generation(),
@@ -156,6 +185,7 @@ impl crate::Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut: None,
display_fit: None,
@@ -193,7 +223,7 @@ impl crate::Session {
let needed = (edge as f64 * w.max(h) / side).ceil().min(SourceLevel::Preview.max_edge() as f64);
let level = SourceLevel::for_size(needed as usize);
let source = self.media.source_ref(&p, level);
let ck = Self::variant_key(&p, &settings, edge);
let ck = Self::variant_key(&p, &settings, edge, self.media.camera_profile_salt(&settings.profile.id));
let preview_cut = self.face_preview_cut(&p, rect, edge, needed as usize);
Some(RenderJob {
request_id: 0,
@@ -211,6 +241,7 @@ impl crate::Session {
stages: None,
view_cache: None,
display: None,
on_screen: false,
slide: None,
preview_cut,
display_fit: None,
@@ -234,15 +265,14 @@ impl crate::Session {
}
/// Size-independent cache key of a photo's view render (loupe) for its current settings, its lens profile
/// included as in [`Self::variant_key`].
pub(crate) fn view_key(p: &Photo, apply_crop: bool) -> Hash128 {
/// included as in [`Self::variant_key`]. `profile_salt`: [`MediaCache::camera_profile_salt`] of the photo's profile.
pub(crate) fn view_key(p: &Photo, apply_crop: bool, profile_salt: u64) -> Hash128 {
let mut k = Hasher128::new();
k.str(&content_key(p))
.str("view")
.u64(p.develop.hash64())
.u64(apply_crop as u64)
.u64(RENDER_CACHE_VERSION)
.u64(crate::camera_profiles::cache_key());
k.str(&content_key(p)).str("view").u64(p.develop.hash64()).u64(apply_crop as u64).u64(RENDER_CACHE_VERSION);
with_process(&mut k, &p.develop).u64(crate::camera_profiles::cache_key());
if profile_salt != 0 {
k.str("dcp").u64(profile_salt);
}
let lens = super::quick::lens_key(p);
if lens != 0 {
k.u64(lens);
@@ -255,7 +285,8 @@ impl crate::Session {
pub fn loupe_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool) -> Option<RenderJob> {
let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?;
let p = self.catalog.photo(id)?;
job.view_cache = Some((self.media.rendered.clone(), Self::view_key(p, apply_crop)));
let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id);
job.view_cache = Some((self.media.rendered.clone(), Self::view_key(p, apply_crop, profile_salt)));
Some(job)
}
@@ -364,8 +395,9 @@ impl crate::Session {
let p = self.catalog.photo(id)?.clone();
let small = self.thumb_job(id, THUMB_SIZES[THUMB_SIZES.len() - 1])?;
// (the thumbnail job itself starts with the cached thumbnail, after the sharper embedded preview)
let cached = vec![(self.media.rendered.clone(), Self::view_key(&p, apply_crop))];
let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).finish();
let profile_salt = self.media.camera_profile_salt(&p.develop.profile.id);
let cached = vec![(self.media.rendered.clone(), Self::view_key(&p, apply_crop, profile_salt))];
let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).u64(profile_salt).finish();
let key = h.0 as u64;
let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge())));
Some(QuickJob { request_id: 0, photo: id, key, cached, embedded, minimum_embedded_edge: None, small: apply_crop.then(|| Box::new(small)) })
@@ -496,8 +528,10 @@ impl crate::Session {
/// Prefer decoder facts to header-only metadata for pixel-statistics commands.
pub fn source_info(&self, id: PhotoId) -> SourceInfo {
let header = self.catalog.photo(id).map(|p| source_info(p)).unwrap_or_default();
self.media.source_facts(id, header)
let photo = self.catalog.photo(id);
let header = photo.map(|p| source_info(p)).unwrap_or_default();
let profile = photo.and_then(|p| self.media.camera_profile_of(p)).map(|(tag, _)| tag);
self.media.source_facts(id, header, profile.as_deref())
}
/// The source proxy for pixel-statistics commands (auto tone/WB), loading synchronously.
@@ -511,4 +545,37 @@ impl crate::Session {
self.media.insert_source(id, level, r);
Ok(image)
}
/// [`Session::source_now`] for several photos at once, each with the facts its decoder gave
/// ([`Session::source_info`], read before another photo can push it out of the cache): the
/// ones not in memory are decoded in parallel, so a selection costs about one decode per core,
/// not one after another. In the order of `ids`. Callers pass a few at a time (all of them are
/// held decoded until this returns).
pub(crate) fn sources_now(&mut self, ids: &[PhotoId], level: SourceLevel) -> Vec<(PhotoId, Result<(Arc<Rgb32f>, SourceInfo), String>)> {
use rayon::prelude::*;
let refs: Vec<(PhotoId, Option<SourceRef>)> =
ids.iter().map(|&id| (id, self.catalog.photo(id).cloned().map(|p| self.media.source_ref(&p, level)))).collect();
let loaded: Vec<(PhotoId, Result<super::source::DecodedSource, String>)> =
refs.into_par_iter().map(|(id, r)| (id, r.ok_or_else(|| "no such photo".to_string()).and_then(|r| r.load_source()))).collect();
loaded
.into_iter()
.map(|(id, r)| {
let r = r.map(|r| {
let image = r.image.clone();
if let Some(info) = &r.info {
self.learn_as_shot_wb(id, info);
}
// read before the insert: the cache's budget may evict this very entry, and
// the header facts alone lack the decoder's camera colour
let facts = match r.info {
Some(_) => r.info_or(self.catalog.photo(id).map(|p| source_info(p)).unwrap_or_default()),
None => self.source_info(id),
};
self.media.insert_source(id, level, r);
(image, facts)
});
(id, r)
})
.collect()
}
}
+16 -1
View File
@@ -1,4 +1,4 @@
use super::{Arc, DevelopSettings, HashMap, PhotoId, VecDeque, Weak};
use super::{Arc, DevelopSettings, HashMap, Hasher128, PhotoId, VecDeque, Weak};
pub(super) const SETTINGS_HASH_ENTRIES: usize = 1024;
@@ -34,3 +34,18 @@ impl SettingsHashes {
hash
}
}
/// Add the rendering process `s` renders with in this build to persistent render key `h`, from
/// process V3 on: a process number from a newer LightCraft renders with an older build's latest
/// process, so the same settings (and settings hash) render differently in a build that knows that
/// process, and the keys must tell those renders apart. Builds before V3 (which have no process in
/// their keys) resolve every number above V2 to V2: naming V3 and later keeps this build's renders
/// of those numbers apart from theirs, and V1 and V2 keep the keys they always had, so their
/// cached renders stay valid (`docs/process-versions.md`).
pub(super) fn with_process<'a>(h: &'a mut Hasher128, s: &DevelopSettings) -> &'a mut Hasher128 {
let v = s.process.process().version().0;
if v >= lightcraft_develop::Process::V3.version().0 {
h.u64(u64::from(v));
}
h
}
+26 -12
View File
@@ -1,7 +1,7 @@
use super::{Arc, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
pub const RENDER_CACHE_VERSION: u64 = 74;
pub const RENDER_CACHE_VERSION: u64 = 75;
/// 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];
@@ -75,12 +75,14 @@ pub(super) fn source_edge_needed(p: &Photo, settings: &DevelopSettings, apply_cr
}
/// Decodes a file into a linear Rec.2020 image no larger than `max_edge` (set by the app).
pub type FileLoader = Arc<dyn Fn(&str, usize) -> Result<(Rgb32f, SourceInfo), String> + Send + Sync>;
/// The third argument is the photo's imported camera profile ([`crate::cmd::dcp_profiles`]): a raw file is developed
/// with its colour model.
pub type FileLoader = Arc<dyn Fn(&str, usize, Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo), String> + Send + Sync>;
/// [`FileLoader`] for a thumbnail: a raw file that keeps smaller copies of its raw image (Lightroom's merged DNGs)
/// develops the smallest that covers `max_edge` (set by the app); the flag says it did. Never used for an export,
/// which must render the full image.
pub type ReducedLoader = Arc<dyn Fn(&str, usize) -> Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>;
pub type ReducedLoader = Arc<dyn Fn(&str, usize, Option<&DcpProfile>) -> Result<(Rgb32f, SourceInfo, bool), String> + Send + Sync>;
/// A raw file's embedded (camera-rendered) preview as display sRGB, oriented, no larger than
/// `max_edge` (set by the app). `None`: no usable preview.
@@ -103,7 +105,8 @@ pub struct DenoiseSpec {
/// Decodes a raw file once and develops it twice: as usual, and from the denoised picture in `spec` when that can be
/// read (`None` when it cannot). Both are at most `max_edge` long and the same size.
pub type PairLoader = Arc<dyn Fn(&str, usize, &DenoiseSpec) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> + Send + Sync>;
pub type PairLoader =
Arc<dyn Fn(&str, usize, &DenoiseSpec, Option<&DcpProfile>) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> + Send + Sync>;
/// A photo's denoised picture next to its plain one, and the last mix of the two that was asked for.
pub struct Twin {
@@ -133,6 +136,9 @@ pub struct DecodedSource {
pub camera_tone: Option<lightcraft_pipeline::tone::CameraTone>,
/// The same picture developed from the AI-denoised mosaic, when the photo has one cached.
pub denoised: Option<Arc<Twin>>,
/// The imported camera profile (`dcp:…` id) the raw file was developed with, if any: a cached source made with
/// another one (or none) doesn't stand in for it.
pub camera_profile: Option<String>,
/// These pixels came from the photo's smart preview (an offline original), not from its file.
/// A refresh must never rebuild a proxy from itself: that would stamp its older look as current.
pub from_proxy: bool,
@@ -143,7 +149,7 @@ pub struct DecodedSource {
impl DecodedSource {
pub fn new(image: Arc<Rgb32f>, info: Option<SourceInfo>) -> Self {
DecodedSource { image, info, camera_tone: None, denoised: None, from_proxy: false, reduced: false }
DecodedSource { image, info, camera_tone: None, denoised: None, camera_profile: None, from_proxy: false, reduced: false }
}
/// The picture to develop for a Denoise `amount` (0 to 1, see [`DevelopSettings::denoise_amount`]): the plain one,
@@ -235,6 +241,8 @@ pub enum SourceRef {
fallback: Option<std::path::PathBuf>,
/// The photo has a cached denoised picture: load it with the plain one (see [`PairLoader`]).
denoise: Option<(DenoiseSpec, PairLoader)>,
/// The photo's imported camera profile (id and profile): its raw file is developed with it.
camera_profile: Option<(String, Arc<DcpProfile>)>,
/// A thumbnail's loader, used instead of `loader` (see [`ReducedLoader`]); `None` for every other job.
reduced: Option<ReducedLoader>,
},
@@ -262,12 +270,17 @@ impl SourceRef {
return Ok(DecodedSource { image: Arc::new(image), denoised: None, ..(**from).clone() });
}
SourceRef::Demo { scene, max_edge } => crate::demo::scene_pixels(scene, *max_edge)?,
SourceRef::File { path, max_edge, loader, fallback, denoise, reduced } => {
SourceRef::File { path, max_edge, loader, fallback, denoise, camera_profile, reduced } => {
let dcp = camera_profile.as_ref().map(|(_, p)| p.as_ref());
let made_with = camera_profile.as_ref().map(|(id, _)| id.clone());
let plain = || match (reduced, loader) {
(Some(l), _) => {
l(path, *max_edge).map(|(image, info, reduced)| DecodedSource { reduced, ..DecodedSource::new(Arc::new(image), Some(info)) })
}
(None, Some(l)) => l(path, *max_edge).map(|(image, info)| DecodedSource::new(Arc::new(image), Some(info))),
(Some(l), _) => l(path, *max_edge, dcp).map(|(image, info, reduced)| DecodedSource {
reduced,
camera_profile: made_with.clone(),
..DecodedSource::new(Arc::new(image), Some(info))
}),
(None, Some(l)) => l(path, *max_edge, dcp)
.map(|(image, info)| DecodedSource { camera_profile: made_with.clone(), ..DecodedSource::new(Arc::new(image), Some(info)) }),
(None, None) => Err(format!("no decoder available for {path}")),
};
// the denoised picture comes with the plain one from a single decode; when it cannot be read the
@@ -281,7 +294,7 @@ impl SourceRef {
None => true,
};
if made {
pair(path, *max_edge, spec).and_then(|(image, twin, info)| {
pair(path, *max_edge, spec, dcp).and_then(|(image, twin, info)| {
if spec.make.is_some() && twin.is_none() {
return Err("the cached AI Denoise picture could not be read; clear the denoise cache and retry".into());
}
@@ -290,6 +303,7 @@ impl SourceRef {
info: Some(info),
camera_tone: None,
denoised: twin.map(|t| Arc::new(Twin::new(Arc::new(t)))),
camera_profile: made_with.clone(),
from_proxy: false,
reduced: false,
})
+4 -2
View File
@@ -83,13 +83,14 @@ fn decoder_info_survives_render_jobs_cache_and_eviction() {
job.source = SourceRef::File {
path: "synthetic.arw".into(),
max_edge: 64,
loader: Some(Arc::new(move |_, _| {
loader: Some(Arc::new(move |_, _, _| {
let mut image = Rgb32f::new(64, 64);
image.data.fill([0.1; 3]);
Ok((image, loaded_info.clone()))
})),
fallback: None,
denoise: None,
camera_profile: None,
reduced: None,
};
job.info = SourceInfo::default(); // Header facts cannot override decoder facts.
@@ -143,9 +144,10 @@ fn old_relative_white_balance_on_a_kelvin_camera_keeps_its_look_and_learns_the_a
job.source = SourceRef::File {
path: "/photos/DSC00001.ARW".into(),
max_edge: 64,
loader: Some(Arc::new(move |_, _| Ok((loaded_pixels.clone(), loaded_info.clone())))),
loader: Some(Arc::new(move |_, _, _| Ok((loaded_pixels.clone(), loaded_info.clone())))),
fallback: None,
denoise: None,
camera_profile: None,
reduced: None,
};
let undo_before = s.undo.len();
@@ -6,6 +6,77 @@ fn session() -> crate::Session {
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
s
}
/// Settings saved by a newer LightCraft (a process number this build doesn't know) render with
/// this build's latest process, and a build that resolved the number to an older process
/// cached other pixels under the same settings hash: the persistent keys (thumbnails, the
/// loupe's view render, variants) name the process the settings render with, so those are
/// never served (review of 5a7016c8: a catalog saved with a newer process kept main's V2 thumbnails).
#[test]
fn persistent_keys_name_the_process_the_settings_render_with() {
use lightcraft_develop::ProcessVersion;
let mut s = session();
let newer = DevelopSettings { process: ProcessVersion(ProcessVersion::LATEST.0 + 1), ..DevelopSettings::default() };
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(newer.clone()), label: "newer".into(), edited: None }).unwrap();
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
let unnamed = |kind: Option<&str>, size: u64| {
let mut h = Hasher128::new();
h.str(&content_key(&p));
if let Some(k) = kind {
h.str(k);
}
h.u64(newer.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()).finish()
};
let named = |kind: Option<&str>, size: u64, process: u64| {
let mut h = Hasher128::new();
h.str(&content_key(&p));
if let Some(k) = kind {
h.str(k);
}
h.u64(newer.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(process).u64(crate::camera_profiles::cache_key()).finish()
};
let resolved = u64::from(lightcraft_develop::Process::LATEST.version().0);
let keys = [
(s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1, None, 256),
(crate::Session::view_key(&p, true, 0), Some("view"), 1),
(crate::Session::variant_key(&p, &newer, 256, 0), Some("variant"), 256),
];
for (key, kind, size) in keys {
assert_ne!(key, unnamed(kind, size), "old builds did not name their resolved process");
assert_eq!(key, named(kind, size, resolved), "the key names the process used for rendering");
assert_ne!(key, named(kind, size, u64::from(newer.process.0)), "the saved future number is not the resolved process");
}
}
/// Photos on V1 and V2 keep the persistent keys builds before process V3 gave them (no process
/// in them), so their cached thumbnails, view renders and variants stay valid after upgrading
/// (review of 26cd2df1: every V1/V2 photo rendered again, and offline ones without smart
/// previews lost their thumbnails); V3 and later name their process.
#[test]
fn v1_and_v2_photos_keep_the_render_cache_keys_they_had() {
use lightcraft_develop::Process;
let mut s = session();
for process in [Process::V1, Process::V2, Process::V3] {
let settings = DevelopSettings { process: process.version(), ..DevelopSettings::default() };
s.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(settings.clone()), label: "p".into(), edited: None }).unwrap();
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
let before_v3 = |kind: Option<&str>, size: u64| {
let mut h = Hasher128::new();
h.str(&content_key(&p));
if let Some(k) = kind {
h.str(k);
}
h.u64(settings.hash64()).u64(size).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key()).finish()
};
let keys = [
s.thumb_job(PhotoId(1), 256).unwrap().cache.unwrap().1 == before_v3(None, 256),
crate::Session::view_key(&p, true, 0) == before_v3(Some("view"), 1),
crate::Session::variant_key(&p, &settings, 256, 0) == before_v3(Some("variant"), 256),
];
let old = process <= Process::V2;
assert_eq!(keys, [old; 3], "{process:?}: thumbnail, view and variant keys");
}
}
#[test]
fn hashes_match_uncached_keys_and_are_not_recomputed_for_sizes_metadata_or_before() {
let mut s = session();
@@ -21,6 +92,7 @@ fn hashes_match_uncached_keys_and_are_not_recomputed_for_sizes_metadata_or_befor
.u64(settings)
.u64(b as u64)
.u64(RENDER_CACHE_VERSION)
.u64(u64::from(p.develop.process.process().version().0))
.u64(crate::camera_profiles::cache_key())
.finish();
let job = s.thumb_job(p.id, edge).unwrap();
@@ -70,7 +142,7 @@ fn hash_cache_is_bounded_weak_and_shared_settings_remain_independent() {
#[test]
fn source_from_before_content_reload_is_not_accepted() {
let mut s = session();
s.media.file_loader = Some(Arc::new(|_, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
let old = s.thumb_job(PhotoId(1), 256).unwrap().run();
assert!(old.loaded.is_some());
s.catalog
@@ -94,7 +166,7 @@ fn source_from_before_content_reload_is_not_accepted() {
#[test]
fn source_from_before_a_lens_profile_change_is_not_accepted() {
let mut s = session();
s.media.file_loader = Some(Arc::new(|_, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
let old = s.thumb_job(PhotoId(1), 256).unwrap().run();
assert!(old.loaded.is_some());
let lens = lightcraft_develop::EmbeddedLens { source: lightcraft_develop::LensSource::Database, ..Default::default() };
@@ -132,7 +204,7 @@ fn a_hover_preview_key_follows_the_lens_profile() {
#[test]
fn a_render_that_panics_fails_instead_of_never_answering() {
let mut s = session();
s.media.file_loader = Some(Arc::new(|_, _| panic!("decoder bug")));
s.media.file_loader = Some(Arc::new(|_, _, _| panic!("decoder bug")));
let mut job = s.thumb_job(PhotoId(1), 256).unwrap();
job.request_id = 42;
let (key, level, source_key) = (job.key, job.level, job.source_key);
+32 -13
View File
@@ -523,7 +523,23 @@ impl Session {
if let Some(p) = profile(id) {
return Some((p.name, p.group));
}
self.lut_profiles.iter().find(|p| p.id == id).map(|p| (p.name.as_str(), p.group.as_str()))
if let Some(p) = self.lut_profiles.iter().find(|p| p.id == id) {
return Some((p.name.as_str(), p.group.as_str()));
}
self.dcp_profiles.iter().find(|p| p.id == id).map(|p| (p.name.as_str(), crate::cmd::dcp_profiles::DCP_GROUP))
}
/// The imported profiles as (id, name, group): LUT profiles, then camera profiles (`.dcp`). A camera profile
/// whose file is missing or damaged (not loaded when the library opened) is left out, so it can't be chosen; its
/// entry stays and it is offered again once the file is back.
pub fn imported_profiles(&self) -> Vec<(String, String, String)> {
let luts = self.lut_profiles.iter().map(|p| (p.id.clone(), p.name.clone(), p.group.clone()));
let dcps = self
.dcp_profiles
.iter()
.filter(|p| self.media.camera_profiles.contains_key(&p.id))
.map(|p| (p.id.clone(), p.name.clone(), crate::cmd::dcp_profiles::DCP_GROUP.to_string()));
luts.chain(dcps).collect()
}
/// Remember `id` as the most recently applied profile.
@@ -537,28 +553,31 @@ impl Session {
pub fn profile_menu(&self) -> Value {
let item =
|p: &ProfileInfo| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.iter().any(|f| f == p.id)});
let lut_item = |id: &str| {
self.lut_profiles
.iter()
.find(|p| p.id == id)
.map(|p| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.contains(&p.id), "imported": true}))
let imported = self.imported_profiles();
let imported_item = |(id, name, group): &(String, String, String)| {
let mut v = json!({"id": id, "name": name, "group": group, "favorite": self.profile_favorites.contains(id), "imported": true});
if let Some(d) = self.dcp_profiles.iter().find(|d| &d.id == id) {
v["cameraModel"] = json!(d.camera_model);
}
v
};
let lut_item = |id: &str| imported.iter().find(|p| p.0 == id).map(imported_item);
let list = |ids: &[String]| ids.iter().filter_map(|id| profile(id).map(item).or_else(|| lut_item(id))).collect::<Vec<_>>();
let mut groups: Vec<Value> = profile_groups()
.into_iter()
.map(|g| json!({"name": g, "profiles": PROFILES.iter().filter(|p| p.group == g).map(item).collect::<Vec<_>>()}))
.collect();
// imported LUT profiles, by their groups
// imported LUT profiles by their groups, then camera profiles
let mut lut_groups: Vec<&str> = self.lut_profiles.iter().map(|p| p.group.as_str()).collect();
lut_groups.sort_unstable();
lut_groups.dedup();
// the camera profiles' group once, last (a LUT group of the same name joins it rather than showing twice)
lut_groups.retain(|g| *g != crate::cmd::dcp_profiles::DCP_GROUP);
if imported.iter().any(|p| p.2 == crate::cmd::dcp_profiles::DCP_GROUP) {
lut_groups.push(crate::cmd::dcp_profiles::DCP_GROUP);
}
for g in lut_groups {
let profiles: Vec<Value> = self
.lut_profiles
.iter()
.filter(|p| p.group == g)
.map(|p| json!({"id": p.id, "name": p.name, "group": p.group, "favorite": self.profile_favorites.contains(&p.id), "imported": true}))
.collect();
let profiles: Vec<Value> = imported.iter().filter(|p| p.2 == g).map(imported_item).collect();
groups.push(json!({"name": g, "profiles": profiles, "imported": true}));
}
json!({
+1
View File
@@ -363,6 +363,7 @@ impl TitleCompose {
quick: None,
display: None,
gpu_fallback: None,
frame: None,
}
}
}
+1
View File
@@ -502,6 +502,7 @@ pub fn load(path: &Path) -> Result<crate::media::DecodedSource, String> {
info,
camera_tone,
denoised: None,
camera_profile: None,
from_proxy: true,
reduced: false,
})
+132
View File
@@ -0,0 +1,132 @@
//! Auto Sync carries the active photo's VALUE to every selected photo, as Lightroom Classic does
//! (test notes 2026-10-24 note 18, the user's rule "same value for all synced values"). Where white
//! balance is a mode rather than a number, the mode travels and each photo applies it to itself:
//! As Shot gives each photo its own camera white, Auto each photo's own white from its pixels, a
//! light preset its numbers.
//!
//! A typed or dragged Temp or Tint is set on each photo's own scale: a raw edited in Kelvin gets
//! the same Kelvin (an old relative-scale value converted first, never read as Kelvin, which turned
//! photos blue: test notes 2026-10-15), and only the slider that moved changes (a Temp move keeps
//! each photo's own tint). A photo on another scale than the active one (a JPEG next to a raw) has
//! no "same" number and moves by as much as the active photo instead.
use std::collections::HashMap;
use lightcraft_catalog::PhotoId;
use lightcraft_develop::{DevelopSettings, WbMode};
use lightcraft_pipeline::SourceInfo;
use crate::Session;
/// White balance on this source is edited in Kelvin (a raw with a measured camera scale), not on
/// the relative scale (6500 K / 0 = as shot).
fn kelvin(info: &SourceInfo) -> bool {
info.raw && !info.relative_wb
}
/// The temperature and tint `mode` stands for on a source with `info` (As Shot and the light
/// presets; `None` for Auto and Custom, which need the pixels or the numbers).
fn wb_of_mode(info: &SourceInfo, mode: WbMode) -> Option<(f64, f64)> {
match mode {
WbMode::AsShot => Some((info.as_shot_temp, info.as_shot_tint)),
m => m.preset().map(|(t, ti)| {
// presets are Kelvin on raws with that scale, relative to daylight (6500 K = as shot) elsewhere
if kelvin(info) { (t, ti) } else { (6500.0 * t / 5500.0, ti) }
}),
}
}
/// `synced.wb` for a photo (source `oinfo`, settings `own` before the sync) when the active
/// photo's white balance went from `old` to `new` (source `ainfo`). `auto`: the photo's own Auto
/// white balance, when `new` is Auto (`None`: it couldn't be worked out, and the photo keeps its
/// white balance).
pub(crate) fn synced_wb(
ainfo: &SourceInfo,
old: &DevelopSettings,
new: &DevelopSettings,
oinfo: &SourceInfo,
own: &DevelopSettings,
auto: Option<(f64, f64)>,
synced: &mut DevelopSettings,
) {
use lightcraft_pipeline::local::{effective_wb, normalize_wb};
let mut d = own.clone();
normalize_wb(&mut d, oinfo);
// A light preset with numbers of its own (`develop.wb {mode, tint}` on a photo on the
// relative scale, where the stored numbers are what renders): those numbers travel, as a
// Custom white balance does (review of #3585)
let overridden = new.wb.mode.preset().is_some()
&& wb_of_mode(ainfo, new.wb.mode).is_some_and(|(t, ti)| {
let (at, ati) = effective_wb(ainfo, new);
(at - t).abs() > 1e-6 || (ati - ti).abs() > 1e-6
});
let mode = if overridden { WbMode::Custom } else { new.wb.mode };
let resolved = match mode {
WbMode::Auto => auto,
WbMode::Custom => None,
m => wb_of_mode(oinfo, m),
};
match (mode, resolved) {
(WbMode::Custom, _) => {
let (ot, oti) = effective_wb(oinfo, own);
let (at0, ati0) = effective_wb(ainfo, old);
let (at, ati) = effective_wb(ainfo, new);
let same_scale = kelvin(ainfo) == kelvin(oinfo);
// only what moved: a Temp move leaves each photo's own tint
let pick = |own: f64, was: f64, now: f64| {
if (now - was).abs() < 1e-9 {
own
} else if same_scale {
now
} else {
own + (now - was)
}
};
d.wb.temp = pick(ot, at0, at);
d.wb.tint = pick(oti, ati0, ati);
d.wb.mode = WbMode::Custom;
}
(m, Some((t, ti))) => {
d.wb.temp = t;
d.wb.tint = ti;
d.wb.mode = m;
}
// Auto couldn't be worked out on this photo (its pixels didn't load): it keeps its own
(_, None) => {
synced.wb = own.wb;
return;
}
}
let (t, ti) = (d.wb.temp, d.wb.tint);
lightcraft_develop::controls::set(&mut d, "wb.temp", t);
lightcraft_develop::controls::set(&mut d, "wb.tint", ti);
synced.wb = d.wb;
}
impl Session {
/// Each other selected photo's own Auto white balance, worked out on its own pixels, when
/// Auto Sync is about to carry the active photo's (`id`) switch to Auto (`new`) over. Empty
/// otherwise. A photo whose pixels don't load is left out (it keeps its white balance).
pub(crate) fn own_auto_wb(&mut self, id: PhotoId, new: &DevelopSettings, label: &str) -> HashMap<PhotoId, (f64, f64)> {
let mut own = HashMap::new();
if !self.auto_sync_applies(id, label) || new.wb.mode != WbMode::Auto || self.develop_of(id).is_some_and(|old| old.wb == new.wb) {
return own;
}
let others: Vec<PhotoId> = self.selection.ids.iter().copied().filter(|x| *x != id).collect();
// decoded in parallel, a core's worth at a time: a big selection never holds more
// decoded thumbnails at once than that, whatever the cache keeps
let batch = rayon::current_num_threads().clamp(1, 16);
for chunk in others.chunks(batch) {
for (x, src) in self.sources_now(chunk, crate::media::SourceLevel::Thumb) {
match src {
// with the facts its own decoder gave
Ok((src, info)) => {
own.insert(x, lightcraft_pipeline::auto::auto_wb(&src, &info));
}
Err(e) => log::warn!("Auto Sync: Auto white balance on photo {}: {e}", x.0),
}
}
}
own
}
}
+5
View File
@@ -7,10 +7,13 @@ mod album_missing;
mod album_order;
mod album_remove;
mod albums_local;
mod autosync_wb;
mod color;
mod constrain_crop;
mod crop_angle;
mod crop_aspect;
mod dcp;
mod dcp_corpus;
mod denoise;
mod export;
mod face_models;
@@ -49,6 +52,8 @@ mod settings_files;
mod shelved_folder;
mod slide;
mod slideshow_export;
#[cfg(not(target_arch = "wasm32"))]
mod slow_drive;
mod spots;
mod sync;
mod view_follow;
+189
View File
@@ -0,0 +1,189 @@
//! LRC-DEV-AUTOSYNC (N-A3, test notes 2026-10-24 note 18): Auto Sync sets every selected photo to
//! the active photo's value, and where white balance is a mode or another scale, each photo applies
//! it to itself. As Shot gives each photo its own camera white, Auto each photo's own from its
//! pixels, a light preset its numbers. A typed or dragged Temp is the same number on each photo of
//! the same scale (the same Kelvin on raws edited in Kelvin; an old relative-scale value converted
//! first, never read as Kelvin), moves a photo of another scale (a JPEG beside a raw) by as much as
//! the active photo, and leaves each photo's own tint.
use lightcraft_catalog::PhotoId;
use lightcraft_develop::{WbMode, WbScale, WhiteBalance};
use serde_json::json;
use crate::Session;
/// Give photo `id` a decoded raw source (thumbnail and preview) with as-shot white `(temp, tint)`;
/// `legacy`: a camera whose settings without a scale were written on the relative scale; `warm`
/// tints its pixels, so Auto finds another white on each photo.
fn raw_as_shot(s: &mut Session, id: PhotoId, temp: f64, tint: f64, legacy: bool, warm: f32) {
use crate::media::SourceLevel;
let mut img = lightcraft_raster::Rgb32f::new(48, 32);
for (i, px) in img.data.iter_mut().enumerate() {
let v = 0.1 + 0.6 * ((i % 48) as f32 / 48.0);
*px = [v * warm, v, v / warm];
}
let img = std::sync::Arc::new(img);
let info =
lightcraft_pipeline::SourceInfo { raw: true, legacy_relative_wb: legacy, as_shot_temp: temp, as_shot_tint: tint, ..Default::default() };
s.media.insert_with_info(id, SourceLevel::Thumb, img.clone(), info.clone());
s.media.insert_with_info(id, SourceLevel::Preview, img, info);
}
/// The white balance photo `id` renders with (Kelvin, tint).
fn wb(s: &Session, id: PhotoId) -> (f64, f64) {
lightcraft_pipeline::local::effective_wb(&s.source_info(id), &s.develop_of(id).unwrap())
}
fn close(x: (f64, f64), y: (f64, f64)) -> bool {
(x.0 - y.0).abs() < 1.0 && (x.1 - y.1).abs() < 0.5
}
/// Three demo photos (a active, b, c) selected, Auto Sync on, each a raw of another as-shot white;
/// c still holds an old relative-scale white (7000 there meant "a little warmer than as shot").
fn three_raws() -> (Session, [PhotoId; 3]) {
let mut s = Session::with_demo();
let ids: Vec<PhotoId> = s.visible_cloned().into_iter().take(3).collect();
let (a, b, c) = (ids[0], ids[1], ids[2]);
raw_as_shot(&mut s, a, 5200.0, 4.0, false, 1.0);
raw_as_shot(&mut s, b, 3300.0, -12.0, false, 1.4);
raw_as_shot(&mut s, c, 6100.0, 8.0, true, 0.7);
let mut d = (*s.develop_of(c).unwrap()).clone();
d.wb = WhiteBalance { mode: WbMode::Custom, temp: 7000.0, tint: 0.0, scale: WbScale::Legacy };
s.catalog.apply(lightcraft_catalog::Op::SetDevelop { id: c, settings: std::sync::Arc::new(d), label: "x".into(), edited: None }).unwrap();
s.execute("library.select", &json!({"ids": [a.0, b.0, c.0], "active": a.0})).unwrap();
s.execute("develop.autoSync", &json!({"on": true})).unwrap();
(s, [a, b, c])
}
/// As Shot and Auto are modes: each photo gets its own camera white, or its own Auto white worked
/// out on its own pixels, never the active photo's numbers. A light preset gives its numbers.
#[test]
fn auto_sync_white_balance_modes_apply_to_each_photo() {
let (mut s, [a, b, c]) = three_raws();
// As Shot: each photo's own camera white
s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap();
for (id, own) in [(a, (5200.0, 4.0)), (b, (3300.0, -12.0)), (c, (6100.0, 8.0))] {
assert!(close(wb(&s, id), own), "As Shot on photo {}: {:?}, its own is {own:?}", id.0, wb(&s, id));
assert_eq!(s.develop_of(id).unwrap().wb.mode, WbMode::AsShot);
}
// a light preset: its numbers on every raw
s.execute("develop.wb", &json!({"mode": "tungsten"})).unwrap();
for id in [a, b, c] {
assert!(close(wb(&s, id), (2850.0, 0.0)), "Tungsten on photo {}: {:?}", id.0, wb(&s, id));
}
// Auto: each photo's own, from its own pixels
s.execute("develop.wb", &json!({"mode": "auto"})).unwrap();
for id in [b, c] {
let src = s.source_now(id, crate::media::SourceLevel::Thumb).unwrap();
let own = lightcraft_pipeline::auto::auto_wb(&src, &s.source_info(id));
assert!(close(wb(&s, id), own), "Auto on photo {}: {:?}, its own Auto is {own:?}", id.0, wb(&s, id));
assert_eq!(s.develop_of(id).unwrap().wb.mode, WbMode::Auto);
}
assert!(!close(wb(&s, a), wb(&s, b)), "not the active photo's Auto copied over: {:?}", wb(&s, a));
// one undo step puts every photo back
s.execute("edit.undo", &json!({})).unwrap();
for id in [a, b, c] {
assert!(close(wb(&s, id), (2850.0, 0.0)), "undo, photo {}: {:?}", id.0, wb(&s, id));
}
}
/// A Temp typed or dragged from As Shot: the same Kelvin on every raw, each keeping its own tint;
/// the photo holding an old relative-scale value gets the Kelvin too, never read on that scale.
#[test]
fn auto_sync_temp_is_the_same_kelvin_and_keeps_each_photos_tint() {
let (mut s, [a, b, c]) = three_raws();
s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap();
// typed
s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap();
assert!(close(wb(&s, a), (5600.0, 4.0)), "a: {:?}", wb(&s, a));
assert!(close(wb(&s, b), (5600.0, -12.0)), "b keeps its own tint: {:?}", wb(&s, b));
assert!(close(wb(&s, c), (5600.0, 8.0)), "c keeps its own tint: {:?}", wb(&s, c));
// a drag, synced on release
s.execute("develop.beginInteraction", &json!({"label": "Temp"})).unwrap();
for v in [5000.0, 4600.0] {
s.execute("develop.set", &json!({"control": "wb.temp", "value": v})).unwrap();
}
s.execute("develop.endInteraction", &json!({})).unwrap();
assert!(close(wb(&s, b), (4600.0, -12.0)) && close(wb(&s, c), (4600.0, 8.0)), "b {:?} c {:?}", wb(&s, b), wb(&s, c));
// a Tint move: the same tint on every photo, each keeping its Kelvin (all at 4600 here)
s.execute("develop.set", &json!({"control": "wb.tint", "value": 10.0})).unwrap();
for id in [a, b, c] {
assert!(close(wb(&s, id), (4600.0, 10.0)), "photo {}: {:?}", id.0, wb(&s, id));
}
}
/// A photo still holding an old relative-scale value: a Temp synced from a photo in Kelvin reaches
/// it as Kelvin, never as a number on the relative scale (where 6500 is as shot), which turned
/// photos blue (test notes 2026-10-15). Main already got this right; the guard keeps it so.
#[test]
fn auto_sync_temp_never_lands_on_an_old_relative_scale() {
let (mut s, [_, _, c]) = three_raws();
s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap();
assert!((wb(&s, c).0 - 5600.0).abs() < 1.0, "c renders at {:?}", wb(&s, c));
assert_eq!(s.develop_of(c).unwrap().wb.scale, WbScale::Kelvin);
}
/// A JPEG selected with a raw has no "same" Kelvin (its white balance is relative to its own
/// colours): it moves by as much as the raw did. Before, it got the raw's Kelvin number, read on
/// its own scale.
#[test]
fn auto_sync_temp_moves_a_jpeg_by_as_much_as_the_raw() {
let mut s = Session::with_demo();
let ids: Vec<PhotoId> = s.visible_cloned().into_iter().take(2).collect();
let (a, b) = (ids[0], ids[1]);
raw_as_shot(&mut s, a, 5200.0, 4.0, false, 1.0);
// b: a JPEG (no raw white balance scale: 6500 / 0 = its own colours)
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::filled(48, 32, [0.4, 0.4, 0.4]));
let info = lightcraft_pipeline::SourceInfo { raw: false, as_shot_temp: 6500.0, as_shot_tint: 0.0, ..Default::default() };
s.media.insert_with_info(b, crate::media::SourceLevel::Thumb, img.clone(), info.clone());
s.media.insert_with_info(b, crate::media::SourceLevel::Preview, img, info);
assert!(!s.source_info(b).raw);
s.execute("library.select", &json!({"ids": [a.0, b.0], "active": a.0})).unwrap();
s.execute("develop.autoSync", &json!({"on": true})).unwrap();
s.execute("develop.wb", &json!({"mode": "asShot"})).unwrap();
let before = wb(&s, b);
s.execute("develop.set", &json!({"control": "wb.temp", "value": 5600.0})).unwrap();
assert!(close(wb(&s, b), (before.0 + 400.0, before.1)), "the JPEG: {:?}, was {before:?}", wb(&s, b));
}
/// The other photos' pixels for Auto are read together (in parallel, review of #3571): in the
/// order asked, each photo its own, and a photo the library doesn't have is an error, not a panic.
#[test]
fn sources_for_auto_come_back_in_order_and_per_photo() {
let (mut s, [a, b, c]) = three_raws();
let want: Vec<_> = [b, c, a].iter().map(|&x| s.source_now(x, crate::media::SourceLevel::Thumb).unwrap()).collect();
let got = s.sources_now(&[b, PhotoId(u64::MAX), c, a], crate::media::SourceLevel::Thumb);
assert_eq!(got.iter().map(|(x, _)| *x).collect::<Vec<_>>(), vec![b, PhotoId(u64::MAX), c, a]);
assert!(got[1].1.is_err());
for (i, k) in [0, 2, 3].into_iter().enumerate() {
let (img, info) = got[k].1.as_ref().unwrap();
assert!(std::sync::Arc::ptr_eq(img, &want[i]), "photo {k}");
// the facts its decoder gave (the as-shot whites differ per photo here)
assert_eq!(info.as_shot_temp, s.source_info(got[k].0).as_shot_temp, "photo {k}");
}
assert_eq!(got[0].1.as_ref().unwrap().1.as_shot_temp, 3300.0, "b's own");
}
/// Review of #3585: a light preset given a tint of its own on a JPEG (where the stored numbers are
/// what renders) carries that tint to the other photos, as a Custom white balance would, not the
/// preset's tint.
#[test]
fn a_preset_with_its_own_tint_on_a_jpeg_carries_that_tint() {
let mut s = Session::with_demo();
let ids: Vec<PhotoId> = s.visible_cloned().into_iter().take(2).collect();
let (a, b) = (ids[0], ids[1]);
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::filled(48, 32, [0.4, 0.4, 0.4]));
let info = lightcraft_pipeline::SourceInfo { raw: false, as_shot_temp: 6500.0, as_shot_tint: 0.0, ..Default::default() };
for id in [a, b] {
s.media.insert_with_info(id, crate::media::SourceLevel::Thumb, img.clone(), info.clone());
s.media.insert_with_info(id, crate::media::SourceLevel::Preview, img.clone(), info.clone());
}
s.execute("library.select", &json!({"ids": [a.0, b.0], "active": a.0})).unwrap();
s.execute("develop.autoSync", &json!({"on": true})).unwrap();
s.execute("develop.wb", &json!({"mode": "daylight", "tint": 30.0})).unwrap();
assert!(close(wb(&s, a), (6500.0, 30.0)), "a: {:?}", wb(&s, a));
assert!(close(wb(&s, b), wb(&s, a)), "b renders a's numbers: {:?}", wb(&s, b));
// a plain preset still gives the preset's numbers
s.execute("develop.wb", &json!({"mode": "shade"})).unwrap();
assert!(close(wb(&s, b), (6500.0 * 7500.0 / 5500.0, 10.0)), "b: {:?}", wb(&s, b));
}
+563
View File
@@ -0,0 +1,563 @@
//! Imported camera profiles (`.dcp`): import, choosing one for a raw photo, decoding with it, the
//! source cache, persistence and deletion. Profiles are built in memory (no profile file is committed).
use std::path::PathBuf;
use lightcraft_catalog::PhotoId;
use lightcraft_raw::dcp::{DcpProfile, write_dcp};
use lightcraft_raw::{ColorData, Mat3};
use serde_json::json;
use crate::Session;
use crate::media::SourceRef;
fn temp_dir(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("lc-dcp-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// A profile whose matrix swaps the camera's red and blue (our own numbers): photos developed with it
/// come out with red and blue exchanged, which is easy to see in a test.
fn swapping_profile(name: &str) -> DcpProfile {
let m = Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]);
let xyz_to_cam = m.mul(&Mat3([[3.2406, -1.5372, -0.4986], [-0.9689, 1.8758, 0.0415], [0.0557, -0.2040, 1.0570]]));
DcpProfile {
name: name.into(),
camera_model: "LightCraft Test Camera".into(),
color: ColorData { illuminant: [21, 0], color_matrix: [Some(xyz_to_cam), None], ..Default::default() },
}
}
fn mean_rgb(img: &lightcraft_raster::Rgb32f) -> [f32; 3] {
let n = img.data.len().max(1) as f32;
let s = img.data.iter().fold([0.0f32; 3], |a, p| [a[0] + p[0], a[1] + p[1], a[2] + p[2]]);
[s[0] / n, s[1] / n, s[2] / n]
}
#[test]
fn a_camera_profile_replaces_the_raw_colour_model_when_decoding() {
let dng = crate::tests_xmp::synthetic_dng_with(None, Default::default());
let (plain, plain_info) = crate::files::load_bytes(&dng, 64).unwrap();
let p = swapping_profile("Swap");
let (with, info) = crate::files::load_bytes_with(&dng, 64, Some(&p)).unwrap();
let (a, b) = (mean_rgb(&plain), mean_rgb(&with));
assert!((a[0] - b[0]).abs() > 1e-3 || (a[2] - b[2]).abs() > 1e-3, "the profile changes the colour: {a:?} vs {b:?}");
// white balance at render time works from the profile's matrices
let tags = &info.camera_color.as_ref().expect("a matrix colour model").tags;
assert_eq!(tags.color_matrix, p.color.color_matrix);
assert_ne!(plain_info.camera_color.as_ref().map(|c| c.tags.color_matrix), Some(p.color.color_matrix));
}
#[test]
fn a_profile_without_a_tone_curve_keeps_the_photos_contrast() {
use lightcraft_raw::profile::ToneCurve;
// a DNG with a tone curve of its own (our numbers: 18 % grey → 30 %)
let plain = crate::tests_xmp::synthetic_dng_with(None, Default::default());
let mut raw = lightcraft_raw::decode(&plain).unwrap();
raw.color.profile.tone_curve = ToneCurve::from_tag(&[0.0, 0.0, 0.18, 0.3, 1.0, 1.0]);
let dng = lightcraft_raw::write_dng(&raw, &Default::default()).unwrap();
// a chart-style profile (no curve) keeps the file's curve
let (_, info) = crate::files::load_bytes_with(&dng, 64, Some(&swapping_profile("Swap"))).unwrap();
let tone = info.camera_tone.expect("the file's tone curve stays");
assert!((tone.apply(0.18) - 0.3).abs() < 0.01, "{}", tone.apply(0.18));
// a profile with a curve of its own uses that one (18 % → 45 %)
let mut curved = swapping_profile("Curved");
curved.color.profile.tone_curve = ToneCurve::from_tag(&[0.0, 0.0, 0.18, 0.45, 1.0, 1.0]);
let (_, info) = crate::files::load_bytes_with(&dng, 64, Some(&curved)).unwrap();
let tone = info.camera_tone.expect("the profile's tone curve");
assert!((tone.apply(0.18) - 0.45).abs() < 0.01, "{}", tone.apply(0.18));
}
#[test]
fn import_choose_cache_persist_and_delete() {
let dir = temp_dir("session");
let (lib, files) = (dir.join("lib"), dir.join("files"));
std::fs::create_dir_all(files.join("profiles")).unwrap();
let raw = files.join("IMG_0001.dng");
std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap();
std::fs::write(files.join("profiles").join("Swap.dcp"), write_dcp(&swapping_profile("Swap")).unwrap()).unwrap();
std::fs::write(files.join("profiles").join("Broken.dcp"), b"IIRC\x08\0\0\0junk").unwrap();
let id;
let dcp_id;
{
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap();
id = PhotoId(r["imported"][0].as_u64().unwrap());
s.execute("library.select", &json!({"ids": [id.0]})).unwrap();
// a folder: the good profile comes in, the broken one is reported
let r = s.execute("profile.import", &json!({"paths": [files.join("profiles").to_string_lossy()]})).unwrap();
assert_eq!(r["imported"].as_array().unwrap().len(), 1, "{r}");
assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}");
dcp_id = r["imported"][0]["id"].as_str().unwrap().to_string();
assert!(dcp_id.starts_with("dcp:"));
assert_eq!(r["imported"][0]["cameraModel"], "LightCraft Test Camera");
// importing it again adds nothing
let again = s.execute("profile.import", &json!({"paths": [files.join("profiles").join("Swap.dcp").to_string_lossy()]})).unwrap();
assert_eq!(again["imported"][0]["existing"], true);
// a single .dcp file is a camera profile only, not also a LUT that "couldn't be read"
assert_eq!(again["failed"], json!([]), "{again}");
assert_eq!(s.dcp_profiles.len(), 1);
// the library keeps its own copy
assert!(std::path::Path::new(&s.dcp_profiles[0].file).starts_with(&lib));
// listed in the profile menu under Camera Profiles
let menu = s.profile_menu();
let group = menu["groups"].as_array().unwrap().iter().find(|g| g["name"] == "Camera Profiles").expect("a Camera Profiles group");
assert_eq!(group["profiles"][0]["id"], dcp_id.as_str());
// develop the photo with it: a decode made without it doesn't stand in
let before = s.render_job(id, 48, 48, false, true).unwrap().run();
let loaded = before.loaded.clone().expect("decoded from the file");
assert!(loaded.camera_profile.is_none());
s.media.insert(id, before.level, loaded.image.clone());
assert!(matches!(s.render_job(id, 48, 48, false, true).unwrap().source, SourceRef::Loaded(_)), "cached while nothing changed");
s.execute("develop.profile", &json!({"id": dcp_id})).unwrap();
let job = s.render_job(id, 48, 48, false, true).unwrap();
match &job.source {
SourceRef::File { camera_profile: Some((pid, _)), .. } => assert!(pid.starts_with(&format!("{dcp_id}#")), "{pid}"),
_ => panic!("the photo is decoded again with its camera profile"),
}
let after = job.run();
assert_eq!(
after.loaded.as_ref().and_then(|l| l.camera_profile.clone()),
s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0)
);
assert!(after.rendered.is_ok());
assert_ne!(mean_rgb(&before.loaded.unwrap().image), mean_rgb(&after.loaded.unwrap().image));
s.persist().unwrap();
s.close_library().unwrap();
}
// reopened: the profile is there and decodes again
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
assert_eq!(s.dcp_profiles.len(), 1);
assert!(s.media.camera_profiles.contains_key(&dcp_id));
assert_eq!(s.catalog.photo(id).unwrap().develop.profile.id, dcp_id);
assert_eq!(s.profile_info(&dcp_id).map(|(_, g)| g), Some("Camera Profiles"));
// deleted: photos using it develop with their file's own colour, the library's copy goes
let file = s.dcp_profiles[0].file.clone();
s.execute("profile.deleteImported", &json!({"id": dcp_id})).unwrap();
assert!(s.dcp_profiles.is_empty() && !std::path::Path::new(&file).exists());
let p = s.catalog.photo(id).unwrap().clone();
assert!(s.media.camera_profile_of(&p).is_none());
assert!(s.execute("develop.profile", &json!({"id": dcp_id})).is_err(), "no longer a known profile");
let _ = std::fs::remove_dir_all(&dir);
}
/// Hovering a camera profile (the loupe's preview, the browser's thumbnails) develops the photo with
/// it, and hovering a built-in profile while one is applied develops without it. Before, both used
/// the photo's own decode: a camera profile's colour never showed in a hover.
#[test]
fn hover_previews_and_browser_thumbnails_decode_with_the_hovered_camera_profile() {
let dir = temp_dir("hover");
let (lib, files) = (dir.join("lib"), dir.join("files"));
std::fs::create_dir_all(&files).unwrap();
let raw = files.join("IMG_0002.dng");
std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap();
let dcp_file = files.join("Swap.dcp");
std::fs::write(&dcp_file, write_dcp(&swapping_profile("Swap")).unwrap()).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap();
let id = PhotoId(r["imported"][0].as_u64().unwrap());
s.execute("library.select", &json!({"ids": [id.0]})).unwrap();
let dcp_id =
s.execute("profile.import", &json!({"paths": [dcp_file.to_string_lossy()]})).unwrap()["imported"][0]["id"].as_str().unwrap().to_string();
let mean = |j: crate::media::RenderJob| {
let img = j.run().rendered.unwrap().image;
let n = img.data.len().max(1) as f64;
img.data.iter().fold([0.0f64; 3], |a, p| [a[0] + f64::from(p[0]) / n, a[1] + f64::from(p[1]) / n, a[2] + f64::from(p[2]) / n])
};
let differ = |a: [f64; 3], b: [f64; 3]| a.iter().zip(b).any(|(x, y)| (x - y).abs() > 2.0);
let close = |a: [f64; 3], b: [f64; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.6);
let own = (*s.develop_of(id).unwrap()).clone();
let mut hovered = own.clone();
hovered.profile.id = dcp_id.clone();
let builtin = mean(s.render_job(id, 64, 64, false, true).unwrap());
let hover = mean(s.preview_job(id, 64, 64, true, &hovered).unwrap());
assert!(differ(hover, builtin), "the hover shows the camera profile: {hover:?} vs {builtin:?}");
// the browser's thumbnail too, under its own cache key
let (va, vb) = (s.variant_job(id, &own, 64).unwrap(), s.variant_job(id, &hovered, 64).unwrap());
assert_ne!(va.cache.as_ref().unwrap().1, vb.cache.as_ref().unwrap().1);
assert!(matches!(&vb.source, SourceRef::File { camera_profile: Some(_), .. }), "decoded with the camera profile");
assert!(differ(mean(va), mean(vb)));
// selected: the same picture as the hover; hovering the built-in profile then: without it
s.execute("develop.profile", &json!({"id": dcp_id})).unwrap();
let selected = mean(s.render_job(id, 64, 64, false, true).unwrap());
assert!(close(hover, selected), "{hover:?} vs {selected:?}");
let back = mean(s.preview_job(id, 64, 64, true, &own).unwrap());
assert!(close(back, builtin), "{back:?} vs {builtin:?}");
// the profile's file replaced under the same id: the hover's key changes with it, so the old picture isn't
// taken for current (CodeRabbit on #1063)
let before = s.preview_job(id, 64, 64, true, &hovered).unwrap().key;
s.media.camera_profiles.get_mut(&dcp_id).unwrap().fingerprint ^= 0x10;
assert_ne!(s.preview_job(id, 64, 64, true, &hovered).unwrap().key, before);
let _ = std::fs::remove_dir_all(&dir);
}
/// A library with one raw photo and the `Swap` profile imported from `files/<sub>/Swap.dcp` and selected for it.
fn library_with_profile(dir: &std::path::Path) -> (Session, PhotoId, String) {
let (lib, files) = (dir.join("lib"), dir.join("files"));
std::fs::create_dir_all(files.join("a")).unwrap();
let raw = files.join("IMG_0003.dng");
std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap();
std::fs::write(files.join("a").join("Swap.dcp"), write_dcp(&swapping_profile("Swap")).unwrap()).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
let r = s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap();
let id = PhotoId(r["imported"][0].as_u64().unwrap());
s.execute("library.select", &json!({"ids": [id.0]})).unwrap();
let r = s.execute("profile.import", &json!({"paths": [files.join("a").join("Swap.dcp").to_string_lossy()]})).unwrap();
let dcp_id = r["imported"][0]["id"].as_str().unwrap().to_string();
s.execute("develop.profile", &json!({"id": dcp_id})).unwrap();
(s, id, dcp_id)
}
/// The thumbnail, browser-thumbnail and loupe cache keys of photo `id` (as it is now), and its source tag.
fn render_keys(s: &mut Session, id: PhotoId) -> [lightcraft_preview::Hash128; 3] {
let settings = (*s.develop_of(id).unwrap()).clone();
[
s.thumb_job(id, 256).unwrap().cache.unwrap().1,
s.variant_job(id, &settings, 64).unwrap().cache.unwrap().1,
s.loupe_job(id, 200, 200, true).unwrap().view_cache.unwrap().1,
]
}
/// A camera profile deleted, or replaced by a different file under the same id, never has renders or decoded
/// sources made with the old one stand in: before, the cache keys followed only the profile id, which the photo keeps.
#[test]
fn a_deleted_or_replaced_camera_profile_never_reuses_renders_made_with_it() {
let dir = temp_dir("replace");
let (mut s, id, dcp_id) = library_with_profile(&dir);
let with = render_keys(&mut s, id);
let level = s.render_job(id, 48, 48, false, true).unwrap().level;
let old_tag = s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0);
assert!(old_tag.is_some());
// deleted: the photo keeps the id, renders without the profile, under other keys
s.execute("profile.deleteImported", &json!({"id": dcp_id})).unwrap();
assert_eq!(s.catalog.photo(id).unwrap().develop.profile.id, dcp_id);
let without = render_keys(&mut s, id);
for (a, b) in with.iter().zip(&without) {
assert_ne!(a, b, "a render made with the deleted profile would stand in");
}
// another profile under the same file name gets the same id back, and other keys again
let other_dir = dir.join("files").join("b");
std::fs::create_dir_all(&other_dir).unwrap();
let mut other = swapping_profile("Swap");
other.color.color_matrix = [Some(Mat3([[3.2406, -1.5372, -0.4986], [-0.9689, 1.8758, 0.0415], [0.0557, -0.2040, 1.0570]])), None];
std::fs::write(other_dir.join("Swap.dcp"), write_dcp(&other).unwrap()).unwrap();
let r = s.execute("profile.import", &json!({"paths": [other_dir.join("Swap.dcp").to_string_lossy()]})).unwrap();
assert_eq!(r["imported"][0]["id"], dcp_id.as_str(), "{r}");
let replaced = render_keys(&mut s, id);
for ((a, b), c) in with.iter().zip(&without).zip(&replaced) {
assert_ne!(a, c, "a render made with the replaced profile would stand in");
assert_ne!(b, c);
}
// nor does a source decoded with the old file
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4));
s.media.insert_source(id, level, crate::media::DecodedSource { camera_profile: old_tag, ..crate::media::DecodedSource::new(img, None) });
assert!(!matches!(s.render_job(id, 48, 48, false, true).unwrap().source, SourceRef::Loaded(_)), "decoded again with the new file");
let _ = std::fs::remove_dir_all(&dir);
}
/// A grid thumbnail is cut from the photo's decoded preview only when that preview was decoded with the camera profile
/// the photo uses now; before, one made with another profile (or none) was fitted and cached under the new key.
#[test]
fn a_thumbnail_is_not_cut_from_a_preview_decoded_with_another_camera_profile() {
let dir = temp_dir("fit");
let (mut s, id, _) = library_with_profile(&dir);
let p = (**s.catalog.photo(id).unwrap()).clone();
let tag = s.media.camera_profile_of(&p).map(|c| c.0);
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(1600, 1000));
let preview = |camera_profile| crate::media::DecodedSource { camera_profile, ..crate::media::DecodedSource::new(img.clone(), None) };
use crate::media::SourceLevel;
s.media.insert_source(id, SourceLevel::Preview, preview(None));
assert!(!matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "decoded without the profile");
s.media.insert_source(id, SourceLevel::Preview, preview(tag));
assert!(matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "decoded with it: still cut from it");
let _ = std::fs::remove_dir_all(&dir);
}
/// A library moved (or restored) elsewhere finds its camera profiles in its own `Profiles/` folder, and a camera
/// profile can be a favourite, which survives reopening like the recent list.
#[test]
fn a_moved_library_keeps_its_camera_profiles_and_their_favourites() {
let dir = temp_dir("moved");
let (mut s, id, dcp_id) = library_with_profile(&dir);
assert_eq!(s.execute("profile.favorite", &json!({"id": dcp_id})).unwrap()["favorite"], true);
assert!(s.profile_recent.contains(&dcp_id));
s.persist().unwrap();
s.close_library().unwrap();
drop(s);
let moved = dir.join("moved");
std::fs::rename(dir.join("lib"), &moved).unwrap();
let mut s = Session::new().with_fs();
s.open_library(&moved, false).unwrap();
assert!(s.media.camera_profiles.contains_key(&dcp_id), "the profile is found in the moved library");
assert!(std::path::Path::new(&s.dcp_profiles[0].file).starts_with(&moved), "{}", s.dcp_profiles[0].file);
assert!(s.media.camera_profile_of(s.catalog.photo(id).unwrap()).is_some());
assert!(s.profile_favorites.contains(&dcp_id) && s.profile_recent.contains(&dcp_id));
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
fn distance(a: [f32; 3], b: [f32; 3]) -> f32 {
(0..3).map(|i| (a[i] - b[i]).abs()).sum()
}
/// A smart preview keeps the file's own colour: Build Smart Previews never develops it with the photo's imported
/// camera profile, nor takes a cached source decoded with it. Before, only the stale-proxy refresh left the profile out.
#[test]
fn smart_previews_are_built_without_the_imported_camera_profile() {
use crate::media::{DecodedSource, SourceLevel};
let dir = temp_dir("smart");
let (mut s, id, _) = library_with_profile(&dir);
let p = (**s.catalog.photo(id).unwrap()).clone();
s.execute("library.smartPreviews", &json!({"ids": [id.0], "discard": true})).unwrap();
// a cached preview decoded with the profile (flat magenta, so it shows if the proxy is cut from it)
let tag = s.media.camera_profile_of(&p).map(|c| c.0);
let mut magenta = lightcraft_raster::Rgb32f::new(8, 8);
magenta.data.iter_mut().for_each(|px| *px = [1.0, 0.0, 1.0]);
s.media.insert_source(id, SourceLevel::Preview, DecodedSource { camera_profile: tag, ..DecodedSource::new(std::sync::Arc::new(magenta), None) });
let r = s.execute("library.smartPreviews", &json!({"ids": [id.0]})).unwrap();
assert_eq!((r["built"].as_u64(), r["repaired"].as_u64()), (Some(1), Some(0)), "{r}");
let smart_dir = s.media.smart_dir.clone().unwrap();
let proxy = crate::smart::load(&crate::smart::existing_file_path(&smart_dir, crate::smart::sharded_file_path(&smart_dir, &p))).unwrap();
let got = mean_rgb(&proxy.image);
let dng = std::fs::read(dir.join("files").join("IMG_0003.dng")).unwrap();
let edge = SourceLevel::Preview.max_edge();
let plain = mean_rgb(&crate::files::load_bytes(&dng, edge).unwrap().0);
let with = mean_rgb(&crate::files::load_bytes_with(&dng, edge, Some(&swapping_profile("Swap"))).unwrap().0);
assert!(distance(got, plain) < distance(got, with), "the proxy has the file's own colour: {got:?}, plain {plain:?}, profiled {with:?}");
// nor from the file developed with the profile
s.media.forget(id);
s.execute("library.smartPreviews", &json!({"ids": [id.0], "discard": true})).unwrap();
s.execute("library.smartPreviews", &json!({"ids": [id.0]})).unwrap();
let proxy = crate::smart::load(&crate::smart::existing_file_path(&smart_dir, crate::smart::sharded_file_path(&smart_dir, &p))).unwrap();
let got = mean_rgb(&proxy.image);
assert!(distance(got, plain) < distance(got, with), "the proxy has the file's own colour: {got:?}, plain {plain:?}, profiled {with:?}");
let _ = std::fs::remove_dir_all(&dir);
}
/// While the original is offline, a cached smart preview stands in for a photo developed with an imported camera
/// profile: it has no profile and decoding it again gives the same picture. Before, it was decoded again for every
/// render. Once the original is back, the photo is decoded from it with its profile.
#[test]
fn a_cached_smart_preview_stands_in_while_the_original_is_offline() {
use crate::media::{DecodedSource, SourceLevel, SourceRef};
let dir = temp_dir("proxy-offline");
let (mut s, id, _) = library_with_profile(&dir);
let p = (**s.catalog.photo(id).unwrap()).clone();
assert!(s.media.camera_profile_of(&p).is_some());
let proxy = DecodedSource { from_proxy: true, ..DecodedSource::new(std::sync::Arc::new(lightcraft_raster::Rgb32f::new(8, 8)), None) };
s.media.insert_source(id, SourceLevel::Preview, proxy);
let offline = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
let probe_offline = offline.clone();
s.media.availability.set_probe(std::sync::Arc::new(move |path: &str| {
!(path.ends_with("IMG_0003.dng") && probe_offline.load(std::sync::atomic::Ordering::Relaxed)) && std::path::Path::new(path).exists()
}));
assert!(matches!(s.media.source_ref(&p, SourceLevel::Preview), SourceRef::Loaded(a) if a.from_proxy), "the proxy stands in");
assert!(matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }), "the thumbnail is cut from it");
offline.store(false, std::sync::atomic::Ordering::Relaxed);
assert!(!matches!(s.media.source_ref(&p, SourceLevel::Preview), SourceRef::Loaded(_)), "the original is back: decoded with the profile");
assert!(!matches!(s.media.source_ref(&p, SourceLevel::Thumb), SourceRef::Fit { .. }));
let _ = std::fs::remove_dir_all(&dir);
}
/// The decoder facts reported for a photo come from a cached source developed with the camera profile it uses now;
/// before, a thumbnail decoded with another profile (or none) answered first.
#[test]
fn source_facts_come_from_a_source_developed_with_the_current_camera_profile() {
use crate::media::{DecodedSource, SourceLevel};
let dir = temp_dir("facts");
let (mut s, id, _) = library_with_profile(&dir);
let tag = s.media.camera_profile_of(s.catalog.photo(id).unwrap()).map(|c| c.0);
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4));
let facts = |temp: f64, camera_profile| DecodedSource {
camera_profile,
..DecodedSource::new(img.clone(), Some(lightcraft_pipeline::SourceInfo { as_shot_temp: temp, ..Default::default() }))
};
s.media.insert_source(id, SourceLevel::Thumb, facts(3100.0, None));
s.media.insert_source(id, SourceLevel::Preview, facts(6200.0, tag));
assert_eq!(s.source_info(id).as_shot_temp, 6200.0);
let _ = std::fs::remove_dir_all(&dir);
}
/// The Before side (and its region renders) decodes with the Before settings' camera profile — here none, the
/// import defaults — not with the edit's: before, it reused or decoded a source developed with the edit's profile.
#[test]
fn the_before_side_decodes_with_its_own_camera_profile() {
use crate::media::{DecodedSource, SourceLevel};
let dir = temp_dir("before");
let (mut s, id, _) = library_with_profile(&dir);
let camera = |job: &crate::media::RenderJob| match &job.source {
SourceRef::File { camera_profile, .. } => camera_profile.as_ref().map(|c| c.0.clone()),
SourceRef::Loaded(a) => a.camera_profile.clone(),
_ => None,
};
s.media.forget(id);
let after = s.render_job(id, 256, 256, false, true).unwrap();
let tag = camera(&after);
assert!(tag.is_some(), "the edit develops with the imported profile");
let before = s.render_job(id, 256, 256, true, true).unwrap();
assert_eq!(camera(&before), None, "the Before side develops with the file's own colour");
// nor does a cached source developed with the edit's profile stand in for it
for level in [SourceLevel::Thumb, SourceLevel::Preview, SourceLevel::Full] {
let img = std::sync::Arc::new(lightcraft_raster::Rgb32f::new(4, 4));
s.media.insert_source(id, level, DecodedSource { camera_profile: tag.clone(), ..DecodedSource::new(img, None) });
}
let before = s.render_job(id, 256, 256, true, true).unwrap();
assert!(!matches!(before.source, SourceRef::Loaded(_)), "the Before side is decoded afresh");
assert_eq!(camera(&before), None);
let _ = std::fs::remove_dir_all(&dir);
}
/// A profile whose copy into the library fails is reported as failed on its own: the profiles imported with
/// it stay imported (and are saved), and the command does not fail.
#[test]
fn a_profile_that_cannot_be_copied_fails_on_its_own() {
let dir = temp_dir("copy-fails");
let (lib, files) = (dir.join("lib"), dir.join("files"));
std::fs::create_dir_all(&files).unwrap();
for name in ["A", "B"] {
std::fs::write(files.join(format!("{name}.dcp")), write_dcp(&swapping_profile(name)).unwrap()).unwrap();
}
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
// a folder where B's copy goes: writing it fails
let blocked = lib.join("Profiles").join(format!("{}.dcp", crate::presets::slug("LightCraft Test Camera-B")));
std::fs::create_dir_all(&blocked).unwrap();
let r = s.execute("profile.import", &json!({"paths": [files.to_string_lossy()]})).unwrap();
let imported: Vec<&str> = r["imported"].as_array().unwrap().iter().filter_map(|p| p["name"].as_str()).collect();
assert_eq!(imported, ["A"], "{r}");
let failed = r["failed"].as_array().unwrap();
assert_eq!(failed.len(), 1, "{r}");
assert!(failed[0][0].as_str().is_some_and(|f| f.ends_with("B.dcp")), "{r}");
assert_eq!(s.dcp_profiles.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["A"]);
assert!(blocked.is_dir(), "the folder in the way is left alone");
let _ = std::fs::remove_dir_all(&dir);
}
/// A file that is neither a `.cube`, a `.dcp` nor a `.zip` is reported as failed instead of being passed over.
#[test]
fn importing_an_unsupported_profile_file_reports_it() {
let dir = temp_dir("unsupported");
let notes = dir.join("notes.txt");
std::fs::write(&notes, "not a profile").unwrap();
let mut s = Session::new();
let r = s.execute("profile.import", &json!({"paths": [notes.to_string_lossy()]})).unwrap();
assert_eq!(r["imported"].as_array().map(Vec::len), Some(0), "{r}");
assert_eq!(r["failed"], json!([["notes", "not a .cube, .dcp or .zip file"]]), "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A library copy that can't be removed keeps its profile: the command fails and nothing is forgotten, so the
/// library never holds a profile file it no longer lists (CodeRabbit on #1063).
#[test]
fn a_profile_whose_copy_cannot_be_deleted_stays() {
let dir = temp_dir("delete-fails");
let (mut s, _, dcp_id) = library_with_profile(&dir);
let file = s.dcp_profiles.iter().find(|p| p.id == dcp_id).map(|p| PathBuf::from(&p.file)).unwrap();
// a folder in the copy's place: removing it as a file fails (as a file in use does)
std::fs::remove_file(&file).unwrap();
std::fs::create_dir_all(&file).unwrap();
let r = s.execute("profile.deleteCamera", &json!({"id": dcp_id}));
assert!(r.is_err(), "{r:?}");
assert!(s.dcp_profiles.iter().any(|p| p.id == dcp_id), "the profile is still listed");
// gone already: deleting just forgets it
std::fs::remove_dir_all(&file).unwrap();
s.execute("profile.deleteCamera", &json!({"id": dcp_id})).unwrap();
assert!(s.dcp_profiles.iter().all(|p| p.id != dcp_id));
let _ = std::fs::remove_dir_all(&dir);
}
/// A listed path that climbs out of the profiles folder with `..` is not the library's copy: deleting the profile
/// leaves that file alone (CodeRabbit on #1063).
#[test]
fn deleting_a_profile_never_follows_dot_dot_out_of_the_profiles_folder() {
let dir = temp_dir("delete-dotdot");
let (mut s, _, dcp_id) = library_with_profile(&dir);
let entry = s.dcp_profiles.iter_mut().find(|p| p.id == dcp_id).unwrap();
let profiles = PathBuf::from(&entry.file).parent().unwrap().to_path_buf();
let outside = profiles.parent().unwrap().join("keep.txt");
std::fs::write(&outside, b"the user's").unwrap();
entry.file = profiles.join("..").join("keep.txt").to_string_lossy().into_owned();
s.execute("profile.deleteCamera", &json!({"id": dcp_id})).unwrap();
assert!(s.dcp_profiles.iter().all(|p| p.id != dcp_id), "forgotten");
assert!(outside.exists(), "the file outside the profiles folder stays");
let _ = std::fs::remove_dir_all(&dir);
}
/// CodeRabbit on #1063: a camera profile whose library copy is missing or damaged when the library opens stayed in the
/// profile browser and `develop.profile` accepted it, and the photo then silently developed with the raw's own
/// colour. It is no longer offered or accepted; its entry stays, and once the file is back it is offered again.
#[test]
fn a_damaged_camera_profile_is_not_offered_until_its_file_is_back() {
let dir = temp_dir("damaged");
let (mut s, _id, dcp_id) = library_with_profile(&dir);
let file = std::path::PathBuf::from(&s.dcp_profiles[0].file);
s.persist().unwrap();
s.close_library().unwrap();
drop(s);
let good = std::fs::read(&file).unwrap();
std::fs::write(&file, b"not a profile").unwrap();
let mut s = Session::new().with_fs();
s.open_library(dir.join("lib"), false).unwrap();
assert_eq!(s.dcp_profiles.len(), 1, "the entry stays");
assert!(!s.imported_profiles().iter().any(|p| p.0 == dcp_id), "not offered");
let menu = s.profile_menu().to_string();
assert!(!menu.contains(&dcp_id), "not in the profile menu: {menu}");
assert!(s.execute("develop.profile", &json!({"id": dcp_id})).is_err(), "not accepted");
s.close_library().unwrap();
drop(s);
std::fs::write(&file, good).unwrap();
let mut s = Session::new().with_fs();
s.open_library(dir.join("lib"), false).unwrap();
assert!(s.imported_profiles().iter().any(|p| p.0 == dcp_id), "offered again");
s.execute("develop.profile", &json!({"id": dcp_id})).unwrap();
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// CodeRabbit on #1063: a LUT profile group named like the camera profiles' ("Camera Profiles") that doesn't sort last
/// made the profile menu list that group twice, each with the same profiles. It is one group, last.
#[test]
fn a_lut_group_named_camera_profiles_joins_the_camera_profiles_group() {
let dir = temp_dir("group");
let (mut s, _id, dcp_id) = library_with_profile(&dir);
for (id, group) in [("lut:a", crate::cmd::dcp_profiles::DCP_GROUP), ("lut:z", "Zebra")] {
s.lut_profiles.push(crate::cmd::lut_profiles::LutProfile { id: id.into(), name: id.into(), group: group.into(), file: String::new() });
}
let menu = s.profile_menu();
let groups: Vec<&str> = menu["groups"].as_array().unwrap().iter().filter_map(|g| g["name"].as_str()).collect();
assert_eq!(groups.iter().filter(|g| **g == crate::cmd::dcp_profiles::DCP_GROUP).count(), 1, "{groups:?}");
assert_eq!(groups.last(), Some(&crate::cmd::dcp_profiles::DCP_GROUP), "{groups:?}");
let ids: Vec<&str> = menu["groups"]
.as_array()
.unwrap()
.iter()
.filter(|g| g["name"] == crate::cmd::dcp_profiles::DCP_GROUP)
.flat_map(|g| g["profiles"].as_array().unwrap().iter().filter_map(|p| p["id"].as_str()))
.collect();
assert!(ids.contains(&"lut:a") && ids.contains(&dcp_id.as_str()), "{ids:?}");
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// A `.dcp` file larger than the parser accepts is refused while it is read, before the whole file is loaded into
/// memory (CodeRabbit on #1063): the import reports it as failed with its own reason.
#[test]
fn an_oversized_camera_profile_is_refused_while_it_is_read() {
let dir = temp_dir("oversized");
let big = dir.join("Big.dcp");
let mut bytes = write_dcp(&swapping_profile("Big")).unwrap();
bytes.truncate(4);
std::fs::write(&big, &bytes).unwrap();
std::fs::OpenOptions::new().write(true).open(&big).unwrap().set_len(lightcraft_raw::dcp::MAX_DCP_BYTES + 1).unwrap();
let mut s = Session::new();
let r = s.execute("profile.import", &json!({"paths": [big.to_string_lossy()]})).unwrap();
assert_eq!(r["imported"], json!([]), "{r}");
assert_eq!(r["failed"][0][1], json!("the camera profile is larger than 64 MiB"), "{r}");
let _ = std::fs::remove_dir_all(&dir);
}
+243
View File
@@ -0,0 +1,243 @@
//! A real camera profile end to end: the Nikon D750 ColorChecker DCP and chart NEFs dieli released
//! under CC0 (github.com/dieli/d750-lightcraft-colorchecker, pinned in `D750_COLORCHECKER`,
//! xtask/src/main.rs; `cargo xtask corpus --download`). Each chart is imported, developed with the
//! imported profile, white balanced on the second-lightest grey patch (as in the reference) and
//! exported as sRGB; the 24 patches are then compared in CIELAB (ΔE2000) with Lightroom Classic
//! 15.6's render of the same NEF with the same profile.
//!
//! The comparison is lenient on purpose: the profile is matrix-only, so the colour model is the same,
//! but Lightroom adds its own default tone curve and rendering, which LightCraft does not copy. The
//! test pins the measured agreement against regressions (see `MEAN_LIMIT`, `MAX_LIMIT`) and prints
//! every patch's ΔE. Missing files are reported as skipped.
use std::path::{Path, PathBuf};
use lightcraft_catalog::PhotoId;
use serde_json::json;
use crate::Session;
use crate::export::{ExportOptions, export_photo};
/// Upper bounds for the mean and the largest patch ΔE2000 against Lightroom. Measured when this test
/// was written (2026-10-22): daylight/flash mean 3.84, max 7.77 (patch 16, yellow); indoor mean 3.35,
/// max 5.24 (patch 13, blue). The grey row agrees within about 1-3; the colour patches come out less
/// saturated than Lightroom's (its own rendering on top of the profile), which is most of the rest.
const MEAN_LIMIT: f64 = 5.0;
const MAX_LIMIT: f64 = 10.0;
fn set_dir() -> PathBuf {
std::env::var_os("LIGHTCRAFT_CORPUS")
.map(PathBuf::from)
.unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"))
.join("d750-colorchecker")
}
/// Patch centres (row-major, normalized x, y) in Lightroom's render of each chart, a crop around the
/// ColorChecker. Row 4 is the grey row, white to black.
fn reference_centres(chart: &str) -> Vec<(f64, f64)> {
let (xs, ys): (&[f64], &[f64]) = if chart.contains("indoor") {
(&[193.0, 361.0, 527.0, 692.0, 857.0, 1022.0], &[152.0, 318.0, 486.0, 660.0])
} else {
(&[197.0, 378.0, 555.0, 731.0, 906.0, 1080.0], &[135.0, 312.0, 490.0, 668.0])
};
ys.iter().flat_map(|y| xs.iter().map(move |x| (x / 1200.0, y / 801.0))).collect()
}
/// The same patches in the whole NEF frame (our export, uncropped), read off a 1200 × 802 render.
fn frame_centres(chart: &str) -> Vec<(f64, f64)> {
let (xs, ys): (&[f64], &[f64]) = if chart.contains("indoor") {
(&[468.0, 528.0, 587.0, 645.0, 704.0, 765.0], &[527.0, 585.0, 644.0, 705.0])
} else {
(&[462.0, 512.0, 560.0, 609.0, 658.0, 706.0], &[381.0, 430.0, 479.0, 529.0])
};
ys.iter().flat_map(|y| xs.iter().map(move |x| (x / 1200.0, y / 802.0))).collect()
}
/// Mean CIELAB (D50) of a box of half-width `radius` (a fraction of the image width) around each
/// centre, and the largest standard deviation of L* inside a box (a box on a patch edge shows up there).
fn patch_labs(bytes: &[u8], centres: &[(f64, f64)], radius: f64) -> (Vec<[f64; 3]>, f64) {
let d = lightcraft_codecs::decode(bytes, Default::default()).unwrap();
let to_xyz = d.space.to_xyz_d50;
let (w, h) = (d.image.width, d.image.height);
let r = (w as f64 * radius).max(1.0) as isize;
let mut worst = 0.0f64;
let labs = centres
.iter()
.map(|&(x, y)| {
let (cx, cy) = ((x * w as f64) as isize, (y * h as f64) as isize);
let (mut acc, mut ls) = ([0.0f64; 3], Vec::new());
for yy in (cy - r).max(0)..(cy + r).min(h as isize) {
for xx in (cx - r).max(0)..(cx + r).min(w as isize) {
let p = d.image.data[yy as usize * w + xx as usize];
let rgb = [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])];
for (a, v) in acc.iter_mut().zip(rgb) {
*a += v;
}
ls.push(lab(to_xyz.apply(rgb))[0]);
}
}
let n = ls.len().max(1) as f64;
let mean_l = ls.iter().sum::<f64>() / n;
worst = worst.max((ls.iter().map(|l| (l - mean_l).powi(2)).sum::<f64>() / n).sqrt());
lab(to_xyz.apply(acc.map(|v| v / n)))
})
.collect();
(labs, worst)
}
fn lab(xyz: [f64; 3]) -> [f64; 3] {
let white = [0.9642, 1.0, 0.8249];
let f = |t: f64| if t > 216.0 / 24389.0 { t.cbrt() } else { (24389.0 / 27.0 * t + 16.0) / 116.0 };
let [fx, fy, fz] = [f(xyz[0] / white[0]), f(xyz[1] / white[1]), f(xyz[2] / white[2])];
[116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]
}
/// CIEDE2000 (Sharma, Wu and Dalal 2005).
fn de2000(a: [f64; 3], b: [f64; 3]) -> f64 {
use std::f64::consts::PI;
let (l1, a1, b1, l2, a2, b2) = (a[0], a[1], a[2], b[0], b[1], b[2]);
let c_bar = ((a1 * a1 + b1 * b1).sqrt() + (a2 * a2 + b2 * b2).sqrt()) / 2.0;
let g = 0.5 * (1.0 - (c_bar.powi(7) / (c_bar.powi(7) + 25f64.powi(7))).sqrt());
let (a1p, a2p) = ((1.0 + g) * a1, (1.0 + g) * a2);
let (c1p, c2p) = ((a1p * a1p + b1 * b1).sqrt(), (a2p * a2p + b2 * b2).sqrt());
let hue = |b: f64, a: f64| if b == 0.0 && a == 0.0 { 0.0 } else { b.atan2(a).rem_euclid(2.0 * PI) };
let (h1p, h2p) = (hue(b1, a1p), hue(b2, a2p));
let dl = l2 - l1;
let dc = c2p - c1p;
let dh = if c1p * c2p == 0.0 {
0.0
} else {
let d = h2p - h1p;
if d.abs() <= PI {
d
} else if d > PI {
d - 2.0 * PI
} else {
d + 2.0 * PI
}
};
let dhh = 2.0 * (c1p * c2p).sqrt() * (dh / 2.0).sin();
let l_bar = (l1 + l2) / 2.0;
let cp_bar = (c1p + c2p) / 2.0;
let hp_bar = if c1p * c2p == 0.0 {
h1p + h2p
} else if (h1p - h2p).abs() <= PI {
(h1p + h2p) / 2.0
} else if h1p + h2p < 2.0 * PI {
(h1p + h2p + 2.0 * PI) / 2.0
} else {
(h1p + h2p - 2.0 * PI) / 2.0
};
let t = 1.0 - 0.17 * (hp_bar - PI / 6.0).cos() + 0.24 * (2.0 * hp_bar).cos() + 0.32 * (3.0 * hp_bar + PI / 30.0).cos()
- 0.20 * (4.0 * hp_bar - 63.0 * PI / 180.0).cos();
let d_theta = 30.0 * (-(((hp_bar * 180.0 / PI) - 275.0) / 25.0).powi(2)).exp();
let rc = 2.0 * (cp_bar.powi(7) / (cp_bar.powi(7) + 25f64.powi(7))).sqrt();
let sl = 1.0 + 0.015 * (l_bar - 50.0).powi(2) / (20.0 + (l_bar - 50.0).powi(2)).sqrt();
let sc = 1.0 + 0.045 * cp_bar;
let sh = 1.0 + 0.015 * cp_bar * t;
let rt = -(2.0 * d_theta * PI / 180.0).sin() * rc;
((dl / sl).powi(2) + (dc / sc).powi(2) + (dhh / sh).powi(2) + rt * (dc / sc) * (dhh / sh)).sqrt()
}
#[test]
fn de2000_matches_the_published_test_pairs() {
// Sharma, Wu and Dalal (2005), table 1: pairs 1, 7 and 17
let cases = [
([50.0, 2.6772, -79.7751], [50.0, 0.0, -82.7485], 2.0425),
([50.0, 0.0, 0.0], [50.0, -1.0, 2.0], 2.3669),
([50.0, 2.5, 0.0], [73.0, 25.0, -18.0], 27.1492),
];
for (a, b, e) in cases {
assert!((de2000(a, b) - e).abs() < 1e-3, "{a:?} {b:?}: {} vs {e}", de2000(a, b));
}
}
#[test]
fn the_d750_profile_develops_its_charts_close_to_lightroom() {
let set = set_dir();
let dcp = set.join("profiles/20261016_NikonD750_DualIllumination_ColorCheckerPassport.dcp");
let charts = [("daylight_flash", "raw/chart-daylight_flash.NEF"), ("indoor", "raw/chart-indoor.NEF")];
let mut needed = vec![dcp.clone()];
for (name, raw) in charts {
needed.push(set.join(raw));
needed.push(set.join(format!("images/{name}-lightroom.jpg")));
}
if let Some(missing) = needed.iter().find(|p| !p.exists()) {
lightcraft_testkit::skip!(Corpus, "{} absent (cargo xtask corpus --download)", missing.display());
return;
}
let lib = std::env::temp_dir().join(format!("lc-dcp-d750-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&lib);
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
let r = s.execute("profile.import", &json!({"paths": [dcp.to_string_lossy()]})).unwrap();
let dcp_id = r["imported"][0]["id"].as_str().expect("the D750 profile imports").to_string();
assert!(r["imported"][0]["cameraModel"].as_str().unwrap().contains("D750"), "{r}");
let o = ExportOptions::from_json(&json!({"format": "png", "longEdge": 1200, "colorSpace": "srgb"}));
let mut report = String::new();
let mut means = Vec::new();
for (name, raw) in charts {
let r = s.execute("library.import", &json!({"paths": [set.join(raw).to_string_lossy()]})).unwrap();
let id = PhotoId(r["imported"][0].as_u64().expect("the NEF imports"));
s.execute("library.select", &json!({"ids": [id.0]})).unwrap();
s.execute("develop.profile", &json!({"id": dcp_id})).unwrap();
let centres = frame_centres(name);
let (reference, spread) =
patch_labs(&std::fs::read(set.join(format!("images/{name}-lightroom.jpg"))).unwrap(), &reference_centres(name), 0.02);
assert!(spread < 4.0, "{name}: every reference box lies inside its patch (L* spread {spread:.1})");
// white balance on the second-lightest grey (patch 20), as the reference was made
let wb = s.execute("develop.wbPick", &json!({"x": centres[19].0, "y": centres[19].1})).unwrap();
// exposure: the value whose grey row is closest to the reference's (golden-section search)
let render = |s: &mut Session, ev: f64| {
s.execute("develop.set", &json!({"control": "light.exposure", "value": ev})).unwrap();
let e = export_photo(s, id, &o, 1).expect("the chart develops with the D750 profile");
patch_labs(&e.bytes, &centres, 0.006)
};
let grey_de = |(labs, _): &(Vec<[f64; 3]>, f64)| (18..24).map(|i| de2000(labs[i], reference[i])).sum::<f64>() / 6.0;
let (mut lo, mut hi) = (-1.5f64, 1.5f64);
let phi = (5f64.sqrt() - 1.0) / 2.0;
let (mut m1, mut m2) = (hi - phi * (hi - lo), lo + phi * (hi - lo));
let (mut f1, mut f2) = (grey_de(&render(&mut s, m1)), grey_de(&render(&mut s, m2)));
for _ in 0..8 {
if f1 < f2 {
(hi, m2, f2) = (m2, m1, f1);
m1 = hi - phi * (hi - lo);
f1 = grey_de(&render(&mut s, m1));
} else {
(lo, m1, f1) = (m1, m2, f2);
m2 = lo + phi * (hi - lo);
f2 = grey_de(&render(&mut s, m2));
}
}
let ev = (lo + hi) / 2.0;
let (ours, spread) = render(&mut s, ev);
assert!(spread < 4.0, "{name}: every box lies inside its patch (L* spread {spread:.1})");
// LIGHTCRAFT_DCP_DUMP=<folder>: keep our renders, to check the patch boxes by eye
if let Some(dir) = std::env::var_os("LIGHTCRAFT_DCP_DUMP") {
s.execute("develop.set", &json!({"control": "light.exposure", "value": ev})).unwrap();
let _ = std::fs::write(Path::new(&dir).join(format!("{name}.png")), export_photo(&mut s, id, &o, 1).unwrap().bytes);
}
let des: Vec<f64> = ours.iter().zip(&reference).map(|(a, b)| de2000(*a, *b)).collect();
let mean = des.iter().sum::<f64>() / des.len() as f64;
let max = des.iter().cloned().fold(0.0, f64::max);
report += &format!("{name}: wb {} K / tint {}, exposure {ev:+.2}, mean ΔE2000 {mean:.2}, max {max:.2}\n", wb["temp"], wb["tint"]);
for (i, d) in des.iter().enumerate() {
report += &format!(
" patch {:2}: ΔE {d:5.2} ours L*a*b* {:6.1} {:6.1} {:6.1} Lightroom {:6.1} {:6.1} {:6.1}\n",
i + 1,
ours[i][0],
ours[i][1],
ours[i][2],
reference[i][0],
reference[i][1],
reference[i][2]
);
}
means.push((name, mean, max));
}
eprintln!("{report}");
let _ = std::fs::remove_dir_all(&lib);
for (name, mean, max) in means {
assert!(mean < MEAN_LIMIT && max < MAX_LIMIT, "{name}: mean ΔE2000 {mean:.2}, max {max:.2}\n{report}");
}
}
+34
View File
@@ -189,6 +189,40 @@ fn presets_conflicts_and_subfolders() {
assert_eq!(written, ["out/Sub/LC01347.png"]);
}
/// Issue #2571: a subfolder with `..`, a root or a drive wrote outside the chosen folder. It is
/// cleaned where the folder is used, so a preset or the Export dialog's field (which set it
/// without `from_json`) are covered as well as command parameters.
#[test]
fn a_subfolder_never_leaves_the_destination_folder() {
use crate::export::{Destination, export_batch};
let mut s = Session::with_demo();
let id = s.active().unwrap();
let to = Destination { dir: "out".into(), exact: None };
let written_to = |s: &mut Session, sub: &str| {
let o = ExportOptions { subfolder: sub.into(), naming: "x".into(), ..ExportOptions::from_json(&json!({"format": "png", "width": 16})) };
let mut written: Vec<String> = Vec::new();
let mut write = |p: &str, _: &[u8]| {
written.push(p.to_string());
Ok(())
};
export_batch(s, &[id], &o, &to, &mut write, &|_| false).unwrap();
written
};
for (sub, want) in [
("../../escaped", "out/escaped/x.png"),
("..", "out/x.png"),
("/etc", "out/etc/x.png"),
("C:\\Windows", "out/C__Windows/x.png"),
("a/./b/../c", "out/a/b/c/x.png"),
(" Client / Jobs ", "out/Client/Jobs/x.png"),
] {
assert_eq!(written_to(&mut s, sub), [want], "{sub:?}");
}
// command parameters get the same cleaning
let o = ExportOptions::from_json(&json!({"subfolder": "../up"}));
assert_eq!(o.subfolder, "up");
}
#[test]
fn prepared_exports_run_on_another_thread() {
fn send<T: Send>(_: &T) {}
+2 -2
View File
@@ -91,9 +91,9 @@ fn count_loads(s: &mut Session) -> Loads {
let loads = Loads::default();
let file = s.media.file_loader.clone().unwrap();
let n = loads.files.clone();
s.media.file_loader = Some(Arc::new(move |p: &str, e: usize| {
s.media.file_loader = Some(Arc::new(move |p: &str, e: usize, dcp: Option<&crate::media::DcpProfile>| {
n.fetch_add(1, Ordering::SeqCst);
file(p, e)
file(p, e, dcp)
}));
let preview = s.media.preview_loader.clone().unwrap();
let n = loads.previews.clone();
+5 -5
View File
@@ -974,7 +974,7 @@ fn smart_previews_keep_the_decoder_facts_offline_edits_need() {
let mut s = Session::new().with_fs();
s.open_library(&lib, false).unwrap();
let (p, i) = (pixels.clone(), info.clone());
s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge| Ok((p.clone(), i.clone()))));
s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge, _| Ok((p.clone(), i.clone()))));
s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()]})).unwrap();
let id = s.active().unwrap();
let r = s.execute("library.smartPreviews", &json!({})).unwrap();
@@ -2107,9 +2107,9 @@ fn look_loader(
tone: lightcraft_pipeline::tone::CameraTone,
calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
) -> crate::media::FileLoader {
std::sync::Arc::new(move |path, max_edge| {
std::sync::Arc::new(move |path, max_edge, dcp| {
calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let (img, mut info) = plain(path, max_edge)?;
let (img, mut info) = plain(path, max_edge, dcp)?;
info.camera_tone = Some(tone);
Ok((img, info))
})
@@ -2277,7 +2277,7 @@ fn a_proxy_with_an_older_encoding_is_refreshed_without_the_camera_look() {
let pixels = lightcraft_raster::Rgb32f::from_fn(48, 32, |x, y| [0.02 + (x % 9) as f32 * 0.05, 0.03 + (y % 7) as f32 * 0.04, 0.06]);
let info = lightcraft_pipeline::SourceInfo { raw: true, as_shot_temp: 5200.0, as_shot_tint: 6.0, ..Default::default() };
let (p, i) = (pixels.clone(), info.clone());
s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge| Ok((p.clone(), i.clone()))));
s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge, _| Ok((p.clone(), i.clone()))));
s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()]})).unwrap();
let id = s.active().unwrap();
let mut raw = (**s.catalog.photo(id).unwrap()).clone();
@@ -2321,7 +2321,7 @@ fn a_stale_refresh_never_rebuilds_a_proxy_from_itself() {
let pixels = lightcraft_raster::Rgb32f::from_fn(48, 32, |x, y| [0.02 + (x % 9) as f32 * 0.05, 0.03 + (y % 7) as f32 * 0.04, 0.06]);
let info = lightcraft_pipeline::SourceInfo { raw: true, as_shot_temp: 5200.0, as_shot_tint: 6.0, ..Default::default() };
let (p, i) = (pixels.clone(), info.clone());
s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge| Ok((p.clone(), i.clone()))));
s.media.file_loader = Some(std::sync::Arc::new(move |_path, _max_edge, _| Ok((p.clone(), i.clone()))));
s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()]})).unwrap();
let id = s.active().unwrap();
// a raw that takes the per-file camera look, so an older fit makes its proxy stale
+1 -1
View File
@@ -237,7 +237,7 @@ fn a_new_database_profile_changes_the_render_and_cache_keys() {
let render = s.render_job(id, 800, 600, false, true).unwrap().key;
let thumb = s.thumb_job(id, 256).unwrap().cache.unwrap().1;
let p = s.catalog.photo(id).unwrap().clone();
(render, thumb, Session::variant_key(&p, &p.develop, 128), Session::view_key(&p, true))
(render, thumb, Session::variant_key(&p, &p.develop, 128, 0), Session::view_key(&p, true, 0))
};
let before = keys(&mut s);
s.catalog.apply(Op::SetEmbeddedLens { id, lens: Some(Box::new(lens(-0.03))) }).unwrap();
+5 -1
View File
@@ -69,7 +69,9 @@ fn threshold_compaction_runs_in_the_background() {
background += 1;
}
if k == 30 {
// a crash while a compaction may be in flight
// a crash while a compaction may be in flight (once the log's thread has written what it
// was handed: a process that crashes in LightCraft's code keeps running it)
s.library.as_mut().unwrap().journal_mut().flush().unwrap();
let expect = s.catalog.to_snapshot();
let copy = temp_dir("bg-compact-crash");
std::fs::create_dir_all(&copy).unwrap();
@@ -544,6 +546,8 @@ fn a_library_open_elsewhere_is_refused() {
let dir = temp_dir("locked");
let mut s = open(&dir, true);
s.execute("photo.rate", &json!({"rating": 3})).unwrap();
// (written by the log's own thread)
s.library.as_mut().unwrap().journal_mut().flush().unwrap();
let log = std::fs::read(dir.join("catalog.log")).unwrap();
let mut other = Session::new();
+317
View File
@@ -0,0 +1,317 @@
//! PERF-STEP-STALL: culling on a slow or failing drive. A flag or rating never waits for the drive
//! (the catalog log is written and synced by a thread of its own), and nothing made meanwhile is
//! lost: it is on disk once the save lands, after a clean quit, after a quit with no close, and,
//! when the drive fails, held, retried and reported as unsaved until it is written.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use lightcraft_catalog::fault::{self, Step};
use lightcraft_catalog::{Flag, PhotoId};
use serde_json::json;
use crate::Session;
fn temp_dir(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lc-engine-slow-drive-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
d
}
fn open(dir: &std::path::Path) -> Session {
let mut s = Session::new();
s.open_library(dir, true).unwrap();
s
}
fn ids(s: &Session) -> Vec<PhotoId> {
let mut v: Vec<PhotoId> = s.catalog.photos().map(|p| p.id).collect();
v.sort();
v
}
/// Every sync of the log in `dir` takes `sync` (a busy disk: Windows makes a write wait for a sync
/// of the same file in flight); `fail` makes every write fail while it is set.
fn slow_drive(dir: &std::path::Path, sync: Duration, fail: Arc<AtomicBool>) {
fault::install(
dir,
Arc::new(move |step| {
if fail.load(Ordering::SeqCst) {
return Err(std::io::Error::other("the drive is gone (test)"));
}
if step == Step::Sync {
std::thread::sleep(sync);
}
Ok(())
}),
);
}
/// The flag or rating each photo got, as `(id, flag, rating)`.
fn culled(s: &Session) -> Vec<(PhotoId, Flag, u8)> {
ids(s).into_iter().filter_map(|id| s.catalog.photo(id).map(|p| (id, p.flag, p.rating))).collect()
}
/// Flag and rate every photo the way a photographer culls: pick / reject in turn, a rating on
/// every other one. Returns the slowest command, in ms.
fn cull(s: &mut Session, rounds: usize) -> f64 {
let all = ids(s);
let mut slowest = 0.0f64;
for k in 0..rounds {
for (i, id) in all.iter().enumerate() {
let flag = if (i + k) % 2 == 0 { "pick" } else { "reject" };
let t = Instant::now();
s.execute("photo.flag", &json!({"flag": flag, "ids": [id.0]})).unwrap();
slowest = slowest.max(t.elapsed().as_secs_f64() * 1000.0);
if i % 2 == 0 {
let t = Instant::now();
s.execute("photo.rate", &json!({"rating": ((i + k) % 5) as u8 + 1, "ids": [id.0]})).unwrap();
slowest = slowest.max(t.elapsed().as_secs_f64() * 1000.0);
}
}
}
slowest
}
/// (a) With every sync of the log taking 300 ms, a flag or rating returns long before one sync.
/// The same culling with the log written on the caller's thread (as before PERF-STEP-STALL) waits
/// for a sync on every key, which is what this test would see without the fix.
#[test]
fn a_flag_never_waits_for_a_slow_drive() {
let sync = Duration::from_millis(300);
let mut seen = Vec::new();
for on_caller in [true, false] {
let dir = temp_dir(if on_caller { "wait-before" } else { "wait" });
fault::write_on_caller(&dir, on_caller);
let mut s = open(&dir);
slow_drive(&dir, sync, Arc::new(AtomicBool::new(false)));
let t = Instant::now();
let slowest = cull(&mut s, 1);
let total = t.elapsed().as_secs_f64() * 1000.0;
let n = s.library.as_ref().map_or(0, |l| l.journal().stats().appends);
eprintln!(
"{} drive syncing in 300 ms: slowest command {slowest:.1} ms, {total:.0} ms for the culling",
if on_caller { "before (log written on the caller):" } else { "after (log on its own thread):" }
);
seen.push((slowest, total, n));
drop(s);
fault::remove(&dir);
fault::write_on_caller(&dir, false);
let _ = std::fs::remove_dir_all(&dir);
}
let ((before, _, _), (after, _, _)) = (seen[0], seen[1]);
assert!(before >= 300.0, "the caller waited for its sync before: {before:.1} ms");
// a debug build of the whole workspace's tests at once leaves room; one sync is 300 ms
assert!(after < 120.0, "a command waited for the drive: {after:.1} ms");
}
/// (b) Everything flagged and rated while slow saves are in flight is on disk once they land
/// (a flush), after a quit with no close (the process ends normally: the log's thread finishes),
/// and after a clean quit (`close_library`).
#[test]
fn every_change_made_during_a_slow_save_is_on_disk() {
for how in ["flush", "drop", "close"] {
let dir = temp_dir(&format!("kept-{how}"));
let mut s = open(&dir);
slow_drive(&dir, Duration::from_millis(150), Arc::new(AtomicBool::new(false)));
cull(&mut s, 3);
let want = culled(&s);
let expect = s.catalog.to_snapshot();
match how {
"flush" => {
s.library.as_mut().unwrap().journal_mut().flush().unwrap();
// a copy of the files taken now (the next crash) holds everything
let copy = temp_dir("kept-copy");
std::fs::create_dir_all(&copy).unwrap();
for f in [lightcraft_catalog::journal::SNAPSHOT, lightcraft_catalog::journal::LOG] {
if dir.join(f).exists() {
std::fs::copy(dir.join(f), copy.join(f)).unwrap();
}
}
let (_, c, _) = lightcraft_catalog::Journal::open(Box::new(lightcraft_catalog::store::FsStore::open(&copy).unwrap())).unwrap();
assert_eq!(c.to_snapshot(), expect, "{how}");
let _ = std::fs::remove_dir_all(&copy);
}
"close" => s.close_library().unwrap(),
_ => {}
}
assert!(s.unsaved().is_none(), "{how}: {:?}", s.unsaved());
drop(s);
fault::remove(&dir);
let again = open(&dir);
assert_eq!(culled(&again), want, "{how}");
assert_eq!(again.catalog.to_snapshot(), expect, "{how}");
drop(again);
let _ = std::fs::remove_dir_all(&dir);
}
}
/// Wait (bounded) until `done` holds, calling the frame loop's save meanwhile.
fn frames_until(s: &mut Session, what: &str, mut done: impl FnMut(&Session) -> bool) {
let t = Instant::now();
while !done(s) {
assert!(t.elapsed() < Duration::from_secs(20), "{what}: {:?}", s.unsaved());
s.persist_if_dirty();
std::thread::sleep(Duration::from_millis(20));
}
}
/// (c) A drive that fails: the flags handed over before the failure are held and retried, never
/// dropped; the failure is reported (`unsaved`, the quit prompt's source) and later flags fail
/// with `NotSaved` and stay queued; once the drive is back, all of it is written, in order, with
/// no gap in the log.
#[test]
fn a_failed_write_is_reported_and_retried_never_dropped() {
let dir = temp_dir("fail");
let mut s = open(&dir);
let fail = Arc::new(AtomicBool::new(false));
slow_drive(&dir, Duration::from_millis(5), fail.clone());
let all = ids(&s);
fail.store(true, Ordering::SeqCst);
// handed over before the thread found out: accepted, then held
s.execute("photo.flag", &json!({"flag": "pick", "ids": [all[0].0]})).unwrap();
// the quit check reads it at once, not as of the last frame (review of #3557)
let t = Instant::now();
while s.library.as_ref().unwrap().journal().unwritten().is_none() {
assert!(t.elapsed() < Duration::from_secs(20), "the log thread never reported the failure");
std::thread::sleep(Duration::from_millis(10));
}
s.refresh_unsaved();
assert!(s.unsaved().is_some(), "refreshed for the quit check");
let (n, why) = s.unsaved().map(|(n, w)| (n, w.to_string())).unwrap();
assert!(n >= 1 && why.contains("the drive is gone"), "{n} {why}");
// later flags: refused with the reason, kept in memory and queued
let r = s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[1].0]}));
assert!(matches!(r, Err(crate::EngineError::NotSaved(_))), "{r:?}");
assert_eq!(s.catalog.photo(all[1]).unwrap().flag, Flag::Reject, "applied in memory");
let _ = s.execute("photo.rate", &json!({"rating": 4, "ids": [all[2].0]}));
assert!(s.unsaved().is_some_and(|(n, _)| n >= 3), "{:?}", s.unsaved());
// the drive is back: the held record and the queued ones are written by the frame loop
fail.store(false, Ordering::SeqCst);
frames_until(&mut s, "written once the drive is back", |s| s.unsaved().is_none() && s.pending_log.is_empty());
let want = culled(&s);
let expect = s.catalog.to_snapshot();
// a crash now: the files alone hold everything, and the log has no gap (no damage on load)
s.library.as_mut().unwrap().journal_mut().flush().unwrap();
let copy = temp_dir("fail-copy");
std::fs::create_dir_all(&copy).unwrap();
for f in [lightcraft_catalog::journal::SNAPSHOT, lightcraft_catalog::journal::LOG] {
if dir.join(f).exists() {
std::fs::copy(dir.join(f), copy.join(f)).unwrap();
}
}
let (_, c, report) = lightcraft_catalog::Journal::open(Box::new(lightcraft_catalog::store::FsStore::open(&copy).unwrap())).unwrap();
assert!(report.damaged.is_none(), "{report:?}");
assert_eq!(c.to_snapshot(), expect);
let _ = std::fs::remove_dir_all(&copy);
fault::remove(&dir);
drop(s);
assert_eq!(culled(&open(&dir)), want);
let _ = std::fs::remove_dir_all(&dir);
}
/// (c) The drive stays broken for the log until the quit: the quit prompt is told (unsaved), and
/// the closing snapshot (a fresh file) saves the held flags, so they are there on the next open.
#[test]
fn a_log_that_stays_broken_is_saved_by_the_closing_snapshot() {
let dir = temp_dir("broken");
let mut s = open(&dir);
let all = ids(&s);
let fail = Arc::new(AtomicBool::new(false));
slow_drive(&dir, Duration::from_millis(5), fail.clone());
fail.store(true, Ordering::SeqCst);
s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap();
frames_until(&mut s, "the failure is reported", |s| s.unsaved().is_some());
let _ = s.execute("photo.flag", &json!({"flag": "pick", "ids": [all[1].0]}));
let want = culled(&s);
// (the snapshot itself is written by the store, which the hook leaves alone; the log's reset
// after it fails, so close reports it, but the snapshot holds everything)
let _ = s.close_library();
// the snapshot holds them: the quit prompt must not say they would be lost (review of #3557)
assert!(s.unsaved().is_none(), "{:?}", s.unsaved());
drop(s);
fault::remove(&dir);
let again = open(&dir);
assert!(again.library.as_ref().unwrap().report.damaged.is_none());
assert_eq!(culled(&again), want);
drop(again);
let _ = std::fs::remove_dir_all(&dir);
}
/// The same library opened again in the same session (Settings, Libraries; a reopen after an
/// error): everything the old session's log thread was handed is in the files before the new one
/// reads them (review of #3557).
#[test]
fn reopening_the_same_library_reads_what_its_log_thread_was_handed() {
let dir = temp_dir("reopen");
let mut s = open(&dir);
fault::install(
&dir,
Arc::new(|step| {
if step == Step::Write {
std::thread::sleep(Duration::from_millis(300));
}
Ok(())
}),
);
let all = ids(&s);
s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap();
s.open_library(&dir, true).unwrap();
fault::remove(&dir);
assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject);
drop(s);
let _ = std::fs::remove_dir_all(&dir);
}
/// The same library opened again while its log's thread can't write what it was handed: the open
/// fails and the current library stays open with the change (held, retried), instead of a new
/// catalog read from files that miss it (review of #3557). Once the drive is back, the reopen
/// reads it.
#[test]
fn a_reopen_waits_for_what_the_log_thread_could_not_write() {
let dir = temp_dir("reopen-fail");
let mut s = open(&dir);
let all = ids(&s);
let fail = Arc::new(AtomicBool::new(false));
slow_drive(&dir, Duration::from_millis(5), fail.clone());
fail.store(true, Ordering::SeqCst);
s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap();
let r = s.open_library(&dir, true);
assert!(matches!(r, Err(crate::EngineError::NotSaved(_))), "{r:?}");
assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject, "the open library keeps the change");
assert!(s.unsaved().is_some(), "and says it isn't saved yet");
fail.store(false, Ordering::SeqCst);
let t = Instant::now();
while s.library.as_mut().unwrap().journal_mut().flush().is_err() {
assert!(t.elapsed() < Duration::from_secs(20), "never written");
std::thread::sleep(Duration::from_millis(50));
}
s.open_library(&dir, true).unwrap();
fault::remove(&dir);
assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject);
drop(s);
let _ = std::fs::remove_dir_all(&dir);
}
/// A reopen while the log still can't be written, but after a snapshot that holds every change
/// (the log's reset after it failed): nothing is missing from the files, so the open goes ahead
/// (review of #3557).
#[test]
fn a_reopen_after_a_snapshot_that_holds_everything_goes_ahead() {
let dir = temp_dir("reopen-snap");
let mut s = open(&dir);
let all = ids(&s);
let fail = Arc::new(AtomicBool::new(false));
slow_drive(&dir, Duration::from_millis(5), fail.clone());
fail.store(true, Ordering::SeqCst);
s.execute("photo.flag", &json!({"flag": "reject", "ids": [all[0].0]})).unwrap();
let _ = s.close_library();
assert!(s.snapshot_holds_everything());
s.open_library(&dir, true).unwrap();
assert_eq!(s.catalog.photo(all[0]).unwrap().flag, Flag::Reject);
fault::remove(&dir);
drop(s);
assert_eq!(open(&dir).catalog.photo(all[0]).unwrap().flag, Flag::Reject);
let _ = std::fs::remove_dir_all(&dir);
}
+58
View File
@@ -57,6 +57,19 @@ pub fn cell_glyphs(font: &FontRef<'_>, data: &harfrust::ShaperData, text: &str,
Some(glyphs)
}
/// NFC, except CJK compatibility ideographs, which NFC would swap for their unified forms.
fn compose(text: &str) -> String {
use unicode_normalization::UnicodeNormalization;
let compatibility = |c: char| matches!(c, '\u{F900}'..='\u{FAFF}' | '\u{2F800}'..='\u{2FA1F}');
let mut out = String::with_capacity(text.len());
for part in text.split_inclusive(compatibility) {
let kept = part.chars().next_back().filter(|&c| compatibility(c));
out.extend(kept.and_then(|c| part.strip_suffix(c)).unwrap_or(part).nfc());
out.extend(kept);
}
out
}
/// A string laid out at one size: its glyphs relative to the box's top-left corner and the box's
/// size in pixels (lines are `px` apart; vertical text: columns `px` wide, right to left).
pub struct TextLayout {
@@ -79,6 +92,9 @@ impl TextLayout {
Some((i, _)) => text.get(..i).unwrap_or(text),
None => text,
};
// macOS file names are often decomposed (NFD); the layout below draws one glyph per char
let composed = compose(text);
let text = composed.as_str();
let fonts = faces(craft);
let latin = fonts.first()?.clone();
let vertical_data: Vec<_> = if vertical {
@@ -264,6 +280,48 @@ mod tests {
}
}
fn assert_draws_composed(text: &str, craft: &'static [CraftFont]) {
use unicode_normalization::UnicodeNormalization;
let nfc: String = text.nfc().collect();
let nfd: String = text.nfd().collect();
assert_ne!(nfc, nfd);
let (a, b) = (TextLayout::new(&nfc, 40.0, false, craft).unwrap(), TextLayout::new(&nfd, 40.0, false, craft).unwrap());
let ids = |l: &TextLayout| l.glyphs.iter().map(|(face, g, _)| (*face, g.id.0)).collect::<Vec<_>>();
assert_eq!(ids(&b), ids(&a));
assert_eq!(b.width, a.width);
assert!(a.glyphs.iter().all(|(_, g, _)| g.id.0 != 0));
}
#[test]
fn decomposed_vietnamese_draws_its_composed_letters() {
assert_draws_composed("HỌC ĐỂ ỨNG DỤNG", &[]);
}
#[test]
fn decomposed_hangul_draws_whole_syllables() {
if !CRAFT_FONTS.iter().any(|font| font.covers("Hang")) {
lightcraft_testkit::skip!(Fonts, "built without a Hangul face from craft-fonts");
return;
}
assert_draws_composed("제주도 바다 여행.jpg", CRAFT_FONTS);
}
#[test]
fn compatibility_ideographs_keep_their_code_points() {
use unicode_normalization::UnicodeNormalization;
let nfd = |s: &str| s.nfd().collect::<String>();
let text = format!("\u{FA10}{} \u{2F800}{}\u{F900}", nfd("본 제주"), nfd("Ọ"));
assert_eq!(compose(&text), "\u{FA10}본 제주 \u{2F800}Ọ\u{F900}");
}
#[test]
fn already_composed_text_stays_as_it_is() {
for text in ["", "plain.jpg", "제주도 바다 여행.jpg", "HỌC ĐỂ ỨNG DỤNG"] {
assert!(unicode_normalization::is_nfc(text), "{text}");
assert_eq!(compose(text), text);
}
}
#[test]
fn bundled_thai_uses_its_glyphs() {
assert_script_glyphs("Thai", "สวัสดีครับ");
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "lightcraft-film"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "LightCraft film-negative conversion: film base, levels in density space, film presets, colour and tone (L1)"
[lints]
workspace = true
[dependencies]
# Pure-Rust libm: the conversion's maths gives the same numbers on every target, the browser included.
libm = { workspace = true }
+202
View File
@@ -0,0 +1,202 @@
//! What the conversion needs to know about one negative, and how to measure it from pixels
//! without an allocator (a fixed-size histogram per channel).
use crate::{RANGE_STOPS, color::Encoding, film};
/// Film base and levels, per channel.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Analysis {
/// The film base (unexposed film, the border) in linear light: scene black.
pub base: [f32; 3],
/// Relative exposure ([`film::exposure`]) that maps to black.
pub black: [f32; 3],
/// Relative exposure that maps to white.
pub white: [f32; 3],
}
impl Analysis {
/// Levels from the base alone: the base is black and a scene [`RANGE_STOPS`] stops brighter
/// is white, on every channel. Needs nothing from the image, so it is identical on every band.
pub fn manual(base_linear: [f32; 3]) -> Self {
Self::from_base(base_linear, [crate::NEGATIVE_GAMMA; 3])
}
/// [`Analysis::manual`] for a film whose layers have the given density per log-exposure: a
/// steeper layer reaches the same scene brightness at a higher density, so its white point
/// sits further from the base. Relative exposures stay in the [`film::exposure`] convention.
pub fn from_base(base_linear: [f32; 3], gamma: [f32; 3]) -> Self {
let mut white = [0.0; 3];
for (w, g) in white.iter_mut().zip(gamma) {
let g = if g.is_finite() && g > 0.05 { g } else { crate::NEGATIVE_GAMMA };
*w = libm::exp2f(g / crate::NEGATIVE_GAMMA * RANGE_STOPS);
}
Self { base: base_linear, black: [1.0; 3], white }
}
/// Levels from three scan values per channel in the host encoding: the film base, the
/// brightest value that still counts as exposed (black) and the darkest (white). `None`
/// when a channel has no range between black and white.
pub fn from_scan_values(base: [f32; 3], black: [f32; 3], white: [f32; 3], enc: Encoding) -> Option<Self> {
let mut a = Self { base: [0.0; 3], black: [0.0; 3], white: [0.0; 3] };
for ch in 0..3 {
a.base[ch] = enc.decode(base[ch]);
a.black[ch] = film::exposure(enc.decode(black[ch]), a.base[ch]);
a.white[ch] = film::exposure(enc.decode(white[ch]), a.base[ch]);
if !a.white[ch].is_finite() || !a.black[ch].is_finite() || a.white[ch] <= a.black[ch] * 1.0001 {
return None;
}
}
Some(a)
}
}
/// Bins per channel.
pub const BINS: usize = 1024;
/// Per-channel histogram of scan values in the host encoding, 0..1. One pass over a band gives
/// the film base (a high quantile: the unexposed border is the brightest the scan gets) and the
/// black and white points (the quantiles the black and white clips leave).
#[derive(Clone, Copy, Debug)]
pub struct ValueHistogram {
bins: [[u32; BINS]; 3],
count: u32,
}
impl Default for ValueHistogram {
fn default() -> Self {
Self::new()
}
}
impl ValueHistogram {
pub const fn new() -> Self {
Self { bins: [[0; BINS]; 3], count: 0 }
}
/// Account for one sample (host encoding, 0..1 per channel).
pub fn push(&mut self, rgb: [f32; 3]) {
for (bins, v) in self.bins.iter_mut().zip(rgb) {
if let Some(b) = bins.get_mut(bin(v)) {
*b = b.saturating_add(1);
}
}
self.count = self.count.saturating_add(1);
}
pub fn count(&self) -> u32 {
self.count
}
/// The value below which a fraction `q` (0..1) of channel `ch` lies.
pub fn quantile(&self, ch: usize, q: f32) -> Option<f32> {
self.bins.get(ch).and_then(|bins| quantile_bin(bins, self.count, q)).map(|b| b as f32 / (BINS - 1) as f32)
}
/// The analysis of the pixels seen: the base at the `1 − base_clip` quantile, black at
/// `1 − black_clip`, white at `white_clip` (all fractions, 0..1), for samples in `enc`.
pub fn analysis(&self, base_clip: f32, black_clip: f32, white_clip: f32, enc: Encoding) -> Option<Analysis> {
let (mut base, mut black, mut white) = ([0.0; 3], [0.0; 3], [0.0; 3]);
for ch in 0..3 {
base[ch] = self.quantile(ch, 1.0 - base_clip.clamp(0.0, 0.5))?;
black[ch] = self.quantile(ch, 1.0 - black_clip.clamp(0.0, 0.5))?;
white[ch] = self.quantile(ch, white_clip.clamp(0.0, 0.5))?;
}
Analysis::from_scan_values(base, black, white, enc)
}
}
/// The bin of a value in 0..1.
fn bin(v: f32) -> usize {
if v.is_finite() { (v.clamp(0.0, 1.0) * (BINS - 1) as f32) as usize } else { 0 }
}
/// The first bin at which the cumulative count reaches `q` of `count` (`None` when empty).
fn quantile_bin(bins: &[u32; BINS], count: u32, q: f32) -> Option<usize> {
if count == 0 {
return None;
}
let target = libm::ceil(f64::from(q.clamp(0.0, 1.0)) * f64::from(count)).max(1.0) as u64;
let mut seen = 0u64;
for (i, n) in bins.iter().enumerate() {
seen += u64::from(*n);
if seen >= target {
return Some(i);
}
}
Some(BINS - 1)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::color;
const BASE: [f32; 3] = [0.6, 0.35, 0.15];
#[test]
fn histogram_finds_base_and_levels_of_a_synthetic_negative() {
let mut h = ValueHistogram::new();
assert_eq!(h.analysis(0.001, 0.0, 0.0, Encoding::Srgb), None);
// Scene exposures from 1 (black, at the base) to 2^5 (white), evenly on a log scale,
// plus a hot pixel brighter than the base.
for i in 0..=1000 {
let e = libm::exp2f(5.0 * i as f32 / 1000.0);
let mut rgb = [0.0; 3];
for (v, b) in rgb.iter_mut().zip(BASE) {
*v = color::srgb_encode(film::transmittance(e, b));
}
h.push(rgb);
}
h.push([1.0; 3]);
assert_eq!(h.count(), 1002);
let a = h.analysis(0.005, 0.0, 0.0, Encoding::Srgb).unwrap();
for (ch, b) in BASE.iter().enumerate() {
// The clip takes the top 0.5 % of a 5-stop log ramp: 0.025 stops under the base.
assert!((a.base[ch] - b).abs() < 0.01, "{a:?}");
assert!((a.black[ch] - 1.0).abs() < 0.03, "{a:?}");
assert!((a.white[ch] - 32.0).abs() / 32.0 < 0.05, "{a:?}");
}
let clipped = h.analysis(0.005, 0.1, 0.1, Encoding::Srgb).unwrap();
assert!(clipped.black[0] > a.black[0] * 1.2 && clipped.white[0] < a.white[0] * 0.8, "{clipped:?}");
// A flat band (all one value) has no range.
let mut flat = ValueHistogram::new();
flat.push([0.3; 3]);
assert_eq!(flat.analysis(0.0, 0.0, 0.0, Encoding::Srgb), None);
}
#[test]
fn a_steeper_layer_puts_white_further_from_the_base() {
let a = Analysis::from_base(BASE, [0.6, 0.6, 0.72]);
assert_eq!(a.white[0], a.white[1]);
assert!(a.white[2] > a.white[0] * 1.5, "{a:?}");
assert_eq!(Analysis::from_base(BASE, [f32::NAN, 0.0, 0.6]).white, Analysis::manual(BASE).white);
}
#[test]
fn scan_values_give_levels_in_linear_too() {
let a = Analysis::from_scan_values(BASE, BASE, [0.1, 0.1, 0.1], Encoding::Linear).unwrap();
assert_eq!(a.base, BASE);
assert_eq!(a.black, [1.0; 3]);
assert!(a.white[0] > a.white[2], "the same scan value is further below a brighter base: {a:?}");
assert_eq!(Analysis::from_scan_values(BASE, [0.1; 3], [0.1; 3], Encoding::Linear), None);
}
#[test]
fn quantile_edges() {
let mut bins = [0u32; BINS];
bins[10] = 5;
bins[500] = 5;
assert_eq!(quantile_bin(&bins, 10, 0.0), Some(10));
assert_eq!(quantile_bin(&bins, 10, 0.5), Some(10));
assert_eq!(quantile_bin(&bins, 10, 0.51), Some(500));
assert_eq!(quantile_bin(&bins, 10, 1.0), Some(500));
assert_eq!(quantile_bin(&bins, 0, 0.5), None);
assert_eq!(bin(f32::NAN), 0);
assert_eq!(bin(1.0), BINS - 1);
let mut h = ValueHistogram::new();
h.push([f32::NAN, 2.0, -1.0]);
assert_eq!(h.quantile(0, 0.5), Some(0.0));
assert_eq!(h.quantile(1, 0.5), Some(1.0));
assert_eq!(h.quantile(3, 0.5), None);
}
}
+145
View File
@@ -0,0 +1,145 @@
//! sRGB transfer functions and luminance, including the fused forms the conversion runs on
//! (one `powf` where the naive chain would need two: the host meters instructions per sample).
/// How a host's samples are encoded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Encoding {
/// Display-referred, sRGB transfer (8- and 16-bit documents).
Srgb,
/// Scene-linear (32-bit float documents).
Linear,
}
impl Encoding {
/// The usual encoding of a document of `depth` bits per sample.
pub fn for_depth(depth: u32) -> Self {
if depth >= 32 { Self::Linear } else { Self::Srgb }
}
pub fn parse(s: &str) -> Option<Self> {
match s {
"srgb" => Some(Self::Srgb),
"linear" => Some(Self::Linear),
_ => None,
}
}
/// A sample in this encoding as linear light.
pub fn decode(self, v: f32) -> f32 {
match self {
Self::Srgb => srgb_decode(v),
Self::Linear => v,
}
}
/// Three linear values as samples in this encoding.
pub fn encode3(self, rgb: [f32; 3]) -> [f32; 3] {
[self.encode(rgb[0]), self.encode(rgb[1]), self.encode(rgb[2])]
}
/// Linear light as a sample in this encoding.
pub fn encode(self, v: f32) -> f32 {
match self {
Self::Srgb => srgb_encode(v),
Self::Linear => v,
}
}
}
/// Below this encoded value the sRGB curve is linear.
const SRGB_KNEE_ENCODED: f32 = 0.04045;
/// Below this linear value the sRGB curve is linear.
const SRGB_KNEE_LINEAR: f32 = 0.003_130_8;
/// sRGB-encoded 0..1 to linear light (non-finite input reads as 0).
pub fn srgb_decode(v: f32) -> f32 {
if !v.is_finite() {
return 0.0;
}
let v = v.clamp(0.0, 1.0);
if v <= SRGB_KNEE_ENCODED { v / 12.92 } else { libm::powf((v + 0.055) / 1.055, 2.4) }
}
/// `srgb_decode(v)^e` in one `powf`, for `v` in 0..1 and finite `e`.
pub fn srgb_decode_pow(v: f32, e: f32) -> f32 {
if !v.is_finite() {
return 0.0;
}
let v = v.clamp(0.0, 1.0);
if v <= SRGB_KNEE_ENCODED { libm::powf(v / 12.92, e) } else { libm::powf((v + 0.055) / 1.055, 2.4 * e) }
}
/// Linear light 0..1 to sRGB-encoded (clamped; non-finite input reads as 0).
pub fn srgb_encode(v: f32) -> f32 {
if !v.is_finite() {
return 0.0;
}
let v = v.clamp(0.0, 1.0);
if v <= SRGB_KNEE_LINEAR { v * 12.92 } else { 1.055 * libm::powf(v, 1.0 / 2.4) - 0.055 }
}
/// `srgb_encode(v^e)` in one `powf`, for `v` in 0..1 and `e > 0`; `knee` is
/// [`encode_pow_knee`]`(e)`, the `v` below which `v^e` is in the curve's linear part.
pub fn srgb_encode_pow(v: f32, e: f32, knee: f32) -> f32 {
if !v.is_finite() {
return 0.0;
}
let v = v.clamp(0.0, 1.0);
if v <= knee { 12.92 * libm::powf(v, e) } else { 1.055 * libm::powf(v, e / 2.4) - 0.055 }
}
/// The `v` below which `v^e` falls in the sRGB curve's linear part.
pub fn encode_pow_knee(e: f32) -> f32 {
if e.is_finite() && e > 0.0 { libm::powf(SRGB_KNEE_LINEAR, 1.0 / e) } else { SRGB_KNEE_LINEAR }
}
/// Rec. 709 luminance of a linear RGB triple.
pub fn luminance(rgb: [f32; 3]) -> f32 {
0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn srgb_round_trips_and_pins_known_points() {
for v in [0.0, 0.001, 0.04045, 0.1, 0.5, 0.9, 1.0] {
assert!((srgb_decode(srgb_encode(v)) - v).abs() < 1e-6, "{v}");
}
assert!((srgb_encode(0.18) - 0.4613).abs() < 1e-3);
assert!((srgb_decode(0.5) - 0.2140).abs() < 1e-3);
assert_eq!(srgb_encode(f32::NAN), 0.0);
assert_eq!(srgb_decode(2.0), 1.0);
}
#[test]
fn fused_forms_match_the_chains() {
for v in [0.0f32, 0.001, 0.02, 0.04045, 0.1, 0.5, 0.9, 1.0] {
for e in [0.5, 1.0, 1.7, -1.6] {
// Negative exponents blow up at 0; callers clamp first, as the test does.
let v = if e < 0.0 { v.max(0.001) } else { v };
let want = libm::powf(srgb_decode(v), e);
let got = srgb_decode_pow(v, e);
assert!((got - want).abs() / want.max(1.0) < 1e-4, "decode {v}^{e}: {got} vs {want}");
}
for e in [0.5, 1.0, 2.0] {
let want = srgb_encode(libm::powf(v, e));
let got = srgb_encode_pow(v, e, encode_pow_knee(e));
assert!((got - want).abs() < 1e-5, "encode {v}^{e}: {got} vs {want}");
}
}
assert_eq!(srgb_decode_pow(f32::NAN, 2.0), 0.0);
assert_eq!(srgb_encode_pow(f32::INFINITY, 1.0, encode_pow_knee(1.0)), 0.0);
assert_eq!(encode_pow_knee(f32::NAN), SRGB_KNEE_LINEAR);
}
#[test]
fn depth_picks_encoding() {
assert_eq!(Encoding::for_depth(8), Encoding::Srgb);
assert_eq!(Encoding::for_depth(16), Encoding::Srgb);
assert_eq!(Encoding::for_depth(32), Encoding::Linear);
assert_eq!(Encoding::parse("linear"), Some(Encoding::Linear));
assert_eq!(Encoding::parse("auto"), None);
}
}
+105
View File
@@ -0,0 +1,105 @@
//! The negative's characteristic curve, straight-line approximation.
//!
//! Density `D = D_base + γ · log10(E)` for scene exposure `E` relative to the exposure that just
//! starts to darken the film; what the scanner sees is the transmittance `T = 10^−D`. So the
//! relative exposure that produced a scan value `t` with film base `t_base` is
//! `E = (t_base / t)^(1/γ)`: 1 at the base (scene black), growing as the negative gets denser.
use crate::{NEGATIVE_GAMMA, color::Encoding};
/// Transmittance below which a sample reads as fully dense (avoids division by zero).
pub const MIN_TRANSMITTANCE: f32 = 1e-5;
/// The sRGB-encoded value of [`MIN_TRANSMITTANCE`] (in the curve's linear part).
const MIN_TRANSMITTANCE_SRGB: f32 = MIN_TRANSMITTANCE * 12.92;
/// Relative scene exposure (≥ 1) behind a linear scan value `t` of a negative with film base
/// `t_base` (both linear light, 0..1). Values brighter than the base read as the base.
pub fn exposure(t: f32, t_base: f32) -> f32 {
let t_base = if t_base.is_finite() { t_base.max(MIN_TRANSMITTANCE) } else { MIN_TRANSMITTANCE };
let t = if t.is_finite() { t.clamp(MIN_TRANSMITTANCE, t_base) } else { t_base };
libm::powf(t_base / t, 1.0 / NEGATIVE_GAMMA)
}
/// `t_base^(1/γ)`: the factor that turns `t^(−1/γ)` into [`exposure`].
pub fn base_factor(t_base: f32) -> f32 {
let t_base = if t_base.is_finite() { t_base.max(MIN_TRANSMITTANCE) } else { MIN_TRANSMITTANCE };
libm::powf(t_base, 1.0 / NEGATIVE_GAMMA)
}
/// `factor · t^(−exponent)` for a scan value `v` in its host encoding: one `powf` per sample.
/// With `exponent = 1/γ` and `factor` the base's [`base_factor`] this is [`exposure`]; a
/// different exponent per channel normalises channels of unequal density range
/// ([`crate::Converter`]). Results below 1 read as 1 (brighter than the base); non-finite
/// input reads as the base.
pub fn exposure_encoded(v: f32, enc: Encoding, factor: f32, exponent: f32) -> f32 {
exposure_encoded_raw(v, enc, factor, exponent).max(1.0)
}
/// [`exposure_encoded`] before its floor at 1: it keeps going below 1 past the base, so that a
/// table of it interpolates straight through the black point instead of across a corner.
pub fn exposure_encoded_raw(v: f32, enc: Encoding, factor: f32, exponent: f32) -> f32 {
if !v.is_finite() {
return 1.0;
}
let e = match enc {
Encoding::Srgb => factor * color::srgb_decode_pow(v.max(MIN_TRANSMITTANCE_SRGB), -exponent),
Encoding::Linear => factor * libm::powf(v.max(MIN_TRANSMITTANCE), -exponent),
};
if e.is_finite() { e } else { 1.0 }
}
use crate::color;
/// The inverse: the linear scan value a relative exposure `e` (≥ 1) leaves on a negative with
/// film base `t_base`. Used to synthesise negatives in tests and to reason about levels.
pub fn transmittance(e: f32, t_base: f32) -> f32 {
transmittance_at(e, t_base, NEGATIVE_GAMMA)
}
/// [`transmittance`] for a channel whose density grows by `gamma` per log-exposure: a scan of
/// colour film, whose channels spread apart ([`crate::SCAN_SPREAD`]).
pub fn transmittance_at(e: f32, t_base: f32, gamma: f32) -> f32 {
t_base * libm::powf(e.max(1.0), -gamma)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base_is_unit_exposure_and_density_grows_with_exposure() {
assert_eq!(exposure(0.5, 0.5), 1.0);
assert_eq!(exposure(0.9, 0.5), 1.0, "brighter than the base clamps");
let e1 = exposure(0.25, 0.5);
let e2 = exposure(0.125, 0.5);
assert!(e1 > 1.0 && e2 > e1);
// Halving the transmittance (0.3 density) is 0.5 log-exposure at γ 0.6: ×2^(1/0.6) ≈ 3.17.
assert!((e2 / e1 - 3.175).abs() < 0.01, "{e1} {e2}");
}
#[test]
fn transmittance_inverts_exposure() {
for e in [1.0, 2.0, 10.0, 64.0] {
let t = transmittance(e, 0.6);
assert!((exposure(t, 0.6) - e).abs() / e < 1e-4, "{e}");
}
assert!(exposure(0.0, 0.6).is_finite());
assert!(exposure(f32::NAN, f32::NAN).is_finite());
}
#[test]
fn encoded_form_matches_the_linear_one() {
let base = 0.6;
let k = base_factor(base);
for t in [0.6, 0.3, 0.1, 0.02, 0.001, 0.0] {
let want = exposure(t, base);
let lin = exposure_encoded(t, Encoding::Linear, k, 1.0 / NEGATIVE_GAMMA);
let srgb = exposure_encoded(color::srgb_encode(t), Encoding::Srgb, k, 1.0 / NEGATIVE_GAMMA);
assert!((lin - want).abs() / want < 1e-3, "linear {t}: {lin} vs {want}");
assert!((srgb - want).abs() / want < 2e-3, "srgb {t}: {srgb} vs {want}");
}
assert_eq!(exposure_encoded(0.9, Encoding::Linear, k, 1.0 / NEGATIVE_GAMMA), 1.0, "brighter than the base");
assert_eq!(exposure_encoded(f32::NAN, Encoding::Srgb, k, 1.0 / NEGATIVE_GAMMA), 1.0);
assert!(exposure_encoded(0.0, Encoding::Srgb, f32::INFINITY, 1.0 / NEGATIVE_GAMMA).is_finite());
}
}
+718
View File
@@ -0,0 +1,718 @@
//! Film-negative conversion: a scanned colour or black-and-white negative to a positive.
//!
//! Ported from Film Lab (github.com/smyrgeorge/film-lab, by the same author), whose PhotoCraft
//! plug-ins run the same maths. Hosts hand over RGB samples in 0..1 and say how they are encoded
//! ([`Encoding`]); this crate gives back the positive. Nothing in here knows a host's pixel layout;
//! [`measure`] analyses a whole scan once, so every render (a preview, a zoomed window, an export)
//! uses the same numbers.
//!
//! # The model
//!
//! A negative records scene exposure as density. In the straight part of its characteristic
//! curve, density grows by [`NEGATIVE_GAMMA`] per stop, so the light a scanner sees through the
//! film falls as the scene brightens. Reading that back:
//!
//! 1. **Film base.** The unexposed film (the border, orange on colour negative film) is the
//! brightest the scan gets and stands for scene black. Every channel is measured relative to
//! it, which also removes the orange mask ([`film::exposure`]).
//! 2. **Levels.** Each channel's density range between its black and white points is mapped onto
//! the same [`RANGE_STOPS`] of scene brightness, so channels of unequal range (a scan whose
//! blue runs much denser than its red) come out balanced, and black and white land on 0 and 1
//! ([`Analysis`]: the base for black and the fixed range for white when only the base is
//! known, or scan values for black and white from an analysis of the image).
//! 3. **Colour** in linear light ([`look::Colour`]): exposure, white balance (sliders, a preset,
//! a neutral sample), the colour model, pre-saturation, mid-tone balance; black-and-white.
//! 4. **Tone** ([`tone::Curve`]): white and black points, brightness as a gamma, then in display
//! (sRGB-encoded) space a tone profile, contrast, lights / darks, fade / glow and soft ends.
//! 5. **Toning** ([`look::Toning`]): highlight and shadow colour balance and saturation on the
//! encoded result.
//!
//! The workflow this serves is the usual one for negatives: sample the film border, exclude
//! the border and sprocket holes from the evaluated area, convert, then edit.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod analysis;
pub mod color;
pub mod film;
pub mod look;
pub mod measure;
pub mod preset;
pub mod tone;
pub use analysis::{Analysis, ValueHistogram};
pub use color::Encoding;
pub use look::{Look, WbPreset};
pub use measure::{MeasureOptions, Measurement};
pub use preset::{PRESETS, Preset, SCAN_SPREAD, Sliders};
pub use tone::Tone;
/// The negative's contrast: density per log-exposure in the straight part of its characteristic
/// curve. Colour negative film sits near 0.6; the brightness and contrast controls absorb the
/// difference for other stocks.
pub const NEGATIVE_GAMMA: f32 = 0.6;
/// Stops of scene brightness between the film base and the positive's white when only the base
/// is known (a density range of about 1.1 at [`NEGATIVE_GAMMA`], typical of a well-exposed
/// colour negative).
pub const RANGE_STOPS: f32 = 6.0;
/// Stops the density range between the black and white points is rendered over by default
/// ([`Params::range`]). Fewer stops than the film's own [`RANGE_STOPS`] render mid-tones the way
/// a lab scan does: measured against a lab-converted reference, 3 matches its mid-tones; 6 is
/// the scene-linear rendition.
pub const DISPLAY_STOPS: f32 = 3.0;
/// Channel indices in the RGB triples.
pub const RED: usize = 0;
pub const GREEN: usize = 1;
pub const BLUE: usize = 2;
/// The user's edits. Slider ranges follow the Convert Negative panel: ±50 for the bipolar controls,
/// 0..100 for amounts, exposure in stops, pre-saturation 1..5.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Params {
/// Stops of scene brightness mapped between the black and white points (default
/// [`DISPLAY_STOPS`]); fewer stops render mid-tones brighter, as lab scans do, and
/// [`RANGE_STOPS`] is the scene-linear rendition.
pub range: f32,
/// Stops; positive brightens the whole positive.
pub exposure: f32,
/// Mid-tone gamma, −50..50; positive brightens mid-tones without moving black or white.
pub brightness: f32,
/// Added to the tone profile's contrast, −50..50.
pub contrast: f32,
pub tone: Tone,
/// −50..50; positive brightens the lighter tones.
pub lights: f32,
/// −50..50; positive brightens the darker tones.
pub darks: f32,
/// −50..50; moves the white point (positive brightens whites; clipped detail stays clipped).
pub whites: f32,
/// −50..50; moves the black point (positive lifts it for a faded look).
pub blacks: f32,
/// −100..100: positive lifts black for smoother shadows with no pure black; negative
/// expands the shadow tonality.
pub fade: f32,
/// −100..100: positive compresses the highlights into a soft shoulder; negative expands them.
pub glow: f32,
/// 0..100: tonal roll-off into white.
pub soft_highs: f32,
/// 0..100: tonal roll-off into black.
pub soft_lows: f32,
pub wb: WbPreset,
/// −50..50; positive is warmer.
pub temp: f32,
/// −50..50; positive is more magenta, negative more green.
pub tint: f32,
/// Per-channel mid-tone gammas (0.4..2.5, 1 = none): a colour balance that leaves black and
/// white alone, what an automatic neutral balance computes from the channel medians.
pub balance: [f32; 3],
/// 1..5, default 3: saturation before the tone curve, which also sets colour separation.
pub presat: f32,
/// −50..50: saturation after the tone curve.
pub saturation: f32,
pub look: Look,
/// Mid-tone colour balance, −50..50 each: red / cyan, green / magenta, blue / yellow.
pub mids_red: f32,
pub mids_green: f32,
pub mids_blue: f32,
/// Highlight toning balance, −50..50 each, and how far down it reaches (0..100).
pub highs_red: f32,
pub highs_green: f32,
pub highs_blue: f32,
pub highs_range: f32,
/// Shadow toning balance, −50..50 each, and how far up it reaches (0..100).
pub lows_red: f32,
pub lows_green: f32,
pub lows_blue: f32,
pub lows_range: f32,
/// Black-and-white film: the positive is the luminance (toning still colours it).
pub monochrome: bool,
/// Density per log-exposure of the red, green and blue channels of the scan, for levels
/// derived from a base alone ([`Analysis::from_base`]); a measured range makes it irrelevant.
/// A preset sets it to its [`Preset::scan_gamma`].
pub film_gamma: [f32; 3],
}
impl Default for Params {
fn default() -> Self {
Self {
range: DISPLAY_STOPS,
exposure: 0.0,
brightness: 0.0,
contrast: 0.0,
tone: Tone::LabStandard,
lights: 0.0,
darks: 0.0,
whites: 0.0,
blacks: 0.0,
fade: 0.0,
glow: 0.0,
soft_highs: 0.0,
soft_lows: 0.0,
wb: WbPreset::AsIs,
temp: 0.0,
tint: 0.0,
balance: [1.0; 3],
presat: 3.0,
saturation: 0.0,
look: Look::Neutral,
mids_red: 0.0,
mids_green: 0.0,
mids_blue: 0.0,
highs_red: 0.0,
highs_green: 0.0,
highs_blue: 0.0,
highs_range: 30.0,
lows_red: 0.0,
lows_green: 0.0,
lows_blue: 0.0,
lows_range: 30.0,
monochrome: false,
film_gamma: [NEGATIVE_GAMMA; 3],
}
}
}
/// A conversion ready to run on pixels of one encoding: the analysis and the edits folded into
/// per-channel factors, one exponent, one colour pipeline and one tone curve. [`Converter::convert`]
/// is the exact path (two `powf` per channel, and an `expf` when the curve has contrast);
/// [`Converter::convert_with`] runs through [`Tables`] instead, with no transcendental call per
/// sample, for hosts that meter instructions.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Converter {
enc: Encoding,
/// Per channel, the normalised exposure `2^(u · RANGE_STOPS)` of a scan value `t` is
/// `factor · t^(−exponent)`, where `u` is the position of its density between the black and
/// white points (0..1): levels in density space folded into one `powf`.
factor: [f32; 3],
exponent: [f32; 3],
/// `gain / (2^RANGE_STOPS − 1)`: the normalised exposure to a positive, exposure folded in.
scale: f32,
colour: look::Colour,
monochrome: bool,
/// White point as a gain on the linear positive.
white_gain: f32,
/// Black point: lifted (positive) or crushed (negative), as a fraction of the range.
black_point: f32,
/// Exponent applied to the levelled positive per channel (brightness and balance).
gamma: [f32; 3],
/// [`color::encode_pow_knee`] of each `gamma`.
knee: [f32; 3],
curve: tone::Curve,
toning: look::Toning,
}
impl Converter {
/// `neutral` is a scan sample (host encoding) of something that should come out grey, if the
/// user picked one with the colour picker.
pub fn new(a: &Analysis, p: &Params, enc: Encoding, neutral: Option<[f32; 3]>) -> Self {
let gain = libm::exp2f(finite(p.exposure, 0.0).clamp(-10.0, 10.0));
let stops = finite(p.range, DISPLAY_STOPS).clamp(1.0, 10.0);
let scale = gain / (libm::exp2f(stops) - 1.0);
let mut factor = [0.0; 3];
let mut exponent = [0.0; 3];
for ch in 0..3 {
// Stops between the black and white points; the base-only default is RANGE_STOPS.
let black = if a.black[ch].is_finite() { a.black[ch].max(1.0) } else { 1.0 };
let white = if a.white[ch].is_finite() { a.white[ch] } else { 0.0 };
let range = libm::log2f(white) - libm::log2f(black);
let range = if range.is_finite() && range > 1e-3 { range } else { RANGE_STOPS };
// 2^(u · S) = (E / black)^(S / range) = base^(S/(γ range)) · black^(−S/range) · t^(−S/(γ range)).
let e = stops / (NEGATIVE_GAMMA * range);
exponent[ch] = e;
let base = if a.base[ch].is_finite() { a.base[ch].max(film::MIN_TRANSMITTANCE) } else { film::MIN_TRANSMITTANCE };
factor[ch] = libm::powf(base, e) * libm::powf(black, -stops / range);
}
let levelled = |neg: [f32; 3]| {
let mut out = [0.0; 3];
for ch in 0..3 {
let e = film::exposure_encoded(neg[ch], enc, factor[ch], exponent[ch]);
out[ch] = ((e - 1.0) * scale).max(0.0);
}
out
};
// Brightness, the profile's mid-tone gamma and the per-channel balance as one exponent per
// channel on the linear positive (a gamma in encoded space is close to the same gamma on
// the linear value, after encoding).
let brightness = libm::exp2f(-finite(p.brightness, 0.0).clamp(-50.0, 50.0) / 50.0) * p.tone.gamma();
// The per-channel balance corrects a colour cast; a monochrome positive has none, and
// unequal gammas would tint it.
let balance = if p.monochrome { [1.0; 3] } else { p.balance };
let mut gamma = [0.0; 3];
let mut knee = [0.0; 3];
for ch in 0..3 {
gamma[ch] = brightness * finite(balance[ch], 1.0).clamp(0.4, 2.5);
knee[ch] = color::encode_pow_knee(gamma[ch]);
}
Self {
enc,
factor,
exponent,
scale,
colour: look::Colour::new(p, neutral.map(levelled)),
monochrome: p.monochrome,
white_gain: libm::exp2f(finite(p.whites, 0.0).clamp(-50.0, 50.0) / 100.0),
black_point: finite(p.blacks, 0.0).clamp(-50.0, 50.0) / 100.0 * 0.2,
gamma,
knee,
curve: tone::Curve::new(p),
toning: look::Toning::new(p),
}
}
pub fn encoding(&self) -> Encoding {
self.enc
}
/// The levelled linear positive of channel `ch`'s scan value, exposure folded in, capped at
/// [`LEVELS_CAP`].
fn levelled(&self, v: f32, ch: usize) -> f32 {
let e = film::exposure_encoded(v, self.enc, self.factor[ch], self.exponent[ch]);
((e - 1.0) * self.scale).clamp(0.0, LEVELS_CAP)
}
/// The white and black points on a linear positive, clamped to 0..1.
fn points(&self, v: f32) -> f32 {
let mut x = v * self.white_gain;
if self.black_point > 0.0 {
x = self.black_point + x * (1.0 - self.black_point);
} else if self.black_point < 0.0 {
x = (x + self.black_point) / (1.0 + self.black_point);
}
x.clamp(0.0, 1.0)
}
/// The colour stage, monochrome and the points on a levelled positive.
fn graded(&self, mut p: [f32; 3]) -> [f32; 3] {
p = self.colour.apply(p);
if self.monochrome {
p = [color::luminance(p).max(0.0); 3];
}
for v in &mut p {
*v = self.points(*v);
}
p
}
/// One RGB sample of the negative, in the converter's encoding, as the linear positive before
/// the gammas and the tone curve: levels, exposure, colour, the white and black points.
fn positive(&self, neg: [f32; 3]) -> [f32; 3] {
let mut p = [0.0f32; 3];
for (ch, (v, n)) in p.iter_mut().zip(neg).enumerate() {
*v = self.levelled(n, ch);
}
self.graded(p)
}
/// Channel `ch` of a linear positive (after the points) as the sRGB-encoded sample before
/// toning: brightness (a gamma) and the tone curve, which act in sRGB-encoded space.
fn encoded(&self, p: f32, ch: usize) -> f32 {
self.curve.apply(color::srgb_encode_pow(p, self.gamma[ch], self.knee[ch]))
}
/// The toning and the host's encoding on an sRGB-encoded positive.
fn finished(&self, mut out: [f32; 3]) -> [f32; 3] {
out = self.toning.apply(out);
match self.enc {
Encoding::Srgb => out,
Encoding::Linear => [color::srgb_decode(out[0]), color::srgb_decode(out[1]), color::srgb_decode(out[2])],
}
}
/// One RGB sample of the negative, in the converter's encoding, as the positive in the same
/// encoding, 0..1: the exact path, two `powf` per channel.
pub fn convert(&self, neg: [f32; 3]) -> [f32; 3] {
let p = self.positive(neg);
if self.enc == Encoding::Linear && self.curve.is_identity() && self.toning.is_identity {
// Encoding and decoding again would cancel: a gamma on the linear value.
return [libm::powf(p[0], self.gamma[0]), libm::powf(p[1], self.gamma[1]), libm::powf(p[2], self.gamma[2])];
}
self.finished([self.encoded(p[0], 0), self.encoded(p[1], 1), self.encoded(p[2], 2)])
}
/// Channel `ch` of a linear positive as the output table holds it: sRGB-encoded, or in the
/// host's encoding when `folded` (no toning to follow).
fn output_entry(&self, p: f32, ch: usize, folded: bool) -> f32 {
let out = self.encoded(p, ch);
if folded && self.enc == Encoding::Linear { color::srgb_decode(out) } else { out }
}
/// Where a scan value sits in the levels table: as it is for an sRGB host, whose samples are
/// already spaced the way the levels curve bends; by its square root for a linear host, so
/// that the dense end (small values, the highlights) gets most of the entries.
fn levels_index(&self, v: f32) -> f32 {
match self.enc {
Encoding::Srgb => v,
Encoding::Linear => libm::sqrtf(v.max(0.0)),
}
}
/// Fills `t` with this conversion's transfer functions, for [`Converter::convert_with`].
pub fn tables(&self, t: &mut Tables) {
let step = 1.0 / (TABLE_SIZE - 1) as f32;
t.folded = self.toning.is_identity;
for (ch, (levels, output)) in t.levels.iter_mut().zip(t.output.iter_mut()).enumerate() {
// The scan value at which the relative exposure is 1: the black point.
let black = libm::powf(self.factor[ch], 1.0 / self.exponent[ch]);
t.black[ch] = self.levels_index(match self.enc {
Encoding::Srgb => color::srgb_encode(black),
Encoding::Linear => black,
});
for (i, v) in levels.iter_mut().enumerate() {
let u = i as f32 * step;
let scan = match self.enc {
Encoding::Srgb => u,
Encoding::Linear => u * u,
};
// Unfloored, so the entries run straight through the black point and an
// interpolation lands on it; `convert_with` floors the result.
let e = film::exposure_encoded_raw(scan, self.enc, self.factor[ch], self.exponent[ch]);
*v = ((e - 1.0) * self.scale).min(LEVELS_CAP);
}
for (i, v) in output.iter_mut().enumerate() {
*v = self.output_entry(i as f32 * step, ch, t.folded);
}
}
}
/// [`Converter::convert`] through `t`, filled by [`Converter::tables`] for this converter:
/// the same positive to within the tables' interpolation (under a thousandth of the range)
/// with no transcendental call per sample, which is what counts under an interpreter. The
/// darkest inputs, where a steep gamma or a dense highlight outruns any table, take the
/// exact path: few pixels, so little cost.
pub fn convert_with(&self, t: &Tables, neg: [f32; 3]) -> [f32; 3] {
let index = match self.enc {
Encoding::Srgb => neg,
Encoding::Linear => [libm::sqrtf(neg[0].max(0.0)), libm::sqrtf(neg[1].max(0.0)), libm::sqrtf(neg[2].max(0.0))],
};
let mut p = [0.0f32; 3];
for (ch, (v, (table, (n, u)))) in p.iter_mut().zip(t.levels.iter().zip(neg.into_iter().zip(index))).enumerate() {
// At and past the black point (and for NaN) the positive is 0; the darkest inputs
// take the exact path; the rest interpolate.
*v = if u >= t.black[ch] || u.is_nan() {
0.0
} else if u < EXACT_BELOW {
self.levelled(n, ch)
} else {
lookup(table, u).max(0.0)
};
}
p = self.graded(p);
let mut out = [0.0f32; 3];
for (ch, (o, (table, v))) in out.iter_mut().zip(t.output.iter().zip(p)).enumerate() {
*o = if v < EXACT_BELOW { self.output_entry(v, ch, t.folded) } else { lookup(table, v) };
}
if t.folded { out } else { self.finished(out) }
}
}
/// Entries per channel in [`Tables`].
pub const TABLE_SIZE: usize = 2048;
/// Where the levelled positive stops: four stops over white, deep in what the white point clips.
/// Without it a scan value near zero puts a channel at 10⁸ and the colour stage's rounding
/// then zeroes the other two.
const LEVELS_CAP: f32 = 16.0;
/// Inputs below this (the tables' first eight entries) take the exact path in
/// [`Converter::convert_with`]: a gamma of 0.2 or a highlight denser than the second entry
/// changes faster there than an interpolation can follow.
const EXACT_BELOW: f32 = 8.0 / (TABLE_SIZE - 1) as f32;
/// The per-channel transfer functions of a [`Converter`] sampled over their input range, so that
/// a sample costs an interpolation per channel and stage instead of a `powf`. 48 KiB: keep one
/// in static memory and refill it per converter with [`Converter::tables`].
pub struct Tables {
/// Host-encoded scan value (0..1; its square root for a linear host) → levelled linear
/// positive, exposure folded in, unfloored (negative past the black point).
levels: [[f32; TABLE_SIZE]; 3],
/// Linear positive after the colour stage and the points (0..1) → the output sample: the
/// brightness gamma and the tone curve, and the host's encoding when `folded`.
output: [[f32; TABLE_SIZE]; 3],
/// Where in `levels` each channel reaches its black point: at and past it the positive is
/// exactly 0, as on the exact path, rather than an interpolation's few millionths (which a
/// lifting gamma would make visible).
black: [f32; 3],
/// The toning (which mixes channels, so cannot be a table) is identity, and `output` ends
/// in the host's encoding; otherwise it ends sRGB-encoded for the toning to follow.
folded: bool,
}
impl Tables {
pub const fn blank() -> Self {
Self { levels: [[0.0; TABLE_SIZE]; 3], output: [[0.0; TABLE_SIZE]; 3], black: [0.0; 3], folded: false }
}
}
impl Default for Tables {
fn default() -> Self {
Self::blank()
}
}
/// `table` at `x` (0..1, finite), linearly interpolated.
fn lookup(table: &[f32; TABLE_SIZE], x: f32) -> f32 {
let x = x.clamp(0.0, 1.0) * (TABLE_SIZE - 1) as f32;
let i = x as usize;
match (table.get(i), table.get(i + 1)) {
(Some(a), Some(b)) => a + (b - a) * (x - i as f32),
(Some(a), None) => *a,
_ => 0.0,
}
}
/// `v`, or `fallback` when it is NaN or infinite.
pub(crate) fn finite(v: f32, fallback: f32) -> f32 {
if v.is_finite() { v } else { fallback }
}
#[cfg(test)]
mod tests {
use super::*;
const BASE: [f32; 3] = [0.6, 0.35, 0.15];
/// No edits and the scene-linear rendition: the film model's round trip.
fn neutral() -> Params {
Params { tone: Tone::Linear, range: RANGE_STOPS, ..Params::default() }
}
/// The linear scan value a scene value `s` (0..1 of the positive's range) leaves, per channel.
fn negative(s: f32, ch: usize) -> f32 {
let white = libm::exp2f(RANGE_STOPS);
film::transmittance(1.0 + s * (white - 1.0), BASE[ch])
}
fn scan(s: f32, enc: Encoding) -> [f32; 3] {
[enc.encode(negative(s, 0)), enc.encode(negative(s, 1)), enc.encode(negative(s, 2))]
}
fn convert(p: &Params, s: f32) -> [f32; 3] {
Converter::new(&Analysis::manual(BASE), p, Encoding::Srgb, None).convert(scan(s, Encoding::Srgb))
}
#[test]
fn manual_conversion_inverts_the_film_model_in_both_encodings() {
for enc in [Encoding::Srgb, Encoding::Linear] {
let c = Converter::new(&Analysis::manual(BASE), &neutral(), enc, None);
assert_eq!(c.encoding(), enc);
for s in [0.0, 0.01, 0.1, 0.18, 0.5, 0.9, 1.0] {
let out = c.convert(scan(s, enc));
let want = enc.encode(s);
for v in out {
assert!((v - want).abs() < 2e-3, "{enc:?} scene {s}: got {out:?}, want {want}");
}
}
}
}
#[test]
fn base_is_black_and_brighter_than_base_stays_black() {
let c = Converter::new(&Analysis::manual(BASE), &neutral(), Encoding::Linear, None);
assert_eq!(c.convert(BASE), [0.0; 3]);
assert_eq!(c.convert([0.9, 0.9, 0.9]), [0.0; 3]);
// Nothing transmitted at all: the brightest possible scene tone.
assert!(c.convert([0.0; 3]).iter().all(|v| (v - 1.0).abs() < 1e-6));
}
#[test]
fn exposure_brightness_whites_and_blacks_move_tones_the_right_way() {
let base = convert(&neutral(), 0.18)[0];
let up = convert(&Params { exposure: 1.0, ..neutral() }, 0.18)[0];
let bright = convert(&Params { brightness: 25.0, ..neutral() }, 0.18)[0];
let dark = convert(&Params { brightness: -25.0, ..neutral() }, 0.18)[0];
assert!(up > base && bright > base && dark < base, "{base} {up} {bright} {dark}");
assert!((color::srgb_decode(up) / color::srgb_decode(base) - 2.0).abs() < 0.02, "one stop doubles linear light");
// Brightness is a gamma: black and white stay put.
assert_eq!(convert(&Params { brightness: 40.0, ..neutral() }, 0.0)[0], 0.0);
assert!((convert(&Params { brightness: 40.0, ..neutral() }, 1.0)[0] - 1.0).abs() < 1e-5);
// Whites scale towards white, blacks lift or crush the black point.
assert!(convert(&Params { whites: 50.0, ..neutral() }, 0.5)[0] > convert(&neutral(), 0.5)[0]);
assert!(convert(&Params { whites: 50.0, ..neutral() }, 0.0)[0] == 0.0);
assert!(convert(&Params { blacks: 50.0, ..neutral() }, 0.0)[0] > 0.05, "lifted black");
assert!(convert(&Params { blacks: -50.0, ..neutral() }, 0.05)[0] == 0.0, "crushed black");
assert!((convert(&Params { blacks: -50.0, ..neutral() }, 1.0)[0] - 1.0).abs() < 1e-5);
}
#[test]
fn white_balance_presets_looks_and_monochrome() {
let warm = convert(&Params { temp: 50.0, ..neutral() }, 0.3);
assert!(warm[0] > warm[1] && warm[1] > warm[2], "{warm:?}");
let magenta = convert(&Params { tint: 50.0, ..neutral() }, 0.3);
assert!(magenta[1] < magenta[0] && magenta[1] < magenta[2], "{magenta:?}");
let preset = convert(&Params { wb: WbPreset::Warm, ..neutral() }, 0.3);
assert!(preset[0] > preset[2], "{preset:?}");
let lab = convert(&Params { look: Look::LabWarm, ..neutral() }, 0.3);
assert!(lab[0] > lab[2], "{lab:?}");
assert!(convert(&Params { tone: Tone::LinearDeep, ..neutral() }, 0.3)[0] < convert(&neutral(), 0.3)[0], "deep darkens mid-tones");
let mono = convert(&Params { monochrome: true, temp: 50.0, ..neutral() }, 0.3);
assert!(mono[0] == mono[1] && mono[1] == mono[2], "{mono:?}");
let toned = convert(&Params { monochrome: true, lows_blue: 50.0, lows_range: 100.0, ..neutral() }, 0.1);
assert!(toned[2] > toned[0], "toning colours a black-and-white positive: {toned:?}");
let grey = convert(&Params { saturation: -50.0, temp: 50.0, ..neutral() }, 0.3);
assert!((grey[0] - grey[2]).abs() < 1e-5, "{grey:?}");
}
#[test]
fn unequal_channel_ranges_are_balanced_by_the_levels() {
// A scan whose blue runs twice as dense as its red for the same scene: with black and
// white points per channel, a scene grey still comes out grey at every tone.
let stops = [4.0f32, 6.0, 8.0];
let scan = |s: f32| {
let mut v = [0.0; 3];
for ch in 0..3 {
v[ch] = Encoding::Srgb.encode(film::transmittance(libm::exp2f(s * stops[ch]), BASE[ch]));
}
v
};
let a = Analysis::from_scan_values(
[Encoding::Srgb.encode(BASE[0]), Encoding::Srgb.encode(BASE[1]), Encoding::Srgb.encode(BASE[2])],
scan(0.0),
scan(1.0),
Encoding::Srgb,
)
.unwrap();
let c = Converter::new(&a, &neutral(), Encoding::Srgb, None);
for s in [0.0, 0.2, 0.5, 0.8, 1.0] {
let out = c.convert(scan(s));
assert!((out[0] - out[1]).abs() < 4e-3 && (out[1] - out[2]).abs() < 4e-3, "scene {s}: {out:?}");
let want = color::srgb_encode((libm::exp2f(s * RANGE_STOPS) - 1.0) / (libm::exp2f(RANGE_STOPS) - 1.0));
assert!((out[1] - want).abs() < 4e-3, "scene {s}: {out:?} vs {want}");
}
}
#[test]
fn range_and_balance_move_midtones_without_moving_the_ends() {
let wide = convert(&neutral(), 0.18)[0];
let narrow = convert(&Params { range: 3.0, ..neutral() }, 0.18)[0];
assert!(narrow > wide, "fewer stops between black and white render mid-tones brighter: {narrow} vs {wide}");
assert_eq!(Params::default().range, DISPLAY_STOPS);
assert_eq!(convert(&Params { range: 3.0, ..neutral() }, 0.0)[0], 0.0);
assert!((convert(&Params { range: 3.0, ..neutral() }, 1.0)[0] - 1.0).abs() < 1e-5);
let balanced = convert(&Params { balance: [0.8, 1.0, 1.25], ..neutral() }, 0.3);
assert!(balanced[0] > balanced[1] && balanced[1] > balanced[2], "{balanced:?}");
assert_eq!(convert(&Params { balance: [0.8, 1.0, 1.25], ..neutral() }, 0.0), [0.0; 3]);
assert!(convert(&Params { balance: [0.8, 1.0, 1.25], ..neutral() }, 1.0).iter().all(|v| (v - 1.0).abs() < 1e-5));
}
#[test]
fn neutral_sample_balances_the_positive() {
// A scene grey that the scan renders with a cast (a stronger red mask than the base says).
let a = Analysis::manual(BASE);
let cast = [0.8, 1.0, 1.0];
let scan_of =
|s: f32| [Encoding::Srgb.encode(negative(s, 0) * cast[0]), Encoding::Srgb.encode(negative(s, 1)), Encoding::Srgb.encode(negative(s, 2))];
let before = Converter::new(&a, &neutral(), Encoding::Srgb, None).convert(scan_of(0.4));
assert!(before[0] > before[1] + 0.02, "the cast shows: {before:?}");
let after = Converter::new(&a, &neutral(), Encoding::Srgb, Some(scan_of(0.4))).convert(scan_of(0.4));
assert!((after[0] - after[1]).abs() < 2e-3 && (after[1] - after[2]).abs() < 2e-3, "{after:?}");
}
#[test]
fn a_balance_never_tints_a_monochrome_positive() {
let p = Params { monochrome: true, balance: [0.7, 1.0, 1.5], ..neutral() };
for s in [0.05, 0.3, 0.7] {
let out = convert(&p, s);
assert!((out[0] - out[1]).abs() < 1e-6 && (out[1] - out[2]).abs() < 1e-6, "{out:?}");
}
let colour = convert(&Params { balance: [0.7, 1.0, 1.5], ..neutral() }, 0.3);
assert!(colour[0] > colour[2] + 0.02, "the same balance does tint a colour positive: {colour:?}");
}
#[test]
fn tables_match_the_exact_conversion() {
let mut t = std::boxed::Box::new(Tables::blank());
let cases = [
Params::default(),
neutral(),
Params {
brightness: 20.0,
contrast: 25.0,
temp: 15.0,
tint: -10.0,
saturation: 20.0,
lows_blue: 30.0,
lows_range: 40.0,
..Params::default()
},
Params { monochrome: true, balance: [0.8, 1.0, 1.3], ..Params::default() },
// The steepest gammas the sliders and a balance reach, and the hardest curve.
Params { brightness: 50.0, balance: [0.4, 1.0, 2.5], contrast: 50.0, ..Params::default() },
Params { brightness: -50.0, balance: [2.5, 1.0, 0.4], whites: 30.0, blacks: -20.0, ..Params::default() },
];
for enc in [Encoding::Srgb, Encoding::Linear] {
// The base alone, and a measurement whose blue highlight sits two entries from black.
let dense = [0.2, 0.1, if enc == Encoding::Linear { 0.001 } else { 0.03 }];
let analyses = [Analysis::manual(BASE), Analysis::from_scan_values(enc.encode3(BASE), enc.encode3(BASE), dense, enc).unwrap()];
for (p, a) in cases.iter().flat_map(|p| analyses.iter().map(move |a| (p, a))) {
let c = Converter::new(a, p, enc, None);
c.tables(&mut t);
// Compared as displayed: a linear host's output is sRGB-encoded first.
let shown = |v: f32| if enc == Encoding::Linear { color::srgb_encode(v) } else { v };
let (mut worst, mut at) = (0.0f32, [0.0f32; 3]);
for i in 0..=255u32 {
for j in (0..=255u32).step_by(15) {
for k in (0..=255u32).step_by(15) {
let neg = [i as f32 / 255.0, j as f32 / 255.0, k as f32 / 255.0];
// A hair above the black point no path is stable: a lifting gamma
// turns the rounding of a millionth into percents.
if (0..3).any(|ch| (0.0..1e-5).contains(&c.levelled(neg[ch], ch)) && c.levelled(neg[ch], ch) > 0.0) {
continue;
}
let exact = c.convert(neg);
let fast = c.convert_with(&t, neg);
for ch in 0..3 {
let d = (shown(exact[ch]) - shown(fast[ch])).abs();
if d > worst {
(worst, at) = (d, neg);
}
}
}
}
}
let (exact, fast) = (c.convert(at), c.convert_with(&t, at));
std::eprintln!(
"{enc:?}, brightness {}, contrast {}, white {:?}: the tables stray by {worst} at {at:?}: {exact:?} vs {fast:?}",
p.brightness,
p.contrast,
a.white
);
assert!(worst < 1e-3, "{enc:?}: the tables stray by {worst} (an 8-bit level is 0.0039)");
}
}
// Non-finite input is black, as on the exact path.
let c = Converter::new(&Analysis::manual(BASE), &Params::default(), Encoding::Srgb, None);
c.tables(&mut t);
let odd = [f32::NAN, 0.5, f32::INFINITY];
assert!(c.convert_with(&t, odd).iter().zip(c.convert(odd)).all(|(a, b)| (a - b).abs() < 1e-3));
}
#[test]
fn tone_curves_reach_linear_documents_too() {
let strong = Params { tone: Tone::LabHard, range: RANGE_STOPS, ..Params::default() };
let lin = Converter::new(&Analysis::manual(BASE), &strong, Encoding::Linear, None).convert(scan(0.05, Encoding::Linear))[0];
let srgb = Converter::new(&Analysis::manual(BASE), &strong, Encoding::Srgb, None).convert(scan(0.05, Encoding::Srgb))[0];
assert!((color::srgb_encode(lin) - srgb).abs() < 2e-3, "{lin} vs {srgb}");
assert!(lin < 0.05, "a dark tone drops under a hard curve: {lin}");
}
#[test]
fn hostile_parameters_do_not_poison_the_output() {
let p = Params {
exposure: f32::NAN,
brightness: f32::INFINITY,
temp: -1e9,
saturation: f32::NEG_INFINITY,
presat: f32::NAN,
whites: 1e9,
..Params::default()
};
let out = convert(&p, 0.5);
assert!(out.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{out:?}");
let c = Converter::new(&Analysis::manual([f32::NAN, 0.0, f32::INFINITY]), &Params::default(), Encoding::Srgb, Some([f32::NAN; 3]));
let out = c.convert([f32::NAN, -1.0, 2.0]);
assert!(out.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{out:?}");
}
}
+331
View File
@@ -0,0 +1,331 @@
//! Colour: white-balance presets, the colour models (looks), mid-tone colour balance and
//! highlight / shadow toning. Everything here is a per-channel gain or a small matrix, so the
//! conversion stays within the host's instruction budget.
use crate::{Params, color, finite};
/// White-balance presets: fixed temperature / tint offsets for film stocks whose balance a
/// neutral conversion tends to miss. `AsIs` leaves the sliders alone.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WbPreset {
#[default]
AsIs,
/// A touch of warmth, what most colour negative film wants after an inversion.
Warm,
Cool,
/// Tungsten-balanced cine stock shot in daylight: a stronger warm correction.
TungstenFilm,
}
impl WbPreset {
pub const ALL: [(WbPreset, &'static str); 4] =
[(WbPreset::AsIs, "as_is"), (WbPreset::Warm, "warm"), (WbPreset::Cool, "cool"), (WbPreset::TungstenFilm, "tungsten_film")];
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.iter().find(|(_, name)| *name == s).map(|(t, _)| *t)
}
/// (temperature, tint) offsets in slider units.
pub fn offsets(self) -> (f32, f32) {
match self {
Self::AsIs => (0.0, 0.0),
Self::Warm => (8.0, 2.0),
Self::Cool => (-8.0, -2.0),
Self::TungstenFilm => (18.0, 4.0),
}
}
}
/// Colour models: how the positive's colours are rendered.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Look {
/// Colour accuracy over character.
#[default]
Neutral,
/// The rendering of a minilab scanner: teal blues, golden yellows, warm neutrals.
LabWarm,
/// The same family, less warm.
LabCool,
/// Print-like depth: denser shadows with a touch of green, lifted saturation.
Print,
/// Luminosity first: clean contrast, restrained colour.
Clean,
}
impl Look {
pub const ALL: [(Look, &'static str); 5] =
[(Look::Neutral, "neutral"), (Look::LabWarm, "lab_warm"), (Look::LabCool, "lab_cool"), (Look::Print, "print"), (Look::Clean, "clean")];
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.iter().find(|(_, name)| *name == s).map(|(t, _)| *t)
}
pub fn name(self) -> &'static str {
Self::ALL.iter().find(|(t, _)| *t == self).map_or("neutral", |(_, name)| name)
}
/// A row-major matrix on linear RGB (rows sum to 1, so neutrals stay neutral), plus
/// temperature / tint offsets, a saturation factor and a shadow tint (linear RGB gains
/// weighted towards black).
pub fn recipe(self) -> Recipe {
let identity = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
match self {
Self::Neutral => Recipe { matrix: identity, temp: 0.0, tint: 0.0, saturation: 1.0, shadow_tint: [1.0; 3] },
Self::LabWarm => Recipe {
matrix: [[1.00, 0.06, -0.06], [0.02, 1.00, -0.02], [-0.08, 0.12, 0.96]],
temp: 5.0,
tint: 1.0,
saturation: 1.12,
shadow_tint: [1.0; 3],
},
Self::LabCool => Recipe {
matrix: [[1.00, 0.03, -0.03], [0.0, 1.00, 0.0], [-0.06, 0.10, 0.96]],
temp: 0.0,
tint: 0.0,
saturation: 1.08,
shadow_tint: [1.0; 3],
},
Self::Print => Recipe { matrix: identity, temp: 2.0, tint: -1.0, saturation: 1.1, shadow_tint: [0.97, 1.02, 0.98] },
Self::Clean => Recipe { matrix: identity, temp: 0.0, tint: 0.0, saturation: 0.92, shadow_tint: [1.0; 3] },
}
}
}
/// What a [`Look`] does, see [`Look::recipe`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Recipe {
pub matrix: [[f32; 3]; 3],
pub temp: f32,
pub tint: f32,
pub saturation: f32,
pub shadow_tint: [f32; 3],
}
/// Per-channel gains for a temperature / tint pair (slider units, −50..50 each; larger values
/// from presets are allowed), applied in linear light.
pub fn white_balance(temp: f32, tint: f32) -> [f32; 3] {
let t = finite(temp, 0.0).clamp(-100.0, 100.0) / 50.0;
let u = finite(tint, 0.0).clamp(-100.0, 100.0) / 50.0;
[(1.0 + 0.4 * t).max(0.05), (1.0 - 0.3 * u).max(0.05), (1.0 - 0.4 * t).max(0.05)]
}
/// Gains that make the linear positive `sample` neutral (the colour picker on a grey card or a
/// white wall): each channel to the sample's luminance. `None` for a sample without colour.
pub fn neutralise(sample: [f32; 3]) -> Option<[f32; 3]> {
let y = color::luminance(sample);
if !y.is_finite() || y <= 1e-6 || sample.iter().any(|v| !v.is_finite() || *v <= 1e-6) {
return None;
}
Some([(y / sample[0]).clamp(0.2, 5.0), (y / sample[1]).clamp(0.2, 5.0), (y / sample[2]).clamp(0.2, 5.0)])
}
/// Weight of the highlights for toning: 0 below `1 − reach`, 1 at white (`reach` 0..1).
pub fn highs_weight(y: f32, reach: f32) -> f32 {
let reach = reach.clamp(0.05, 1.0);
smoothstep((y - (1.0 - reach)) / reach)
}
/// Weight of the shadows for toning: 1 at black, 0 above `reach` (`reach` 0..1).
pub fn lows_weight(y: f32, reach: f32) -> f32 {
let reach = reach.clamp(0.05, 1.0);
smoothstep((reach - y) / reach)
}
/// Weight of the mid-tones: 1 at middle grey, 0 at black and white.
pub fn mids_weight(y: f32) -> f32 {
let y = y.clamp(0.0, 1.0);
4.0 * y * (1.0 - y)
}
fn smoothstep(x: f32) -> f32 {
let x = finite(x, 0.0).clamp(0.0, 1.0);
x * x * (3.0 - 2.0 * x)
}
/// The colour part of a conversion, folded from [`Params`]: everything in linear light.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Colour {
/// White balance (sliders, preset, look and neutral sample) as gains.
pub gains: [f32; 3],
pub matrix: [[f32; 3]; 3],
/// Saturation before the tone curve (pre-saturation and the look), as a chroma factor.
pub presat: f32,
/// Mid-tone balance gains at full weight (red/cyan, green/magenta, blue/yellow).
pub mids: [f32; 3],
pub shadow_tint: [f32; 3],
/// The matrix is not the identity.
mixes: bool,
/// The mid-tone balance or the shadow tint is not neutral, so the luminance weights are needed.
weighted: bool,
pub is_identity: bool,
}
impl Colour {
/// `neutral` is a linear positive sample that should come out grey, if the user picked one.
pub fn new(p: &Params, neutral: Option<[f32; 3]>) -> Self {
let recipe = p.look.recipe();
let (pt, pu) = p.wb.offsets();
let mut gains = white_balance(finite(p.temp, 0.0) + pt + recipe.temp, finite(p.tint, 0.0) + pu + recipe.tint);
if let Some(n) = neutral.and_then(neutralise) {
for (g, k) in gains.iter_mut().zip(n) {
*g *= k;
}
}
let presat = (finite(p.presat, 3.0).clamp(1.0, 5.0) / 3.0 * recipe.saturation).max(0.0);
let mut mids = [1.0; 3];
for (m, v) in mids.iter_mut().zip([p.mids_red, p.mids_green, p.mids_blue]) {
*m = 1.0 + finite(v, 0.0).clamp(-50.0, 50.0) / 50.0 * 0.25;
}
let mixes = recipe.matrix != Look::Neutral.recipe().matrix;
let weighted = mids != [1.0; 3] || recipe.shadow_tint != [1.0; 3];
let is_identity = gains == [1.0; 3] && !mixes && (presat - 1.0).abs() < 1e-6 && !weighted;
Self { gains, matrix: recipe.matrix, presat, mids, shadow_tint: recipe.shadow_tint, mixes, weighted, is_identity }
}
/// One linear positive sample (levelled, 0..1-ish) through the colour pipeline.
pub fn apply(&self, mut p: [f32; 3]) -> [f32; 3] {
if self.is_identity {
return p;
}
for (v, g) in p.iter_mut().zip(self.gains) {
*v *= g;
}
if self.mixes {
let m = &self.matrix;
p = [
m[0][0] * p[0] + m[0][1] * p[1] + m[0][2] * p[2],
m[1][0] * p[0] + m[1][1] * p[1] + m[1][2] * p[2],
m[2][0] * p[0] + m[2][1] * p[1] + m[2][2] * p[2],
];
}
let y = color::luminance(p).max(0.0);
if !self.weighted {
for v in &mut p {
*v = (y + (*v - y) * self.presat).max(0.0);
}
return p;
}
// Perceptual weights from the luminance; a square root is one instruction.
let yl = libm::sqrtf(y);
let w_mid = mids_weight(yl);
let w_low = lows_weight(yl, 0.35);
for (ch, v) in p.iter_mut().enumerate() {
let mut x = y + (*v - y) * self.presat;
x *= 1.0 + (self.mids[ch] - 1.0) * w_mid;
x *= 1.0 + (self.shadow_tint[ch] - 1.0) * w_low;
*v = x.max(0.0);
}
p
}
}
/// Highlight and shadow toning, applied to the encoded positive after the tone curve: a
/// red / cyan, green / magenta and blue / yellow balance for each end, with a `range` that
/// says how far from the end the toning reaches.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Toning {
highs: [f32; 3],
highs_reach: f32,
lows: [f32; 3],
lows_reach: f32,
/// Saturation after the curve, as a chroma factor.
saturation: f32,
pub is_identity: bool,
}
impl Toning {
pub fn new(p: &Params) -> Self {
let slider = |v: f32| finite(v, 0.0).clamp(-50.0, 50.0) / 50.0 * 0.15;
let reach = |v: f32| 0.2 + finite(v, 30.0).clamp(0.0, 100.0) / 100.0 * 0.6;
let highs = [slider(p.highs_red), slider(p.highs_green), slider(p.highs_blue)];
let lows = [slider(p.lows_red), slider(p.lows_green), slider(p.lows_blue)];
let saturation = (1.0 + finite(p.saturation, 0.0).clamp(-50.0, 50.0) / 50.0).max(0.0);
let is_identity = highs == [0.0; 3] && lows == [0.0; 3] && (saturation - 1.0).abs() < 1e-6;
Self { highs, highs_reach: reach(p.highs_range), lows, lows_reach: reach(p.lows_range), saturation, is_identity }
}
/// One encoded RGB sample (0..1) toned and saturated, 0..1.
pub fn apply(&self, mut c: [f32; 3]) -> [f32; 3] {
if self.is_identity {
return c;
}
let y = (c[0] + c[1] + c[2]) / 3.0;
let w_hi = highs_weight(y, self.highs_reach);
let w_lo = lows_weight(y, self.lows_reach);
for (ch, x) in c.iter_mut().enumerate() {
let v = y + (*x - y) * self.saturation;
*x = (v + self.highs[ch] * w_hi + self.lows[ch] * w_lo).clamp(0.0, 1.0);
}
c
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn presets_and_looks_parse_and_keep_neutrals_neutral() {
for (preset, name) in WbPreset::ALL {
assert_eq!(WbPreset::parse(name), Some(preset));
}
for (look, name) in Look::ALL {
assert_eq!(Look::parse(name), Some(look));
let m = look.recipe().matrix;
for row in m {
assert!((row.iter().sum::<f32>() - 1.0).abs() < 1e-6, "{name}: {row:?}");
}
}
assert_eq!(Look::parse("frontier"), None);
let warm = Colour::new(&Params { look: Look::LabWarm, ..Params::default() }, None);
let grey = warm.apply([0.3, 0.3, 0.3]);
assert!(grey[0] > grey[2], "the warm lab look warms neutrals: {grey:?}");
let neutral = Colour::new(&Params::default(), None);
assert!(neutral.is_identity);
assert_eq!(neutral.apply([0.2, 0.4, 0.6]), [0.2, 0.4, 0.6]);
}
#[test]
fn toning_colours_the_ends_and_post_saturation_scales_chroma() {
let warm_highs = Toning::new(&Params { highs_blue: -50.0, highs_range: 10.0, ..Params::default() });
assert!(!warm_highs.is_identity);
let hi = warm_highs.apply([0.95, 0.95, 0.95]);
assert!(hi[2] < hi[0] && hi[0] == 0.95, "yellow highlights: {hi:?}");
assert_eq!(warm_highs.apply([0.3, 0.3, 0.3]), [0.3, 0.3, 0.3], "mid-tones untouched at a short range");
let cool_lows = Toning::new(&Params { lows_blue: 50.0, lows_range: 100.0, ..Params::default() });
let lo = cool_lows.apply([0.1, 0.1, 0.1]);
assert!(lo[2] > lo[0], "{lo:?}");
assert_eq!(cool_lows.apply([1.0; 3]), [1.0; 3]);
let grey = Toning::new(&Params { saturation: -50.0, ..Params::default() }).apply([0.2, 0.5, 0.8]);
assert!((grey[0] - grey[2]).abs() < 1e-6, "{grey:?}");
assert!(Toning::new(&Params::default()).is_identity);
}
#[test]
fn neutral_sample_is_made_grey() {
let sample = [0.5, 0.4, 0.3];
let c = Colour::new(&Params::default(), Some(sample));
let out = c.apply(sample);
assert!((out[0] - out[1]).abs() < 1e-5 && (out[1] - out[2]).abs() < 1e-5, "{out:?}");
assert_eq!(neutralise([0.0, 0.5, 0.5]), None);
assert_eq!(neutralise([f32::NAN; 3]), None);
}
#[test]
fn presat_mids_and_toning_helpers() {
let vivid = Colour::new(&Params { presat: 5.0, ..Params::default() }, None).apply([0.6, 0.3, 0.3]);
let flat = Colour::new(&Params { presat: 1.0, ..Params::default() }, None).apply([0.6, 0.3, 0.3]);
assert!(vivid[0] - vivid[1] > 0.3 && flat[0] - flat[1] < 0.3, "{vivid:?} {flat:?}");
let mids = Colour::new(&Params { mids_red: 50.0, ..Params::default() }, None);
let mid = mids.apply([0.2, 0.2, 0.2]);
assert!(mid[0] > mid[1], "{mid:?}");
let black = mids.apply([0.0; 3]);
assert_eq!(black, [0.0; 3]);
assert_eq!(highs_weight(1.0, 0.5), 1.0);
assert_eq!(highs_weight(0.4, 0.5), 0.0);
assert_eq!(lows_weight(0.0, 0.3), 1.0);
assert_eq!(lows_weight(0.5, 0.3), 0.0);
assert_eq!(mids_weight(0.5), 1.0);
assert_eq!(white_balance(0.0, 0.0), [1.0; 3]);
}
}
+173
View File
@@ -0,0 +1,173 @@
//! What belongs to the scan rather than the film, measured once on the whole image: the film base
//! and each channel's black and white point, and a mid-tone balance that makes the scene average
//! grey. A host stores the result with the photo's settings, so every render of it (a draft, a
//! zoomed window, a full-size export) converts with the same numbers.
use crate::{Analysis, Converter, Encoding, Params, Tone, ValueHistogram, color};
/// How a scan is measured.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MeasureOptions {
/// Fraction of each edge left out (film holder, sprocket holes, the border itself), 0..0.45.
pub border: f32,
/// Share of the brightest samples that may lie above the film base (dust, hot pixels).
pub base_clip: f32,
/// Shares of samples allowed beyond black and white.
pub black_clip: f32,
pub white_clip: f32,
/// Bring each channel's median to the common one with a per-channel gamma (a grey scene
/// average). Off: the black and white points are neutral and the scene keeps its own colour.
pub neutral: bool,
/// At most this many pixels are sampled (a regular grid over the image).
pub max_samples: usize,
}
impl Default for MeasureOptions {
fn default() -> Self {
Self { border: 0.08, base_clip: 0.001, black_clip: 0.003, white_clip: 0.003, neutral: true, max_samples: 1_000_000 }
}
}
/// A measured scan: scan values in linear light, 0..1, per channel.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Measurement {
/// The film base: the unexposed film, scene black.
pub base: [f32; 3],
/// The brightest value that still counts as exposed (the positive's black).
pub black: [f32; 3],
/// The densest value (the positive's white).
pub white: [f32; 3],
/// Per-channel mid-tone gammas that neutralise the scene average (1 = none).
pub balance: [f32; 3],
}
impl Measurement {
/// The levels of this measurement for linear samples; with a `base` picked from the border,
/// that base is black and the measured white point still applies. `None` when a channel has
/// no range left between black and white.
pub fn analysis(&self, base: Option<[f32; 3]>) -> Option<Analysis> {
match base {
Some(b) => Analysis::from_scan_values(b, b, self.white, Encoding::Linear),
None => Analysis::from_scan_values(self.base, self.black, self.white, Encoding::Linear),
}
}
}
/// Measures a `w × h` scan of linear samples (row-major, 0..1 per channel).
pub fn measure(pixels: &[[f32; 3]], w: usize, h: usize, o: &MeasureOptions) -> Result<Measurement, String> {
if pixels.len() < w.saturating_mul(h) {
return Err("the image is smaller than its size says".into());
}
let border = if o.border.is_finite() { o.border.clamp(0.0, 0.45) } else { 0.0 };
let (bx, by) = ((w as f32 * border) as usize, (h as f32 * border) as usize);
let (x0, x1, y0, y1) = (bx, w.saturating_sub(bx), by, h.saturating_sub(by));
if x1 <= x0 || y1 <= y0 {
return Err("the border leaves no pixels to measure".into());
}
let area = (x1 - x0).saturating_mul(y1 - y0);
let step = (libm::ceil(libm::sqrt(area as f64 / o.max_samples.max(1) as f64)) as usize).max(1);
// The histogram is binned on the sRGB-encoded values, which spread the dense end (the
// highlights, near 0 in linear light) over many more bins than a linear scale would.
let mut hist = ValueHistogram::new();
for y in (y0..y1).step_by(step) {
for x in (x0..x1).step_by(step) {
if let Some(p) = pixels.get(y * w + x) {
hist.push(Encoding::Srgb.encode3(*p));
}
}
}
if hist.count() == 0 {
return Err("no pixels to measure".into());
}
let q = |ch: usize, frac: f32| hist.quantile(ch, frac).map(color::srgb_decode).ok_or_else(|| "empty histogram".to_string());
let mut m = Measurement { base: [0.0; 3], black: [0.0; 3], white: [0.0; 3], balance: [1.0; 3] };
let mut median = [0.0; 3];
for (ch, med) in median.iter_mut().enumerate() {
m.base[ch] = q(ch, 1.0 - o.base_clip.clamp(0.0, 0.5))?;
m.black[ch] = q(ch, 1.0 - o.black_clip.clamp(0.0, 0.5))?;
m.white[ch] = q(ch, o.white_clip.clamp(0.0, 0.5))?;
*med = q(ch, 0.5)?;
if m.white[ch] >= m.black[ch] {
return Err("the scan has no tonal range between black and white (a flat image, or the border leaves too little)".into());
}
}
if o.neutral {
m.balance = neutral_balance(&m, median);
}
Ok(m)
}
/// Per-channel gammas that bring each channel's median positive to the geometric mean of the
/// three: the scene averages grey, black and white stay put.
fn neutral_balance(m: &Measurement, median: [f32; 3]) -> [f32; 3] {
let Some(a) = m.analysis(None) else { return [1.0; 3] };
let c = Converter::new(&a, &Params { tone: Tone::Linear, ..Params::default() }, Encoding::Linear, None);
let out = c.convert(median).map(|v| v.clamp(1e-3, 0.999));
let target = (libm::logf(out[0]) + libm::logf(out[1]) + libm::logf(out[2])) / 3.0;
out.map(|v| {
let b = target / libm::logf(v);
if b.is_finite() { b.clamp(0.4, 2.5) } else { 1.0 }
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{RANGE_STOPS, film};
const BASE: [f32; 3] = [0.6, 0.35, 0.15];
/// A synthetic negative: a log ramp of scene exposures across the width, with a cast in the
/// blue mid-tones the neutral balance should take out, framed by a border of film base.
fn scan(w: usize, h: usize) -> Vec<[f32; 3]> {
let mut px = Vec::with_capacity(w * h);
for y in 0..h {
for x in 0..w {
let inside = x >= w / 10 && x < w - w / 10 && y >= h / 10 && y < h - h / 10;
let s = x as f32 / (w - 1) as f32;
let e = libm::exp2f(s * RANGE_STOPS);
px.push(if inside {
[film::transmittance(e, BASE[0]), film::transmittance(e, BASE[1]), film::transmittance(e, BASE[2]) * 0.8]
} else {
BASE
});
}
}
px
}
#[test]
fn measures_base_levels_and_balance_of_a_synthetic_negative() {
let (w, h) = (300, 200);
let px = scan(w, h);
let m = measure(&px, w, h, &MeasureOptions { border: 0.12, ..MeasureOptions::default() }).unwrap();
for ch in 0..3 {
assert!(m.white[ch] < m.black[ch] && m.black[ch] <= m.base[ch] * 1.01, "{m:?}");
}
assert!(m.balance[2] != 1.0, "the blue cast gets a balance: {m:?}");
// With the border in the measured area, the base is the border.
let framed = measure(&px, w, h, &MeasureOptions { border: 0.0, ..MeasureOptions::default() }).unwrap();
for ch in 0..3 {
assert!((framed.base[ch] - BASE[ch]).abs() < 0.01, "{framed:?}");
}
let a = m.analysis(None).unwrap();
assert!(a.white.iter().zip(a.black).all(|(w, b)| *w > b));
// A picked base is black; the measured white point stays.
let picked = m.analysis(Some(BASE)).unwrap();
assert_eq!(picked.base, BASE);
assert_eq!(picked.black, [1.0; 3]);
}
#[test]
fn bad_input_is_an_error_not_a_panic() {
assert!(measure(&[], 0, 0, &MeasureOptions::default()).is_err());
assert!(measure(&[[0.5; 3]; 4], 10, 10, &MeasureOptions::default()).is_err(), "short buffer");
assert!(measure(&[[0.5; 3]; 100], 10, 10, &MeasureOptions::default()).is_err(), "flat image");
let px = scan(40, 30);
assert!(measure(&px, 40, 30, &MeasureOptions { border: f32::NAN, ..MeasureOptions::default() }).is_ok());
// One sample has no range: an error too.
assert!(measure(&px, 40, 30, &MeasureOptions { max_samples: 0, ..MeasureOptions::default() }).is_err());
let nan = vec![[f32::NAN, f32::INFINITY, -1.0]; 100];
assert!(measure(&nan, 10, 10, &MeasureOptions::default()).is_err());
}
}
+416
View File
@@ -0,0 +1,416 @@
//! Presets: the character of a film stock as a conversion recipe.
//!
//! A preset carries what belongs to the *film*: the contrast of each colour layer (density per
//! log-exposure), the typical colour of its mask, a tone profile, a colour model, saturation,
//! a warmth offset and a touch of toning. It does not carry what belongs to the *scan* (the
//! actual film base and the black and white points), which is measured; the preset's mask
//! colour is only the fallback when nothing was measured.
//!
//! The recipes are starting points derived from the stocks' published characteristic curves
//! and the way they are known to render, named after the stock they take after. Names are
//! lower-case words and numbers, which a host that labels a choice from its value renders
//! capitalised (`portra 400` → "Portra 400"); [`Preset::parse`] accepts any spelling of them.
use crate::{Look, NEGATIVE_GAMMA, Params, Tone, color, finite};
/// How much more density each channel of a scan of colour negative film spans than the layer's
/// own gamma gives, red, green, blue: a scan's blue runs far denser than its red (the orange
/// mask, the dyes' side absorptions, the scanner's or camera's channel sensitivities). Only the
/// levels derived from a base alone use it ([`Preset::scan_gamma`]); a measurement makes it
/// irrelevant.
///
/// Provisional: fitted on three frames of one Kodak Ektar 100 strip photographed against
/// daylight, matching the colour of each frame's mean to the photographer's own positive (the
/// best fit per preset ran 0.62 to 0.78 for red and 1.30 to 1.52 for blue). Without it, those
/// frames came out strongly blue. More scans are needed to settle it.
pub const SCAN_SPREAD: [f32; 3] = [0.7, 1.0, 1.4];
/// One recipe.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Preset {
/// The parameter value and its menu entry, as shown ([`Preset::parse`] takes any spelling).
pub name: &'static str,
/// Density per log-exposure of the red, green and blue layers (as the film's data gives
/// it; a scan spreads them further, [`SCAN_SPREAD`]).
pub gamma: [f32; 3],
/// Typical mask colour of an unexposed, normally scanned frame, sRGB-encoded 0..1: the
/// fallback film base.
pub base: [f32; 3],
pub tone: Tone,
pub look: Look,
pub presat: f32,
/// Offsets added to the sliders.
pub contrast: f32,
pub temp: f32,
pub tint: f32,
pub saturation: f32,
/// Highlight and shadow toning (red, green, blue balance, −50..50) at the default range.
pub highs: [f32; 3],
pub lows: [f32; 3],
pub monochrome: bool,
}
/// Every preset, in menu order. The first is the default.
///
/// The film names are the trademarks of their makers (Eastman Kodak, FUJIFILM, CineStill), used
/// to say which stock a recipe takes after; the recipes are this project's own, built from the
/// stocks' published characteristics and the way they are known to render, and are starting
/// points to tune against your own scans.
pub const PRESETS: [Preset; 12] = [
// A neutral lab scan: even layer contrast, neutral colour, the lab tone profile.
Preset {
name: "Standard",
gamma: [NEGATIVE_GAMMA; 3],
base: [0.80, 0.52, 0.36],
tone: Tone::LabStandard,
look: Look::Neutral,
presat: 3.0,
contrast: 0.0,
temp: 0.0,
tint: 0.0,
saturation: 0.0,
highs: [0.0; 3],
lows: [0.0; 3],
monochrome: false,
},
// Kodak Portra 160: the gentlest of the family. Low contrast, pastel saturation, warm
// natural skin, soft warm highlights.
Preset {
name: "Portra 160",
gamma: [0.56, 0.58, 0.60],
base: [0.79, 0.53, 0.37],
tone: Tone::LabSoft,
look: Look::Neutral,
presat: 2.4,
contrast: -4.0,
temp: 4.0,
tint: 1.0,
saturation: -8.0,
highs: [3.0, 1.0, -4.0],
lows: [0.0, 0.0, 1.0],
monochrome: false,
},
// Kodak Portra 400: the portrait standard. Moderate contrast, warm natural skin, muted but
// full colour, warm highlights, a touch of cool in the shadows.
Preset {
name: "Portra 400",
gamma: [0.58, 0.60, 0.63],
base: [0.79, 0.53, 0.37],
tone: Tone::LabSoft,
look: Look::Neutral,
presat: 2.8,
contrast: 0.0,
temp: 9.0,
tint: -2.0,
saturation: -2.0,
highs: [5.0, 1.0, -6.0],
lows: [-1.0, 1.0, 0.0],
monochrome: false,
},
// Kodak Ektar 100: the saturated one. Steep layers, strong separation, vivid reds and
// blues, clean neutrals, contrast to match.
Preset {
name: "Ektar 100",
gamma: [0.63, 0.65, 0.69],
base: [0.78, 0.50, 0.33],
tone: Tone::LabStandard,
look: Look::Neutral,
presat: 4.0,
contrast: 10.0,
temp: 3.0,
tint: 1.0,
saturation: 14.0,
highs: [2.0, 0.0, -2.0],
lows: [0.0, 0.0, -3.0],
monochrome: false,
},
// Kodak Gold 200: golden. Warm yellow highlights, warm neutrals, saturated reds and
// yellows, the minilab rendering.
Preset {
name: "Gold 200",
gamma: [0.60, 0.62, 0.66],
base: [0.82, 0.54, 0.35],
tone: Tone::LabStandard,
look: Look::LabWarm,
presat: 3.2,
contrast: 2.0,
temp: 12.0,
tint: 3.0,
saturation: 6.0,
highs: [8.0, 3.0, -10.0],
lows: [3.0, 0.0, -3.0],
monochrome: false,
},
// Kodak ColorPlus 200: the everyday stock. Warm like Gold but softer and less saturated,
// warm shadows, a little faded: the look of old snapshots.
Preset {
name: "ColorPlus 200",
gamma: [0.58, 0.60, 0.63],
base: [0.83, 0.55, 0.36],
tone: Tone::LabSoft,
look: Look::LabWarm,
presat: 2.8,
contrast: -2.0,
temp: 10.0,
tint: 2.0,
saturation: -2.0,
highs: [6.0, 2.0, -8.0],
lows: [4.0, 1.0, -2.0],
monochrome: false,
},
// Kodak UltraMax 400: the punchy consumer stock. Saturated, contrasty, warm, strong blues.
Preset {
name: "UltraMax 400",
gamma: [0.61, 0.63, 0.67],
base: [0.81, 0.53, 0.35],
tone: Tone::LabStandard,
look: Look::LabWarm,
presat: 3.5,
contrast: 6.0,
temp: 6.0,
tint: 2.0,
saturation: 10.0,
highs: [4.0, 2.0, -6.0],
lows: [1.0, 0.0, -1.0],
monochrome: false,
},
// Fujifilm Superia X-TRA 400: Fuji's greens. Cooler than Kodak, a steeper green layer,
// vivid, teal shadows, a touch of magenta in skin.
Preset {
name: "Superia 400",
gamma: [0.60, 0.64, 0.66],
base: [0.76, 0.50, 0.34],
tone: Tone::LabStandard,
look: Look::LabCool,
presat: 3.4,
contrast: 6.0,
temp: -5.0,
tint: -5.0,
saturation: 8.0,
highs: [0.0, 3.0, -2.0],
lows: [-3.0, 2.0, 5.0],
monochrome: false,
},
// Fujifilm C200: clean and cool. Soft contrast, restrained saturation, cool neutrals, a
// green-cyan lean in the shadows.
Preset {
name: "C200",
gamma: [0.58, 0.61, 0.63],
base: [0.77, 0.51, 0.35],
tone: Tone::LabSoft,
look: Look::LabCool,
presat: 2.8,
contrast: 0.0,
temp: -4.0,
tint: -3.0,
saturation: -4.0,
highs: [0.0, 2.0, 0.0],
lows: [-2.0, 2.0, 3.0],
monochrome: false,
},
// Fujifilm Pro 400H: the pastel wedding stock. Flat layers, airy highlights, mint greens,
// cyan shadows, soft skin; made to be overexposed.
Preset {
name: "Pro 400H",
gamma: [0.55, 0.58, 0.60],
base: [0.78, 0.52, 0.36],
tone: Tone::LabSoft,
look: Look::Clean,
presat: 2.3,
contrast: -8.0,
temp: -3.0,
tint: -6.0,
saturation: -6.0,
highs: [-2.0, 2.0, 2.0],
lows: [-4.0, 3.0, 5.0],
monochrome: false,
},
// CineStill 800T: tungsten cine stock shot in daylight. Low, cinematic contrast, muted
// colour, teal-blue shadows against warm orange highlights. (The halation it is known for
// is not a colour and is not modelled.)
Preset {
name: "CineStill 800",
gamma: [0.55, 0.57, 0.60],
base: [0.80, 0.52, 0.36],
tone: Tone::Cinematic,
look: Look::Clean,
presat: 2.6,
contrast: 0.0,
temp: -3.0,
tint: 2.0,
saturation: -8.0,
highs: [10.0, 2.0, -8.0],
lows: [-8.0, 0.0, 12.0],
monochrome: false,
},
// Black-and-white: a paper-like straight line with some contrast, no colour.
Preset {
name: "Monochrome",
gamma: [0.65; 3],
base: [0.74; 3],
tone: Tone::Linear,
look: Look::Neutral,
presat: 3.0,
contrast: 15.0,
temp: 0.0,
tint: 0.0,
saturation: 0.0,
highs: [0.0; 3],
lows: [0.0; 3],
monochrome: true,
},
];
/// The sliders a user sets on top of a preset.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Sliders {
pub exposure: f32,
pub brightness: f32,
pub contrast: f32,
pub temp: f32,
pub tint: f32,
pub saturation: f32,
}
/// A preset name reduced to what [`Preset::parse`] compares: its letters and digits, lower-case.
fn name_key(s: &str) -> impl Iterator<Item = char> + '_ {
s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase())
}
impl Preset {
/// The preset with this name, spelled any way: case, spaces, hyphens and underscores do not
/// count (`portra 400`, `portra400` and `PORTRA_400` are the same preset).
pub fn parse(name: &str) -> Option<&'static Preset> {
PRESETS.iter().find(|p| name_key(p.name).eq(name_key(name)))
}
pub fn default_preset() -> &'static Preset {
&PRESETS[0]
}
/// The fallback film base in linear light.
pub fn base_linear(&self) -> [f32; 3] {
[color::srgb_decode(self.base[0]), color::srgb_decode(self.base[1]), color::srgb_decode(self.base[2])]
}
/// Density per log-exposure of each channel as a scan sees it: [`Preset::gamma`] spread by
/// [`SCAN_SPREAD`] for colour film, as it is for black-and-white (no mask, one dye).
pub fn scan_gamma(&self) -> [f32; 3] {
if self.monochrome {
return self.gamma;
}
[self.gamma[0] * SCAN_SPREAD[0], self.gamma[1] * SCAN_SPREAD[1], self.gamma[2] * SCAN_SPREAD[2]]
}
/// The conversion parameters for this preset with `s` on top.
pub fn params(&self, s: &Sliders) -> Params {
let d = Params::default();
Params {
exposure: finite(s.exposure, 0.0),
brightness: finite(s.brightness, 0.0),
contrast: self.contrast + finite(s.contrast, 0.0),
tone: self.tone,
temp: self.temp + finite(s.temp, 0.0),
tint: self.tint + finite(s.tint, 0.0),
presat: self.presat,
saturation: self.saturation + finite(s.saturation, 0.0),
look: self.look,
highs_red: self.highs[0],
highs_green: self.highs[1],
highs_blue: self.highs[2],
lows_red: self.lows[0],
lows_green: self.lows[1],
lows_blue: self.lows[2],
monochrome: self.monochrome,
film_gamma: self.scan_gamma(),
..d
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Analysis, Converter, Encoding, RANGE_STOPS, film};
#[test]
fn presets_parse_and_the_first_is_standard() {
assert_eq!(Preset::default_preset().name, "Standard");
for p in &PRESETS {
assert_eq!(Preset::parse(p.name).map(|q| q.name), Some(p.name));
assert!(p.gamma.iter().all(|g| (0.4..=0.8).contains(g)), "{}", p.name);
assert!(p.base.iter().all(|b| (0.3..=0.95).contains(b)), "{}", p.name);
}
assert!(Preset::parse("portra").is_none());
}
#[test]
fn names_parse_in_any_spelling() {
for (spelling, name) in [
("portra 400", "Portra 400"),
("portra400", "Portra 400"),
("PORTRA_400", "Portra 400"),
("pro 400h", "Pro 400H"),
("CineStill-800", "CineStill 800"),
] {
assert_eq!(Preset::parse(spelling).map(|p| p.name), Some(name), "{spelling}");
}
assert!(Preset::parse("kodachrome").is_none() && Preset::parse("").is_none());
// A host shows a choice with a space exactly as written (PhotoCraft does), so the names
// are the menu's text: capitalised words and numbers, distinct however they are spelled.
for p in &PRESETS {
assert!(p.name.starts_with(|c: char| c.is_ascii_uppercase()), "{}", p.name);
assert!(p.name.chars().all(|c| c.is_ascii_alphanumeric() || c == ' '), "{}", p.name);
assert_eq!(PRESETS.iter().filter(|q| name_key(q.name).eq(name_key(p.name))).count(), 1, "{}", p.name);
}
}
#[test]
fn every_preset_converts_a_ramp_monotonically_and_finitely() {
let white = libm::exp2f(RANGE_STOPS);
for preset in &PRESETS {
let base = preset.base_linear();
let p = preset.params(&Sliders::default());
let c = Converter::new(&Analysis::from_base(base, p.film_gamma), &p, Encoding::Srgb, None);
let mut last = [-1.0f32; 3];
for i in 0..=40 {
let s = i as f32 / 40.0;
let e = 1.0 + s * (white - 1.0);
let scan = [
color::srgb_encode(film::transmittance(e, base[0])),
color::srgb_encode(film::transmittance(e, base[1])),
color::srgb_encode(film::transmittance(e, base[2])),
];
let out = c.convert(scan);
assert!(out.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{}: {out:?}", preset.name);
let y = color::luminance(out);
assert!(y >= color::luminance(last) - 1e-3, "{} not monotonic at {s}: {out:?} after {last:?}", preset.name);
if preset.monochrome {
assert!((out[0] - out[1]).abs() < 1e-5 && (out[1] - out[2]).abs() < 1e-5, "{}: {out:?}", preset.name);
}
last = out;
}
assert!(color::luminance(last) > 0.9, "{} reaches white: {last:?}", preset.name);
}
}
#[test]
fn sliders_add_to_the_preset() {
let golden = Preset::parse("gold 200").unwrap();
let p = golden.params(&Sliders { temp: 10.0, contrast: -8.0, exposure: f32::NAN, ..Sliders::default() });
assert_eq!(p.temp, golden.temp + 10.0);
assert_eq!(p.contrast, golden.contrast - 8.0);
assert_eq!(p.exposure, 0.0);
assert_eq!(p.look, Look::LabWarm);
assert_eq!(p.film_gamma, golden.scan_gamma());
}
#[test]
fn a_scan_spreads_colour_layers_but_not_black_and_white() {
let portra = Preset::parse("portra 400").unwrap();
let g = portra.scan_gamma();
assert!(g[0] < portra.gamma[0] && g[1] == portra.gamma[1] && g[2] > portra.gamma[2], "{g:?}");
let mono = Preset::parse("monochrome").unwrap();
assert_eq!(mono.scan_gamma(), mono.gamma);
}
}
+331
View File
@@ -0,0 +1,331 @@
//! Tone shaping in display (sRGB-encoded) space: the tone profiles, the tone sliders, and the
//! lab-scanner look of a lifted toe (fade) and a soft shoulder (glow).
use crate::{Params, finite};
/// The tone profiles: three families, as lab-style negative conversion software offers them.
///
/// - **Linear**: a flat, neutral start, a straight line between the black and white points;
/// `Deep` darkens the mid-tones, `Flat` lifts black and lowers white a little.
/// - **Cinematic**: smooth, low-contrast mid-tones and shadows with strong highlight
/// separation, the look of scanned cine film; `Flat` lifts the toe further, `Rich` adds
/// contrast.
/// - **Lab**: the contrast of a lab scanner, tones close to clipping. `Standard` is the
/// default; the others change the steepness on one side or both.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Tone {
Linear,
LinearDeep,
LinearFlat,
Cinematic,
CinematicFlat,
CinematicRich,
LabSoft,
#[default]
LabStandard,
LabHard,
LabHighlightSoft,
LabHighlightHard,
LabShadowSoft,
LabShadowHard,
}
/// A profile's shape: logistic steepness on the shadow and highlight sides (0 = straight),
/// a black lift, a white ceiling and a mid-tone gamma.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Profile {
k_lo: f32,
k_hi: f32,
lift: f32,
ceiling: f32,
gamma: f32,
}
impl Tone {
/// Every profile with its parameter name, in menu order.
pub const ALL: [(Tone, &'static str); 13] = [
(Tone::Linear, "linear"),
(Tone::LinearDeep, "linear_deep"),
(Tone::LinearFlat, "linear_flat"),
(Tone::Cinematic, "cinematic"),
(Tone::CinematicFlat, "cinematic_flat"),
(Tone::CinematicRich, "cinematic_rich"),
(Tone::LabSoft, "lab_soft"),
(Tone::LabStandard, "lab_standard"),
(Tone::LabHard, "lab_hard"),
(Tone::LabHighlightSoft, "lab_highlight_soft"),
(Tone::LabHighlightHard, "lab_highlight_hard"),
(Tone::LabShadowSoft, "lab_shadow_soft"),
(Tone::LabShadowHard, "lab_shadow_hard"),
];
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.iter().find(|(_, name)| *name == s).map(|(t, _)| *t)
}
pub fn name(self) -> &'static str {
Self::ALL.iter().find(|(t, _)| *t == self).map_or("linear", |(_, name)| name)
}
/// The profile's mid-tone gamma (> 1 darkens), applied with brightness by the converter.
pub fn gamma(self) -> f32 {
self.profile().gamma
}
fn profile(self) -> Profile {
let p = |k_lo, k_hi, lift, ceiling, gamma| Profile { k_lo, k_hi, lift, ceiling, gamma };
match self {
Self::Linear => p(0.0, 0.0, 0.0, 1.0, 1.0),
Self::LinearDeep => p(0.0, 0.0, 0.0, 1.0, 1.15),
Self::LinearFlat => p(0.0, 0.0, 0.04, 0.97, 1.0),
Self::Cinematic => p(1.5, 3.5, 0.03, 1.0, 0.95),
Self::CinematicFlat => p(1.0, 2.5, 0.06, 0.98, 0.95),
Self::CinematicRich => p(2.5, 4.5, 0.0, 1.0, 1.05),
Self::LabSoft => p(2.5, 2.5, 0.0, 1.0, 1.0),
Self::LabStandard => p(4.0, 4.0, 0.0, 1.0, 1.0),
Self::LabHard => p(6.0, 6.0, 0.0, 1.0, 1.0),
Self::LabHighlightSoft => p(4.0, 2.0, 0.0, 1.0, 1.0),
Self::LabHighlightHard => p(4.0, 6.5, 0.0, 1.0, 1.0),
Self::LabShadowSoft => p(2.0, 4.0, 0.0, 1.0, 1.0),
Self::LabShadowHard => p(6.5, 4.0, 0.0, 1.0, 1.0),
}
}
}
/// Steepness the contrast slider adds at ±50.
const CONTRAST_STEEPNESS: f32 = 4.0;
/// Steepest logistic allowed.
const MAX_STEEPNESS: f32 = 10.0;
/// The folded tone curve of one conversion.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Curve {
/// Logistic steepness on the shadow and highlight sides; both ≤ 0 means "towards flat"
/// by `−k / MAX_STEEPNESS`.
k_lo: f32,
k_hi: f32,
lights: f32,
darks: f32,
/// Black lift (positive fade and the profile's lift) and shadow expansion (negative fade).
lift: f32,
expand_lows: f32,
ceiling: f32,
/// Highlight compression (positive glow) and expansion (negative glow).
glow: f32,
expand_highs: f32,
soft_highs: f32,
soft_lows: f32,
}
impl Curve {
pub fn new(p: &Params) -> Self {
let prof = p.tone.profile();
let contrast = finite(p.contrast, 0.0).clamp(-50.0, 50.0) / 50.0 * CONTRAST_STEEPNESS;
let fade = finite(p.fade, 0.0).clamp(-100.0, 100.0) / 100.0;
let glow = finite(p.glow, 0.0).clamp(-100.0, 100.0) / 100.0;
Self {
k_lo: (prof.k_lo + contrast).clamp(-MAX_STEEPNESS, MAX_STEEPNESS),
k_hi: (prof.k_hi + contrast).clamp(-MAX_STEEPNESS, MAX_STEEPNESS),
lights: finite(p.lights, 0.0).clamp(-50.0, 50.0) / 100.0,
darks: finite(p.darks, 0.0).clamp(-50.0, 50.0) / 100.0,
lift: prof.lift + fade.max(0.0) * 0.2,
expand_lows: (-fade).max(0.0) * 2.0,
ceiling: prof.ceiling,
glow: glow.max(0.0) * 2.0,
expand_highs: (-glow).max(0.0) * 2.0,
soft_highs: finite(p.soft_highs, 0.0).clamp(0.0, 100.0) / 100.0 * 2.0,
soft_lows: finite(p.soft_lows, 0.0).clamp(0.0, 100.0) / 100.0 * 2.0,
}
}
/// True when the curve changes nothing, so a host can skip the encode / decode around it.
pub fn is_identity(&self) -> bool {
self.k_lo.abs() <= 1e-6
&& self.k_hi.abs() <= 1e-6
&& self.lights == 0.0
&& self.darks == 0.0
&& self.lift <= 0.0
&& self.expand_lows <= 0.0
&& self.ceiling >= 1.0
&& self.glow <= 0.0
&& self.expand_highs <= 0.0
&& self.soft_highs <= 0.0
&& self.soft_lows <= 0.0
}
/// `x` (sRGB-encoded, 0..1) through the curve, 0..1.
pub fn apply(&self, x: f32) -> f32 {
let mut y = finite(x, 0.0).clamp(0.0, 1.0);
// The contrast S: one symmetric logistic per side (each pinned at 0, ½ and 1), blended
// across the middle so the join is smooth and mid-grey stays where it is.
if (self.k_lo - self.k_hi).abs() <= 1e-6 {
y = s_curve(y, self.k_lo);
} else {
let w = smoothstep((y - 0.3) / 0.4);
y = s_curve(y, self.k_lo) * (1.0 - w) + s_curve(y, self.k_hi) * w;
}
// Bumps centred on the shadows (⅓) and highlights (⅔), zero at both ends.
y += self.darks * 3.0 * y * (1.0 - y) * (1.0 - y);
y += self.lights * 3.0 * y * y * (1.0 - y);
y = y.clamp(0.0, 1.0);
// Shadow and highlight tonality: expansion steepens an end, compression softens it.
if self.expand_lows > 0.0 {
y = remap(y, 0.0, 0.5, |t| compress_top(t, self.expand_lows));
}
if self.expand_highs > 0.0 {
y = remap(y, 0.5, 1.0, |t| compress_bottom(t, self.expand_highs));
}
if self.glow > 0.0 {
y = remap(y, 0.5, 1.0, |t| compress_top(t, self.glow));
}
if self.soft_lows > 0.0 {
y = remap(y, 0.0, 0.3, |t| compress_bottom(t, self.soft_lows));
}
if self.soft_highs > 0.0 {
y = remap(y, 0.7, 1.0, |t| compress_top(t, self.soft_highs));
}
// Lift and ceiling last, so black and white land where the profile and fade say.
if self.lift > 0.0 || self.ceiling < 1.0 {
y = self.lift + y * (self.ceiling - self.lift);
}
y.clamp(0.0, 1.0)
}
}
fn sigmoid(x: f32) -> f32 {
1.0 / (1.0 + libm::expf(-x))
}
/// A symmetric contrast curve through (0, 0), (½, ½) and (1, 1): a logistic of steepness `k`
/// when `k > 0`, a pull towards flat when `k < 0`, identity at 0.
fn s_curve(y: f32, k: f32) -> f32 {
if k > 1e-6 {
let half = sigmoid(k * 0.5) - 0.5;
(0.5 + 0.5 * (sigmoid(k * (y - 0.5)) - 0.5) / half).clamp(0.0, 1.0)
} else if k < -1e-6 {
y + (0.5 - y) * (-k / MAX_STEEPNESS)
} else {
y
}
}
fn smoothstep(x: f32) -> f32 {
let x = x.clamp(0.0, 1.0);
x * x * (3.0 - 2.0 * x)
}
/// `t` in 0..1 with its slope reduced towards 1 (Reinhard with the white point kept at 1).
fn compress_top(t: f32, a: f32) -> f32 {
t * (1.0 + a) / (1.0 + a * t)
}
/// `t` in 0..1 with its slope reduced towards 0.
fn compress_bottom(t: f32, a: f32) -> f32 {
1.0 - compress_top(1.0 - t, a)
}
/// `y` with `f` applied to the part of it inside `lo..hi` (unchanged outside).
fn remap(y: f32, lo: f32, hi: f32, f: impl Fn(f32) -> f32) -> f32 {
if y <= lo || y >= hi {
return y;
}
lo + f((y - lo) / (hi - lo)) * (hi - lo)
}
#[cfg(test)]
mod tests {
use super::*;
fn curve(p: Params) -> Curve {
Curve::new(&p)
}
fn linear() -> Params {
Params { tone: Tone::Linear, ..Params::default() }
}
#[test]
fn names_round_trip_and_default_is_lab_standard() {
for (tone, name) in Tone::ALL {
assert_eq!(Tone::parse(name), Some(tone));
assert_eq!(tone.name(), name);
}
assert_eq!(Tone::parse("lab"), None);
assert_eq!(Tone::default(), Tone::LabStandard);
assert_eq!(Params::default().tone, Tone::LabStandard);
}
#[test]
fn linear_profile_is_identity_and_every_profile_is_monotonic_and_pinned() {
let c = curve(linear());
assert!(c.is_identity());
for x in [0.0, 0.25, 0.5, 0.75, 1.0] {
assert!((c.apply(x) - x).abs() < 1e-6);
}
for (tone, name) in Tone::ALL {
let c = curve(Params { tone, ..Params::default() });
let mut last = -1.0;
for i in 0..=200 {
let y = c.apply(i as f32 / 200.0);
assert!(y >= last - 1e-5, "{name} not monotonic at {i}: {y} < {last}");
last = y;
}
let lo = c.apply(0.0);
let hi = c.apply(1.0);
assert!((0.0..=0.07).contains(&lo) && (0.96..=1.0).contains(&hi), "{name}: ends {lo} {hi}");
if tone != Tone::Linear && tone != Tone::LinearDeep {
assert!(!c.is_identity(), "{name}");
}
}
}
#[test]
fn lab_profiles_order_by_steepness_on_each_side() {
let at = |tone, x: f32| curve(Params { tone, ..Params::default() }).apply(x);
assert!(at(Tone::LabHard, 0.25) < at(Tone::LabStandard, 0.25) && at(Tone::LabStandard, 0.25) < at(Tone::LabSoft, 0.25));
assert!(at(Tone::LabHard, 0.75) > at(Tone::LabStandard, 0.75) && at(Tone::LabStandard, 0.75) > at(Tone::LabSoft, 0.75));
// Highlight-side variants leave the shadows where Standard has them, and mid-grey stays put.
assert!((at(Tone::LabHighlightHard, 0.15) - at(Tone::LabStandard, 0.15)).abs() < 1e-5);
assert!((at(Tone::LabHighlightSoft, 0.5) - 0.5).abs() < 1e-5 && (at(Tone::LabShadowHard, 0.5) - 0.5).abs() < 1e-5);
assert!(at(Tone::LabHighlightHard, 0.85) > at(Tone::LabStandard, 0.85));
assert!(at(Tone::LabHighlightSoft, 0.85) < at(Tone::LabStandard, 0.85));
assert!(at(Tone::LabShadowHard, 0.15) < at(Tone::LabStandard, 0.15));
assert!(at(Tone::LabShadowSoft, 0.15) > at(Tone::LabStandard, 0.15));
// Cinematic: flatter shadows than Lab Standard, a lifted toe, separated highlights.
assert!(at(Tone::Cinematic, 0.0) > 0.0 && at(Tone::Cinematic, 0.2) > at(Tone::LabStandard, 0.2));
assert!(Tone::LinearDeep.gamma() > 1.0 && Tone::Cinematic.gamma() < 1.0 && Tone::LabStandard.gamma() == 1.0);
assert!(at(Tone::LinearFlat, 0.0) > 0.0 && at(Tone::LinearFlat, 1.0) < 1.0);
}
#[test]
fn contrast_slider_adds_and_removes_steepness() {
let more = curve(Params { contrast: 30.0, ..Params::default() }).apply(0.25);
let standard = curve(Params::default()).apply(0.25);
let less = curve(Params { contrast: -50.0, ..linear() }).apply(0.25);
assert!(more < standard, "{more} {standard}");
assert!(less > 0.25, "negative contrast on a straight line flattens: {less}");
assert!(curve(Params { contrast: -50.0, ..linear() }).apply(0.0) > 0.0);
}
#[test]
fn lights_darks_fade_glow_and_soft_ends_act_where_they_should() {
let lin = linear();
let darks = curve(Params { darks: 50.0, ..lin });
assert!(darks.apply(0.3) > 0.3 && (darks.apply(0.3) - 0.3) > (darks.apply(0.9) - 0.9), "darks lift the low end most");
let lights = curve(Params { lights: -50.0, ..lin });
assert!(lights.apply(0.7) < 0.7 && (0.7 - lights.apply(0.7)) > (0.1 - lights.apply(0.1)), "lights act on the high end");
let fade = curve(Params { fade: 100.0, ..lin });
assert!((fade.apply(0.0) - 0.2).abs() < 1e-6 && (fade.apply(1.0) - 1.0).abs() < 1e-6);
let unfade = curve(Params { fade: -100.0, ..lin });
assert!(unfade.apply(0.1) > 0.1 && unfade.apply(0.0) == 0.0 && (unfade.apply(0.5) - 0.5).abs() < 1e-6, "negative fade steepens the shadows");
let glow = curve(Params { glow: 100.0, ..lin });
assert!(glow.apply(0.75) > 0.75 && (glow.apply(1.0) - 1.0).abs() < 1e-6 && (glow.apply(0.5) - 0.5).abs() < 1e-6);
assert!(glow.apply(0.99) - glow.apply(0.9) < 0.09, "the shoulder compresses the top");
let unglow = curve(Params { glow: -100.0, ..lin });
assert!(unglow.apply(0.75) < 0.75 && (unglow.apply(1.0) - 1.0).abs() < 1e-6, "negative glow expands the highlights");
let soft = curve(Params { soft_highs: 100.0, soft_lows: 100.0, ..lin });
assert!((soft.apply(0.5) - 0.5).abs() < 1e-6 && soft.apply(0.85) > 0.85 && soft.apply(0.15) < 0.15);
assert!(soft.apply(0.02) < 0.02 * 0.6 && (1.0 - soft.apply(0.98)) < 0.02 * 0.6, "flatter at both ends");
assert!(curve(Params { fade: f32::NAN, glow: f32::INFINITY, darks: -1e9, ..lin }).apply(f32::NAN).is_finite());
}
}
+261
View File
@@ -12,6 +12,9 @@
//! (the platform default), or `off` (no GPU compute; the window still needs one backend and
//! keeps the platform default);
//! - else `WGPU_BACKEND` (wgpu's own variable, same names) for both the window and compute.
//! - `LIGHTCRAFT_GPU_ADAPTER` = (part of) a graphics card's name, any case (`4070`): the card for
//! the compute devices — the render device, the denoise network's, the face detector's
//! ([`pick_adapter`]). The window stays on the card that drives the screen.
//!
//! Backends this build doesn't contain (e.g. `gl`: the GL backend isn't compiled in) are ignored
//! with a warning and the platform default is used.
@@ -166,6 +169,173 @@ pub fn instance_flags_from_env(flags: wgpu::InstanceFlags) -> wgpu::InstanceFlag
instance_flags(flags, std::env::var("WGPU_VALIDATION_INDIRECT_CALL").ok().as_deref())
}
/// The graphics card `LIGHTCRAFT_GPU_ADAPTER` asks for: (part of) its name, trimmed and in lower
/// case; `None` when it is unset or blank.
pub fn wanted_adapter() -> Option<String> {
wanted_adapter_from(std::env::var("LIGHTCRAFT_GPU_ADAPTER").ok().as_deref())
}
/// [`wanted_adapter`] from the variable's value `env`.
pub fn wanted_adapter_from(env: Option<&str>) -> Option<String> {
env.map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty())
}
/// Whether the adapter called `name` is the one `wanted` asks for: `wanted` is part of its name,
/// ignoring case (`4070` matches "NVIDIA GeForce RTX 4070 SUPER").
pub fn adapter_name_matches(wanted: &str, name: &str) -> bool {
let wanted = wanted.trim().to_lowercase();
!wanted.is_empty() && name.to_lowercase().contains(&wanted)
}
/// One adapter as [`choose_named_adapter`] sees it, in wgpu's order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Candidate<'a> {
pub name: &'a str,
/// Order among several matching cards, lower first ([`kind_rank`]).
pub rank: u8,
/// A software renderer (WARP, llvmpipe): never picked, the CPU pipeline is faster.
pub software: bool,
}
impl<'a> Candidate<'a> {
/// A candidate from an adapter's name and kind.
pub fn of(name: &'a str, kind: wgpu::DeviceType) -> Candidate<'a> {
Candidate { name, rank: kind_rank(kind), software: kind == wgpu::DeviceType::Cpu }
}
}
/// The order among cards that all match: dedicated, built-in, virtual, other, software.
pub fn kind_rank(kind: wgpu::DeviceType) -> u8 {
match kind {
wgpu::DeviceType::DiscreteGpu => 0,
wgpu::DeviceType::IntegratedGpu => 1,
wgpu::DeviceType::VirtualGpu => 2,
wgpu::DeviceType::Other => 3,
wgpu::DeviceType::Cpu => 4,
}
}
/// What a `LIGHTCRAFT_GPU_ADAPTER` name picks among the candidates ([`choose_named_adapter`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NamedChoice {
/// The card used (the first of `matches`), `None`: the default choice.
pub index: Option<usize>,
/// Every hardware card whose name matches, in the defined order.
pub matches: Vec<usize>,
/// Software renderers whose name matches (never used).
pub software: Vec<usize>,
}
/// Which of `candidates` (in wgpu's order) `wanted` picks: of the hardware cards whose name
/// contains it (any case), the one whose whole name it is, then dedicated before built-in before
/// virtual cards ([`kind_rank`]), then wgpu's order. Software renderers are never picked.
pub fn choose_named_adapter(wanted: &str, candidates: &[Candidate<'_>]) -> NamedChoice {
let w = wanted.trim().to_lowercase();
let hits = || candidates.iter().enumerate().filter(|(_, c)| adapter_name_matches(&w, c.name));
let software: Vec<usize> = hits().filter(|(_, c)| c.software).map(|(i, _)| i).collect();
let mut ranked: Vec<(bool, u8, usize)> =
hits().filter(|(_, c)| !c.software).map(|(i, c)| (c.name.trim().to_lowercase() != w, c.rank, i)).collect();
// (the index last: equal ones keep wgpu's order)
ranked.sort_unstable();
let matches: Vec<usize> = ranked.into_iter().map(|(_, _, i)| i).collect();
NamedChoice { index: matches.first().copied(), matches, software }
}
/// The log line for `choice` (warning: `true`): which card the name picked and why, or why none.
pub fn named_choice_note(wanted: &str, choice: &NamedChoice, candidates: &[Candidate<'_>]) -> (bool, String) {
let name = |i: &usize| candidates.get(*i).map_or("?", |c| c.name);
let list = |v: &[usize]| v.iter().map(name).collect::<Vec<_>>().join(", ");
match (choice.index, choice.matches.len()) {
(Some(i), 1) => (false, format!("gpu: LIGHTCRAFT_GPU_ADAPTER={wanted}: using {}", name(&i))),
(Some(i), n) => (
false,
format!(
"gpu: LIGHTCRAFT_GPU_ADAPTER={wanted} matches {n} graphics cards ({}): using {} (a card's whole name first, then dedicated before built-in cards, then the system's order); give more of the name to pick another",
list(&choice.matches),
name(&i)
),
),
(None, _) if !choice.software.is_empty() => (
true,
format!(
"gpu: LIGHTCRAFT_GPU_ADAPTER={wanted} names only a software renderer ({}), never used: the processor is faster; using the default choice",
list(&choice.software)
),
),
(None, _) => {
let all: Vec<&str> = candidates.iter().map(|c| c.name).collect();
(true, format!("gpu: LIGHTCRAFT_GPU_ADAPTER={wanted} names none of the graphics cards ({}); using the default choice", all.join(", ")))
}
}
}
/// Lines already logged by [`log_once`] (each device that picks a card asks again).
static LOGGED: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// Log `line` (as a warning when `warn`) the first time only; whether it was logged now.
pub fn log_once(warn: bool, line: &str) -> bool {
let mut seen = LOGGED.lock().unwrap_or_else(|e| e.into_inner());
if seen.iter().any(|l| l == line) {
return false;
}
// (a handful of distinct lines in a run; the cap only bounds a pathological caller)
if seen.len() < 64 {
seen.push(line.to_string());
}
if warn {
log::warn!("{line}");
} else {
log::info!("{line}");
}
true
}
/// Which of `adapters` (name and kind, in wgpu's order) `wanted` picks ([`choose_named_adapter`]).
pub fn find_named_adapter<'a>(wanted: &str, adapters: impl IntoIterator<Item = (&'a str, wgpu::DeviceType)>) -> Option<usize> {
let candidates: Vec<Candidate<'a>> = adapters.into_iter().map(|(n, k)| Candidate::of(n, k)).collect();
choose_named_adapter(wanted, &candidates).index
}
/// The adapter for a compute device (the render device, the denoise network's, the face detector's)
/// on `instance` with `backends`: the card `LIGHTCRAFT_GPU_ADAPTER` names, else the
/// high-performance one. A name that matches no card is logged (once) and the high-performance one
/// is used; never a panic. Each device makes its own instance and device on the card, so two
/// devices never share a buffer, pipeline or queue.
pub fn pick_adapter(instance: &wgpu::Instance, backends: Backends) -> Result<wgpu::Adapter, String> {
pick_adapter_named(instance, backends, wanted_adapter().as_deref())
}
/// [`pick_adapter`] for an explicit `wanted` name (part of it, any case) instead of the variable's.
pub fn pick_adapter_named(instance: &wgpu::Instance, backends: Backends, wanted: Option<&str>) -> Result<wgpu::Adapter, String> {
if let Some(w) = wanted {
let all = pollster::block_on(instance.enumerate_adapters(backends));
let infos: Vec<wgpu::AdapterInfo> = all.iter().map(|a| a.get_info()).collect();
let candidates: Vec<Candidate<'_>> = infos.iter().map(|i| Candidate::of(&i.name, i.device_type)).collect();
let choice = choose_named_adapter(w, &candidates);
let (warn, line) = named_choice_note(w, &choice, &candidates);
log_once(warn, &line);
if let Some(adapter) = choice.index.and_then(|i| all.into_iter().nth(i)) {
return Ok(adapter);
}
}
pollster::block_on(
instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }),
)
.map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))
}
/// Whether the render device may share the window's device (adapter `window_adapter`): yes unless
/// `LIGHTCRAFT_GPU_ADAPTER` names another card, which then renders on a device of its own (the
/// window stays on the card that drives the screen; renders come back as pixels).
pub fn may_adopt_window_device(window_adapter: &str) -> bool {
may_adopt_window_device_for(wanted_adapter().as_deref(), window_adapter)
}
/// [`may_adopt_window_device`] for an explicit `wanted` name.
pub fn may_adopt_window_device_for(wanted: Option<&str>, window_adapter: &str) -> bool {
wanted.is_none_or(|w| adapter_name_matches(w, window_adapter))
}
/// `LIGHTCRAFT_GPU_BACKEND=off`.
pub(crate) fn env_off() -> bool {
env_choice() == BackendChoice::Off
@@ -410,6 +580,97 @@ mod tests {
}
}
/// `LIGHTCRAFT_GPU_ADAPTER` picks a card by part of its name, any case; software adapters never.
#[test]
fn gpu_adapter_variable_matches_part_of_the_card_name() {
use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu};
assert_eq!(wanted_adapter_from(None), None);
assert_eq!(wanted_adapter_from(Some(" ")), None);
assert_eq!(wanted_adapter_from(Some(" RTX 4070 ")).as_deref(), Some("rtx 4070"));
assert!(adapter_name_matches("4070", "NVIDIA GeForce RTX 4070 SUPER"));
assert!(adapter_name_matches("geforce rtx 4070 super", "NVIDIA GeForce RTX 4070 SUPER"));
assert!(adapter_name_matches(" Super ", "NVIDIA GeForce RTX 4070 SUPER"));
assert!(!adapter_name_matches("4070", "NVIDIA GeForce RTX 5070"));
assert!(!adapter_name_matches("", "NVIDIA GeForce RTX 5070"), "a blank name matches nothing");
// two cards: the screen's card first in wgpu's order, as here
let two = [("NVIDIA GeForce RTX 5070", DiscreteGpu), ("NVIDIA GeForce RTX 4070 SUPER", DiscreteGpu), ("Microsoft Basic Render Driver", Cpu)];
assert_eq!(find_named_adapter("4070", two), Some(1));
assert_eq!(find_named_adapter("5070", two), Some(0));
// "070" is in both: the first one in wgpu's order
assert_eq!(find_named_adapter("070", two), Some(0));
assert_eq!(find_named_adapter("radeon", two), None, "no match: the caller falls back to the default choice");
assert_eq!(find_named_adapter("basic render", two), None, "a software adapter is never picked");
assert_eq!(find_named_adapter("intel", [("Intel(R) UHD Graphics 770", IntegratedGpu)]), Some(0));
assert_eq!(find_named_adapter("4070", [] as [(&str, wgpu::DeviceType); 0]), None);
}
/// A fake adapter list (a laptop: built-in card first, a dedicated one, WARP; and two of a
/// kind): no match, several matches, software, and the one log line each gives.
#[test]
fn a_fake_adapter_list_picks_in_a_defined_order() {
use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu, VirtualGpu};
let laptop = [
Candidate::of("Intel(R) Iris(R) Xe Graphics", IntegratedGpu),
Candidate::of("NVIDIA GeForce RTX 4060 Laptop GPU", DiscreteGpu),
Candidate::of("Microsoft Basic Render Driver", Cpu),
];
// no match: the default choice, and a warning that lists the cards
let none = choose_named_adapter("radeon", &laptop);
assert_eq!(none, NamedChoice::default());
let (warn, line) = named_choice_note("radeon", &none, &laptop);
assert!(warn && line.contains("names none") && line.contains("RTX 4060 Laptop GPU") && line.contains("default choice"), "{line}");
// several: dedicated before built-in although the built-in card comes first in wgpu's order
let g = choose_named_adapter("g", &laptop);
assert_eq!((g.index, g.matches.clone()), (Some(1), vec![1, 0]));
let (warn, line) = named_choice_note("g", &g, &laptop);
assert!(!warn && line.contains("matches 2") && line.contains("using NVIDIA GeForce RTX 4060 Laptop GPU"), "{line}");
// one: says which
let one = choose_named_adapter("iris", &laptop);
assert_eq!(one.index, Some(0));
assert_eq!(
named_choice_note("iris", &one, &laptop),
(false, "gpu: LIGHTCRAFT_GPU_ADAPTER=iris: using Intel(R) Iris(R) Xe Graphics".to_string())
);
// a software renderer: never, and the warning says so
let warp = choose_named_adapter("basic render", &laptop);
assert_eq!((warp.index, warp.software.clone()), (None, vec![2]));
let (warn, line) = named_choice_note("basic render", &warp, &laptop);
assert!(warn && line.contains("only a software renderer"), "{line}");
// a card's whole name beats a longer name that contains it, wherever it is listed
let twins = [
Candidate::of("NVIDIA GeForce RTX 4070 SUPER", DiscreteGpu),
Candidate::of("NVIDIA GeForce RTX 4070", DiscreteGpu),
Candidate::of("Virtual RTX 4070", VirtualGpu),
];
assert_eq!(choose_named_adapter("nvidia geforce rtx 4070", &twins).matches, vec![1, 0]);
// same kind: wgpu's order; virtual after dedicated
assert_eq!(choose_named_adapter("4070", &twins).matches, vec![0, 1, 2]);
// the same card on two backends (Vulkan and GL on Linux): the first listed
let both = [Candidate::of("AMD Radeon RX 7800 XT", DiscreteGpu), Candidate::of("AMD Radeon RX 7800 XT", DiscreteGpu)];
assert_eq!(choose_named_adapter("7800", &both).index, Some(0));
assert_eq!(choose_named_adapter("7800", &[]), NamedChoice::default());
}
/// The render device, the denoise network's and the face detector's each ask for a card: the
/// line about it is logged once, not three times.
#[test]
fn a_choice_is_logged_once() {
let line = "gpu: LIGHTCRAFT_GPU_ADAPTER=test-only-name names none of the graphics cards (); using the default choice";
assert!(log_once(true, line));
assert!(!log_once(true, line));
assert!(!log_once(false, line));
assert!(log_once(true, &format!("{line} (another)")));
}
/// The render device shares the window's device only when the variable names the window's card.
#[test]
fn window_device_is_adopted_only_for_the_wanted_card() {
assert!(may_adopt_window_device_for(None, "NVIDIA GeForce RTX 5070"));
assert!(may_adopt_window_device_for(Some("5070"), "NVIDIA GeForce RTX 5070"));
assert!(!may_adopt_window_device_for(Some("4070"), "NVIDIA GeForce RTX 5070"));
assert!(may_adopt_window_device_for(Some("4070"), "NVIDIA GeForce RTX 4070 SUPER"));
}
#[test]
fn resolves_against_the_build() {
let compiled = Backends::DX12 | Backends::VULKAN;
+270 -40
View File
@@ -30,7 +30,12 @@ const MODULES: &[Module] = &[
Module {
src: include_str!("wgsl/blur.wgsl"),
bindings: &[("src", false, "f32"), ("dst", true, "f32")],
entries: &["box_h", "box_v", "median_h", "median_v"],
entries: &["box_h", "box_v", "minmax", "median_h", "median_v"],
},
Module {
src: include_str!("wgsl/gauss.wgsl"),
bindings: &[("src", false, "f32"), ("taps", false, "f32"), ("dst", true, "f32")],
entries: &["gauss_h", "gauss_v"],
},
Module {
src: include_str!("wgsl/resize.wgsl"),
@@ -55,13 +60,26 @@ const MODULES: &[Module] = &[
"xguided_pre",
"xguided_ab",
"xguided_apply",
"fringe_lab",
"fringe_apply",
],
},
Module {
src: include_str!("wgsl/spot.wgsl"),
bindings: &[("img", true, "f32"), ("pts", false, "f32"), ("al", true, "f32"), ("sp", true, "f32"), ("df", true, "f32"), ("wt", true, "f32")],
entries: &["spot_prep", "spot_apply", "spot_score"],
},
Module { src: include_str!("wgsl/hist.wgsl"), bindings: &[("px", false, "u32"), ("bins", true, "atomic<u32>")], entries: &["histogram"] },
Module {
src: include_str!("wgsl/mask.wgsl"),
bindings: &[("img", false, "f32"), ("log_l", false, "f32"), ("aux", false, "f32"), ("c", true, "f32"), ("alpha", true, "f32")],
entries: &["shape", "combine", "finalize"],
},
Module {
src: include_str!("wgsl/present.wgsl"),
bindings: &[("px", false, "u32"), ("dst", true, "u32"), ("count", true, "atomic<u32>")],
entries: &["unwritten", "pad_rows"],
},
Module {
src: include_str!("wgsl/geom.wgsl"),
bindings: &[("src", false, "f32"), ("dst", true, "f32"), ("coverage", false, "u32")],
@@ -337,6 +355,8 @@ pub struct Gpu {
free: std::sync::Mutex<Vec<Tracked>>,
/// Largest storage buffer the device accepts (bytes).
pub max_buffer: u64,
/// The device is the window's (eframe's): renders can hand it textures to draw directly.
pub window: bool,
}
/// WGSL constants shared by every module (generated from the CPU pipeline's values).
@@ -345,7 +365,15 @@ fn constants() -> String {
use lightcraft_pipeline::tone::{CHROMA_N, LUT_MAX_EV, LUT_MIN_EV, LUT_N};
let mut s = String::new();
let [to_lms, from_lms, to_lab, from_lab] = lightcraft_color::perceptual::oklab_matrices();
for (name, m) in [("OK_TO_LMS", to_lms), ("OK_FROM_LMS", from_lms), ("OK_TO_LAB", to_lab), ("OK_FROM_LAB", from_lab)] {
let (to_pro, from_pro) = lightcraft_pipeline::light_v3::prophoto_matrices();
for (name, m) in [
("OK_TO_LMS", to_lms),
("OK_FROM_LMS", from_lms),
("OK_TO_LAB", to_lab),
("OK_FROM_LAB", from_lab),
("PRO_FROM_2020", to_pro),
("PRO_TO_2020", from_pro),
] {
let rows: Vec<String> = m.iter().map(|r| format!("vec3<f32>({:?}, {:?}, {:?})", r[0], r[1], r[2])).collect();
s += &format!("const {name} = array<vec3<f32>, 3>({});\n", rows.join(", "));
}
@@ -360,10 +388,18 @@ fn constants() -> String {
crate::params::CURVE_N
);
s += &format!("const POINT_WORDS: u32 = {}u;\n", lightcraft_pipeline::colorops::POINT_WORDS);
let y = lightcraft_pipeline::light_v3::PRO_Y;
s += &format!("const PRO_Y = vec3<f32>({:?}, {:?}, {:?});\nconst LIGHT_N: u32 = {}u;\n", y[0], y[1], y[2], lightcraft_pipeline::light_v3::LUT_N);
s += &format!("const EYE_WORDS: u32 = {}u;\n", lightcraft_pipeline::redeye::EYE_WORDS);
use lightcraft_pipeline::masks::{AUTO_TOL_CHROMA, AUTO_TOL_EV};
s += &format!("const AUTO_TOL_EV: f32 = {AUTO_TOL_EV:?};\nconst AUTO_TOL_CHROMA: f32 = {AUTO_TOL_CHROMA:?};\n");
s += &format!("const SHADOW_TINT_K: f32 = {:?};\n", lightcraft_pipeline::colorops::SHADOW_TINT);
s += &format!("const GAMUT_WARN: f32 = {:?};\n", lightcraft_pipeline::finish::GAMUT_WARN);
s += &format!("const NCAND: u32 = {}u;\n", lightcraft_pipeline::spots::candidates(1.0).len());
use lightcraft_pipeline::output::{PROOF_DEST_WARNING, PROOF_DISPLAY_WARNING};
for (name, c) in [("PROOF_DEST", PROOF_DEST_WARNING), ("PROOF_DISP", PROOF_DISPLAY_WARNING)] {
s += &format!("const {name}_R: f32 = {:?};\nconst {name}_G: f32 = {:?};\nconst {name}_B: f32 = {:?};\n", c[0], c[1], c[2]);
}
for (i, h) in GRAIN_HASH.iter().enumerate() {
s += &format!("const GRAIN_H{i}: u32 = {h}u;\n");
}
@@ -397,10 +433,8 @@ impl Gpu {
// no indirect-call validation pipeline: Intel Metal fails to compile it (#250)
desc.flags = crate::backend::instance_flags_from_env(desc.flags);
let instance = wgpu::Instance::new(desc);
let adapter = pollster::block_on(
instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }),
)
.map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?;
// the card LIGHTCRAFT_GPU_ADAPTER names, else the high-performance one
let adapter = crate::backend::pick_adapter(&instance, backends)?;
let info = adapter.get_info();
if refuse_adapter(info.device_type, software_allowed()) {
log::info!("gpu: only a software adapter ({}), using the CPU pipeline", info.name);
@@ -414,17 +448,46 @@ impl Gpu {
log::info!("gpu: {} has too few storage buffers per stage", info.name);
return Err(format!("{} has too few storage buffers per shader stage ({} < 10)", info.name, limits.max_storage_buffers_per_shader_stage));
}
if let Some((binding, buffer)) = limits_override() {
limits.max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size.min(binding);
limits.max_buffer_size = limits.max_buffer_size.min(buffer);
log::info!("gpu: LIGHTCRAFT_GPU_LIMITS: storage bindings ≤ {} MiB, buffers ≤ {} MiB", binding >> 20, buffer >> 20);
}
limits = capped(limits, limits_override());
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("lightcraft"),
required_limits: limits.clone(),
..Default::default()
}))
.map_err(|e| format!("{}: device creation failed ({e})", info.name))?;
Gpu::with_device(device, queue, info, limits, false)
}
/// The renderer on the window's device ([`crate::adopt_window_device`]), within its limits
/// lowered by `LIGHTCRAFT_GPU_LIMITS` as a device of its own would be.
pub fn adopt(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo) -> Result<Gpu, String> {
Gpu::adopt_capped(device, queue, info, limits_override())
}
/// [`Gpu::adopt`] with the limits override given (`LIGHTCRAFT_GPU_LIMITS`, parsed).
fn adopt_capped(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo, cap: Option<(u64, u64)>) -> Result<Gpu, String> {
let limits = capped(device.limits(), cap);
Gpu::with_device(device, queue, info, limits, true)
}
/// The renderer on an existing device: the window's (`window`, see [`crate::adopt_window_device`])
/// or one [`Gpu::new`] created with `limits`. Builds the kernels (~0.4–2 s: not on the UI thread).
pub fn with_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo, limits: wgpu::Limits, window: bool) -> Result<Gpu, String> {
if limits.max_storage_buffers_per_shader_stage < 10 {
return Err(format!("{} has too few storage buffers per shader stage ({} < 10)", info.name, limits.max_storage_buffers_per_shader_stage));
}
let started = std::time::Instant::now();
let kernels = match build_kernels(&device) {
Ok(kernels) => kernels,
Err(e) => {
log::error!("gpu: kernels failed to build on {}: {e}", info.name);
return Err(format!("{}: kernels failed to build ({e})", info.name));
}
};
let build_ms = started.elapsed().as_millis();
// Only a device the renderer keeps gets these: a window's device declined above keeps the
// window's own handler, so a later error of the window's can't stop the renderer's device
// (review of PR #1065).
// Errors outside a render's error scopes (see `ErrorScopes`): log, and stop using the GPU.
device.on_uncaptured_error(std::sync::Arc::new(|e| {
log::error!("gpu: {e}");
@@ -437,15 +500,6 @@ impl Gpu {
log::error!("gpu: device lost ({reason:?}): {msg}");
crate::mark_broken(&format!("device lost ({reason:?}): {msg}"));
});
let started = std::time::Instant::now();
let kernels = match build_kernels(&device) {
Ok(kernels) => kernels,
Err(e) => {
log::error!("gpu: kernels failed to build on {}: {e}", info.name);
return Err(format!("{}: kernels failed to build ({e})", info.name));
}
};
let build_ms = started.elapsed().as_millis();
let dummy = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("dummy"),
size: 16,
@@ -453,8 +507,15 @@ impl Gpu {
mapped_at_creation: false,
});
let max_buffer = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size);
log::info!("gpu: {} ({:?}), {} kernels in {build_ms} ms, buffers ≤ {} MiB", info.name, info.backend, kernels.len(), max_buffer >> 20);
Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer })
log::info!(
"gpu: {} ({:?}), {} kernels in {build_ms} ms, buffers ≤ {} MiB{}",
info.name,
info.backend,
kernels.len(),
max_buffer >> 20,
if window { ", the window's device" } else { "" }
);
Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, window })
}
/// A buffer of `len` 32-bit values with undefined contents (a recycled one when possible).
@@ -542,24 +603,7 @@ impl Gpu {
/// second panic while a failed render unwinds aborts the process. A lost device is not polled
/// again; a poll that panics counts as one and stops the GPU.
pub(crate) fn poll(&self, t: wgpu::PollType) -> Result<wgpu::PollStatus, String> {
if DEVICE_LOST.load(Ordering::Relaxed) {
return Err("the device is lost".into());
}
let polled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
#[cfg(test)]
if SIMULATED_LOST_POLL.with(std::cell::Cell::get) {
panic!("Error in Device::poll: Validation Error\n\nCaused by:\n Parent device is lost (simulated)");
}
self.device.poll(t)
}));
match polled {
Ok(r) => r.map_err(|e| e.to_string()),
Err(_) => {
DEVICE_LOST.store(true, Ordering::Relaxed);
crate::mark_broken("device lost: Device::poll failed");
Err("the device is lost (Device::poll failed)".into())
}
}
poll_device(&self.device, t)
}
/// Upload 32-bit values.
@@ -771,6 +815,108 @@ fn limits_override() -> Option<(u64, u64)> {
parse_limits(&std::env::var("LIGHTCRAFT_GPU_LIMITS").ok()?)
}
/// `limits` lowered to `cap` ([`limits_override`]: storage binding bytes, buffer bytes).
fn capped(mut limits: wgpu::Limits, cap: Option<(u64, u64)>) -> wgpu::Limits {
if let Some((binding, buffer)) = cap {
limits.max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size.min(binding);
limits.max_buffer_size = limits.max_buffer_size.min(buffer);
log::info!("gpu: LIGHTCRAFT_GPU_LIMITS: storage bindings ≤ {} MiB, buffers ≤ {} MiB", binding >> 20, buffer >> 20);
}
limits
}
/// `device.poll` that never panics: see [`Gpu::poll`]. [`read_texture`] uses it too: its device
/// (the window's, when adopted) shares the device-lost flag.
fn poll_device(device: &wgpu::Device, t: wgpu::PollType) -> Result<wgpu::PollStatus, String> {
if DEVICE_LOST.load(Ordering::Relaxed) {
return Err("the device is lost".into());
}
let polled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
#[cfg(test)]
if SIMULATED_LOST_POLL.with(std::cell::Cell::get) {
panic!("Error in Device::poll: Validation Error\n\nCaused by:\n Parent device is lost (simulated)");
}
device.poll(t)
}));
match polled {
Ok(r) => r.map_err(|e| e.to_string()),
Err(_) => {
DEVICE_LOST.store(true, Ordering::Relaxed);
crate::mark_broken("device lost: Device::poll failed");
Err("the device is lost (Device::poll failed)".into())
}
}
}
/// See [`crate::read_texture`].
pub(crate) fn read_texture(
device: &wgpu::Device,
queue: &wgpu::Queue,
texture: &wgpu::Texture,
width: usize,
height: usize,
) -> Result<lightcraft_raster::Rgba8, String> {
if DEVICE_LOST.load(Ordering::Relaxed) {
return Err("the device is lost".into());
}
if width == 0 || height == 0 {
return Err("an empty texture".into());
}
let (Ok(w32), Ok(h32)) = (u32::try_from(width), u32::try_from(height)) else { return Err("texture too large".into()) };
if w32 > texture.width() || h32 > texture.height() || texture.format() != wgpu::TextureFormat::Rgba8Unorm {
return Err("not an 8-bit view texture of that size".into());
}
// texture copies take rows of a multiple of 256 bytes
let stride = width.checked_mul(4).ok_or("texture too large")?.next_multiple_of(256);
let size = stride.checked_mul(height).ok_or("texture too large")?;
let (Ok(stride32), Ok(size64)) = (u32::try_from(stride), u64::try_from(size)) else { return Err("texture too large".into()) };
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
let staging = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("view readback"),
size: size64,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("view readback") });
enc.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::TexelCopyBufferInfo {
buffer: &staging,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride32), rows_per_image: Some(h32) },
},
wgpu::Extent3d { width: w32, height: h32, depth_or_array_layers: 1 },
);
queue.submit([enc.finish()]);
if let Some(e) = pollster::block_on(scope.pop()) {
return Err(format!("texture copy failed: {e}"));
}
let slice = staging.slice(..);
let (tx, rx) = std::sync::mpsc::channel();
slice.map_async(wgpu::MapMode::Read, move |r| {
let _ = tx.send(r);
});
// (the render path's wait: queued work ahead of the copy can take that long too)
let wait = READBACK_TIMEOUT;
poll_device(device, wgpu::PollType::Wait { submission_index: None, timeout: Some(wait) })?;
match rx.recv_timeout(wait) {
Ok(Ok(())) => {}
Ok(Err(e)) => return Err(format!("{e}")),
Err(e) => return Err(format!("map callback: {e}")),
}
let bytes = slice.get_mapped_range().map_err(|e| format!("{e:?}"))?;
let mut data = Vec::with_capacity(width * height);
for row in bytes.chunks(stride).take(height) {
let row = row.get(..width * 4).ok_or("short readback row")?;
data.extend(row.as_chunks::<4>().0.iter().copied());
}
drop(bytes);
staging.unmap();
if data.len() != width * height {
return Err("incomplete readback".into());
}
Ok(lightcraft_raster::Rgba8 { width, height, data })
}
fn parse_limits(v: &str) -> Option<(u64, u64)> {
let v = v.trim().to_ascii_lowercase();
match v.as_str() {
@@ -927,6 +1073,54 @@ mod tests {
assert_eq!(super::parse_limits("17592186044416"), None);
}
/// `LIGHTCRAFT_GPU_LIMITS` caps the window's device as it caps a device of its own (review of
/// PR #1065: adopting the window's device skipped it, so a 1024 × 1024 RGB float buffer — 12 MiB —
/// was taken under an 8 MiB cap).
#[test]
fn the_limits_override_caps_an_adopted_device() {
let big = wgpu::Limits { max_storage_buffer_binding_size: 1 << 30, max_buffer_size: 1 << 31, ..wgpu::Limits::default() };
let c = super::capped(big.clone(), super::parse_limits("8"));
assert_eq!((c.max_storage_buffer_binding_size, c.max_buffer_size), (8 << 20, 16 << 20));
let c = super::capped(big.clone(), None);
assert_eq!((c.max_storage_buffer_binding_size, c.max_buffer_size), (1 << 30, 1 << 31));
let _lock = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let Some((device, queue, info)) = test_device() else {
lightcraft_testkit::skip!(Gpu, "no GPU adapter");
return;
};
let full = device.limits().max_storage_buffer_binding_size.min(device.limits().max_buffer_size);
if full <= 12 << 20 {
lightcraft_testkit::skip!(Gpu, "the adapter's buffers are already ≤ 12 MiB");
return;
}
let g = super::Gpu::adopt_capped(device, queue, info, super::parse_limits("8")).expect("kernels build");
assert!(g.window);
assert_eq!(g.limit(), 8 << 20, "the cap applies to the adopted device");
assert!(1024 * 1024 * 3 * 4 > g.limit(), "a 12 MiB buffer is over it");
}
/// A device as eframe makes the window's (the adapter's own limits).
fn test_device() -> Option<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> {
let backends = crate::backend::compute_backends()?;
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
desc.backends = backends;
desc.backend_options = crate::backend::backend_options();
let instance = wgpu::Instance::new(desc);
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?;
let info = adapter.get_info();
if info.device_type == wgpu::DeviceType::Cpu {
return None;
}
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("test window"),
required_limits: adapter.limits(),
..Default::default()
}))
.ok()?;
Some((device, queue, info))
}
/// Issue #2936: the kernels are built on several threads; every entry point of every module has one.
#[test]
fn every_entry_point_has_a_kernel() {
@@ -1009,6 +1203,42 @@ mod tests {
}
}
/// Review of PR #1065: a view readback (headless screenshot) whose poll finds the device lost
/// returns an error instead of panicking, stops the GPU, and doesn't poll the device again.
#[test]
fn a_view_readback_on_a_lost_device_fails_without_a_panic() {
if run_child("lost_readback_child").is_none() {
lightcraft_testkit::skip!(Gpu, "no GPU device");
}
}
#[test]
#[ignore = "run in its own process by a_view_readback_on_a_lost_device_fails_without_a_panic"]
fn lost_readback_child() {
let Some(g) = crate::device() else {
println!("CHILD: no GPU");
return;
};
let texture = g.device.create_texture(&wgpu::TextureDescriptor {
label: Some("view"),
size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
assert!(super::read_texture(&g.device, &g.queue, &texture, 8, 8).is_ok(), "a live device reads back");
super::SIMULATED_LOST_POLL.with(|c| c.set(true));
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::read_texture(&g.device, &g.queue, &texture, 8, 8)));
assert!(matches!(r, Ok(Err(_))), "the lost device fails the readback without a panic");
assert!(!crate::available(), "the GPU is not used again");
super::SIMULATED_LOST_POLL.with(|c| c.set(false));
assert!(super::read_texture(&g.device, &g.queue, &texture, 8, 8).is_err(), "a lost device is not polled again");
println!("CHILD: survived");
}
/// A Metal device really lost (its command buffers exhausted) is never polled again.
#[test]
fn a_really_lost_device_is_not_polled_again() {
+1 -14
View File
@@ -107,20 +107,7 @@ fn make_device(backends: wgpu::Backends) -> Result<Dev, String> {
desc.backend_options = crate::backend::backend_options();
desc.flags = crate::backend::instance_flags_from_env(desc.flags);
let instance = wgpu::Instance::new(desc);
let wanted = std::env::var("LIGHTCRAFT_GPU_ADAPTER").ok().map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty());
let adapter = match &wanted {
Some(w) => pollster::block_on(instance.enumerate_adapters(backends))
.into_iter()
.find(|a| {
let i = a.get_info();
i.device_type != wgpu::DeviceType::Cpu && i.name.to_lowercase().contains(w.as_str())
})
.ok_or_else(|| format!("no GPU adapter named like `{w}`"))?,
None => pollster::block_on(
instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }),
)
.map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?,
};
let adapter = crate::backend::pick_adapter(&instance, backends)?;
let info = adapter.get_info();
if info.device_type == wgpu::DeviceType::Cpu {
return Err(format!("software adapter ({}) skipped: the CPU is faster", info.name));
+146 -10
View File
@@ -45,7 +45,14 @@ mod params;
mod render;
#[cfg(not(target_arch = "wasm32"))]
pub use render::GpuStages;
pub use render::{DisplayFrame, GpuStages, Output};
/// The wgpu the renderer is built on (the same crate eframe uses: hosts hand over its device).
#[cfg(not(target_arch = "wasm32"))]
pub use wgpu;
/// Unit tests that create the device or swap the crash sentinel's path take turns.
#[cfg(test)]
pub(crate) static DEVICE_TEST_LOCK: Mutex<()> = Mutex::new(());
static ENABLED: AtomicBool = AtomicBool::new(true);
/// Set when a GPU render failed: the process stays on the CPU from then on.
@@ -277,6 +284,21 @@ fn env_disabled() -> bool {
#[cfg(not(target_arch = "wasm32"))]
static GPU: std::sync::OnceLock<Result<ctx::Gpu, String>> = std::sync::OnceLock::new();
/// Set while [`adopt_window_device`] is about to run or running: [`device`] and [`warm_up`] then
/// don't create a device of their own (review of PR #1065: the settings' warm-up raced the
/// adoption thread and could win, so the window's device went unused).
#[cfg(not(target_arch = "wasm32"))]
static WINDOW_PENDING: AtomicBool = AtomicBool::new(false);
/// Announce (before spawning it) that [`adopt_window_device`] will run, or withdraw that when it
/// can't (`false`). Until it has finished, renders take the CPU path and [`warm_up`] does nothing.
pub fn set_window_device_pending(pending: bool) {
#[cfg(not(target_arch = "wasm32"))]
WINDOW_PENDING.store(pending, Ordering::Release);
#[cfg(target_arch = "wasm32")]
let _ = pending;
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn device() -> Option<&'static ctx::Gpu> {
// turned off (preference, environment): don't even load the driver (issue #136)
@@ -286,6 +308,11 @@ pub(crate) fn device() -> Option<&'static ctx::Gpu> {
if let Some(g) = GPU.get() {
return g.as_ref().ok();
}
// the window's device is being adopted: render on the CPU until it is, rather than create a
// device of our own first (which would leave the window's unused)
if WINDOW_PENDING.load(Ordering::Acquire) {
return None;
}
// creating the device is a long call into the driver: not once the process is ending
let _work = exit::enter()?;
GPU.get_or_init(|| {
@@ -313,7 +340,7 @@ pub(crate) fn existing_device() -> Option<&'static ctx::Gpu> {
/// while GPU rendering is turned off. Repeated calls start one thread at most.
pub fn warm_up() {
#[cfg(not(target_arch = "wasm32"))]
if !env_disabled() && ENABLED.load(Ordering::SeqCst) && GPU.get().is_none() {
if !env_disabled() && ENABLED.load(Ordering::SeqCst) && GPU.get().is_none() && !WINDOW_PENDING.load(Ordering::Acquire) {
static STARTED: AtomicBool = AtomicBool::new(false);
if STARTED.swap(true, Ordering::SeqCst) {
return;
@@ -328,8 +355,9 @@ pub fn warm_up() {
// again. Released first, then the preference read again: a call made while this
// thread still held the flag (turned back on meanwhile) returned without starting
// one, so this thread tries again itself rather than leave "starting" for good.
// The window's device being adopted meanwhile: that creates the device, not this.
STARTED.store(false, Ordering::SeqCst);
if !ENABLED.load(Ordering::SeqCst) || STARTED.swap(true, Ordering::SeqCst) {
if WINDOW_PENDING.load(Ordering::Acquire) || !ENABLED.load(Ordering::SeqCst) || STARTED.swap(true, Ordering::SeqCst) {
break;
}
}
@@ -492,6 +520,114 @@ pub fn try_render(
stages: Option<&StageCache>,
) -> Result<Rendered, Fallback> {
#[cfg(not(target_arch = "wasm32"))]
{
match run(src, info, s, req, stages, false)? {
render::Output::Image(r) => Ok(r),
// (not asked for)
render::Output::Display { .. } => Err(Fallback::NotTried),
}
}
#[cfg(target_arch = "wasm32")]
{
let _ = (src, info, s, req, stages);
Err(Fallback::NotTried)
}
}
/// [`render`] for the window: when the device is the window's ([`adopt_window_device`]) and the
/// render allows it, the result stays on the device as a texture to draw ([`Output::Display`]);
/// otherwise pixels as from [`render`]. `None`: render on the CPU instead.
#[cfg(not(target_arch = "wasm32"))]
pub fn render_display(src: &Arc<Rgb32f>, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, stages: Option<&StageCache>) -> Option<Output> {
run(src, info, s, req, stages, true).ok()
}
/// Whether renders run on the window's device (and so can be handed over as textures).
pub fn on_window_device() -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
existing_device().is_some_and(|g| g.window)
}
#[cfg(target_arch = "wasm32")]
{
false
}
}
/// Render on the window's device (eframe's) instead of a device of its own, so finished views can
/// be drawn without reading them back ([`render_display`]). Builds the kernels on it (~0.4–2 s:
/// call it off the UI thread), in place of [`warm_up`]. When that fails, or the window's device
/// doesn't suit (a software adapter, too few storage buffers), a device of its own is created as
/// before; `Err` says why the window's wasn't used. Does nothing once a device exists.
#[cfg(not(target_arch = "wasm32"))]
pub fn adopt_window_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo) -> Result<(), String> {
/// Whatever the outcome, renders may create or use a device again afterwards.
struct Done;
impl Drop for Done {
fn drop(&mut self) {
WINDOW_PENDING.store(false, Ordering::Release);
}
}
let _done = Done;
if env_disabled() || !ENABLED.load(Ordering::Relaxed) {
return Err("GPU rendering is off".into());
}
let _work = exit::enter().ok_or("LightCraft is closing")?;
let mut declined = None;
let g = GPU.get_or_init(|| {
let adopted = if info.device_type == wgpu::DeviceType::Cpu {
Err(format!("software adapter ({}) skipped: the CPU pipeline is faster", info.name))
} else if !backend::may_adopt_window_device(&info.name) {
// (the photos render on the card LIGHTCRAFT_GPU_ADAPTER names, on a device of its own)
Err(format!("LIGHTCRAFT_GPU_ADAPTER names another card than the window's ({})", info.name))
} else {
// (building the kernels is a long call into the driver: the crash sentinel covers it)
backend::with_init_marker(wgpu::Backends::from(info.backend), || {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ctx::Gpu::adopt(device, queue, info)))
.unwrap_or_else(|_| Err("kernel setup panicked".into()))
})
};
adopted.or_else(|e| {
log::warn!("gpu: not rendering on the window's device ({e}); creating one");
declined = Some(e);
let Some(backends) = backend::compute_backends() else { return Err("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()) };
backend::with_init_marker(backends, || {
std::panic::catch_unwind(|| ctx::Gpu::new(backends)).unwrap_or_else(|_| Err("device creation panicked".into()))
})
})
});
match (g, declined) {
(Ok(g), None) if g.window => Ok(()),
(_, Some(e)) => Err(e),
(Ok(_), None) => Err("a device of its own was created first".into()),
(Err(e), None) => Err(e.clone()),
}
}
/// The pixels of a texture on `device` (a [`DisplayFrame`]'s, or any `Rgba8Unorm` texture with
/// `COPY_SRC`): for a headless screenshot of a view drawn straight from the GPU, and for tests. The
/// app never needs them to draw. Waits for the GPU (at most a minute); `Err` when the copy or
/// the wait fails.
#[cfg(not(target_arch = "wasm32"))]
pub fn read_texture(
device: &wgpu::Device,
queue: &wgpu::Queue,
texture: &wgpu::Texture,
width: usize,
height: usize,
) -> Result<lightcraft_raster::Rgba8, String> {
ctx::read_texture(device, queue, texture, width, height)
}
#[cfg(not(target_arch = "wasm32"))]
fn run(
src: &Arc<Rgb32f>,
info: &SourceInfo,
s: &DevelopSettings,
req: &RenderRequest,
stages: Option<&StageCache>,
display: bool,
) -> Result<Output, Fallback> {
{
// sections switched off with their eye render as if at their defaults (issue #316)
let effective = s.effective();
@@ -501,6 +637,10 @@ pub fn try_render(
return Err(Fallback::NotTried);
}
let s = &*lightcraft_pipeline::settings_for(s, req);
// content-aware Fill spots (`spots::fill_box`) have no GPU kernel: the CPU renders the photo
if s.spots.iter().any(|sp| sp.mode == lightcraft_develop::SpotMode::Fill) {
return Err(Fallback::NotTried);
}
// in flight until this returns; not tried once the process is ending (issue #620)
let _work = exit::enter().ok_or(Fallback::NotTried)?;
let gpu = device().ok_or(Fallback::NotTried)?;
@@ -512,7 +652,7 @@ pub fn try_render(
let (r, scoped) = {
let _scope = ctx::RenderScope::new(gpu);
let errors = ctx::ErrorScopes::push(gpu);
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render::render(gpu, src, info, s, req, ext.as_deref(), fault)));
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render::render(gpu, src, info, s, req, ext.as_deref(), fault, display)));
(r, errors.pop())
};
// An error the device raised explains the readback failures that follow it; a buffer
@@ -533,7 +673,8 @@ pub fn try_render(
e.clear();
}
let what = match &r {
Some(r) => format!("{}×{}", r.image.width, r.image.height),
Some(Output::Image(r)) => format!("{}×{}", r.image.width, r.image.height),
Some(Output::Display { frame, .. }) => format!("{}×{}", frame.width, frame.height),
None => "GPU render".into(),
};
let reason = match f.kind {
@@ -568,11 +709,6 @@ pub fn try_render(
record_fallback(reason.clone());
Err(Fallback::Failed(reason))
}
#[cfg(target_arch = "wasm32")]
{
let _ = (src, info, s, req, stages);
Err(Fallback::NotTried)
}
}
/// Tests: parse and validate a WGSL module with naga, as wgpu does before it hands a shader to the driver. Needs no
+10 -19
View File
@@ -4,7 +4,8 @@
//! The runner has a device of its own, so a denoise job and the interactive renders are separate contexts that the
//! driver time-slices, and a failure of one never takes the other down. It respects the same switches as GPU rendering
//! (`LIGHTCRAFT_GPU`, `LIGHTCRAFT_GPU_BACKEND`, the GPU preference) and the same crash sentinel around device creation.
//! `LIGHTCRAFT_GPU_ADAPTER` picks an adapter by (part of) its name, e.g. to try another card.
//! `LIGHTCRAFT_GPU_ADAPTER` picks an adapter by (part of) its name, e.g. to try another card (`backend::pick_adapter`,
//! shared with the render device).
//!
//! Every failure is an `Err` (never a panic), and a device that errs or is lost stops being used: callers then run the
//! CPU runner. The kernels (`wgsl/nn_conv.wgsl`, `wgsl/nn_pool.wgsl`) are tested against the plain-loop reference
@@ -89,23 +90,7 @@ fn make_device(backends: wgpu::Backends) -> Result<Dev, String> {
// no indirect-call validation pipeline: Intel Metal fails to compile it (#250)
desc.flags = crate::backend::instance_flags_from_env(desc.flags);
let instance = wgpu::Instance::new(desc);
let wanted = std::env::var("LIGHTCRAFT_GPU_ADAPTER").ok().map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty());
let adapter = match &wanted {
Some(w) => {
let all = pollster::block_on(instance.enumerate_adapters(backends));
let names: Vec<String> = all.iter().map(|a| a.get_info().name).collect();
all.into_iter()
.find(|a| {
let i = a.get_info();
i.device_type != wgpu::DeviceType::Cpu && i.name.to_lowercase().contains(w.as_str())
})
.ok_or_else(|| format!("no GPU adapter named like `{w}` (found: {})", names.join(", ")))?
}
None => pollster::block_on(
instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }),
)
.map_err(|e| format!("no GPU adapter among {backends:?} ({e})"))?,
};
let adapter = crate::backend::pick_adapter(&instance, backends)?;
let info = adapter.get_info();
if info.device_type == wgpu::DeviceType::Cpu {
return Err(format!("software adapter ({}) skipped: the CPU is faster", info.name));
@@ -968,6 +953,9 @@ mod tests {
/// The runner, or `None` (with a note) on a machine with no usable GPU.
fn gpu(net: &Net, tile: usize) -> Option<NetRunner> {
// creating the device and building the kernels arms the crash sentinel: take turns with
// the tests that set its path (`backend::tests`)
let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
match runner(net, tile) {
Ok(r) => Some(r),
Err(e) => {
@@ -1087,7 +1075,10 @@ mod tests {
let net = onnx::read(std::path::Path::new(&model)).unwrap();
let tile = 512usize;
let started = Instant::now();
let g = runner(&net, tile).unwrap();
let g = {
let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
runner(&net, tile).unwrap()
};
println!("{}: set up in {:.2} s, {:.0} MB per tile in flight", g.adapter(), started.elapsed().as_secs_f64(), g.bytes_per_tile() as f64 / 1e6);
println!("kernels: {}", g.build_report());
let manifest = DenoiserManifest {
+56 -2
View File
@@ -28,6 +28,11 @@ const FIELDS: &[(&str, usize)] = &[
("DEHAZE", 1),
("SHARPEN", 1),
("SHARPEN_MASK", 1),
("SHARPEN_LIMIT", 1),
("SHARPEN_GAIN", 1),
("SHARPEN_V3", 1),
("SHP_OFF", 1),
("HAS_SHP", 1),
("HAS_CLAR", 1),
("HAS_TEX", 1),
("HAS_DARK", 1),
@@ -73,6 +78,13 @@ const FIELDS: &[(&str, usize)] = &[
("OUT_Y", 3),
("OUT_TRC", 1),
("OUT_GAMMA", 1),
// a LUT profile: its table in `aux` at LUT_OFF (size³ rgb, red fastest), amount and domain
("LUT", 1),
("LUT_OFF", 1),
("LUT_N", 1),
("LUT_AMT", 1),
("LUT_MIN", 3),
("LUT_MAX", 3),
// soft proofing (matrix proofs; `ProofParams`): working → proof RGB, its luma, proof → output, warnings
("PROOF", 1),
("PROOF_M", 9),
@@ -82,6 +94,13 @@ const FIELDS: &[(&str, usize)] = &[
("PROOF_DISP_WARN", 1),
// first row of a band dispatch (the kernel runs over rows Y0.., see `render`)
("Y0", 1),
// process V4's calibrated Contrast, Blacks (`FinishParams::light`): the number of active
// operators (0 = none), each one's mode (`light_v3::Mode::code`) and mix weight, and the offset
// of their tables in `aux` (LIGHT_N entries each, in order)
("LIGHT_OPS", 1),
("LIGHT_MODE", 2),
("LIGHT_W", 2),
("LIGHT_OFF", 1),
];
/// `(name, index)` of every field (for the WGSL constants).
@@ -140,13 +159,15 @@ impl Block {
pub struct Present {
pub clarity: bool,
pub texture: bool,
/// The sharpening blur plane (after the texture plane in `tex` when both are present).
pub sharpen: bool,
pub dark: bool,
/// The blurred chromaticity follows the mask planes in the `masks` buffer.
pub chroma: bool,
}
/// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs |
/// mask terms) for `fp` with `masks` (their local adjustments' terms).
/// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms).
pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec<u32>, Vec<f32>) {
let mut aux: Vec<f32> = fp.tone.lut().to_vec();
aux.extend_from_slice(fp.tone.chroma_lut());
@@ -163,8 +184,28 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
for m in masks {
aux.extend_from_slice(m);
}
let light_off = aux.len();
let light = fp.light.as_ref().map_or(&[][..], |l| &l.ops[..]);
let light = &light[..light.len().min(2)];
for op in light {
aux.extend_from_slice(&op.lut[..]);
}
let lut_off = aux.len();
if let Some((l, _)) = &fp.lut {
aux.extend(l.data.iter().flatten());
}
let mut p = Block::new();
p.u("LIGHT_OPS", light.len() as u32);
p.u("LIGHT_OFF", light_off as u32);
if let Some(i) = index("LIGHT_MODE") {
for (k, op) in light.iter().enumerate() {
if let Some(slot) = p.0.get_mut(i + k) {
*slot = op.mode.code();
}
}
}
p.fs("LIGHT_W", &light.iter().map(|op| op.weight).collect::<Vec<f32>>());
p.u("W", fp.w as u32);
p.u("H", fp.h as u32);
p.u("NMASK", masks.len() as u32);
@@ -184,6 +225,11 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
p.f("DEHAZE", fp.dehaze);
p.f("SHARPEN", fp.sharpen);
p.f("SHARPEN_MASK", fp.sharpen_mask);
p.f("SHARPEN_LIMIT", fp.sharpen_limit);
p.f("SHARPEN_GAIN", fp.sharpen_gain);
p.b("SHARPEN_V3", fp.pixel_sharpen);
p.u("SHP_OFF", if present.texture { (fp.w * fp.h) as u32 } else { 0 });
p.b("HAS_SHP", present.sharpen);
p.b("HAS_CLAR", present.clarity);
p.b("HAS_TEX", present.texture);
p.b("HAS_DARK", present.dark);
@@ -211,6 +257,7 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
}
p.f("SKIN", ops.skin);
p.fs("BANDH", lightcraft_pipeline::colorops::band_hues());
p.fs("VIG_VIEW", &fp.view);
if let Some(v) = &fp.vig {
p.b("VIG", true);
@@ -220,7 +267,6 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
p.f("VIG_ASPECT_MIX", v.aspect_mix);
p.f("VIG_POWER", v.power);
p.f("VIG_HL", v.highlights);
p.fs("VIG_VIEW", &fp.view);
p.u(
"VIG_STYLE",
match v.style {
@@ -240,6 +286,14 @@ 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);
if let Some((l, amount)) = &fp.lut {
p.b("LUT", true);
p.u("LUT_OFF", lut_off as u32);
p.u("LUT_N", l.size as u32);
p.f("LUT_AMT", *amount);
p.fs("LUT_MIN", &l.domain_min);
p.fs("LUT_MAX", &l.domain_max);
}
if let Some(pp) = fp.proof.as_ref().filter(|pp| pp.table.is_none()) {
p.b("PROOF", true);
p.fs("PROOF_M", pp.to_proof.as_flattened());
+283 -19
View File
@@ -44,6 +44,7 @@ struct Planes {
base: Option<(local::BaseKey, Arc<Buf>)>,
clarity: Option<(u32, Arc<Buf>)>,
texture: Option<(u32, Arc<Buf>)>,
sharpen: Option<(local::SharpenKey, Arc<Buf>)>,
dark: Option<(u32, Arc<Buf>, f32)>,
chroma: Option<(u32, Arc<Buf>)>,
}
@@ -105,6 +106,7 @@ impl GpuStages {
p.base.iter().for_each(|(_, b)| add(b));
p.clarity.iter().for_each(|(_, b)| add(b));
p.texture.iter().for_each(|(_, b)| add(b));
p.sharpen.iter().for_each(|(_, b)| add(b));
p.dark.iter().for_each(|(_, b, _)| add(b));
}
if let Some((_, b)) = &*self.source.lock().unwrap_or_else(|e| e.into_inner()) {
@@ -213,6 +215,20 @@ impl<'a> Cx<'a> {
enc.copy_buffer_to_buffer(src.raw(), 0, dst.raw(), (offset * 4) as u64, (src.len * 4) as u64);
}
/// Copy `w × h` texels from `b` (rows of `stride` 32-bit texels, a multiple of 64) into
/// `texture` (recorded).
pub fn copy_to_texture(&mut self, b: &Buf, stride: usize, texture: &wgpu::Texture, w: usize, h: usize) {
let enc = self.enc.get_or_insert_with(|| self.gpu.encoder());
enc.copy_buffer_to_texture(
wgpu::TexelCopyBufferInfo {
buffer: b.raw(),
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some((stride * 4) as u32), rows_per_image: Some(h as u32) },
},
wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 },
);
}
pub fn read_rgb(&mut self, b: &Buf, w: usize, h: usize) -> Rgb32f {
Rgb32f { width: w, height: h, data: self.read(b, w * h * 3) }
}
@@ -263,6 +279,18 @@ pub(crate) fn gaussian(cx: &mut Cx<'_>, src: &Buf, w: usize, h: usize, nc: usize
if last == 0 { a } else { b }
}
/// Exact Gaussian (`lightcraft_raster::blur::gaussian_taps`) of a one-channel plane.
pub(crate) fn gaussian_fir(cx: &mut Cx<'_>, src: &Buf, w: usize, h: usize, sigma: f32) -> Buf {
let taps = lightcraft_raster::blur::gauss_taps(sigma);
let taps_buf = cx.gpu.upload(&taps);
let r = (taps.len() / 2) as u32;
let (tmp, out) = (cx.gpu.buffer(w * h), cx.gpu.buffer(w * h));
let p = [w as u32, h as u32, r];
cx.run("gauss_h", &p, &[Some(src), Some(&taps_buf), Some(&tmp)], groups2(w, h, [16, 16]));
cx.run("gauss_v", &p, &[Some(&tmp), Some(&taps_buf), Some(&out)], groups2(w, h, [16, 16]));
out
}
/// Resample taps of `lightcraft_raster::resample::resize`, packed for the `resize_*` kernels.
fn taps(src: usize, dst: usize, filter: Filter) -> Vec<u32> {
let w = lightcraft_raster::resample::weights(src, dst, filter);
@@ -579,8 +607,34 @@ pub(crate) fn profiling() -> bool {
*ON.get_or_init(|| std::env::var_os("LIGHTCRAFT_PROFILE").is_some())
}
/// Render on `gpu`, reusing `stages` (if given). `None` (or a result the caller discards) when the
/// render failed: the reason is recorded with [`crate::ctx::fail`].
/// A finished render on the window's device, ready to draw: an `Rgba8Unorm` texture (the 8-bit
/// output, sRGB-curve encoded, as egui's own textures) that never went through host memory.
#[derive(Clone, Debug)]
pub struct DisplayFrame {
pub texture: wgpu::Texture,
pub width: usize,
pub height: usize,
}
/// What a render produced: pixels in host memory, or (asked for with `display` and possible) a
/// texture on the window's device plus the histogram.
pub enum Output {
Image(Rendered),
Display { frame: DisplayFrame, histogram: Histogram },
}
/// Whether a render of this plan can end in a texture instead of a readback: the device is the
/// window's, nothing is drawn over the image on the CPU (overlays) or cut from it (a window that
/// spots grew), and the texture fits the device.
fn can_display(gpu: &Gpu, plan: &Plan<'_>, req: &RenderRequest) -> bool {
let max = gpu.device.limits().max_texture_dimension_2d as usize;
gpu.window && req.overlay == lightcraft_pipeline::Overlay::None && plan.keep.is_none() && plan.w <= max && plan.h <= max && plan.w * plan.h > 0
}
/// Render on `gpu`, reusing `stages` (if given); with `display`, into a texture when
/// [`can_display`]. `None` (or a result the caller discards) when the render failed: the reason is
/// recorded with [`crate::ctx::fail`].
#[allow(clippy::too_many_arguments)]
pub fn render(
gpu: &Gpu,
src: &Arc<Rgb32f>,
@@ -589,7 +643,8 @@ pub fn render(
req: &RenderRequest,
stages: Option<&GpuStages>,
fault: Option<crate::Fault>,
) -> Option<Rendered> {
display: bool,
) -> Option<Output> {
let mut t = profiling().then(std::time::Instant::now);
// Each stage is submitted on its own; under `LIGHTCRAFT_PROFILE` also waited for, so the
// timings are real.
@@ -692,9 +747,22 @@ pub fn render(
let present = Present {
clarity: prep.clarity.is_some(),
texture: prep.texture.is_some(),
sharpen: prep.sharpen.is_some(),
dark: prep.dark.is_some(),
chroma: masks.is_some() && prep.chroma.is_some(),
};
// the finish kernel's `tex` binding: the texture plane, then the sharpening plane (one binding
// for both keeps the kernel within the storage-buffer count every supported device has)
let tex_buf: Option<Arc<Buf>> = match (&prep.texture, &prep.sharpen) {
(Some(t), Some(sh)) => {
let both = cx.gpu.buffer(2 * n);
cx.copy_into(t, &both, 0);
cx.copy_into(sh, &both, n);
Some(Arc::new(both))
}
(Some(b), None) | (None, Some(b)) => Some(b.clone()),
(None, None) => None,
};
let (p, aux) = finish_block(&fp, &terms, &present);
let aux = gpu.upload(&aux);
// cleared, so that work which never ran cannot pass for an image (see the check below)
@@ -717,7 +785,7 @@ pub fn render(
Some(&prep.log_l),
Some(&prep.base),
prep.clarity.as_deref(),
prep.texture.as_deref(),
tex_buf.as_deref(),
prep.dark.as_deref(),
masks.as_ref(),
Some(&aux),
@@ -726,6 +794,9 @@ pub fn render(
groups2(w, rows.min(h - y0), [16, 16]),
);
}
if display && can_display(gpu, &plan, req) {
return to_texture(&mut cx, &out, w, h).map(|(frame, histogram)| Output::Display { frame, histogram });
}
// the alpha a mask overlay shows: copied out before the readback below submits
let overlay_mask = req.overlay.mask(s).map(|m| {
let list = s.masks.iter().filter(|m| m.visible && !m.components.is_empty());
@@ -769,10 +840,8 @@ pub fn render(
fail(FailKind::Fatal, format!("the GPU returned an incomplete image ({unwritten} of {n} pixels unwritten)"));
return None;
}
let histogram = match plan.keep {
Some(k) => Histogram::of_srgb8(&image.crop(k.x, k.y, k.w, k.h)),
None => Histogram::of_srgb8(&image),
};
let region = plan.keep.map_or((0, 0, w, h), |k| (k.x, k.y, k.w, k.h));
let histogram = histogram(&mut cx, &out, w, region);
lap("histogram", &mut t, &mut cx);
// An entirely black result (upstream work that did not run would give that too): redo it on
// the CPU, which costs time only for the rare photo that really is black.
@@ -794,8 +863,9 @@ pub fn render(
let overlay_mask = overlay_mask.or_else(|| {
req.overlay.reads_detail().then(|| {
let l = host.log_l.get_or_insert_with(|| Arc::new(cx.read_plane(&prep.log_l, w, h))).clone();
let tex = prep.texture.as_deref().map(|b| cx.read_plane(b, w, h));
lightcraft_pipeline::visualize::sharpen_plane(req.overlay, &plan.settings, &l, tex.as_ref(), plan.px_per_long)
let band = if local::pixel_sharpen(&plan.settings) { &prep.sharpen } else { &prep.texture };
let blur = band.as_deref().map(|b| cx.read_plane(b, w, h));
lightcraft_pipeline::visualize::sharpen_plane(req.overlay, &plan.settings, &l, blur.as_ref(), plan.px_per_long, plan.native_long as f64)
})?
});
lightcraft_pipeline::visualize::apply(&mut image, req.overlay, &plan, overlay_mask.as_ref(), all_overlay_alphas.as_deref());
@@ -803,7 +873,53 @@ pub fn render(
if let Some(k) = plan.keep {
image = image.crop(k.x, k.y, k.w, k.h);
}
Some(Rendered { image, histogram, deep: None })
Some(Output::Image(Rendered { image, histogram, deep: None }))
}
/// The finished output `out` (`w × h` packed RGBA8) as a texture on the device, with its
/// histogram; the same checks as a readback (every pixel written, not entirely black), done on
/// the device: only the histogram and a pixel count come back.
fn to_texture(cx: &mut Cx<'_>, out: &Buf, w: usize, h: usize) -> Option<(DisplayFrame, Histogram)> {
let n = w * h;
let unwritten = cx.zeroed(1);
cx.run("unwritten", &[n as u32], &[Some(out), None, Some(&unwritten)], groups1(n));
let histogram = histogram(cx, out, w, (0, 0, w, h));
let left = cx.read::<u32>(&unwritten, 1).first().copied().unwrap_or(0);
if crate::ctx::failed() {
return None;
}
if left > 0 {
fail(FailKind::Fatal, format!("the GPU returned an incomplete image ({left} of {n} pixels unwritten)"));
return None;
}
if n >= 4096 && [&histogram.r, &histogram.g, &histogram.b].iter().all(|c| c.first() == Some(&histogram.total)) {
fail(FailKind::Blank, "the GPU result is entirely black; rendering it on the CPU to be sure".into());
return None;
}
// texture copies take rows of a multiple of 256 bytes: pad them unless they already are
let stride = w.next_multiple_of(64);
let padded = (stride != w).then(|| {
let b = cx.gpu.buffer(stride * h);
cx.run("pad_rows", &[w as u32, h as u32, stride as u32], &[Some(out), Some(&b), None], groups2(w, h, [16, 16]));
b
});
let texture = cx.gpu.device.create_texture(&wgpu::TextureDescriptor {
label: Some("lightcraft view"),
size: wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
// (COPY_SRC: a screenshot or a test can read it back)
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
cx.copy_to_texture(padded.as_ref().unwrap_or(out), stride, &texture, w, h);
cx.flush();
if crate::ctx::failed() {
return None;
}
Some((DisplayFrame { texture, width: w, height: h }, histogram))
}
/// Pixels whose alpha is not 255 (cheap: no early exit, so it vectorizes).
@@ -816,8 +932,9 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho
let (w, h) = (plan.w, plan.h);
let n = w * h;
let s = &*plan.settings;
let img = if lightcraft_pipeline::lin_needs_cpu(s, info) {
// defringe / spot removal / local tone mapping: CPU
let img = if lightcraft_pipeline::local_tone::enabled(info, s) {
// the camera's local tone mapping (ProRAW gain table, off by default): the whole
// scene-linear stage on the CPU
let mut img = match host.sampled.take() {
Some(i) => i,
None => cx.read_rgb(sampled, w, h),
@@ -825,11 +942,14 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho
lightcraft_pipeline::lin_cpu(&mut img, info, plan);
cx.gpu.upload(rgb_words(&img))
} else {
// `lin_cpu`'s order: white balance, defringe, spots, red eye
let m = local::wb_matrix_for(info, s);
let mut p = vec![m.is_some() as u32];
p.extend(m.unwrap_or_default().iter().flatten().map(|v| v.to_bits()));
let out = cx.gpu.buffer(n * 3);
map(cx, "wb_k", n, &p, [Some(sampled), None, None], &out);
let out = defringe(cx, out, plan);
let out = spots(cx, out, plan);
if plan.eyes.is_empty() {
out
} else {
@@ -843,6 +963,96 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho
denoise(cx, img, plan)
}
/// Defringe (`optics::defringe`) of the white-balanced image.
fn defringe(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf {
use lightcraft_pipeline::optics;
let Some(dp) = optics::defringe_params(&plan.settings, plan.px_per_long / optics::DEFRINGE_REF_LONG) else { return img };
let (w, h) = (plan.w, plan.h);
let n = w * h;
let lab = cx.gpu.buffer(n * 3);
map(cx, "fringe_lab", n, &[], [Some(&img), None, None], &lab);
// the lightness channel, then its min and max around each pixel
let l = cx.gpu.buffer(n);
map(cx, "subsample", n, &[3], [Some(&lab), None, None], &l);
// (a radius past the image reads the same pixels as one at its size)
let r = dp.radius.min(w.max(h)) as u32;
let filtered = |cx: &mut Cx<'_>, max: u32| {
let tmp = cx.gpu.buffer(n);
cx.run("minmax", &[w as u32, h as u32, r, 0, max], &[Some(&l), Some(&tmp)], groups2(w, h, [16, 16]));
let out = cx.gpu.buffer(n);
cx.run("minmax", &[w as u32, h as u32, r, 1, max], &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16]));
out
};
let (lo, hi) = (filtered(cx, 0), filtered(cx, 1));
// the kernel writes only the pixels it changes
let out = cx.copy(&img);
let p = [dp.purple.0, dp.purple.1, dp.green.0, dp.green.1, dp.purple_strength, dp.green_strength].map(f32::to_bits);
map(cx, "fringe_apply", n, &p, [Some(&lab), Some(&lo), Some(&hi)], &out);
out
}
/// Spot removal (`spots::apply`), spot by spot on `img` in place: each spot reads the image as
/// the earlier ones left it.
fn spots(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf {
use lightcraft_pipeline::spots;
let (w, h) = (plan.w, plan.h);
for spot in &plan.settings.spots {
let Some(l) = spots::layout(spot, &plan.frame, w, h, plan.px_per_long) else { continue };
let Some(&first) = l.pts.first() else { continue };
let offset = match l.offset {
Some(o) => o,
None => auto_source(cx, &img, w, h, first, l.r),
};
let pts = cx.gpu.upload(&l.pts.iter().flat_map(|p| [p.0, p.1]).collect::<Vec<f32>>());
let nb = l.bw * l.bh;
let (al, sp, df, wt) = (cx.gpu.buffer(nb), cx.gpu.buffer(3 * nb), cx.gpu.buffer(3 * nb), cx.gpu.buffer(nb));
let mut p = vec![w as u32, h as u32, l.bx as u32, l.by as u32, l.bw as u32, l.bh as u32, l.pts.len() as u32];
p.extend([l.r, l.inner, l.opacity, offset.0, offset.1].map(f32::to_bits));
p.push(l.heal as u32);
let groups = groups2(l.bw, l.bh, [16, 16]);
cx.run("spot_prep", &p, &[Some(&img), Some(&pts), Some(&al), Some(&sp), Some(&df), Some(&wt)], groups);
// Heal: the tone correction is the masked difference's normalized blur
let blurred = l.heal.then(|| {
let sigma = (l.r * 0.6).max(1.0);
(gaussian(cx, &df, l.bw, l.bh, 3, sigma), gaussian(cx, &wt, l.bw, l.bh, 1, sigma))
});
let (bd, bm) = blurred.as_ref().map_or((&df, &wt), |(d, m)| (d, m));
cx.run("spot_apply", &p, &[Some(&img), Some(&pts), Some(&al), Some(&sp), Some(bd), Some(bm)], groups);
}
img
}
/// `spots::auto_source` on the device: every candidate scored at once, the 48 scores read back.
fn auto_source(cx: &mut Cx<'_>, img: &Buf, w: usize, h: usize, target: (f32, f32), r: f32) -> (f32, f32) {
use lightcraft_pipeline::spots;
let cands = spots::candidates(r);
let mut data: Vec<f32> = cands.iter().flat_map(|d| [d.0, d.1]).collect();
data.extend(spots::ring_dirs().iter().flat_map(|d| [d.0, d.1]));
let pts = cx.gpu.upload(&data);
let [around, within] = spots::score_radii(r);
let mut p = vec![w as u32, h as u32];
p.extend([target.0, target.1].iter().chain(&around).chain(&within).map(|v| v.to_bits()));
let scores = cx.gpu.buffer(cands.len());
cx.run("spot_score", &p, &[Some(img), Some(&pts), Some(&scores), None, None, None], [cands.len().div_ceil(64) as u32, 1, 1]);
let scores: Vec<f32> = cx.read(&scores, cands.len());
spots::rank(&cands, &scores).first().copied().unwrap_or_else(|| spots::fallback_source(r))
}
/// The output's histogram (`Histogram::of_srgb8` of the `region` x, y, w, h of the `w`-wide
/// packed RGBA8 `out`, on the same sampling grid), counted on the device.
fn histogram(cx: &mut Cx<'_>, out: &Buf, w: usize, region: (usize, usize, usize, usize)) -> Histogram {
let (x0, y0, rw, rh) = region;
let step = (((rw * rh) as f64 / 1_000_000.0).sqrt().ceil() as usize).max(1);
let (nx, ny) = (rw.div_ceil(step), rh.div_ceil(step));
let bins = cx.zeroed(4 * Histogram::BINS + 1);
let p = [w, x0, y0, nx, ny, step].map(|v| v as u32);
cx.run("histogram", &p, &[Some(out), Some(&bins)], groups2(nx, ny, [16, 16]));
let v: Vec<u32> = cx.read(&bins, 4 * Histogram::BINS + 1);
let part = |k: usize| v.get(k * Histogram::BINS..(k + 1) * Histogram::BINS).map_or_else(|| vec![0; Histogram::BINS], <[u32]>::to_vec);
// (SDR bins: an HDR edit's histogram is made after the render, `media::develop`)
Histogram { r: part(0), g: part(1), b: part(2), luma: part(3), total: v.get(4 * Histogram::BINS).copied().unwrap_or(0), hdr: None }
}
/// Noise reduction (`local::denoise`).
fn denoise(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf {
let (w, h) = (plan.w, plan.h);
@@ -874,6 +1084,7 @@ struct Prep {
base: Arc<Buf>,
clarity: Option<Arc<Buf>>,
texture: Option<Arc<Buf>>,
sharpen: Option<Arc<Buf>>,
dark: Option<Arc<Buf>>,
/// Blurred chromaticity (local Moiré / Noise).
chroma: Option<Arc<Buf>>,
@@ -884,7 +1095,7 @@ struct Prep {
fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, planes: &mut Planes) -> Prep {
let (w, h) = (plan.w, plan.h);
let n = w * h;
let sig = local::plane_sigmas(&plan.settings, plan.px_per_long, req.quality);
let sig = local::plane_sigmas(&plan.settings, plan.px_per_long, plan.native_long as f64, req.quality);
let log_l = match &planes.log_l {
Some(b) => b.clone(),
None => {
@@ -904,6 +1115,7 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla
};
let clarity = sig.clarity.map(|sg| plane_at(&mut planes.clarity, sg.to_bits(), || guided_fast(cx, &log_l, w, h, sg, local::CLARITY_EPS)));
let texture = sig.texture.map(|sg| plane_at(&mut planes.texture, sg.to_bits(), || gaussian(cx, &log_l, w, h, 1, sg)));
let sharpen = sig.sharpen.map(|sg| plane_at(&mut planes.sharpen, local::sharpen_key(&plan.settings, sg), || gaussian_fir(cx, &log_l, w, h, sg)));
let (dark, air) = match sig.dark {
None => (None, 1.0),
Some(sg) => match &planes.dark {
@@ -931,7 +1143,7 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla
gaussian(cx, &ch, w, h, 3, sg)
})
});
Prep { log_l, base, clarity, texture, dark, chroma, air }
Prep { log_l, base, clarity, texture, sharpen, dark, chroma, air }
}
/// Most brush dabs the mask kernel evaluates per pixel (more: the CPU rasterizes the brush).
@@ -958,8 +1170,18 @@ fn brush_aux(dabs: &[&lightcraft_pipeline::masks::BrushDabs], erase: bool) -> Ve
aux
}
/// Cross guided filter (`masks::guided_cross`) of `p` steered by `guide`, max-combined with `p`.
fn guided_cross_max(cx: &mut Cx<'_>, guide: &Buf, p: &Buf, w: usize, h: usize, sigma: f32, eps: f32) -> Buf {
/// How [`guided_cross`] combines the filtered plane with its input.
#[derive(Clone, Copy)]
enum Combine {
/// The larger of the two (Auto Mask strokes).
Max,
/// The input moved towards the filtered plane by this much (Refine Edges).
Mix(f32),
}
/// Cross guided filter (`masks::guided_cross`) of `p` steered by `guide`, combined with `p`.
#[allow(clippy::too_many_arguments)]
fn guided_cross(cx: &mut Cx<'_>, guide: &Buf, p: &Buf, w: usize, h: usize, sigma: f32, eps: f32, how: Combine) -> Buf {
let n = w * h;
let (m0, m1) = (cx.gpu.buffer(2 * n), cx.gpu.buffer(2 * n));
map(cx, "xguided_pre", n, &[0], [Some(guide), Some(p), None], &m0);
@@ -969,7 +1191,11 @@ fn guided_cross_max(cx: &mut Cx<'_>, guide: &Buf, p: &Buf, w: usize, h: usize, s
map(cx, "xguided_ab", n, &[eps.to_bits()], [Some(&b0), Some(&b1), None], &ab);
let ab = gaussian(cx, &ab, w, h, 2, sigma);
let q = cx.gpu.buffer(n);
map(cx, "xguided_apply", n, &[], [Some(guide), Some(&ab), Some(p)], &q);
let mode = match how {
Combine::Max => [0, 0],
Combine::Mix(k) => [1, k.to_bits()],
};
map(cx, "xguided_apply", n, &mode, [Some(guide), Some(&ab), Some(p)], &q);
q
}
@@ -1074,7 +1300,7 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho
cx.run("shape", &q, &[Some(lin), Some(&prep.log_l), Some(&aux), Some(&stroke), Some(&brush)], groups2(w, h, [16, 16]));
let refined = d.auto.then(|| {
let (sigma, eps) = lightcraft_pipeline::masks::auto_refine(d.r);
guided_cross_max(cx, &prep.log_l, &stroke, w, h, sigma, eps)
guided_cross(cx, &prep.log_l, &stroke, w, h, sigma, eps, Combine::Max)
});
let op = if d.erase { 2 } else { 1 };
cx.run(
@@ -1120,6 +1346,15 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho
let k = [n as u32, 0, mi as u32, op];
cx.run("combine", &k, &[None, None, None, Some(cbuf), Some(&alpha)], groups1(n));
}
if m.refine > 0.0 {
// Refine Edges (`masks::evaluate_one`): the combined alpha follows the photo's edges,
// before the mask's invert and amount
let k = (m.refine / 100.0).clamp(0.0, 1.0) as f32;
let sigma = (0.04 * frame.output_long(w, h) as f32 * k).max(1.0);
let plane = cx.slice(&alpha, mi * n, n);
let refined = guided_cross(cx, &prep.log_l, &plane, w, h, sigma, 0.02, Combine::Mix(k.sqrt()));
cx.copy_into(&refined, &alpha, mi * n);
}
let amt = (m.adjust.amount / 100.0) as f32;
cx.run(
"finalize",
@@ -1209,6 +1444,8 @@ mod tests {
/// workgroup, windows wider than the image, and 1, 2 (as two planes) and 3 channels.
#[test]
fn gaussian_matches_cpu() {
// (creating the device writes the crash sentinel another test swaps out)
let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
use lightcraft_raster::blur;
let Some(gpu) = crate::device() else { return };
let _scope = crate::ctx::RenderScope::new(gpu);
@@ -1236,6 +1473,8 @@ mod tests {
#[test]
#[ignore]
fn bench_kernels() {
// (creating the device writes the crash sentinel another test swaps out)
let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let Some(gpu) = crate::device() else { return };
let _scope = crate::ctx::RenderScope::new(gpu);
let (w, h) = (6000, 4000);
@@ -1273,6 +1512,31 @@ mod tests {
time("guided sigma=1.75", &mut |cx| drop(guided(cx, &src, w, h, 1.75, 0.01)));
}
/// The device scores Remove's candidate sources like the CPU and picks the same one.
#[test]
fn auto_source_picks_the_cpu_candidate() {
// (creating the device writes the crash sentinel another test swaps out)
let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let Some(gpu) = crate::device() else {
let why = crate::unavailable_reason().unwrap_or_default();
assert!(!why.contains("kernels failed to build"), "{why}");
return;
};
let _scope = crate::ctx::RenderScope::new(gpu);
let img = lightcraft_scenes::demo_library()[3].render(640, 427);
let buf = gpu.upload(rgb_words(&img));
let mut differ = Vec::new();
for (tx, ty, r) in [(25.6, 213.0, 19.2), (320.0, 192.0, 19.2), (100.0, 50.0, 12.0), (600.0, 400.0, 25.0), (320.0, 213.0, 6.0)] {
let mut cx = Cx::new(gpu);
let g = auto_source(&mut cx, &buf, img.width, img.height, (tx, ty), r);
let c = lightcraft_pipeline::spots::auto_source(&img, (tx, ty), r);
if g != c {
differ.push(((tx, ty, r), g, c));
}
}
assert!(differ.is_empty(), "(target, gpu, cpu): {differ:?}");
}
#[test]
fn orient_map_matches_image_oriented() {
use Orientation::*;
+37
View File
@@ -75,6 +75,43 @@ fn box_v(@builtin(global_invocation_id) g: vec3<u32>) {
}
}
// Square min (P[4] = 0) or max (1) filter of radius r, one axis at a time (`optics::min_filter`):
// clamped to the image, single channel. P: w, h, r, axis (0 horizontal, 1 vertical), max.
@compute @workgroup_size(16, 16)
fn minmax(@builtin(global_invocation_id) g: vec3<u32>) {
let w = pu(0u);
let h = pu(1u);
if (g.x >= w || g.y >= h) {
return;
}
let r = pu(2u);
let vertical = pu(3u) != 0u;
let is_max = pu(4u) != 0u;
let i = g.y * w + g.x;
var v = src[i];
var lo = 0u;
var hi = 0u;
if (vertical) {
lo = g.y - min(g.y, r);
hi = min(g.y + r, h - 1u);
} else {
lo = g.x - min(g.x, r);
hi = min(g.x + r, w - 1u);
}
for (var k = lo; k <= hi; k++) {
var j = g.y * w + k;
if (vertical) {
j = k * w + g.x;
}
if (is_max) {
v = max(v, src[j]);
} else {
v = min(v, src[j]);
}
}
dst[i] = v;
}
// Separable median of a single-channel plane (`lightcraft_pipeline::local::median_hv`): 2r+1
// taps (r ≤ 24, clamped edges) along a row (median_h) or a column (median_v), one thread per
// pixel. The median is a selection, so the result matches the CPU's bit for bit.
+147 -31
View File
@@ -1,7 +1,7 @@
// The per-pixel stage: a straight port of `lightcraft_pipeline::finish` (keep in step with it).
// Bindings: img (rgb, pre-exposure), log_l, base, clar, tex, dark, masks (NMASK planes, then the
// blurred chromaticity when HAS_CHROMA), aux
// (tone LUT | chroma curve | sRGB LUT | curve LUTs | mask terms), out (packed RGBA8).
// (tone LUT | chroma curve | sRGB LUT | curve LUTs | mask terms | light operator tables), out (packed RGBA8).
fn tone_apply(y: f32) -> f32 {
if (y <= 0.0) {
@@ -47,6 +47,56 @@ fn curve(ch: u32, x: f32) -> f32 {
return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t;
}
// Process V4's calibrated Contrast, Blacks (`lightcraft_pipeline::light_v3`): operator `k`'s
// table (linear output over encoded v) at v (`Operator::eval`).
fn light_eval(k: u32, v: f32) -> f32 {
let o = pu(F_LIGHT_OFF) + k * LIGHT_N;
let f = clamp(v, 0.0, 1.0) * f32(LIGHT_N - 1u);
let i = min(u32(f), LIGHT_N - 2u);
let t = f - f32(i);
return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t;
}
// `Operator::channel`: one linear value; above 1 unchanged, below 0 shifted by F(0).
fn light_channel(k: u32, x: f32) -> f32 {
if (x > 1.0) {
return x;
}
if (x < 0.0) {
return aux[pu(F_LIGHT_OFF) + k * LIGHT_N] + x;
}
return light_eval(k, encode_srgb(x));
}
// `Operator::luminance`: scaled by F of the ProPhoto luminance over it.
fn light_lum(k: u32, p: vec3<f32>) -> vec3<f32> {
let y = PRO_Y.x * p.x + PRO_Y.y * p.y + PRO_Y.z * p.z;
if (!(y > 1e-6) || y > 1.0) {
return p;
}
return p * (light_channel(k, y) / y);
}
// `LightOps::apply`: linear Rec.2020 → ProPhoto, the operators in order, back.
fn light_ops(d: vec3<f32>) -> vec3<f32> {
var p = mul3(PRO_FROM_2020, d);
let n = min(pu(F_LIGHT_OPS), 2u);
for (var k = 0u; k < n; k++) {
let mode = pu(F_LIGHT_MODE + k);
if (mode == 0u) {
p = vec3<f32>(light_channel(k, p.x), light_channel(k, p.y), light_channel(k, p.z));
} else if (mode == 1u) {
p = light_lum(k, p);
} else {
let a = vec3<f32>(light_channel(k, p.x), light_channel(k, p.y), light_channel(k, p.z));
let b = light_lum(k, p);
let w = pf(F_LIGHT_W + k);
p = vec3<f32>(w * a.x + (1.0 - w) * b.x, w * a.y + (1.0 - w) * b.y, w * a.z + (1.0 - w) * b.z);
}
}
return mul3(PRO_TO_2020, p);
}
fn band_weights(h: f32) -> array<f32, 8> {
var w: array<f32, 8>;
for (var i = 0u; i < 8u; i++) {
@@ -230,8 +280,69 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 {
return a + (b - a) * v;
}
fn enc8(v: f32) -> u32 {
return u32(clamp(v, 0.0, 1.0) * 255.0 + 0.5);
// The 3×3 matrix at parameter `o` (row-major).
fn mat_at(o: u32) -> array<vec3<f32>, 3> {
return array<vec3<f32>, 3>(
vec3<f32>(pf(o), pf(o + 1u), pf(o + 2u)),
vec3<f32>(pf(o + 3u), pf(o + 4u), pf(o + 5u)),
vec3<f32>(pf(o + 6u), pf(o + 7u), pf(o + 8u)),
);
}
// `finish::out_of_gamut`: needed real desaturation, and isn't a neutral clipping at white/black.
fn out_of_gamut(r: vec3<f32>, t: f32) -> bool {
let lo = min(r.x, min(r.y, r.z));
let hi = max(r.x, max(r.y, r.z));
return t < GAMUT_WARN && (hi - lo) > 0.02 * max(abs(hi), 1e-3) && hi - lo > 1e-3 && (lo < -1e-3 || (hi > 1.0 && lo < 1.0));
}
// `Lut3d::apply` (trilinear) on the LUT profile's table in `aux` (red fastest).
fn lut_at(r: u32, g: u32, b: u32) -> vec3<f32> {
let n = pu(F_LUT_N);
let o = pu(F_LUT_OFF) + 3u * (r + n * (g + n * b));
return vec3<f32>(aux[o], aux[o + 1u], aux[o + 2u]);
}
fn lut_apply(c: vec3<f32>) -> vec3<f32> {
let n = pu(F_LUT_N);
let s = f32(n - 1u);
var idx = vec3<u32>(0u);
var fr = vec3<f32>(0.0);
for (var k = 0u; k < 3u; k++) {
let lo = pf(F_LUT_MIN + k);
let span = max(pf(F_LUT_MAX + k) - lo, 1e-6);
let x = clamp((c[k] - lo) / span, 0.0, 1.0) * s;
let i = min(u32(floor(x)), n - 2u);
idx[k] = i;
fr[k] = x - f32(i);
}
let r = idx.x;
let g = idx.y;
let b = idx.z;
let c00 = mix(lut_at(r, g, b), lut_at(r + 1u, g, b), fr.x);
let c10 = mix(lut_at(r, g + 1u, b), lut_at(r + 1u, g + 1u, b), fr.x);
let c01 = mix(lut_at(r, g, b + 1u), lut_at(r + 1u, g, b + 1u), fr.x);
let c11 = mix(lut_at(r, g + 1u, b + 1u), lut_at(r + 1u, g + 1u, b + 1u), fr.x);
return mix(mix(c00, c10, fr.y), mix(c01, c11, fr.y), fr.z);
}
const BAYER_8X8 = array<f32, 64>(
0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0,
48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0,
12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0,
60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0,
3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0,
51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0,
15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0,
63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0,
);
fn enc8(v: f32, d: f32) -> u32 {
let y = clamp(v, 0.0, 1.0) * 255.0;
if (y >= 254.9) {
return 255u;
}
return u32(clamp(y + d, 0.0, 255.0));
}
// sRGB-curve-encoded value → the output space's own curve (`OutputTrc`: 0 sRGB, 1 gamma, 2 Rec.709).
@@ -254,15 +365,6 @@ fn out_encode(v: f32) -> f32 {
return 1.099 * pow(l, 0.45) - 0.099;
}
// The 3×3 matrix stored row by row from field `o`.
fn mat_at(o: u32) -> array<vec3<f32>, 3> {
return array<vec3<f32>, 3>(
vec3<f32>(pf(o), pf(o + 1u), pf(o + 2u)),
vec3<f32>(pf(o + 3u), pf(o + 4u), pf(o + 5u)),
vec3<f32>(pf(o + 6u), pf(o + 7u), pf(o + 8u)),
);
}
// `finish::gamut_map` (SDR): the chroma scale that brings `r` into 0..1 towards its luminance (1: in gamut) ...
fn gamut_scale(r: vec3<f32>, luma: vec3<f32>) -> f32 {
let yy = clamp(dot(luma, r), 0.0, 1.0);
@@ -287,13 +389,6 @@ fn gamut_apply(r: vec3<f32>, luma: vec3<f32>, tg: f32) -> vec3<f32> {
return r;
}
// `finish::out_of_gamut`: `r` needed desaturating by `t` to fit and isn't just a neutral beyond white or below black.
fn out_of_gamut(r: vec3<f32>, t: f32) -> bool {
let lo = min(r.x, min(r.y, r.z));
let hi = max(r.x, max(r.y, r.z));
return t < 0.995 && (hi - lo) > 0.02 * max(abs(hi), 1e-3) && hi - lo > 1e-3 && (lo < -1e-3 || (hi > 1.0 && lo < 1.0));
}
@compute @workgroup_size(16, 16)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let w = pu(F_W);
@@ -423,19 +518,28 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
delta += cl * 0.85 * det * (0.35 + 0.65 * mid);
}
let tx = pf(F_TEX) + lt[8];
let sp = lt[13] * 0.6 + pf(F_SHARPEN);
if ((tx != 0.0 || sp != 0.0) && pu(F_HAS_TEX) != 0u) {
if (tx != 0.0 && pu(F_HAS_TEX) != 0u) {
let det = l_pre - tex[i];
let tame = 1.0 - 0.6 * sstep(0.4, 1.6, abs(det));
delta += tx * 1.1 * clamp(det, -1.0, 1.0) * tame;
if (sp != 0.0) {
let sm = pf(F_SHARPEN_MASK);
var mk = 1.0;
if (sm > 0.0) {
mk = sstep(sm * 0.25, sm * 0.25 + 0.15, abs(det));
}
delta += sp * 1.3 * clamp(det, -0.8, 0.8) * mk;
}
let sp = lt[13] * 0.6 + pf(F_SHARPEN);
if (pu(F_SHARPEN_V3) != 0u && sp != 0.0 && pu(F_HAS_SHP) != 0u) {
let det = l_pre - tex[pu(F_SHP_OFF) + i];
let sm = pf(F_SHARPEN_MASK);
var mk = 1.0;
if (sm > 0.0) {
mk = sstep(sm * 0.1, sm * 0.1 + 0.06, abs(det));
}
delta += sp * pf(F_SHARPEN_GAIN) * 7.0 * mk * det / (1.0 + abs(det) / pf(F_SHARPEN_LIMIT));
} else if (pu(F_SHARPEN_V3) == 0u && sp != 0.0 && pu(F_HAS_TEX) != 0u) {
let det = l_pre - tex[i];
let sm = pf(F_SHARPEN_MASK);
var mk = 1.0;
if (sm > 0.0) {
mk = sstep(sm * 0.25, sm * 0.25 + 0.15, abs(det));
}
delta += sp * 1.3 * clamp(det, -0.8, 0.8) * mk;
}
// local Noise: smooth (or, negative, boost) small-amplitude detail, keep edges
if (l_noise != 0.0 && pu(F_HAS_TEX) != 0u) {
@@ -468,6 +572,11 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
d = d + (o - d) * t;
}
// --- process V4: calibrated Contrast, Blacks
if (pu(F_LIGHT_OPS) != 0u) {
d = light_ops(d);
}
// --- colour
d = color_ops(d, lt[11], lt[12]);
if (tint_on) {
@@ -558,11 +667,18 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum));
e = e + k;
}
if (pu(F_LUT) != 0u) {
let m = lut_apply(clamp(e, vec3<f32>(0.0), vec3<f32>(1.0)));
e = e + (m - e) * pf(F_LUT_AMT);
}
if (warn == 1u) {
e = vec3<f32>(1.0, 0.0, 0.0);
e = vec3<f32>(PROOF_DEST_R, PROOF_DEST_G, PROOF_DEST_B);
} else if (warn == 2u) {
e = vec3<f32>(0.0, 0.25, 1.0);
e = vec3<f32>(PROOF_DISP_R, PROOF_DISP_G, PROOF_DISP_B);
}
e = vec3<f32>(out_encode(e.x), out_encode(e.y), out_encode(e.z));
out[i] = enc8(e.x) | (enc8(e.y) << 8u) | (enc8(e.z) << 16u) | (255u << 24u);
let abs_x = u32(pf(F_VIG_VIEW)) + x;
let abs_y = u32(pf(F_VIG_VIEW + 1u)) + y;
let dither = (BAYER_8X8[(abs_y & 7u) * 8u + (abs_x & 7u)] + 0.5) / 64.0;
out[i] = enc8(e.x, dither) | (enc8(e.y, dither) << 8u) | (enc8(e.z, dither) << 16u) | (255u << 24u);
}
+36
View File
@@ -0,0 +1,36 @@
// Exact separable Gaussian with explicit taps over a one-channel plane (clamped edges); mirrors
// `lightcraft_raster::blur::gaussian_taps` (same taps, same accumulation order).
// P: w, h, r (taps has 2r+1 entries). Bindings: src, taps, dst.
@compute @workgroup_size(16, 16)
fn gauss_h(@builtin(global_invocation_id) g: vec3<u32>) {
let w = pu(0u);
let h = pu(1u);
let r = i32(pu(2u));
if (g.x >= w || g.y >= h) {
return;
}
let last = i32(w) - 1;
let row = g.y * w;
var acc = 0.0;
for (var k = 0; k <= 2 * r; k++) {
acc += src[row + u32(clamp(i32(g.x) + k - r, 0, last))] * taps[u32(k)];
}
dst[row + g.x] = acc;
}
@compute @workgroup_size(16, 16)
fn gauss_v(@builtin(global_invocation_id) g: vec3<u32>) {
let w = pu(0u);
let h = pu(1u);
let r = i32(pu(2u));
if (g.x >= w || g.y >= h) {
return;
}
let last = i32(h) - 1;
var acc = 0.0;
for (var k = 0; k <= 2 * r; k++) {
acc += src[u32(clamp(i32(g.y) + k - r, 0, last)) * w + g.x] * taps[u32(k)];
}
dst[g.y * w + g.x] = acc;
}
+24
View File
@@ -0,0 +1,24 @@
// The histogram (`Histogram::of_srgb8`) of a region of the packed RGBA8 output, on the same
// sampling grid: every STEP-th pixel of every STEP-th row. Bindings: px (packed RGBA8), bins
// (r | g | b | luma, 256 each, then the total; cleared beforehand).
// P: W (image width), X0, Y0 (region origin), NX, NY (sampled columns / rows), STEP.
@compute @workgroup_size(16, 16)
fn histogram(@builtin(global_invocation_id) g: vec3<u32>) {
if (g.x >= pu(3u) || g.y >= pu(4u)) {
return;
}
let step = pu(5u);
let x = pu(1u) + g.x * step;
let y = pu(2u) + g.y * step;
let p = px[y * pu(0u) + x];
let r = p & 255u;
let gg = (p >> 8u) & 255u;
let b = (p >> 16u) & 255u;
atomicAdd(&bins[r], 1u);
atomicAdd(&bins[256u + gg], 1u);
atomicAdd(&bins[512u + b], 1u);
let l = min((r * 54u + gg * 183u + b * 19u) >> 8u, 255u);
atomicAdd(&bins[768u + l], 1u);
atomicAdd(&bins[1024u], 1u);
}
+58 -2
View File
@@ -105,14 +105,20 @@ fn xguided_ab(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgrou
dst[2u * i + 1u] = mp - k * mi;
}
// `max(p, clamp(a·guide + b, 0, 1))` (a: guide, b: blurred coefficients, c: the input p).
// q = clamp(a·guide + b, 0, 1) (a: guide, b: blurred coefficients, c: the input p), then
// P[1] = 0: max(p, q) (Auto Mask strokes); 1: p + (q − p)·P[2] (Refine Edges).
@compute @workgroup_size(256)
fn xguided_apply(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
let i = lin_index(g, nw);
if (i >= pu(0u)) {
return;
}
dst[i] = max(c[i], clamp(b[2u * i] * a[i] + b[2u * i + 1u], 0.0, 1.0));
let q = clamp(b[2u * i] * a[i] + b[2u * i + 1u], 0.0, 1.0);
if (pu(1u) == 0u) {
dst[i] = max(c[i], q);
} else {
dst[i] = c[i] + (q - c[i]) * pf(2u);
}
}
// White balance: 3×3 matrix (P[1] = has matrix, P[2..11] row-major), clamped at 0.
@@ -226,3 +232,53 @@ fn redeye_k(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups
}
put_rgb(i, c);
}
// Defringe, first step (`optics::defringe`): OkLab of the clamped colour (a: image) → dst
// (lightness, a, b interleaved).
@compute @workgroup_size(256)
fn fringe_lab(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
let i = lin_index(g, nw);
if (i >= pu(0u)) {
return;
}
put_rgb(i, oklab(max(rgb_a(i), vec3<f32>(0.0))));
}
// `optics::hue_weight`: membership of hue h (deg) in [lo, hi] with 8° shoulders.
fn hue_weight(h: f32, lo: f32, hi: f32) -> f32 {
let mid = (lo + hi) / 2.0;
let half = (hi - lo) / 2.0;
var d = abs(h - mid) % 360.0;
if (d > 180.0) {
d = 360.0 - d;
}
return 1.0 - sstep(half, half + 8.0, d);
}
// Defringe, last step: desaturate fringe colours at edges (a: OkLab, b / c: lightness min / max
// around each pixel; dst: the image, written only where it changes, so it starts as a copy).
// P[1..7] = purple lo, hi, green lo, hi, purple strength, green strength.
@compute @workgroup_size(256)
fn fringe_apply(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
let i = lin_index(g, nw);
if (i >= pu(0u)) {
return;
}
let edge = sstep(0.08, 0.25, c[i] - b[i]);
if (edge <= 0.0) {
return;
}
let lab = rgb_a(i);
let ch = sqrt(lab.y * lab.y + lab.z * lab.z);
let chroma_w = sstep(0.015, 0.05, ch);
if (chroma_w <= 0.0) {
return;
}
let hue = rem_euclid(degrees(atan2(lab.z, lab.y)), 360.0);
let k = max(pf(5u) * hue_weight(hue, pf(1u), pf(2u)), pf(6u) * hue_weight(hue, pf(3u), pf(4u))) * edge * chroma_w;
if (k <= 0.0) {
return;
}
let f = 1.0 - min(k, 1.0);
put_rgb(i, max(oklab_inv(vec3<f32>(lab.x, lab.y * f, lab.z * f)), vec3<f32>(0.0)));
}
+24
View File
@@ -0,0 +1,24 @@
// Handing a finished render to the window without a readback (`render::present`).
// Bindings: px (packed RGBA8 output), dst (packed RGBA8, padded rows), count (one atomic word).
// Pixels whose alpha is not 255: work that never ran (the readback's `unwritten`). P[0] = pixels.
@compute @workgroup_size(256)
fn unwritten(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
let i = lin_index(g, nw);
if (i >= pu(0u)) {
return;
}
if ((px[i] >> 24u) != 255u) {
atomicAdd(&count[0], 1u);
}
}
// Rows of P[0] pixels (P[1] rows) re-laid at a stride of P[2] pixels (texture copies take rows of a
// multiple of 256 bytes).
@compute @workgroup_size(16, 16)
fn pad_rows(@builtin(global_invocation_id) g: vec3<u32>) {
if (g.x >= pu(0u) || g.y >= pu(1u)) {
return;
}
dst[g.y * pu(2u) + g.x] = px[g.y * pu(0u) + g.x];
}
+177
View File
@@ -0,0 +1,177 @@
// Spot removal (`lightcraft_pipeline::spots::apply`), one spot at a time, on the image in place.
// Bindings: img (rgb, read-write), pts (f32 data: see each kernel), al / sp / df / wt (work buffers
// over the spot's box: alpha, source patch, masked difference, weights).
//
// Parameters of spot_prep / spot_apply: W, H, BX, BY, BW, BH, NPTS, R, INNER, OPACITY, OFFX, OFFY,
// HEAL. `pts`: the stroke's points (x, y; output pixels).
// `f32::MAX` exactly ("doesn't fit", as the CPU's score; a decimal literal may round below it,
// and naga can't evaluate bitcast in a const).
fn f32_max() -> f32 {
return bitcast<f32>(0x7f7fffffu);
}
// `Rgb32f::get_clamped`.
fn px_at(x: i32, y: i32) -> vec3<f32> {
let w = i32(pu(0u));
let h = i32(pu(1u));
let i = u32(clamp(y, 0, h - 1) * w + clamp(x, 0, w - 1));
return vec3<f32>(img[3u * i], img[3u * i + 1u], img[3u * i + 2u]);
}
// `Rgb32f::sample_bilinear` (pixel centres at +0.5).
fn bilinear(x: f32, y: f32) -> vec3<f32> {
let fx = x - 0.5;
let fy = y - 0.5;
let x0 = floor(fx);
let y0 = floor(fy);
let tx = fx - x0;
let ty = fy - y0;
let ix = i32(x0);
let iy = i32(y0);
let a = px_at(ix, iy);
let b = px_at(ix + 1, iy);
let c = px_at(ix, iy + 1);
let d = px_at(ix + 1, iy + 1);
let top = a + (b - a) * tx;
let bot = c + (d - c) * tx;
return top + (bot - top) * ty;
}
// `spots::smooth`, defined for e1 ≤ e0 as the step at e1 (no feather).
fn spot_smooth(e0: f32, e1: f32, x: f32) -> f32 {
if (e1 <= e0) {
return select(0.0, 1.0, x >= e1);
}
return sstep(e0, e1, x);
}
// Alpha, source patch and (Heal) the difference outside the stroke, over the box.
@compute @workgroup_size(16, 16)
fn spot_prep(@builtin(global_invocation_id) gid: vec3<u32>) {
let bw = pu(4u);
let bh = pu(5u);
if (gid.x >= bw || gid.y >= bh) {
return;
}
let i = gid.y * bw + gid.x;
let gx = pu(2u) + gid.x;
let gy = pu(3u) + gid.y;
let px = f32(gx) + 0.5;
let py = f32(gy) + 0.5;
var d = f32_max();
for (var k = 0u; k < pu(6u); k++) {
let ex = px - pts[2u * k];
let ey = py - pts[2u * k + 1u];
d = min(d, sqrt(ex * ex + ey * ey));
}
let alpha = (1.0 - spot_smooth(pf(8u), pf(7u), d)) * pf(9u);
al[i] = alpha;
let s = bilinear(px + pf(10u), py + pf(11u));
sp[3u * i] = s.x;
sp[3u * i + 1u] = s.y;
sp[3u * i + 2u] = s.z;
let gi = gy * pu(0u) + gx;
let t = vec3<f32>(img[3u * gi], img[3u * gi + 1u], img[3u * gi + 2u]);
let outside = select(0.0, 1.0, alpha < 0.02);
let m = (t - s) * outside;
df[3u * i] = m.x;
df[3u * i + 1u] = m.y;
df[3u * i + 2u] = m.z;
wt[i] = outside;
}
// Blend the (healed) patch into the image (df, wt: the blurred difference and weights).
@compute @workgroup_size(16, 16)
fn spot_apply(@builtin(global_invocation_id) gid: vec3<u32>) {
let bw = pu(4u);
let bh = pu(5u);
if (gid.x >= bw || gid.y >= bh) {
return;
}
let i = gid.y * bw + gid.x;
let a = al[i];
if (a <= 0.0) {
return;
}
var v = vec3<f32>(sp[3u * i], sp[3u * i + 1u], sp[3u * i + 2u]);
if (pu(12u) != 0u) {
let m = max(wt[i], 1e-4);
v = v + vec3<f32>(df[3u * i] / m, df[3u * i + 1u] / m, df[3u * i + 2u] / m);
}
let gi = (pu(3u) + gid.y) * pu(0u) + pu(2u) + gid.x;
let t = vec3<f32>(img[3u * gi], img[3u * gi + 1u], img[3u * gi + 2u]);
let o = max(t + (v - t) * a, vec3<f32>(0.0));
img[3u * gi] = o.x;
img[3u * gi + 1u] = o.y;
img[3u * gi + 2u] = o.z;
}
// `spots::ring_stats`: sample k (spoke-major, 3 radii each) of the rings around c, or a NaN-free
// flag in .w = 0 when it falls outside the image.
fn ring_sample(c: vec2<f32>, k: u32, radii: u32) -> vec4<f32> {
let spoke = k / 3u;
let rr = pf(radii + k % 3u);
let o = 2u * NCAND + 2u * spoke;
let x = c.x + pts[o] * rr;
let y = c.y + pts[o + 1u] * rr;
if (x < 0.0 || y < 0.0 || x >= f32(pu(0u)) || y >= f32(pu(1u))) {
return vec4<f32>(0.0);
}
return vec4<f32>(bilinear(x, y), 1.0);
}
fn ring_fits(c: vec2<f32>, radii: u32) -> bool {
for (var k = 0u; k < 72u; k++) {
if (ring_sample(c, k, radii).w == 0.0) {
return false;
}
}
return true;
}
fn sq(v: f32) -> f32 {
return sqrt(max(v, 0.0));
}
// `spots::score` of every candidate source (one invocation each) into `al`.
// Parameters: W, H, TX, TY, then the surroundings' radii (3) and the inside's (3).
// `pts`: NCAND candidate offsets (x, y), then the 24 spoke directions (cos, sin).
@compute @workgroup_size(64)
fn spot_score(@builtin(global_invocation_id) gid: vec3<u32>) {
let j = gid.x;
if (j >= NCAND) {
return;
}
let tgt = vec2<f32>(pf(2u), pf(3u));
let src = tgt + vec2<f32>(pts[2u * j], pts[2u * j + 1u]);
if (!ring_fits(tgt, 4u) || !ring_fits(src, 4u)) {
al[j] = f32_max();
return;
}
var s = 0.0;
for (var k = 0u; k < 72u; k++) {
let p = ring_sample(tgt, k, 4u).xyz;
let q = ring_sample(src, k, 4u).xyz;
for (var c = 0u; c < 3u; c++) {
let u = sq(p[c]);
let v = sq(q[c]);
s += (u - v) * (u - v);
}
}
if (ring_fits(src, 7u)) {
var mean_a = 0.0;
for (var k = 0u; k < 72u; k++) {
mean_a += sq(ring_sample(tgt, k, 4u).y);
}
mean_a = mean_a / 72.0;
var var_ = 0.0;
for (var k = 0u; k < 72u; k++) {
let e = sq(ring_sample(src, k, 7u).y) - mean_a;
var_ += e * e;
}
var_ = var_ / 72.0;
s += var_ * 72.0 * 0.5;
}
al[j] = s;
}
+80
View File
@@ -0,0 +1,80 @@
//! Renders handed to the window as textures (`render_display` on an adopted device): the texture
//! holds exactly the pixels a readback render returns, the histogram matches, and what can't be a
//! texture (overlays, a window grown by spots) comes back as pixels. Own process: adopting a
//! device is once per process. Skips (passes with a note) without an adapter.
use std::sync::Arc;
use lightcraft_develop::{DevelopSettings, Spot};
use lightcraft_geom::Point;
use lightcraft_gpu::{Output, wgpu};
use lightcraft_pipeline::{Overlay, PixelWindow, Quality, RenderRequest, SourceInfo, StageCache};
/// A device made the way eframe makes the window's (adapter limits, the window's backends).
fn window_device() -> Option<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> {
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
desc.backends = lightcraft_gpu::backend::window_backends();
desc.backend_options = lightcraft_gpu::backend::backend_options();
let instance = wgpu::Instance::new(desc);
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?;
let info = adapter.get_info();
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("test window"),
required_limits: adapter.limits(),
..Default::default()
}))
.ok()?;
Some((device, queue, info))
}
#[test]
fn display_renders_match_readback_renders() {
// switched off for the process (`LIGHTCRAFT_GPU=0`): there is no device to adopt
if let Some(reason) = lightcraft_gpu::env_off_reason() {
lightcraft_testkit::skip!(Gpu, "{reason}");
return;
}
let Some((device, queue, info)) = window_device() else {
lightcraft_testkit::skip!(Gpu, "no GPU adapter");
return;
};
if info.device_type == wgpu::DeviceType::Cpu {
lightcraft_testkit::skip!(Gpu, "software adapter");
return;
}
lightcraft_gpu::adopt_window_device(device.clone(), queue.clone(), info).expect("adopted");
assert!(lightcraft_gpu::on_window_device());
let raw = SourceInfo { raw: true, ..Default::default() };
let mut s = DevelopSettings::default();
s.light.exposure = 0.5;
s.light.highlights = -40.0;
s.effects.clarity = 20.0;
s.detail.nr_luminance = 20.0;
s.grain.amount = 20.0;
// widths that are and aren't a multiple of 64 texels (row padding), draft and full quality
for (w, h, quality) in [(640, 427, Quality::Full), (1000, 667, Quality::Draft), (1024, 683, Quality::Full)] {
let src = Arc::new(lightcraft_scenes::demo_library()[0].render(w, h));
let req = RenderRequest { quality, ..RenderRequest::fit(w, h) };
let stages = StageCache::default();
let pixels = lightcraft_gpu::render(&src, &raw, &s, &req, Some(&stages)).expect("gpu render");
match lightcraft_gpu::render_display(&src, &raw, &s, &req, Some(&stages)).expect("display render") {
Output::Display { frame, histogram } => {
assert_eq!((frame.width, frame.height), (pixels.image.width, pixels.image.height));
let shown = lightcraft_gpu::read_texture(&device, &queue, &frame.texture, frame.width, frame.height).expect("readback");
assert!(shown.data == pixels.image.data, "{w}×{h}: the texture holds the readback's pixels");
assert_eq!(histogram, pixels.histogram);
}
Output::Image(_) => panic!("{w}×{h}: expected a texture"),
}
}
// overlays are drawn on the CPU, and a window that spots grew is cut there: pixels
let src = Arc::new(lightcraft_scenes::demo_library()[0].render(3000, 2000));
let req = RenderRequest { overlay: Overlay::Spots(50), ..RenderRequest::fit(800, 800) };
assert!(matches!(lightcraft_gpu::render_display(&src, &raw, &s, &req, None), Some(Output::Image(_))), "overlay");
s.spots = vec![Spot { points: vec![Point::new(0.5, 0.5)], size: 0.02, source_offset: Some(Point::new(0.15, 0.0)), ..Default::default() }];
let req = RenderRequest { window: Some(PixelWindow { x: 1200, y: 800, w: 500, h: 400 }), ..RenderRequest::fit(3000, 2000) };
match lightcraft_gpu::render_display(&src, &raw, &s, &req, None) {
Some(Output::Image(r)) => assert_eq!((r.image.width, r.image.height), (500, 400)),
_ => panic!("a grown window comes back as pixels"),
}
}
+338 -3
View File
@@ -20,11 +20,58 @@ const MAX_LSB: u8 = 3;
fn gpu() -> bool {
let ok = lightcraft_gpu::available();
if !ok {
let why = lightcraft_gpu::unavailable_reason().unwrap_or_default();
// no adapter (CI) skips; an adapter whose kernels don't build is a bug in them
assert!(!why.contains("kernels failed to build"), "{why}");
lightcraft_testkit::skip!(Gpu, "no GPU adapter");
}
// which card the comparisons ran on (`LIGHTCRAFT_GPU_ADAPTER` picks one on a machine with two)
static NAMED: std::sync::Once = std::sync::Once::new();
NAMED.call_once(|| eprintln!("GPU equivalence tests on {}", lightcraft_gpu::adapter_name().unwrap_or_default()));
ok
}
fn check_v3_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) {
if !gpu() {
return;
}
// These uniform nonnegative sources expose cancellation after camera chroma scaling
// and Contrast, just below the positive Blacks luminance cutoff.
let curve = lightcraft_pipeline::tone::CameraTone::new(std::array::from_fn(|i| {
let x = (i + 1) as f32 / 33.0;
[x, x]
}))
.unwrap()
.with_chroma([chroma; 8])
.unwrap();
let info = SourceInfo { raw: true, camera_tone: Some(curve), ..Default::default() };
let src = Arc::new(Rgb32f::filled(64, 64, pixel));
let mut s = DevelopSettings { process: Process::V4.version(), ..Default::default() };
s.light.contrast = 100.0;
s.light.blacks = 80.0;
let req = RenderRequest::fit(64, 64);
let cpu = render(&src, &info, &s, &req).image;
let gpu = lightcraft_gpu::try_render(&src, &info, &s, &req, None).expect("GPU render without CPU fallback").image;
for image in [&cpu, &gpu] {
assert!(image.data.iter().all(|p| *p == image.data[0]));
for (actual, expected) in image.data[0].into_iter().zip(expected) {
assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {:?}, expected {expected}", image.data[0]);
}
}
let (_, max, _) = diff(&cpu, &gpu);
assert!(max <= 1, "chroma {chroma}: CPU {:?}, GPU {:?}", cpu.data[0], gpu.data[0]);
}
#[test]
fn v3_luminance_cutoff_chroma_2() {
check_v3_luminance_cutoff(2.0, [0.023_433_316, 0.000_071_107_73, 0.005_175_675], [27, 0, 8, 255]);
}
#[test]
fn v3_luminance_cutoff_chroma_4() {
check_v3_luminance_cutoff(4.0, [0.035_338_085, 0.000_048_468_723, 0.010_193_758], [47, 0, 19, 255]);
}
#[test]
fn camera_tone_and_relative_wb() {
if !gpu() {
@@ -236,6 +283,33 @@ fn cases() -> Vec<(&'static str, Edit)> {
s.effects.clarity = -60.0;
s.effects.texture = -40.0;
}),
("sharpen radius 2.5 detail 100", |s| {
s.detail.sharpen_amount = 100.0;
s.detail.sharpen_radius = 2.5;
s.detail.sharpen_detail = 100.0;
}),
("sharpen radius 0.6 detail 0", |s| {
s.detail.sharpen_amount = 80.0;
s.detail.sharpen_radius = 0.6;
s.detail.sharpen_detail = 0.0;
}),
("sharpen + texture + masking", |s| {
s.detail.sharpen_amount = 70.0;
s.detail.sharpen_masking = 30.0;
s.effects.texture = 40.0;
}),
("local sharpness", |s| {
s.masks = vec![Mask {
components: vec![MaskComponent {
name: None,
op: MaskOp::Add,
invert: false,
shape: MaskShape::Linear { start: Point::new(0.5, 0.0), end: Point::new(0.5, 0.6) },
}],
adjust: lightcraft_develop::LocalAdjustments { sharpness: 80.0, ..Default::default() },
..Default::default()
}];
}),
("sharpen masking", |s| {
s.detail.sharpen_amount = 90.0;
s.detail.sharpen_masking = 60.0;
@@ -417,7 +491,7 @@ fn cases() -> Vec<(&'static str, Edit)> {
s.calibration.blue_sat = 60.0;
s.calibration.blue_hue = 25.0;
}),
("spots + defringe (cpu stage)", |s| {
("spots + defringe", |s| {
s.spots = vec![Spot { points: vec![Point::new(0.3, 0.3)], size: 0.03, source_offset: Some(Point::new(0.1, 0.0)), ..Default::default() }];
s.optics.defringe_purple_amount = 5.0;
}),
@@ -616,6 +690,67 @@ fn cached_renders_match_uncached() {
}
}
/// Calibrated Contrast and Blacks, legacy Whites, combined edits, windows and cache reuse.
#[test]
fn light_v3_operators_match() {
if !gpu() {
return;
}
let src = scene(0, 960, 640);
let curve = lightcraft_pipeline::tone::CameraTone::new(std::array::from_fn(|i| {
let x = 0.004 * 1.18f32.powi(i as i32);
[x, 1.0 - (-2.0 * x).exp()]
}))
.unwrap()
.with_chroma([1.3, 1.2, 1.1, 1.0, 0.9, 0.7, 0.5, 0.4])
.unwrap();
let info = SourceInfo { raw: true, camera_tone: Some(curve), ..Default::default() };
let req = RenderRequest::fit(720, 720);
for id in ["light.contrast", "light.whites", "light.blacks"] {
for v in [-100.0, -50.0, 50.0, 100.0] {
let mut s = DevelopSettings::default();
assert_eq!(s.process.process(), Process::V4);
lightcraft_develop::controls::set(&mut s, id, v);
check(&format!("V4 {id} {v}"), &src, &info, &s, &req);
if id == "light.whites" {
let mut old = s.clone();
old.process = Process::V2.version();
assert_eq!(
lightcraft_gpu::render(&src, &info, &s, &req, None).unwrap().image,
lightcraft_gpu::render(&src, &info, &old, &req, None).unwrap().image
);
}
}
}
let mut s = DevelopSettings::default();
typical(&mut s);
s.light.contrast = 35.0;
s.light.whites = 40.0;
s.light.blacks = -30.0;
check("V4 combined, typical", &src, &info, &s, &req);
s.color.vibrance = 30.0;
s.vignette.amount = -20.0;
check("V4 combined, colour", &src, &info, &s, &req);
use lightcraft_pipeline::PixelWindow;
let win = RenderRequest { window: Some(PixelWindow { x: 1200, y: 800, w: 640, h: 480 }), ..RenderRequest::fit(3000, 2000) };
check("V4 combined, window", &src, &info, &s, &win);
s.hdr.enabled = true;
s.hdr.max_ev = 2.0;
check("V4 HDR preview", &src, &info, &s, &req);
// High-bit-depth exports use the CPU; the GPU kernel writes 8-bit previews.
let hdr_req = RenderRequest { depth: lightcraft_pipeline::OutputDepth::F32Hdr, ..req };
assert_eq!(lightcraft_gpu::try_render(&src, &info, &s, &hdr_req, None).err(), Some(lightcraft_gpu::Fallback::NotTried));
s.hdr.enabled = false;
let cache = StageCache::default();
for k in 0..3 {
s.light.exposure = 0.3 * k as f64;
let warm = lightcraft_gpu::render(&src, &info, &s, &req, Some(&cache)).expect("gpu");
let fresh = lightcraft_gpu::render(&src, &info, &s, &req, None).expect("gpu");
assert_eq!(warm.image, fresh.image, "exposure step {k}");
check(&format!("V4 exposure step {k}"), &src, &info, &s, &req);
}
}
/// Issue #632: the Highlights / Shadows base of each process (V1: the edge-aware filter of log
/// luminance; V2: of its fine median, a radius that grows with the render) matches the CPU's, and
/// a warm cache never hands one process the other's base.
@@ -648,7 +783,7 @@ fn highlights_shadows_base_matches_on_every_process() {
}];
check(&format!("{p:?} local highlights {w}"), &src, &raw, &s, &req);
}
for p in [Process::V1, Process::V2, Process::V1, Process::V2] {
for p in [Process::V1, Process::V2, Process::V4, Process::V1, Process::V2, Process::V4] {
let mut s = DevelopSettings { process: p.version(), ..DevelopSettings::default() };
s.light.highlights = -100.0;
let warm = lightcraft_gpu::render(&src, &raw, &s, &req, Some(&cache)).expect("gpu");
@@ -658,6 +793,30 @@ fn highlights_shadows_base_matches_on_every_process() {
}
}
#[test]
fn sharpening_matches_each_process_and_reduced_source() {
if !gpu() {
return;
}
let src = scene(0, 256, 192);
let info = SourceInfo { raw: true, native_long: Some(1024), ..Default::default() };
let req = RenderRequest::fit(128, 128);
let cache = StageCache::default();
for process in [Process::V1, Process::V2, Process::V3, Process::V2, Process::V3] {
let mut s = DevelopSettings { process: process.version(), ..Default::default() };
s.detail.sharpen_amount = 80.0;
s.detail.sharpen_radius = 2.0;
s.detail.sharpen_detail = 75.0;
for nr in [0.0, 50.0, 20.0] {
s.detail.nr_luminance = nr;
check(&format!("{process:?} sharpening NR {nr}"), &src, &info, &s, &req);
let warm = lightcraft_gpu::render(&src, &info, &s, &req, Some(&cache)).expect("gpu");
let fresh = lightcraft_gpu::render(&src, &info, &s, &req, None).expect("gpu");
assert_eq!(warm.image, fresh.image, "{process:?} NR {nr}");
}
}
}
#[test]
fn overlays_match() {
if !gpu() {
@@ -797,7 +956,7 @@ fn red_eye_matches() {
spots: vec![Spot { points: vec![Point::new(0.1, 0.2)], size: 0.02, source_offset: Some(Point::new(0.05, 0.0)), ..Default::default() }],
..Default::default()
};
check("red eye + spot (cpu stage)", &src, &info, &s, &RenderRequest::fit(600, 600));
check("red eye + spot", &src, &info, &s, &RenderRequest::fit(600, 600));
}
fn saturated(s: &mut DevelopSettings) {
@@ -956,6 +1115,89 @@ fn windows_of_a_big_photo_share_one_uploaded_source() {
assert_eq!(lightcraft_gpu::source_uploads() - start, 2);
}
/// A non-trivial 3D LUT (cross-process look: lifted blacks, warm highlights, swapped-ish blues).
fn look_lut(n: usize, domain_max: f32) -> lightcraft_pipeline::lut::Lut3d {
let mut data = Vec::with_capacity(n * n * n);
for b in 0..n {
for g in 0..n {
for r in 0..n {
let c = [r, g, b].map(|v| v as f32 / (n - 1) as f32 * domain_max);
data.push([
(0.06 + 0.9 * c[0].powf(0.9) + 0.05 * c[2]).min(1.0),
(0.04 + 0.92 * c[1] * (1.0 - 0.1 * c[2])).min(1.0),
(0.1 + 0.6 * c[2] + 0.2 * c[0] * c[1]).min(1.0),
]);
}
}
}
lightcraft_pipeline::lut::Lut3d { size: n, data, domain_min: [0.0; 3], domain_max: [domain_max; 3], title: None }
}
/// LUT profiles render on the GPU (the table is applied after grain, blended by the amount).
#[test]
fn lut_profiles_match() {
if !gpu() {
return;
}
let src = scene(1, 900, 600);
let raw = SourceInfo { raw: true, ..Default::default() };
lightcraft_pipeline::lut::register("lut:gpu-test-17", look_lut(17, 1.0));
lightcraft_pipeline::lut::register("lut:gpu-test-domain", look_lut(9, 1.2));
for (id, amount) in [("lut:gpu-test-17", 100.0), ("lut:gpu-test-17", 160.0), ("lut:gpu-test-domain", 60.0)] {
for (name, edit) in [("default", (|_| {}) as Edit), ("saturated + curves + grain", saturated as Edit)] {
let mut s = DevelopSettings::default();
edit(&mut s);
s.profile.id = id.into();
s.profile.amount = amount;
check(&format!("{id} {amount} {name}"), &src, &raw, &s, &RenderRequest::fit(640, 640));
}
}
}
/// Refine Edges on a mask is the cross guided filter on the device, blended by √refine.
#[test]
fn refine_edges_match() {
if !gpu() {
return;
}
let src = scene(0, 900, 600);
let raw = SourceInfo { raw: true, ..Default::default() };
for refine in [15.0, 60.0, 100.0] {
let mut s = DevelopSettings::default();
typical(&mut s);
s.masks = vec![
Mask {
components: vec![MaskComponent {
name: None,
op: MaskOp::Add,
invert: false,
shape: MaskShape::Radial { center: Point::new(0.45, 0.55), rx: 0.3, ry: 0.2, angle: 10.0, feather: 30.0, invert: false },
}],
adjust: lightcraft_develop::LocalAdjustments { exposure: 0.9, saturation: -30.0, ..Default::default() },
refine,
..Default::default()
},
Mask {
components: vec![MaskComponent {
name: None,
op: MaskOp::Add,
invert: false,
shape: MaskShape::Linear { start: Point::new(0.5, 0.0), end: Point::new(0.5, 0.5) },
}],
adjust: lightcraft_develop::LocalAdjustments { exposure: -0.7, amount: 70.0, ..Default::default() },
refine: refine / 2.0,
invert: true,
..Default::default()
},
];
check(&format!("refine edges {refine}"), &src, &raw, &s, &RenderRequest::fit(640, 640));
let gpu = |s: &DevelopSettings| lightcraft_gpu::render(&src, &raw, s, &RenderRequest::fit(640, 640), None).expect("gpu render").image;
let unrefined = DevelopSettings { masks: s.masks.iter().map(|m| Mask { refine: 0.0, ..m.clone() }).collect(), ..s.clone() };
// (a light refine barely moves a soft radial edge; a strong one visibly does)
assert!(refine < 50.0 || diff(&gpu(&s), &gpu(&unrefined)).1 > 3, "refine {refine} changes the mask");
}
}
#[test]
fn soft_proofs_match() {
if !gpu() {
@@ -1006,3 +1248,96 @@ fn soft_proofs_match() {
};
assert!(lightcraft_gpu::render(&src, &raw, &DevelopSettings::default(), &req, None).is_none(), "declined: the CPU renders it");
}
/// Spot removal on the device: Clone, Heal and Remove (automatic source, scored on the device),
/// brushed strokes, overlapping spots (each reads what the earlier ones left), feather 0 and
/// spots cut by the image edge.
#[test]
fn spots_match() {
if !gpu() {
return;
}
use lightcraft_develop::SpotMode;
let src = scene(3, 900, 600);
let raw = SourceInfo { raw: true, ..Default::default() };
let spot = |mode, pts: &[(f64, f64)], size, feather, off: Option<(f64, f64)>| Spot {
mode,
points: pts.iter().map(|p| Point::new(p.0, p.1)).collect(),
size,
feather,
opacity: 100.0,
source_offset: off.map(|o| Point::new(o.0, o.1)),
};
let sets: Vec<(&str, Vec<Spot>)> = vec![
("clone", vec![spot(SpotMode::Clone, &[(0.3, 0.4)], 0.04, 40.0, Some((0.15, 0.05)))]),
("heal", vec![spot(SpotMode::Heal, &[(0.6, 0.5)], 0.05, 60.0, Some((-0.12, 0.1)))]),
("remove (auto source)", vec![spot(SpotMode::Remove, &[(0.5, 0.45)], 0.03, 50.0, None)]),
("remove near the edge (auto)", vec![spot(SpotMode::Remove, &[(0.04, 0.5)], 0.03, 50.0, None)]),
("brushed heal stroke", vec![spot(SpotMode::Heal, &[(0.2, 0.7), (0.3, 0.72), (0.4, 0.69)], 0.02, 30.0, Some((0.0, -0.15)))]),
("feather 0, half opacity", vec![Spot { opacity: 50.0, ..spot(SpotMode::Clone, &[(0.7, 0.3)], 0.04, 0.0, Some((-0.2, 0.0))) }]),
("cut by the edge", vec![spot(SpotMode::Heal, &[(0.99, 0.02)], 0.05, 50.0, Some((-0.2, 0.2)))]),
(
"overlapping, auto after manual",
vec![
spot(SpotMode::Clone, &[(0.45, 0.5)], 0.04, 50.0, Some((0.1, 0.0))),
spot(SpotMode::Remove, &[(0.47, 0.52)], 0.04, 50.0, None),
spot(SpotMode::Heal, &[(0.5, 0.5)], 0.03, 70.0, Some((0.0, 0.12))),
],
),
];
for (name, spots) in sets {
let mut s = DevelopSettings::default();
typical(&mut s);
s.spots = spots;
check(&format!("spots: {name}"), &src, &raw, &s, &RenderRequest::fit(640, 640));
}
}
/// Defringe on the device: purple and green at several amounts and hue ranges, at preview and
/// full size (its filter radius follows the output size).
#[test]
fn defringe_matches() {
if !gpu() {
return;
}
let src = scene(1, 1800, 1200);
let raw = SourceInfo { raw: true, ..Default::default() };
for (purple, green, hue) in [(4.0, 0.0, (30.0, 70.0)), (0.0, 10.0, (20.0, 80.0)), (20.0, 15.0, (0.0, 100.0))] {
let mut s = DevelopSettings::default();
typical(&mut s);
s.color.saturation = 40.0;
s.optics.defringe_purple_amount = purple;
s.optics.defringe_green_amount = green;
s.optics.defringe_purple_hue_lo = hue.0;
s.optics.defringe_purple_hue_hi = hue.1;
s.optics.defringe_green_hue_lo = hue.0;
s.optics.defringe_green_hue_hi = hue.1;
for edge in [640, 1800] {
check(&format!("defringe {purple}/{green} {hue:?} @{edge}"), &src, &raw, &s, &RenderRequest::fit(edge, edge));
}
}
}
/// The histogram counted on the device is exactly the CPU's count of the image the GPU returned,
/// for whole frames (small and over 1 MP, where it samples) and for windows cut back after spots.
#[test]
fn device_histogram_is_exact() {
if !gpu() {
return;
}
let raw = SourceInfo { raw: true, ..Default::default() };
let mut s = DevelopSettings::default();
typical(&mut s);
for (w, h) in [(640, 427), (2400, 1600)] {
let src = scene(0, w, h);
let r = lightcraft_gpu::render(&src, &raw, &s, &RenderRequest::fit(w, h), None).expect("gpu render");
assert_eq!(r.histogram, lightcraft_raster::Histogram::of_srgb8(&r.image), "{w}x{h}");
}
// a window with a spot reading from outside it: the render grows, the histogram is of the cut
let src = scene(0, 3000, 2000);
s.spots = vec![Spot { points: vec![Point::new(0.5, 0.5)], size: 0.02, source_offset: Some(Point::new(0.15, 0.0)), ..Default::default() }];
let req = RenderRequest { window: Some(lightcraft_pipeline::PixelWindow { x: 1200, y: 800, w: 500, h: 400 }), ..RenderRequest::fit(3000, 2000) };
let r = lightcraft_gpu::render(&src, &raw, &s, &req, None).expect("gpu render");
assert_eq!((r.image.width, r.image.height), (500, 400));
assert_eq!(r.histogram, lightcraft_raster::Histogram::of_srgb8(&r.image), "window");
}
+4 -2
View File
@@ -1,9 +1,11 @@
//! The integration tests, one module per file, linked into one test binary.
//! Binaries of their own: `tests/shutdown.rs` and `tests/shutdown_first.rs` close the GPU for the whole
//! process, and `tests/memory.rs` checks the process's device-memory counters, which renders on other test
//! threads would change.
//! process, `tests/memory.rs` checks the process's device-memory counters, which renders on other test
//! threads would change, and `tests/display.rs` and `tests/window_pending.rs` adopt (or wait for) the
//! window's device, once per process.
mod equivalence;
mod fallback;
#[cfg(not(target_arch = "wasm32"))]
mod gpu_probe;
mod thumbs_bench;
+72
View File
@@ -0,0 +1,72 @@
//! Thumbnail throughput, CPU vs GPU: `cargo test --release -p lightcraft-gpu --test it thumbs_bench -- --ignored --nocapture`.
//! Six threads (the app's render workers) each render thumbnails of 512 px sources at 256 px with
//! settings like a typical preset (noise reduction, sharpening, clarity, grading, a gradient mask).
use std::sync::Arc;
use std::time::Instant;
use lightcraft_develop::{DevelopSettings, Mask, MaskComponent, MaskOp, MaskShape};
use lightcraft_geom::Point;
use lightcraft_pipeline::{RenderRequest, SourceInfo};
fn preset_like() -> DevelopSettings {
let mut s = DevelopSettings::default();
s.light.exposure = 0.4;
s.light.contrast = 20.0;
s.light.highlights = -60.0;
s.light.shadows = 50.0;
s.effects.clarity = 15.0;
s.detail.nr_luminance = 16.0;
s.detail.sharpen_amount = 60.0;
s.color.vibrance = 15.0;
s.grading.shadows.hue = 220.0;
s.grading.shadows.sat = 30.0;
s.masks = vec![Mask {
components: vec![MaskComponent {
name: None,
op: MaskOp::Add,
invert: false,
shape: MaskShape::Linear { start: Point::new(0.5, 0.0), end: Point::new(0.5, 0.5) },
}],
adjust: lightcraft_develop::LocalAdjustments { exposure: -0.6, ..Default::default() },
..Default::default()
}];
s
}
#[test]
#[ignore]
fn thumbnail_throughput() {
if !lightcraft_gpu::available() {
eprintln!("skipped: no GPU ({:?})", lightcraft_gpu::unavailable_reason());
return;
}
let lib = lightcraft_scenes::demo_library();
let sources: Vec<Arc<lightcraft_raster::Rgb32f>> = (0..12).map(|i| Arc::new(lib[i % lib.len()].render(512, 341))).collect();
let info = SourceInfo { raw: true, ..Default::default() };
let s = preset_like();
let req = RenderRequest::fit(256, 256);
let per_thread = 40;
for gpu in [false, true, false, true] {
let t = Instant::now();
std::thread::scope(|sc| {
for k in 0..6 {
let (sources, info, s) = (&sources, &info, &s);
sc.spawn(move || {
for i in 0..per_thread {
let src = &sources[(k * per_thread + i) % sources.len()];
let r = if gpu {
lightcraft_gpu::render(src, info, s, &req, None)
} else {
Some(lightcraft_pipeline::render(src, info, s, &req))
};
assert!(r.is_some());
}
});
}
});
let n = 6 * per_thread;
let ms = t.elapsed().as_secs_f64() * 1e3;
eprintln!("{}: {n} thumbnails in {ms:.0} ms ({:.2} ms each)", if gpu { "gpu" } else { "cpu" }, ms / n as f64);
}
}
+25
View File
@@ -0,0 +1,25 @@
//! Review of PR #1065: while the window's device is being adopted (announced with
//! `set_window_device_pending`), neither the settings' warm-up nor a render creates a device of
//! its own, which would leave the window's device unused. One test in its own process: it runs
//! before anything else uses the GPU.
use std::sync::Arc;
use std::time::Duration;
use lightcraft_develop::DevelopSettings;
use lightcraft_pipeline::{RenderRequest, SourceInfo};
#[test]
fn no_device_of_its_own_is_created_while_the_window_device_is_pending() {
lightcraft_gpu::set_window_device_pending(true);
lightcraft_gpu::warm_up();
assert!(!lightcraft_gpu::available());
let src = Arc::new(lightcraft_scenes::demo_library()[0].render(300, 200));
let rendered = lightcraft_gpu::render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(300, 200), None);
assert!(rendered.is_none(), "the render takes the CPU path");
assert!(lightcraft_gpu::wait_idle(Duration::from_secs(60)));
let switched_off = lightcraft_gpu::unavailable_reason().is_some_and(|r| r.starts_with("disabled by LIGHTCRAFT_GPU"));
assert!(switched_off || !lightcraft_gpu::ready(), "no device was created");
// withdrawn (the adoption couldn't start): renders create one as before
lightcraft_gpu::set_window_device_pending(false);
}
+191 -23
View File
@@ -29,6 +29,31 @@ pub fn sharpen_mask_weight(masking: f32, det: f32) -> f32 {
if masking > 0.0 { smooth(masking * 0.25, masking * 0.25 + 0.15, det.abs()) } else { 1.0 }
}
/// Masking weight for the V3 pixel-scale sharpening band, also used by its Alt-drag preview.
#[inline]
pub fn pixel_sharpen_mask_weight(masking: f32, det: f32) -> f32 {
if masking > 0.0 { smooth(masking * 0.1, masking * 0.1 + 0.06, det.abs()) } else { 1.0 }
}
/// Gain of the sharpening detail term (per unit of `Amount / 150`), in stops of luminance per stop of detail.
pub const SHARPEN_GAIN: f32 = 7.0;
/// Soft-clip limit (stops) of the sharpening detail term for Detail `0..=100`: 0.03 stops (large
/// edge detail is flattened so halos stay small) up to 1.5 stops (practically linear).
pub fn sharpen_limit(detail: f64) -> f32 {
let d = (detail / 100.0).clamp(0.0, 1.0) as f32;
0.03 * 50f32.powf(d)
}
/// The sharpening boost (stops) for pixel-scale detail `det` (log luminance minus its blur at the
/// sharpen radius): linear for small detail, soft-clipped at `limit`, and gated by the Masking edge
/// mask (`mask` = Masking / 100) so flat areas and noise can be left alone.
#[inline]
pub fn sharpen_term(det: f32, limit: f32, mask: f32) -> f32 {
let m = pixel_sharpen_mask_weight(mask, det);
SHARPEN_GAIN * m * det / (1.0 + det.abs() / limit)
}
/// Parametric region curve (encoded domain) composed with the master point curve.
fn curve_luts(c: &ToneCurve) -> Option<[Lut1; 3]> {
let parametric = c.highlights != 0.0 || c.lights != 0.0 || c.darks != 0.0 || c.shadows != 0.0;
@@ -155,6 +180,9 @@ pub struct FinishParams {
/// A LUT profile and its amount (0..2), applied to the display-encoded colour.
pub lut: Option<(std::sync::Arc<crate::lut::Lut3d>, f32)>,
pub tone: ToneMap,
/// Process V4's calibrated Contrast and Blacks on the camera-look path, applied after
/// the tone map (`None`: another process or path, or both at 0; see [`crate::light_v3`]).
pub light: Option<crate::light_v3::LightOps>,
pub ops: ColorOps,
/// Calibration: primaries matrix (row-major, linear Rec.2020) and shadows tint (−1..1).
pub calib: Option<[[f32; 3]; 3]>,
@@ -169,7 +197,7 @@ pub struct FinishParams {
pub to_out: [[f32; 3]; 3],
pub out_luma: [f32; 3],
pub out_trc: OutputTrc,
/// Soft proofing (CPU only; the GPU path declines proof renders).
/// Soft proofing (the GPU kernel reads the same parameters).
pub proof: Option<crate::output::ProofParams>,
pub hl: f32,
pub sh: f32,
@@ -178,6 +206,12 @@ pub struct FinishParams {
pub dehaze: f32,
pub sharpen: f32,
pub sharpen_mask: f32,
/// V1/V2 retain their texture-band sharpening; V3 uses the pixel-scale plane.
pub pixel_sharpen: bool,
/// Soft-clip limit (stops) of the sharpening detail term: small damps halos (Detail 0), large keeps all (100).
pub sharpen_limit: f32,
/// Response compensation for a sharpening radius below one output pixel.
pub sharpen_gain: f32,
/// Airlight after and before exposure, exposure gain and EV (see [`crate::Prepared`]).
pub air: f32,
pub air_pre: f32,
@@ -240,6 +274,7 @@ impl FinishParams {
calib: if calibration { crate::colorops::calibration_matrix(&s.calibration) } else { None },
shadow_tint: if calibration { (s.calibration.shadows_tint / 100.0) as f32 } else { 0.0 },
tone: base_tone(s, info, peak),
light: crate::light_v3::LightOps::new(s, info),
lut: crate::lut::get(&s.profile.id).map(|l| (l, (s.profile.amount / 100.0).clamp(0.0, 2.0) as f32)),
ops: ColorOps::new(s),
curves: curve_luts(&s.curve),
@@ -256,6 +291,13 @@ impl FinishParams {
dehaze,
sharpen: (s.detail.sharpen_amount / 150.0) as f32,
sharpen_mask: (s.detail.sharpen_masking / 100.0) as f32,
pixel_sharpen: crate::local::pixel_sharpen(s),
sharpen_limit: sharpen_limit(s.detail.sharpen_detail),
sharpen_gain: crate::local::sharpen_gain(crate::local::sharpen_sigma_raw(
s,
px_per_long,
info.native_long.unwrap_or(0).max(frame.ow.max(frame.oh) as usize).max(1) as f64,
)),
air: air_pre * gain,
air_pre,
gain,
@@ -285,6 +327,8 @@ impl FinishParams {
/// rendering process. This is where a new tone model branches: a retuned default tone curve (issue
/// #146) is a new [`Process`] with its own arm here, and V1's arm stays as it is, so photos edited
/// under V1 keep their look (`docs/process-versions.md`). CPU and GPU both take it from here.
/// From V4 the camera curve keeps V2 Whites; its Contrast and Blacks are the
/// calibrated operators that follow the tone map ([`crate::light_v3`], [`FinishParams::light`]).
/// `peak` is the HDR render's peak relative to SDR white ([`lightcraft_develop::Hdr::peak`]); at 1.0 (SDR)
/// every arm is the SDR tone map. An HDR render keeps the camera's look through the midtones and
/// lifts its highlights past white ([`ToneMap::camera_hdr`]), so it matches the SDR render below them.
@@ -292,14 +336,21 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap {
let l = &s.light;
match s.process.process() {
// V2 changes the Highlights/Shadows base (`local::tone_base`), not the tone map
Process::V1 | Process::V2 => match info.camera_tone.as_ref().filter(|_| info.raw) {
Process::V1 | Process::V2 | Process::V3 => match info.camera_tone.as_ref().filter(|_| info.raw) {
Some(curve) => ToneMap::camera_hdr(curve, l.contrast, l.whites, l.blacks, peak),
None if info.raw => ToneMap::hdr(l.contrast, l.whites, l.blacks, peak),
None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak),
},
// Keep V2 Whites in the camera curve; calibrated Contrast and Blacks follow it.
Process::V4 => match info.camera_tone.as_ref().filter(|_| info.raw) {
Some(curve) => ToneMap::camera_hdr(curve, 0.0, l.whites, 0.0, peak),
None if info.raw => ToneMap::hdr(l.contrast, l.whites, l.blacks, peak),
None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak),
},
}
}
/// Finish the prepared pipeline stages into an 8-bit RGBA image in `space` (or `display`).
pub(crate) fn finish(
p: &Prepared,
s: &DevelopSettings,
@@ -317,11 +368,14 @@ pub(crate) fn finish(
fp.for_display(d, proof);
}
let trc = fp.out_trc;
let data = finish_with(p, &fp, false, |e| match trc {
OutputTrc::Srgb => [enc(e[0]), enc(e[1]), enc(e[2]), 255],
t => {
let x = e.map(|v| enc(t.encode(lightcraft_color::transfer::srgb_to_linear(v.clamp(0.0, 1.0)))));
[x[0], x[1], x[2], 255]
let data = finish_with(p, &fp, false, |x, y, e| {
let d = bayer_dither_offset(x, y);
match trc {
OutputTrc::Srgb => [enc(e[0], d), enc(e[1], d), enc(e[2], d), 255],
t => {
let c = e.map(|v| enc(t.encode(lightcraft_color::transfer::srgb_to_linear(v.clamp(0.0, 1.0))), d));
[c[0], c[1], c[2], 255]
}
}
});
Rgba8 { width: w, height: h, data }
@@ -345,18 +399,18 @@ pub(crate) fn finish_deep(
let trc = fp.out_trc;
let samples = match depth {
OutputDepth::F32Linear => {
let v = finish_with(p, &fp, true, |e| e.map(|v| srgb_to_linear(v.clamp(0.0, 1.0))));
let v = finish_with(p, &fp, true, |_x, _y, e| e.map(|v| srgb_to_linear(v.clamp(0.0, 1.0))));
DeepSamples::F32(v.into_flattened())
}
OutputDepth::F32Hdr => {
// the sRGB curve extended past 1 (it is unbounded), so values up to `peak` survive
let peak = fp.peak;
let v = finish_with(p, &fp, true, |e| e.map(|v| srgb_to_linear(v.max(0.0)).clamp(0.0, peak)));
let v = finish_with(p, &fp, true, |_x, _y, e| e.map(|v| srgb_to_linear(v.max(0.0)).clamp(0.0, peak)));
DeepSamples::F32(v.into_flattened())
}
_ => {
let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16;
let v = finish_with(p, &fp, true, |e| match trc {
let v = finish_with(p, &fp, true, |_x, _y, e| match trc {
OutputTrc::Srgb => e.map(q),
t => e.map(|v| q(t.encode(srgb_to_linear(v.clamp(0.0, 1.0))))),
});
@@ -373,19 +427,21 @@ pub(crate) fn finish_with<T: Copy + Default + Send>(
p: &Prepared,
fp: &FinishParams,
exact: bool,
store: impl Fn([f32; 3]) -> T + Sync + Send,
store: impl Fn(usize, usize, [f32; 3]) -> T + Sync + Send,
) -> Vec<T> {
let (w, h) = (p.img.width, p.img.height);
let p_lut = fp.lut.clone();
let FinishParams { curves, vig, to_out, out_luma, grain, .. } = fp;
let FinishParams { light, curves, vig, to_out, out_luma, grain, .. } = fp;
let terms: Vec<[f32; MASK_TERMS]> = p.masks.iter().map(|m| mask_terms(&m.adjust)).collect();
let out_to_norm = fp.out_to_norm;
let long = fp.ow.max(fp.oh);
let [vx, vy, vw, vh] = fp.view;
let (vx_u, vy_u) = (vx.round() as usize, vy.round() as usize);
// the vignette belongs to the whole output frame, not to the window being drawn
let aspect = vw / vh;
let srgb = srgb_lut();
let preview_light = if exact { None } else { light.as_ref().and_then(|lo| crate::light_v3::PreviewOps::new(lo, &|v| encode_srgb(srgb, v))) };
let peak = fp.peak;
let hdr = peak > 1.0;
let mut out = vec![T::default(); w * h];
@@ -428,6 +484,9 @@ pub(crate) fn finish_with<T: Copy + Default + Send>(
d = d.map(|v| v + (o - v) * t);
}
// --- process V4: calibrated Contrast, Blacks (ProPhoto with the sRGB transfer)
d = apply_light(d, light.as_ref(), preview_light.as_ref(), exact, srgb);
// --- colour
d = fp.ops.apply(d, l_sat, l_hue);
if let Some((dir, amt)) = local.tint {
@@ -549,12 +608,29 @@ pub(crate) fn finish_with<T: Copy + Default + Send>(
}
None => e,
};
*px = store(warn.unwrap_or(e));
*px = store(vx_u + x, vy_u + y, warn.unwrap_or(e));
}
});
out
}
#[inline]
fn apply_light(
color: [f32; 3],
light: Option<&crate::light_v3::LightOps>,
preview: Option<&crate::light_v3::PreviewOps>,
exact: bool,
srgb: &[f32; SRGB_LUT_N + 1],
) -> [f32; 3] {
if let Some(lo) = preview {
lo.apply(color)
} else if let Some(lo) = light {
if exact { lo.apply(color, &linear_to_srgb) } else { lo.apply(color, &|v| encode_srgb(srgb, v)) }
} else {
color
}
}
struct PixelLocalTerms {
values: [f32; MASK_SUMS],
tint: Option<([f32; 3], f32)>,
@@ -662,17 +738,26 @@ fn local_tone_delta(p: &Prepared, fp: &FinishParams, index: usize, base: f32, l1
delta += clarity * 0.85 * detail * (0.35 + 0.65 * midtone);
}
let texture = fp.tex + l_tex;
let sharpen = l_sharp * 0.6 + fp.sharpen;
if (texture != 0.0 || sharpen != 0.0)
if texture != 0.0
&& let Some(blur) = &p.texture_blur
{
let detail = p.log_l.data[index] - blur.data[index];
let tame = 1.0 - 0.6 * smooth(0.4, 1.6, detail.abs());
delta += texture * 1.1 * detail.clamp(-1.0, 1.0) * tame;
if sharpen != 0.0 {
let mask = sharpen_mask_weight(fp.sharpen_mask, detail);
delta += sharpen * 1.3 * detail.clamp(-0.8, 0.8) * mask;
}
let sharpen = l_sharp * 0.6 + fp.sharpen;
if fp.pixel_sharpen {
if sharpen != 0.0
&& let Some(blur) = &p.sharpen_blur
{
delta += sharpen * fp.sharpen_gain * sharpen_term(p.log_l.data[index] - blur.data[index], fp.sharpen_limit, fp.sharpen_mask);
}
} else if sharpen != 0.0
&& let Some(blur) = &p.texture_blur
{
let detail = p.log_l.data[index] - blur.data[index];
let mask = sharpen_mask_weight(fp.sharpen_mask, detail);
delta += sharpen * 1.3 * detail.clamp(-0.8, 0.8) * mask;
}
if l_noise != 0.0
&& let Some(blur) = &p.texture_blur
@@ -685,7 +770,7 @@ fn local_tone_delta(p: &Prepared, fp: &FinishParams, index: usize, base: f32, l1
/// A colour needing more desaturation than this (scale < `GAMUT_WARN`) to fit is out of gamut for
/// the gamut warnings (tolerates rounding at the gamut boundary).
const GAMUT_WARN: f32 = 0.995;
pub const GAMUT_WARN: f32 = 0.995;
/// For the gamut warnings: `r` needed desaturating by `t` to fit, and isn't simply a neutral
/// beyond white or below black (that's clipping, which the clipping warnings show).
@@ -770,17 +855,42 @@ pub fn srgb_lut() -> &'static [f32; SRGB_LUT_N + 1] {
/// Linear → sRGB-encoded (clamped to 0..1) by an interpolated table: within 2e-5 of the exact
/// curve (≪ one 8-bit or 10-bit step), several times faster than `powf`.
#[inline]
fn encode_srgb(lut: &[f32; SRGB_LUT_N + 1], v: f32) -> f32 {
pub(crate) fn encode_srgb(lut: &[f32; SRGB_LUT_N + 1], v: f32) -> f32 {
let f = v.clamp(0.0, 1.0) * SRGB_LUT_N as f32;
let i = (f as usize).min(SRGB_LUT_N - 1);
let t = f - i as f32;
lut[i] + (lut[i + 1] - lut[i]) * t
}
#[rustfmt::skip]
const BAYER_8X8: [u8; 64] = [
0, 32, 8, 40, 2, 34, 10, 42,
48, 16, 56, 24, 50, 18, 58, 26,
12, 44, 4, 36, 14, 46, 6, 38,
60, 28, 52, 20, 62, 30, 54, 22,
3, 35, 11, 43, 1, 33, 9, 41,
51, 19, 59, 27, 49, 17, 57, 25,
15, 47, 7, 39, 13, 45, 5, 37,
63, 31, 55, 23, 61, 29, 53, 21,
];
/// Returns the ordered Bayer 8×8 dither threshold offset in `0..1` for pixel `(x, y)`.
#[inline]
fn enc(v: f32) -> u8 {
// `v` is already sRGB-encoded; round to 8 bits.
(v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
fn bayer_dither_offset(x: usize, y: usize) -> f32 {
let idx = (y & 7) * 8 + (x & 7);
(BAYER_8X8[idx] as f32 + 0.5) / 64.0
}
/// Quantizes display-curve-encoded value `v` (0..1) to 8-bit integer with 8×8 ordered Bayer dithering.
#[inline]
fn enc(v: f32, dither: f32) -> u8 {
let y = v.clamp(0.0, 1.0) * 255.0;
// Guard against floating point rounding error (e.g. sRGB <-> Rec.2020 matrix conversion)
// where numerical white (1.0) evaluates to ~254.95.
if y >= 254.9 {
return 255;
}
(y + dither).clamp(0.0, 255.0) as u8
}
#[cfg(test)]
@@ -822,4 +932,62 @@ mod tests {
assert_eq!(encode_srgb(lut, -1.0), 0.0);
assert!((encode_srgb(lut, 2.0) - 1.0).abs() < 1e-6);
}
/// Verifies 8x8 Bayer dithering preserves endpoints, exact 8-bit quantization steps, and fractional levels.
#[test]
fn bayer_dithering_preserves_extremes_and_dithers_smoothly() {
for y in 0..8 {
for x in 0..8 {
let d = bayer_dither_offset(x, y);
// Zero is strictly 0 across all dither offsets
assert_eq!(enc(0.0, d), 0);
// One is strictly 255 across all dither offsets
assert_eq!(enc(1.0, d), 255);
// Exact 8-bit quantization steps have zero spatial noise
for k in 0..=255 {
assert_eq!(enc(k as f32 / 255.0, d), k);
}
}
}
// Fractional level: 128.5 / 255.0 should dither equally between 128 and 129
let v = 128.5 / 255.0;
let mut sum = 0u32;
let mut count_128 = 0;
let mut count_129 = 0;
for y in 0..8 {
for x in 0..8 {
let val = enc(v, bayer_dither_offset(x, y));
sum += val as u32;
if val == 128 {
count_128 += 1;
} else if val == 129 {
count_129 += 1;
}
}
}
assert_eq!(count_128, 32);
assert_eq!(count_129, 32);
assert_eq!(sum, 32 * 128 + 32 * 129);
// Fractional highlight level: 254.5 / 255.0 should dither equally between 254 and 255
let v = 254.5 / 255.0;
let mut sum_hl = 0u32;
let mut count_254 = 0;
let mut count_255 = 0;
for y in 0..8 {
for x in 0..8 {
let val = enc(v, bayer_dither_offset(x, y));
sum_hl += val as u32;
if val == 254 {
count_254 += 1;
} else if val == 255 {
count_255 += 1;
}
}
}
assert_eq!(count_254, 32);
assert_eq!(count_255, 32);
assert_eq!(sum_hl, 32 * 254 + 32 * 255);
}
}
+35 -4
View File
@@ -31,6 +31,10 @@ pub mod curve;
pub mod dust;
pub mod finish;
pub mod geometry;
pub mod light_v3;
// generated (`light_v3_params.rs`), kept in its own compact layout
#[rustfmt::skip]
pub mod light_v3_params;
pub mod local;
pub mod local_tone;
pub mod lut;
@@ -227,6 +231,8 @@ pub(crate) struct Prepared {
pub base: Arc<Plane>,
pub clarity_blur: Option<Arc<Plane>>,
pub texture_blur: Option<Arc<Plane>>,
/// Log luminance blurred at the sharpen radius (the pixel-scale band sharpening boosts).
pub sharpen_blur: Option<Arc<Plane>>,
pub dark: Option<Arc<Plane>>,
/// Blurred chromaticity (`rgb / Y`) for local Moiré / Noise.
pub chroma_blur: Option<Arc<Rgb32f>>,
@@ -329,7 +335,7 @@ impl StageCache {
}
let pl = &e.planes;
let planes = pl.log_l.iter().chain(pl.base.iter().map(|x| &x.1)).chain(pl.clarity.iter().map(|x| &x.1));
for p in planes.chain(pl.texture.iter().map(|x| &x.1)).chain(pl.dark.iter().map(|x| &x.1)) {
for p in planes.chain(pl.texture.iter().map(|x| &x.1)).chain(pl.sharpen.iter().map(|x| &x.1)).chain(pl.dark.iter().map(|x| &x.1)) {
add(Arc::as_ptr(p) as usize, size(p));
}
}
@@ -389,6 +395,8 @@ pub struct Plan<'a> {
pub px_per_long: f64,
/// Long edge of the source buffer (px).
pub src_long: usize,
/// Long edge of the original photo, shared by sharpening and noise reduction.
pub native_long: usize,
/// Output pixels per pixel of the original photo ([`SourceInfo::native_long`], else the source
/// buffer), at most 1: the scale of noise reduction, whose radii are in the original's pixels.
pub detail_scale: f32,
@@ -478,7 +486,23 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
[d.nr_luminance, d.nr_detail, d.nr_color, d.nr_color_detail, d.nr_color_smoothness].map(f64::to_bits),
detail_scale.to_bits(),
));
Plan { settings, frame, w, h, px_per_long, src_long, detail_scale, geo, lin_key, pre_nr_key, eyes, fixed_air, keep, mattes: info.mattes.clone() }
Plan {
settings,
frame,
w,
h,
px_per_long,
src_long,
native_long,
detail_scale,
geo,
lin_key,
pre_nr_key,
eyes,
fixed_air,
keep,
mattes: info.mattes.clone(),
}
}
/// Whether the scene-linear stage needs work only the CPU does (defringe, spot removal).
@@ -611,7 +635,7 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
Some(p) if req.quality == Quality::Draft && p.pre_nr == plan.pre_nr_key => p.for_other_nr(),
_ => local::Planes { key: lin_key, pre_nr: plan.pre_nr_key, ..Default::default() },
};
let mut prep = local::prepare(lin.clone(), s, frame, px_per_long, req.quality, &mut planes, plan.mattes.as_deref());
let mut prep = local::prepare(lin.clone(), s, frame, px_per_long, plan.native_long as f64, req.quality, &mut planes, plan.mattes.as_deref());
if let Some(a) = plan.fixed_air {
prep.air = a;
}
@@ -689,7 +713,8 @@ pub fn color_range_sample(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings,
/// (the one the render evaluated, or for a hidden mask a fresh evaluation).
fn overlay_alpha(o: Overlay, plan: &Plan<'_>, prep: &Prepared) -> Option<Plane> {
if o.reads_detail() {
return visualize::sharpen_plane(o, &plan.settings, &prep.log_l, prep.texture_blur.as_deref(), plan.px_per_long);
let band = if local::pixel_sharpen(&plan.settings) { &prep.sharpen_blur } else { &prep.texture_blur };
return visualize::sharpen_plane(o, &plan.settings, &prep.log_l, band.as_deref(), plan.px_per_long, plan.native_long as f64);
}
let m = o.mask(&plan.settings)?;
if let Some(e) = prep.masks.iter().find(|e| e.id == m.id) {
@@ -757,12 +782,18 @@ mod tests_geometry;
#[cfg(test)]
mod tests_hdr;
#[cfg(test)]
mod tests_legacy;
#[cfg(test)]
mod tests_light;
#[cfg(test)]
mod tests_local;
#[cfg(test)]
mod tests_mask_geometry;
#[cfg(test)]
mod tests_nr_scale;
#[cfg(test)]
mod tests_sharpen;
#[cfg(test)]
mod tests_tone;
#[cfg(test)]
mod tests_window;
+439
View File
@@ -0,0 +1,439 @@
//! Process V4's Contrast and Blacks on the camera-look path (a raw with its camera's tone
//! curve): pointwise operators fitted to how Lightroom's sliders move a photo's tones, applied
//! after the camera curve with V2 Whites. Method, operator family and the fitted constants' provenance:
//! `docs/light-v3.md`; the constants are in [`crate::light_v3_params`] (generated).
//!
//! Each slider is an operator `F_a` on encoded values `v` (linear ProPhoto RGB, D50, Bradford from
//! the D65 working space, through the sRGB transfer curve), anchored at `F_0` = identity:
//!
//! - `a > 0`: `F_a(v) = v + s(a)·D₊(v)`; `a < 0`: `F_a(v) = max(0, v − s(a)·D₋(v))`, with `D` piecewise
//! linear on 12 fixed knots (`D(1) = 0`, and for Contrast `D(0) = 0`) and the amount law
//! `s(t) = ((1 − e^(−t/τ)) / (1 − e^(−1/τ)))^q`, `t = |a|/100`, one `(τ, q)` per sign;
//! - applied per channel ([`Mode::PerChannel`]), to the encoded ProPhoto luminance with linear RGB
//! scaled by the luminance ratio ([`Mode::Luminance`]), or a blend of the two in linear light
//! ([`Mode::Mix`], one weight per sign).
//!
//! The functions here port `Family.curve`, `Family.apply`, `Family.law` of
//! `fit_pointwise.py` (the fitting tool) exactly; [`Fit::unpack`] is its `Family.unpack`. Each
//! active operator is tabulated once per render ([`LUT_N`] entries over `v` in 0..1, interpolated
//! linearly). High-bit-depth CPU exports and the GPU read these tables ([`LightOps`]); 8-bit CPU
//! renders compose per-channel operations over linear input ([`PreviewOps`]). Luminance operations
//! retain the original evaluation, including any preceding per-channel operation.
use lightcraft_color::{Mat3, PROPHOTO, REC2020};
use lightcraft_develop::{DevelopSettings, Process};
use crate::SourceInfo;
use crate::light_v3_params as fitted;
/// Entries of an operator's table over encoded `v` in 0..=1.
pub const LUT_N: usize = 1024;
/// Linear ProPhoto RGB luminance (the Y row of ProPhoto → XYZ D50), as the fit computes it.
pub const PRO_Y: [f32; 3] = [0.288_040_2, 0.711_874_1, 0.000_085_7];
/// How an operator is applied to a pixel.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
/// To each encoded ProPhoto channel.
PerChannel,
/// To the encoded ProPhoto luminance; linear RGB is scaled by the luminance ratio.
Luminance,
/// `w·PerChannel + (1 − w)·Luminance` in linear light, with a weight per sign.
Mix,
}
impl Mode {
/// The GPU kernel's code (`LIGHT_MODE` in `crates/gpu/src/params.rs`).
pub fn code(self) -> u32 {
match self {
Mode::PerChannel => 0,
Mode::Luminance => 1,
Mode::Mix => 2,
}
}
}
/// One slider's fitted parameters, laid out as `fit_pointwise.py`'s `Family`: 11 values of `D₊` at
/// the knots but the last (`D(1) = 0`), 11 of `D₋`, then `ln τ₊, ln q₊, ln τ₋, ln q₋`, then two mix
/// logits (positive, negative amounts) in [`Mode::Mix`].
#[derive(Clone, Copy, Debug)]
pub struct Fit {
pub mode: Mode,
/// Contrast moves tones both ways around a pivot: its shapes are anchored at black too (`D(0) = 0`).
pub signed: bool,
pub params: &'static [f64],
}
const KNOTS_N: usize = fitted::KNOTS.len();
/// A [`Fit`] unpacked (`Family.unpack`).
#[derive(Clone, Copy, Debug)]
pub struct Unpacked {
pub d_pos: [f64; KNOTS_N],
pub d_neg: [f64; KNOTS_N],
/// `(τ, q)` of the amount law, positive and negative amounts.
pub law_pos: (f64, f64),
pub law_neg: (f64, f64),
/// Mix weights of the per-channel result for positive and negative amounts (1 outside [`Mode::Mix`]).
pub weights: (f64, f64),
}
fn sigmoid(x: f64) -> f64 {
1.0 / (1.0 + (-x).exp())
}
impl Fit {
/// The parameters unpacked; `None` when their number doesn't fit the layout.
pub fn unpack(&self) -> Option<Unpacked> {
let n = KNOTS_N - 1;
let p = self.params;
let mix = self.mode == Mode::Mix;
let len = 2 * n + 4 + if mix { 2 } else { 0 };
if p.len() != len {
return None;
}
// D(1) = 0 is appended (the last knot stays 0)
let shape = |off: usize| -> Option<[f64; KNOTS_N]> {
let mut d = [0.0; KNOTS_N];
for (k, slot) in d.iter_mut().take(n).enumerate() {
*slot = *p.get(off + k)?;
}
Some(d)
};
let (mut d_pos, mut d_neg) = (shape(0)?, shape(n)?);
if self.signed {
d_pos[0] = 0.0;
d_neg[0] = 0.0;
}
let at = |i: usize| p.get(i).copied();
let i = 2 * n;
let law_pos = (at(i)?.exp(), at(i + 1)?.exp());
let law_neg = (at(i + 2)?.exp(), at(i + 3)?.exp());
let weights = if mix { (sigmoid(at(i + 4)?), sigmoid(at(i + 5)?)) } else { (1.0, 1.0) };
Some(Unpacked { d_pos, d_neg, law_pos, law_neg, weights })
}
}
/// The amount law `s(t)` (`Family.law`): 1 at `|a| = 100`, linear as `τ` grows, saturating as it
/// shrinks.
pub fn law((tau, q): (f64, f64), a: f64) -> f64 {
let t = (a.abs() / 100.0).min(1.0);
let tau = tau.clamp(1e-3, 1e3);
((1.0 - (-t / tau).exp()) / (1.0 - (-1.0 / tau).exp())).powf(q)
}
/// `numpy.interp(v, KNOTS, d)`: piecewise linear, constant beyond the ends.
fn interp(v: f64, d: &[f64; KNOTS_N]) -> f64 {
let k = &fitted::KNOTS;
if v <= k[0] {
return d[0];
}
for i in 1..KNOTS_N {
if v <= k[i] {
let t = (v - k[i - 1]) / (k[i] - k[i - 1]);
return d[i - 1] + t * (d[i] - d[i - 1]);
}
}
d[KNOTS_N - 1]
}
impl Unpacked {
/// `F_a(v)` on an encoded value (`Family.curve`).
pub fn curve(&self, a: f64, v: f64) -> f64 {
if a == 0.0 {
return v;
}
if a > 0.0 {
return v + law(self.law_pos, a) * interp(v, &self.d_pos);
}
(v - law(self.law_neg, a) * interp(v, &self.d_neg)).max(0.0)
}
}
/// One slider's operator at one amount, tabulated: `lut[i]` is the *linear* value of
/// `F_a(i / (LUT_N − 1))` (decoded with the sRGB curve), made non-decreasing (see [`Operator::new`]).
#[derive(Clone, Debug)]
pub struct Operator {
pub mode: Mode,
/// Weight of the per-channel result ([`Mode::Mix`]; 1 for per channel, 0 for luminance).
pub weight: f32,
pub lut: Box<[f32; LUT_N]>,
}
impl Operator {
/// `fit` at `amount` (-100..100); `None` at 0 (the identity) or for parameters that do not unpack.
///
/// The table is the running maximum of `F_a`: where a fitted shape folds back (a `D` rising
/// faster than 1), it is flat instead, so no two tones swap. None of the shipped fits folds.
/// The fitting tool inverts `F` the same way.
pub fn new(fit: &Fit, amount: f64) -> Option<Operator> {
let a = if amount.is_finite() { amount.clamp(-100.0, 100.0) } else { 0.0 };
if a == 0.0 {
return None;
}
let u = fit.unpack()?;
let weight = match fit.mode {
Mode::PerChannel => 1.0,
Mode::Luminance => 0.0,
Mode::Mix => (if a > 0.0 { u.weights.0 } else { u.weights.1 }) as f32,
};
let mut lut = Box::new([0.0f32; LUT_N]);
let mut top = 0.0f64;
for (i, slot) in lut.iter_mut().enumerate() {
let v = i as f64 / (LUT_N - 1) as f64;
top = top.max(u.curve(a, v));
*slot = srgb_decode(top) as f32;
}
// The negative Blacks fit rounds to exactly 1 in f32. Avoid calculating a luminance
// result that contributes nothing, on both CPU and GPU.
let mode = if weight == 1.0 {
Mode::PerChannel
} else if weight == 0.0 {
Mode::Luminance
} else {
Mode::Mix
};
Some(Operator { mode, weight, lut })
}
/// The table at encoded `v` (clamped to 0..=1), interpolated: linear output.
#[inline]
pub fn eval(&self, v: f32) -> f32 {
let f = v.clamp(0.0, 1.0) * (LUT_N - 1) as f32;
let i = (f as usize).min(LUT_N - 2);
let t = f - i as f32;
self.lut[i] + (self.lut[i + 1] - self.lut[i]) * t
}
/// One linear value through the operator: values above 1 (HDR renders) pass unchanged, which
/// is continuous because `F_a(1) = 1`; values below 0 (outside ProPhoto's gamut) keep their
/// distance below the image of 0, `F_a(0) + x` (continuous and increasing). This is the
/// per-channel domain: on luminance ([`Self::apply`]) a component above 1 is scaled with its
/// pixel unless the pixel's luminance is above 1.
#[inline]
pub fn channel(&self, x: f32, encode: &impl Fn(f32) -> f32) -> f32 {
if x > 1.0 {
x
} else if x < 0.0 {
self.lut[0] + x
} else {
self.eval(encode(x))
}
}
/// The luminance mode: linear ProPhoto `p` scaled by `F` of its luminance over its luminance
/// (unchanged when the luminance is at most 1e-6, or above 1).
#[inline]
fn luminance(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] {
let y = PRO_Y[0] * p[0] + PRO_Y[1] * p[1] + PRO_Y[2] * p[2];
if y.is_nan() || y <= 1e-6 || y > 1.0 {
return p;
}
let r = self.channel(y, encode) / y;
p.map(|c| c * r)
}
/// The operator on a linear ProPhoto pixel (`Family.apply`). Per channel, each component goes
/// through [`Self::channel`] (one above 1 passes unchanged). On luminance, the pixel is scaled
/// by `F(Y) / Y` as a whole, components above 1 included, and passes unchanged only when `Y`
/// itself is above 1 (or at most 1e-6). Mix blends the two results in linear light, so an HDR
/// component of a pixel with `Y ≤ 1` moves by the luminance part's share.
#[inline]
pub fn apply(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] {
match self.mode {
Mode::PerChannel => p.map(|c| self.channel(c, encode)),
Mode::Luminance => self.luminance(p, encode),
Mode::Mix => {
let (a, b) = (p.map(|c| self.channel(c, encode)), self.luminance(p, encode));
let w = self.weight;
std::array::from_fn(|k| w * a[k] + (1.0 - w) * b[k])
}
}
}
}
/// sRGB decoding in f64 (the tables are built in f64, like the fit).
fn srgb_decode(e: f64) -> f64 {
if e <= 0.04045 { e / 12.92 } else { ((e + 0.055) / 1.055).powf(2.4) }
}
/// Linear Rec.2020 (the working space) → linear ProPhoto RGB (D50, Bradford), and back.
pub fn prophoto_matrices() -> ([[f32; 3]; 3], [[f32; 3]; 3]) {
let to = REC2020.to_space(&PROPHOTO);
let from = to.inverse().unwrap_or(Mat3::IDENTITY);
(to.to_f32(), from.to_f32())
}
/// The active operators of a render, in order (Contrast, Blacks), and the conversions to
/// and from the space they work in. Applied after the tone map, chroma scaling and highlight
/// desaturation, before the colour stage (`finish::finish_with`, the GPU's `finish.wgsl`).
#[derive(Clone, Debug)]
pub struct LightOps {
pub ops: Vec<Operator>,
pub to_pro: [[f32; 3]; 3],
pub from_pro: [[f32; 3]; 3],
}
/// The fits of Contrast and Blacks, in the order they apply.
pub const FITS: [&Fit; 2] = [&fitted::CONTRAST, &fitted::BLACKS];
/// Whether `s` renders `info` with the V4 operators: process V4 and a raw with its camera's tone
/// curve (other sources keep the tone map's own Contrast and Blacks).
pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool {
let camera_look = info.raw && info.camera_tone.is_some();
match s.process.process() {
Process::V1 | Process::V2 | Process::V3 => false,
Process::V4 => camera_look,
}
}
impl LightOps {
/// The operators of `s` for `info` (see [`applies`]); `None` when they don't apply or every
/// slider is at 0.
pub fn new(s: &DevelopSettings, info: &SourceInfo) -> Option<LightOps> {
if !applies(s, info) {
return None;
}
let l = &s.light;
let ops: Vec<Operator> = FITS.iter().zip([l.contrast, l.blacks]).filter_map(|(f, a)| Operator::new(f, a)).collect();
if ops.is_empty() {
return None;
}
let (to_pro, from_pro) = prophoto_matrices();
Some(LightOps { ops, to_pro, from_pro })
}
/// The operators on a linear Rec.2020 pixel; `encode`: linear → sRGB-encoded on 0..1 (the
/// exact curve or the shared table, as the render encodes).
#[inline]
pub fn apply(&self, d: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] {
let mut p = mul3(&self.to_pro, d);
for op in &self.ops {
p = op.apply(p, encode);
}
mul3(&self.from_pro, p)
}
}
/// Number of intervals over linear input for 8-bit CPU renders. Deep exports retain [`LightOps`]
/// with the exact sRGB encoder; this approximation is not used for U16 or F32 samples.
const PREVIEW_INTERVALS: usize = 16_384;
/// An operator with its sRGB encoding and decoding included in one linear-input table.
struct LinearOperator {
black: f32,
white: f32,
// Each linear interval stores [intercept, slope], so a lookup needs no integer-to-float
// conversion or subtraction of neighbouring samples in the pixel loop.
segments: Box<[[f32; 2]; PREVIEW_INTERVALS]>,
}
impl LinearOperator {
fn new(channel: impl Fn(f32) -> f32) -> Self {
let black = channel(0.0);
let mut previous = black;
let mut segments = Box::new([[0.0; 2]; PREVIEW_INTERVALS]);
for (i, segment) in segments.iter_mut().enumerate() {
let next = channel((i + 1) as f32 / PREVIEW_INTERVALS as f32);
let slope = (next - previous) * PREVIEW_INTERVALS as f32;
let intercept = (previous as f64 - slope as f64 * (i as f64 / PREVIEW_INTERVALS as f64)) as f32;
*segment = [intercept, slope];
previous = next;
}
Self { black, white: previous, segments }
}
#[inline(always)]
fn channel(&self, x: f32) -> f32 {
if x >= 1.0 {
if x == 1.0 { self.white } else { x }
} else if x < 0.0 {
self.black + x
} else {
let f = x * PREVIEW_INTERVALS as f32;
let i = (f as u32).min(PREVIEW_INTERVALS as u32 - 1) as usize;
let [intercept, slope] = self.segments[i];
intercept + slope * x
}
}
}
/// CPU preview tables for per-channel operations, built once per render. Luminance operations
/// use [`LightOps`] instead, so interpolation cannot change a nearly cancelling luminance sum.
pub(crate) struct PreviewOps {
ops: PreviewOperators,
to_pro: [[f32; 4]; 3],
from_pro: [[f32; 4]; 3],
}
enum PreviewOperators {
PerChannel(LinearOperator),
Separate(Vec<LinearOperator>),
}
impl PreviewOps {
pub(crate) fn new(exact: &LightOps, encode: &impl Fn(f32) -> f32) -> Option<Self> {
let ops = &exact.ops;
// Small per-channel errors can cross the luminance cutoff at 1e-6, or be amplified
// by F(Y) / Y. Keep every preceding operation exact too, including Contrast.
if ops.iter().any(|o| o.mode != Mode::PerChannel) {
return None;
}
// A preceding black lift could carry a negative input across zero. Only fuse when
// preceding operators fix zero, so the composed negative extension remains F(0) + x.
// Contrast fixes zero and negative Blacks is per channel, so their usual pair fuses.
let fuse = ops.iter().take(ops.len().saturating_sub(1)).all(|o| o.lut[0] == 0.0);
let ops = if fuse {
PreviewOperators::PerChannel(LinearOperator::new(|x| ops.iter().fold(x, |x, o| o.channel(x, encode))))
} else {
PreviewOperators::Separate(ops.iter().map(|o| LinearOperator::new(|x| o.channel(x, encode))).collect())
};
let columns = |m: [[f32; 3]; 3]| std::array::from_fn(|i| [m[0][i], m[1][i], m[2][i], 0.0]);
Some(Self { ops, to_pro: columns(exact.to_pro), from_pro: columns(exact.from_pro) })
}
// Keep the single-table path in the finish loop. An out-of-line call per pixel saves
// little code here but adds register spills to this otherwise small operation.
#[inline(always)]
pub(crate) fn apply(&self, d: [f32; 3]) -> [f32; 3] {
let mut p = mul_preview(&self.to_pro, d);
match &self.ops {
PreviewOperators::PerChannel(op) => p = [op.channel(p[0]), op.channel(p[1]), op.channel(p[2])],
PreviewOperators::Separate(ops) => {
for op in ops {
p = p.map(|c| op.channel(c));
}
}
}
mul_preview(&self.from_pro, p)
}
}
/// Padded columns let the compiler multiply the RGB rows together in vector registers.
/// The fourth lane is unused; each RGB row keeps the same arithmetic order as `mul3`.
#[inline(always)]
fn mul_preview(m: &[[f32; 4]; 3], d: [f32; 3]) -> [f32; 3] {
let out: [f32; 4] = std::array::from_fn(|i| m[0][i] * d[0] + m[1][i] * d[1] + m[2][i] * d[2]);
[out[0], out[1], out[2]]
}
#[inline]
fn mul3(m: &[[f32; 3]; 3], d: [f32; 3]) -> [f32; 3] {
[
m[0][0] * d[0] + m[0][1] * d[1] + m[0][2] * d[2],
m[1][0] * d[0] + m[1][1] * d[1] + m[1][2] * d[2],
m[2][0] * d[0] + m[2][1] * d[1] + m[2][2] * d[2],
]
}
/// `fit_pointwise.py`'s own values for one fit at one amount (generated into
/// [`crate::light_v3_params`]; the tests check the port against them).
#[cfg(test)]
pub struct Reference {
pub amount: f64,
/// `Family.curve` at `light_v3_params::REF_V`.
pub curve: &'static [f64],
/// `Family.apply` on `light_v3_params::REF_PIX` (encoded ProPhoto), where the curve increases.
pub apply: Option<&'static [[f64; 3]]>,
}
+315
View File
@@ -0,0 +1,315 @@
//! Fitted constants of process V4's Contrast and Blacks ([`crate::light_v3`]).
//!
//! GENERATED by `tools/light_v3_constants.py rust` from the committed fits named below: do not edit by hand,
//! regenerate (the script must reproduce this file byte for byte).
//!
//! The values are fitted to black-box Lightroom exports of one person's Sony ILCE-7CR photos (the exports'
//! pixels only: no Lightroom code, tables or files), each slider against the same photo's Neutral or another
//! amount exported in the same batch, on the tune photos; the check photos were held out. The exports are
//! private; errors are published only with at least three contributing photos. These are our operator family's
//! parameters (`docs/light-v3.md`), not Lightroom's.
//!
//! - Contrast: `tools/light_v3_fits/contrast.json` (fitted as `v2-contrast-pc.json`), mode `pc`; 155 tune pairs on 20 photos, 61 check pairs on 6 photos;
//! sha256 `2f04d078f1866ccb05fc279b493ccab545adbe2ac178b12df9ebc524c79c2ce1`.
//! - Blacks: `tools/light_v3_fits/blacks.json` (fitted as `v2-blacks-mix.json`), mode `mix`; 148 tune pairs on 19 photos, 60 check pairs on 6 photos;
//! sha256 `b8ee89df8f632d9559649fcba917607ade1511ecaa2041f481dd5b73a318c090`.
use crate::light_v3::{Fit, Mode};
#[cfg(test)]
use crate::light_v3::Reference;
/// The family's knots: the displacement shapes are piecewise linear on them.
pub const KNOTS: [f64; 12] = [0.0, 0.02, 0.05, 0.09, 0.14, 0.2, 0.28, 0.38, 0.5, 0.65, 0.82, 1.0];
/// `tools/light_v3_fits/contrast.json`.
pub const CONTRAST: Fit = Fit {
mode: Mode::PerChannel,
signed: true,
params: &[
9.797174393178826e-18, -0.017053489024880908, -0.04260284838408044, -0.07195939270312468, -0.09738651081071477,
-0.1088504066519633, -0.10140378035603768, -0.06947815571389163, -0.007856500339789655, 0.08463087858854193, 0.1098534938016389,
0.30583740028604467, -0.05850866310699469, -0.07854274245013221, -0.09074476735486797, -0.0906596002773617, -0.08429179542961336,
-0.07428102082426319, -0.05004459522573259, -0.00906946010144, 0.056653920573147026, 0.09818533983265328, 0.3070552562874873,
0.10657448975892592, -0.13962415708911588, 0.37724097657204825,
],
};
/// `tools/light_v3_fits/blacks.json`.
pub const BLACKS: Fit = Fit {
mode: Mode::Mix,
signed: false,
params: &[
0.0016748697345088984, 0.032126630862752484, 0.07188512588294256, 0.09530584096821723, 0.12925288090794965, 0.12680972925019743,
0.10913227308994669, 0.10024857312175768, 0.0835198499581404, 0.05136152009684992, 0.02045048232256003, 0.00011845423640374467,
0.2706623236742467, 0.42355931120492346, 0.37893058797626605, 0.22045052169596244, 0.20955478047682013, 0.2107908996685734,
0.16685612159796198, 0.13055496600268582, 0.08667135921560576, 0.03499725744978859, 14.344979966519135, 0.1199976090379452,
6.829791928600096, 0.5956122696562978, 0.6007994346537187, 22.053184691621333,
],
};
/// Where the reference values are taken: encoded values and pixels (encoded ProPhoto).
#[cfg(test)]
pub const REF_V: [f64; 16] = [
0.0, 0.004, 0.012, 0.03, 0.07, 0.11, 0.17, 0.25, 0.33, 0.45, 0.58, 0.7, 0.81, 0.9, 0.97, 1.0,
];
#[cfg(test)]
pub const REF_PIX: [[f64; 3]; 6] = [
[0.02, 0.05, 0.01], [0.3, 0.25, 0.2], [0.55, 0.5, 0.62], [0.9, 0.85, 0.7], [0.15, 0.4, 0.35], [0.75, 0.97, 0.99],
];
/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/contrast.json` (12 significant
/// digits).
#[cfg(test)]
pub const CONTRAST_REFERENCE: &[Reference] = &[
Reference {
amount: -100.0,
curve: &[
0.0, 0.0157017326214, 0.0471051978642, 0.0951866895547, 0.154643754903, 0.200710700524, 0.257475697853, 0.328035061301,
0.392162808025, 0.47614243307, 0.554016990408, 0.631130956115, 0.71425768483, 0.845452588982, 0.953635776695, 1.0,
],
apply: Some(&[
[0.078508663107, 0.12854274245, 0.0392543315535], [0.369433735705, 0.328035061301, 0.28429179543],
[0.537161666543, 0.509069460101, 0.576490755562], [0.845452588982, 0.768178883473, 0.631130956115],
[0.239598299469, 0.443215406038, 0.407315522905], [0.668915832804, 0.953635776695, 0.984545258898],
]),
},
Reference {
amount: -63.0,
curve: &[
0.0, 0.0117558826379, 0.0352676479138, 0.0732055944278, 0.126101694535, 0.170122852746, 0.227978700093, 0.301721466955,
0.371201372402, 0.467327147126, 0.562778518405, 0.654353749223, 0.746542204136, 0.86384609598, 0.959153828794, 1.0,
],
apply: Some(&[
[0.0587794131897, 0.102057956904, 0.0293897065949], [0.346020527272, 0.301721466955, 0.255868416571],
[0.541490780829, 0.506011218203, 0.591162168506], [0.86384609598, 0.79576914397, 0.654353749223],
[0.209385555774, 0.428643076049, 0.387988602489], [0.696257592365, 0.959153828794, 0.986384609598],
]),
},
Reference {
amount: -25.0,
curve: &[
0.0, 0.00669797632024, 0.0200939289607, 0.0450295815589, 0.0895156438599, 0.130914451725, 0.19016858264, 0.267991929431,
0.344332389013, 0.456027454879, 0.574009302137, 0.684121407008, 0.787925448518, 0.887423433092, 0.966227029927, 1.0,
],
apply: Some(&[
[0.0334898816012, 0.0681089814742, 0.0167449408006], [0.316008789537, 0.267991929431, 0.219434495337],
[0.547039966578, 0.502091073979, 0.609968416216], [0.887423433092, 0.831135149637, 0.684121407008],
[0.170657974176, 0.409963835778, 0.363214788663], [0.73130506224, 0.966227029927, 0.988742343309],
]),
},
Reference {
amount: -4.0,
curve: &[
0.0, 0.0042211975466, 0.0126635926398, 0.0312322222928, 0.0716000186917, 0.111714702007, 0.171653550835, 0.251475094729,
0.331175061939, 0.450494169731, 0.579508843847, 0.698698170259, 0.808190185513, 0.898968891712, 0.969690667514, 1.0,
],
apply: Some(&[
[0.021105987733, 0.0514846914124, 0.0105529938665], [0.301312504095, 0.251475094729, 0.201593365611],
[0.549757317317, 0.500171439768, 0.619177545887], [0.898968891712, 0.848453337568, 0.698698170259],
[0.151693674318, 0.400816899693, 0.351083433835], [0.748467268102, 0.969690667514, 0.989896889171],
]),
},
Reference {
amount: -1.0,
curve: &[
0.0, 0.00403003956988, 0.0120901187096, 0.0301673410408, 0.0702172893598, 0.110232863843, 0.170224559253, 0.250200324153,
0.330159578421, 0.450067110356, 0.5799332989, 0.699823205971, 0.809754219477, 0.899859971098, 0.96995799133, 1.0,
],
apply: Some(&[
[0.0201501978494, 0.0502016274236, 0.0100750989247], [0.300178243652, 0.250200324153, 0.200216385843],
[0.549967042657, 0.500023282251, 0.619888307225], [0.899859971098, 0.849789956648, 0.699823205971],
[0.150230008193, 0.400110938461, 0.350147134934], [0.749791848474, 0.96995799133, 0.98998599711],
]),
},
Reference {
amount: 1.0,
curve: &[
0.0, 0.00397028327185, 0.0119108498156, 0.0297772142058, 0.0695009210477, 0.109284415638, 0.169101549483, 0.249092158771,
0.329255569926, 0.449707840731, 0.580361320706, 0.700802007104, 0.810944204495, 0.900531739739, 0.970159521922, 1.0,
],
apply: Some(&[
[0.0198514163593, 0.0496288098987, 0.00992570817964], [0.29917212145, 0.249092158771, 0.199051608167],
[0.550200155898, 0.499931547883, 0.620576207118], [0.900531739739, 0.850797609609, 0.700802007104],
[0.149134843694, 0.399484133579, 0.349311202243], [0.750866642282, 0.970159521922, 0.990053173974],
]),
},
Reference {
amount: 4.0,
curve: &[
0.0, 0.00386276829016, 0.0115883048705, 0.0289711762573, 0.067695255762, 0.106695434805, 0.165850959769, 0.245807593504,
0.326562225444, 0.44865080988, 0.581668577311, 0.70370366501, 0.814360331887, 0.902455571598, 0.970736671479, 1.0,
],
apply: Some(&[
[0.0193138414508, 0.0482858458702, 0.0096569207254], [0.296176860778, 0.245807593504, 0.195620331007],
[0.550924318987, 0.499683888448, 0.622660921742], [0.902455571598, 0.853683357397, 0.70370366501],
[0.146004712278, 0.397617731312, 0.34681913522], [0.754002149954, 0.970736671479, 0.99024555716],
]),
},
Reference {
amount: 25.0,
curve: &[
0.0, 0.00303130723309, 0.00909392169928, 0.0227377271685, 0.0537312449465, 0.0866736973109, 0.140712707247, 0.220406592954,
0.305733397543, 0.440476321314, 0.591778172653, 0.726143473036, 0.840778760722, 0.917333416951, 0.975200025085, 1.0,
],
apply: Some(&[
[0.0151565361655, 0.0379001091744, 0.00757826808274], [0.273013181027, 0.220406592954, 0.169084742294],
[0.556524593466, 0.497768628155, 0.638782944901], [0.917333416951, 0.876000125426, 0.726143473036],
[0.121798017215, 0.383184014474, 0.327546875221], [0.778250421984, 0.975200025085, 0.991733341695],
]),
},
Reference {
amount: 63.0,
curve: &[
0.0, 0.00166203669924, 0.00498611009773, 0.0124723297827, 0.0307349682338, 0.0537014072028, 0.0993144142548, 0.178575600043,
0.271431971089, 0.427014372342, 0.608426903093, 0.763097901214, 0.884285279574, 0.941834618872, 0.982550385662, 1.0,
],
apply: Some(&[
[0.00831018349621, 0.0207966223556, 0.00415509174811], [0.234866663076, 0.178575600043, 0.125385281671],
[0.56574726332, 0.494614530364, 0.665333089458], [0.941834618872, 0.912751928309, 0.763097901214],
[0.0819338359776, 0.35941421432, 0.295808843098], [0.818183073196, 0.982550385662, 0.994183461887],
]),
},
Reference {
amount: 100.0,
curve: &[
0.0, 0.000589302195024, 0.00176790658507, 0.00443005785539, 0.0127188794564, 0.0278697600538, 0.0668815412687, 0.145803734783,
0.244559031965, 0.416467809921, 0.621470101755, 0.792049294828, 0.918369810554, 0.961029718779, 0.988308915634, 1.0,
],
apply: Some(&[
[0.00294651097512, 0.00739715161592, 0.00147325548756], [0.204981344572, 0.145803734783, 0.091149593348],
[0.57297262597, 0.49214349966, 0.686133402803], [0.961029718779, 0.941544578168, 0.792049294828],
[0.0507028398824, 0.340792120182, 0.270944156893], [0.849467711067, 0.988308915634, 0.996102971878],
]),
},
];
/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/blacks.json` (12 significant
/// digits).
#[cfg(test)]
pub const BLACKS_REFERENCE: &[Reference] = &[
Reference {
amount: -100.0,
curve: &[
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0396726450283, 0.141176489367, 0.304319552499, 0.472849624284, 0.62852690601,
0.771963089505, 0.880557079195, 0.964167123758, 1.0,
],
apply: Some(&[
[0.0, 0.0, 0.0], [0.0979960559384, 0.0396726450312, 8.67909201708e-12], [0.434072902922, 0.369445033999, 0.524551919414],
[0.880557079192, 0.820835618793, 0.628526906024], [1.62784132506e-11, 0.239194070991, 0.169963444981],
[0.693725171247, 0.964167123755, 0.988055707915],
]),
},
Reference {
amount: -63.0,
curve: &[
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0769799089595, 0.159002658298, 0.248306215942, 0.386971900482, 0.533641791607, 0.669077433807,
0.793543473258, 0.891588093197, 0.967476427959, 1.0,
],
apply: Some(&[
[0.0, 0.0, 0.0], [0.212603750827, 0.159002658299, 0.109336909762], [0.49984457601, 0.443515883354, 0.578704745728],
[0.891588093196, 0.837382139795, 0.669077433813], [0.0554085751144, 0.330427917606, 0.27210785935],
[0.72565290629, 0.967476427958, 0.989158809318],
]),
},
Reference {
amount: -25.0,
curve: &[
0.0, 0.0, 0.0, 0.0039713718625, 0.0375281504298, 0.0844641752827, 0.152600319953, 0.232978681132, 0.314718938796,
0.438210409673, 0.571328561555, 0.694215843567, 0.806921758549, 0.898426528234, 0.96952795847, 1.0,
],
apply: Some(&[
[1.38361828441e-12, 0.0157222994288, 6.91809142207e-13], [0.28365227602, 0.232978681132, 0.183041203846],
[0.540618281274, 0.489434480805, 0.612275601929], [0.898426528233, 0.84763979235, 0.694215843568],
[0.132306397362, 0.386986338539, 0.335430047312], [0.745445804924, 0.96952795847, 0.989842652823],
]),
},
Reference {
amount: -4.0,
curve: &[
0.0, 0.00384203333958, 0.0115267901451, 0.029063081396, 0.0688311531515, 0.109080820198, 0.169373686394, 0.249387305769,
0.329449947556, 0.449575625482, 0.579687865532, 0.699791795259, 0.809889196554, 0.899943361788, 0.969983008536, 1.0,
],
apply: Some(&[
[0.0192115469507, 0.0487661502866, 0.00960560094376], [0.299411552286, 0.249387305769, 0.199389556317],
[0.549662298498, 0.499619686776, 0.61972195491], [0.899943361788, 0.849915042681, 0.699791795259],
[0.149363106446, 0.399531564189, 0.349475544402], [0.749836068575, 0.969983008536, 0.989994336179],
]),
},
Reference {
amount: -1.0,
curve: &[
0.0, 0.00398722513591, 0.0119617312187, 0.0299242307978, 0.0699054746135, 0.109925665346, 0.169949349621, 0.249950451029,
0.32995551691, 0.449965680563, 0.579974757487, 0.69998316235, 0.809991039255, 0.899995419632, 0.96999862589, 1.0,
],
apply: Some(&[
[0.0199362373015, 0.0499002177906, 0.009968104698], [0.29995241186, 0.249950451029, 0.199950633032],
[0.549972689865, 0.499969243828, 0.619977514317], [0.899995419632, 0.849993129448, 0.69998316235],
[0.149948494014, 0.399962117299, 0.349957586943], [0.749986742762, 0.96999862589, 0.989999541963],
]),
},
Reference {
amount: 1.0,
curve: &[
9.31612027339e-06, 0.00404319245864, 0.0121109451354, 0.0302524139772, 0.0704649827756, 0.11060564863, 0.170712147943,
0.250643898657, 0.330582319062, 0.450503332955, 0.580369162543, 0.700235118441, 0.810123865526, 0.900063195347, 0.970018958604,
1.0,
],
apply: Some(&[
[0.0201752429349, 0.0503888012921, 0.0100906298252], [0.300630744288, 0.250626419466, 0.200631616538],
[0.550429399642, 0.500454032729, 0.620394920846], [0.90007223641, 0.850090998192, 0.700176696162],
[0.150565756988, 0.400578185286, 0.350572708933], [0.750135238759, 0.970032675648, 0.990024911688],
]),
},
Reference {
amount: 4.0,
curve: &[
4.44679248931e-05, 0.00420616726172, 0.0125295659354, 0.0312048283459, 0.0722194667453, 0.112890896317, 0.17339924135,
0.253073472246, 0.332779539074, 0.452402520726, 0.581762095353, 0.701122272887, 0.810591237848, 0.900301645519, 0.970090493656,
1.0,
],
apply: Some(&[
[0.0208391227968, 0.0518558616479, 0.0104339209625], [0.303010755867, 0.252990062923, 0.203015330491],
[0.55204964314, 0.502167204295, 0.621885228625], [0.900344802502, 0.850434355079, 0.700843514096],
[0.152703002383, 0.402759872928, 0.352733667786], [0.750645594216, 0.970155972394, 0.990118916658],
]),
},
Reference {
amount: 25.0,
curve: &[
0.000351031037929, 0.00562749010759, 0.0161804082469, 0.0395109485272, 0.0875205323187, 0.132820816064, 0.19683370592,
0.274262075537, 0.351941758888, 0.468965565542, 0.593910029809, 0.708859253437, 0.814667248041, 0.902381198134, 0.97071435944,
1.0,
],
apply: Some(&[
[0.0268094892594, 0.0646518089884, 0.0135180994291], [0.323771669718, 0.273605097162, 0.223833590382],
[0.566181459749, 0.517108276593, 0.63489439536], [0.902722015601, 0.853428836176, 0.7066658074],
[0.171494494367, 0.421790810113, 0.371579649929], [0.755101084946, 0.971231540587, 0.990939254456],
]),
},
Reference {
amount: 63.0,
curve: &[
0.000995014140305, 0.00861319796625, 0.0238495656181, 0.0569592350811, 0.11966278055, 0.174686686427, 0.246061413214,
0.31877200482, 0.392194957135, 0.503758795817, 0.619428639797, 0.725111974413, 0.823229536124, 0.906749619145, 0.972024885744,
1.0,
],
apply: Some(&[
[0.0404539765541, 0.0915381262658, 0.0205483468996], [0.367405560588, 0.316916949778, 0.267702217691],
[0.595875558955, 0.54849590131, 0.662288333975], [0.907716480454, 0.859719346711, 0.718935705489],
[0.211650252506, 0.461789763271, 0.411168543529], [0.764487032294, 0.973492582642, 0.992665468794],
]),
},
Reference {
amount: 100.0,
curve: &[
0.00167486973451, 0.0117652219602, 0.0319459264115, 0.0753794625361, 0.153595483426, 0.218884656944, 0.298031305079,
0.36576131915, 0.434690423106, 0.540490151276, 0.646368740699, 0.742270038399, 0.832268778662, 0.911361379068, 0.97340841372,
1.0,
],
apply: Some(&[
[0.055421940602, 0.119927912612, 0.0288346946948], [0.413495225374, 0.362648809539, 0.314154311953],
[0.627234264731, 0.5816340005, 0.691296631565], [0.912990263469, 0.866360468302, 0.731944464499],
[0.254705410536, 0.504042777472, 0.452962701964], [0.774433618221, 0.975881980047, 0.994492187831],
]),
},
];
+88 -17
View File
@@ -4,7 +4,7 @@
use lightcraft_color::cct::{temp_tint_to_xy, wb_matrix, xy_to_temp_tint};
use lightcraft_color::{REC2020, luminance_2020};
use lightcraft_develop::{DevelopSettings, Process};
use lightcraft_raster::blur::gaussian;
use lightcraft_raster::blur::{gauss_taps, gaussian, gaussian_taps};
use std::sync::Arc;
use lightcraft_raster::{Plane, Rgb32f, par_join};
@@ -371,11 +371,11 @@ pub fn base_detail_radius(px_per_long: f64) -> usize {
}
/// Median radius (px) of the highlights/shadows base of `s`'s rendering process at `px_per_long`:
/// 0 (no median) under V1, [`base_detail_radius`] from V2.
/// 0 (no median) under V1, [`base_detail_radius`] from V2 (later processes keep V2's base).
pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize {
match s.process.process() {
Process::V1 => 0,
Process::V2 => base_detail_radius(px_per_long),
Process::V2 | Process::V3 | Process::V4 => base_detail_radius(px_per_long),
}
}
@@ -521,6 +521,8 @@ pub(crate) struct Planes {
pub base: Option<(BaseKey, Arc<Plane>)>,
pub clarity: Option<(u32, Arc<Plane>)>,
pub texture: Option<(u32, Arc<Plane>)>,
/// Sharpening blur (exact Gaussian at the sharpen radius).
pub sharpen: Option<(SharpenKey, Arc<Plane>)>,
/// Dark channel and its airlight.
pub dark: Option<(u32, Arc<Plane>, f32)>,
/// Blurred chromaticity (local Moiré / Noise).
@@ -532,7 +534,7 @@ impl Planes {
/// enough for a draft: the wide blurs (base, clarity, dehaze, chromaticity). Its `key` matches
/// no image, so only another draft takes them.
pub fn for_other_nr(self) -> Planes {
Planes { key: 0, pre_nr: self.pre_nr, log_l: None, texture: None, ..self }
Planes { key: 0, pre_nr: self.pre_nr, log_l: None, texture: None, sharpen: None, ..self }
}
}
@@ -541,6 +543,16 @@ impl Planes {
/// processes, so a photo moved to another one (Update to Current Process, undo) recomputes it.
pub type BaseKey = (u32, Process, usize);
pub type SharpenKey = (u32, Process);
pub fn sharpen_key(s: &DevelopSettings, sigma: f32) -> SharpenKey {
(sigma.to_bits(), s.process.process())
}
pub fn pixel_sharpen(s: &DevelopSettings) -> bool {
s.process.process() >= Process::V3
}
/// The [`BaseKey`] of a base at `sigma` for `s` (`detail`: [`PlaneSigmas::base_detail`]).
pub fn base_key(s: &DevelopSettings, sigma: f32, detail: usize) -> BaseKey {
(sigma.to_bits(), s.process.process(), detail)
@@ -584,6 +596,8 @@ pub struct PlaneSigmas {
pub clarity: Option<f32>,
/// Texture / sharpening band (Gaussian).
pub texture: Option<f32>,
/// Sharpening blur (exact Gaussian, see [`sharpen_sigma`]).
pub sharpen: Option<f32>,
/// Dehaze dark channel (Gaussian).
pub dark: Option<f32>,
/// Chromaticity blur for local Moiré / colour noise (Gaussian).
@@ -595,7 +609,45 @@ pub fn texture_sigma(px_per_long: f64) -> f32 {
(0.0018 * px_per_long as f32).max(0.6)
}
pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneSigmas {
/// Sharpening blur radius in output pixels before clamping: Radius (source pixels) times the
/// output pixels per original pixel (`native_long` = the original photo's long edge), so a preview and
/// an export show the same detail at the same displayed scale.
pub fn sharpen_sigma_raw(s: &DevelopSettings, px_per_long: f64, native_long: f64) -> f32 {
let r = s.detail.sharpen_radius;
let radius = if r.is_finite() { r.clamp(0.1, 10.0) } else { 1.0 };
(radius * px_per_long / native_long.max(1.0)) as f32
}
/// Smallest and largest sigma (px) of the sharpening blur. The largest is the most the Gaussian taps
/// support (CPU and GPU share them), so an enlarging export keeps every Radius step distinct.
pub const SHARPEN_SIGMA_MIN: f32 = 0.5;
pub const SHARPEN_SIGMA_MAX: f32 = lightcraft_raster::blur::GAUSS_SIGMA_MAX;
/// The sharpening blur's sigma for a raw value of [`sharpen_sigma_raw`].
pub fn sharpen_sigma(raw: f32) -> f32 {
raw.clamp(SHARPEN_SIGMA_MIN, SHARPEN_SIGMA_MAX)
}
/// Match the continuous Gaussian's Nyquist response below half a pixel, using a representable
/// FIR blur. Blend the correction out between half and one pixel: no jump at the floor, and
/// full-pixel sharpening (including Radius 1 at native size) is unchanged.
pub fn sharpen_gain(raw: f32) -> f32 {
if !raw.is_finite() || raw <= 0.0 {
return 0.0;
}
if raw >= 1.0 {
return 1.0;
}
let taps = gauss_taps(sharpen_sigma(raw));
let radius = taps.len() / 2;
let response = taps.iter().enumerate().map(|(i, &t)| if (i + radius).is_multiple_of(2) { t } else { -t }).sum::<f32>();
let desired = -(-0.5 * std::f32::consts::PI.powi(2) * raw * raw).exp_m1();
let ratio = desired / (1.0 - response).max(1e-6);
let blend = ((1.0 - raw) / 0.5).clamp(0.0, 1.0);
1.0 + (ratio - 1.0) * blend
}
pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, native_long: f64, q: Quality) -> PlaneSigmas {
let ppl = px_per_long as f32;
// A hidden mask, or one with no components, does not change the picture. Its sliders must
// not pick the tone base Clarity reads (#1214).
@@ -614,16 +666,19 @@ pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneS
let clarity = (s.effects.clarity != 0.0 || local_any(|a| a.clarity)).then(|| (0.012 * ppl).max(1.0));
// local Noise and Defringe read the fine detail band too
let texture = (s.effects.texture != 0.0
|| s.detail.sharpen_amount != 0.0
|| local_any(|a| a.texture)
|| local_any(|a| a.sharpness)
|| local_any(|a| a.noise)
|| (!pixel_sharpen(s) && (s.detail.sharpen_amount != 0.0 || local_any(|a| a.sharpness)))
|| s.masks.iter().filter(live).any(|m| m.adjust.defringe > 0.0))
.then(|| texture_sigma(px_per_long));
let dark = (s.effects.dehaze != 0.0 || local_any(|a| a.dehaze)).then(|| (0.02 * ppl).max(1.0));
let chroma = (local_any(|a| a.moire) || s.masks.iter().filter(live).any(|m| m.adjust.noise > 0.0)).then(|| (CHROMA_SIGMA * ppl).max(1.0));
let base_detail = if base.is_some() { tone_base_detail(s, px_per_long) } else { 0 };
PlaneSigmas { base, base_detail, clarity, texture, dark, chroma }
// V1/V2 keep their texture-band sharpening; only V3 requests the pixel-scale plane.
let sharpen_raw = sharpen_sigma_raw(s, px_per_long, native_long);
let sharpen = (pixel_sharpen(s) && sharpen_gain(sharpen_raw) > 0.0 && (s.detail.sharpen_amount != 0.0 || local_any(|a| a.sharpness)))
.then(|| sharpen_sigma(sharpen_raw));
PlaneSigmas { base, base_detail, clarity, texture, sharpen, dark, chroma }
}
/// The spatial planes the per-pixel stage needs for `img` (white-balanced, before exposure),
@@ -635,15 +690,23 @@ pub(crate) fn prepare(
s: &DevelopSettings,
frame: &Frame,
px_per_long: f64,
native_long: f64,
q: Quality,
planes: &mut Planes,
mattes: Option<&masks::Mattes>,
) -> Prepared {
let log_l = planes.log_l.get_or_insert_with(|| Arc::new(timed("log_l", || img.map(log_lum)))).clone();
let PlaneSigmas { base: base_sigma, base_detail, clarity: clarity_sigma, texture: texture_sigma, dark: dark_sigma, chroma: chroma_sigma } =
plane_sigmas(s, px_per_long, q);
let PlaneSigmas {
base: base_sigma,
base_detail,
clarity: clarity_sigma,
texture: texture_sigma,
sharpen: sharpen_sigma_px,
dark: dark_sigma,
chroma: chroma_sigma,
} = plane_sigmas(s, px_per_long, native_long, q);
let Planes { base: sb, clarity: sc, texture: st, dark: sd, chroma: sch, .. } = planes;
let Planes { base: sb, clarity: sc, texture: st, sharpen: ss, dark: sd, chroma: sch, .. } = planes;
let chroma_blur = chroma_sigma.map(|sg| match sch {
Some((k, c)) if *k == sg.to_bits() => c.clone(),
_ => {
@@ -653,14 +716,22 @@ pub(crate) fn prepare(
}
});
let l = &log_l;
let (base, (clarity_blur, (texture_blur, dark))) = par_join(
let (base, (clarity_blur, ((texture_blur, sharpen_blur), dark))) = par_join(
|| base_sigma.map(|sg| plane_at(sb, base_key(s, sg, base_detail), || timed("base", || tone_base(l, sg, base_detail)))),
|| {
par_join(
|| clarity_sigma.map(|sg| plane_at(sc, sg.to_bits(), || timed("clarity", || guided_fast(l, sg, CLARITY_EPS)))),
|| {
par_join(
|| texture_sigma.map(|sg| plane_at(st, sg.to_bits(), || timed("texture", || gaussian(l, sg)))),
|| {
par_join(
|| texture_sigma.map(|sg| plane_at(st, sg.to_bits(), || timed("texture", || gaussian(l, sg)))),
|| {
sharpen_sigma_px
.map(|sg| plane_at(ss, sharpen_key(s, sg), || timed("sharpen", || gaussian_taps(l, &gauss_taps(sg)))))
},
)
},
|| {
dark_sigma.map(|sg| match sd {
Some((k, d, air)) if *k == sg.to_bits() => (d.clone(), *air),
@@ -684,7 +755,7 @@ pub(crate) fn prepare(
};
let ev = s.light.exposure as f32;
let masks = timed("masks", || masks::evaluate(&s.masks, frame, img.width, img.height, &img, &log_l, ev, mattes));
Prepared { img, log_l, base, clarity_blur, texture_blur, dark, chroma_blur, air, masks, px_per_long }
Prepared { img, log_l, base, clarity_blur, texture_blur, sharpen_blur, dark, chroma_blur, air, masks, px_per_long }
}
/// The airlight of the whole output frame, estimated on a small render of it (`proxy_w` px wide):
@@ -814,17 +885,17 @@ mod tests {
adjust: lightcraft_develop::LocalAdjustments { highlights: 40.0, ..Default::default() },
..Default::default()
});
assert!(plane_sigmas(&s, 2000.0, Quality::Full).base.is_none());
assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_none());
s.masks[0].visible = true;
s.masks[0].components.clear();
assert!(plane_sigmas(&s, 2000.0, Quality::Full).base.is_none());
assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_none());
s.masks[0].components.push(MaskComponent {
name: None,
op: MaskOp::Add,
invert: false,
shape: MaskShape::Linear { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0) },
});
assert!(plane_sigmas(&s, 2000.0, Quality::Full).base.is_some());
assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_some());
}
#[test]
+2 -2
View File
@@ -1,7 +1,7 @@
//! 3D LUT profiles: `.cube` files (the plain-text Cube LUT format: `LUT_3D_SIZE`, optional
//! `DOMAIN_MIN` / `DOMAIN_MAX`, then size³ "r g b" lines with red changing fastest), applied to
//! the display-encoded output colour and blended by the profile amount. Profiles are registered
//! here by id (`lut:…`) and found by the finishing stage; LUT profiles render on the CPU.
//! here by id (`lut:…`) and found by the finishing stage (CPU loop and GPU kernel alike).
use std::collections::HashMap;
use std::sync::{Arc, OnceLock, RwLock};
@@ -110,7 +110,7 @@ pub fn unregister(id: &str) {
registry().write().unwrap_or_else(|e| e.into_inner()).remove(id);
}
/// Profile ids that render with a LUT (and so on the CPU).
/// Profile ids that render with a LUT.
pub fn is_lut_profile(id: &str) -> bool {
id.starts_with("lut:")
}
+43 -18
View File
@@ -603,35 +603,60 @@ fn hue_weight(h: f32, lo: f32, hi: f32) -> f32 {
/// Long edge (px) at which defringe widths are specified: fringes are 1–7 px wide on a ~4000 px image.
pub const DEFRINGE_REF_LONG: f64 = 4000.0;
/// Defringe: desaturate purple / green colour fringes that sit next to high-contrast edges. `scale` is output
/// pixels per reference pixel (output long edge / [`DEFRINGE_REF_LONG`]) so the fringe width is the same
/// fraction of the image at any size.
pub fn defringe(img: &mut Rgb32f, s: &DevelopSettings, scale: f64) {
/// Defringe's resolved parameters (the CPU stage below and the GPU kernels both read these).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DefringeParams {
/// Radius (output px) of the lightness min / max filters that find edges.
pub radius: usize,
/// Purple and green OkLab hue ranges (degrees, lo ≤ hi) and strengths (0..1).
pub purple: (f32, f32),
pub green: (f32, f32),
pub purple_strength: f32,
pub green_strength: f32,
}
/// Defringe's parameters for `s` at `scale` output pixels per reference pixel, or `None` when it
/// does nothing.
pub fn defringe_params(s: &DevelopSettings, scale: f64) -> Option<DefringeParams> {
let o = &s.optics;
if !s.section_enabled("optics") || (o.defringe_purple_amount <= 0.0 && o.defringe_green_amount <= 0.0) {
return;
return None;
}
let (w, h) = (img.width, img.height);
// as far as the sliders go (0–20): an amount from a damaged catalog or sidecar made the
// radius overflow
let max_amt = o.defringe_purple_amount.max(o.defringe_green_amount).min(20.0);
// fringe width in source px grows with the amount (1..7 px), in output px at least one (and
// never wider than the picture)
let radius = ((1.0 + max_amt * 0.3) * scale).round();
let radius = if radius.is_finite() { radius.clamp(1.0, w.max(h).max(1) as f64) as usize } else { 1 };
// perceptual lightness and its local range (dilated contrast)
let lab: Vec<[f32; 3]> = img.data.iter().map(|p| oklab_from_2020([p[0].max(0.0), p[1].max(0.0), p[2].max(0.0)])).collect();
let l = Plane { width: w, height: h, data: lab.iter().map(|p| p[0]).collect() };
let (lo, hi) = (min_filter(&l, radius, false), min_filter(&l, radius, true));
// fringe width in source px grows with the amount (1..7 px), in output px at least one
let radius = ((1.0 + max_amt * 0.3) * scale).round().max(1.0);
// (an absurd scale must not ask for a filter wider than any image; the stages clamp it to theirs)
let radius = if radius.is_finite() { radius.min(1e6) as usize } else { 1 };
let range = |lo: f64, hi: f64, span: (f32, f32)| {
let a = span.0 + (span.1 - span.0) * (lo / 100.0) as f32;
let b = span.0 + (span.1 - span.0) * (hi / 100.0) as f32;
(a.min(b), a.max(b))
};
let pr = range(o.defringe_purple_hue_lo, o.defringe_purple_hue_hi, PURPLE_HUES);
let gr = range(o.defringe_green_hue_lo, o.defringe_green_hue_hi, GREEN_HUES);
let ps = (o.defringe_purple_amount / 8.0).min(1.0) as f32;
let gs = (o.defringe_green_amount / 8.0).min(1.0) as f32;
Some(DefringeParams {
radius,
purple: range(o.defringe_purple_hue_lo, o.defringe_purple_hue_hi, PURPLE_HUES),
green: range(o.defringe_green_hue_lo, o.defringe_green_hue_hi, GREEN_HUES),
purple_strength: (o.defringe_purple_amount / 8.0).min(1.0) as f32,
green_strength: (o.defringe_green_amount / 8.0).min(1.0) as f32,
})
}
/// Defringe: desaturate purple / green colour fringes that sit next to high-contrast edges. `scale` is output
/// pixels per reference pixel (output long edge / [`DEFRINGE_REF_LONG`]) so the fringe width is the same
/// fraction of the image at any size.
pub fn defringe(img: &mut Rgb32f, s: &DevelopSettings, scale: f64) {
let Some(DefringeParams { radius, purple: pr, green: gr, purple_strength: ps, green_strength: gs }) = defringe_params(s, scale) else {
return;
};
let (w, h) = (img.width, img.height);
// never wider than the picture
let radius = radius.clamp(1, w.max(h).max(1));
// perceptual lightness and its local range (dilated contrast)
let lab: Vec<[f32; 3]> = img.data.iter().map(|p| oklab_from_2020([p[0].max(0.0), p[1].max(0.0), p[2].max(0.0)])).collect();
let l = Plane { width: w, height: h, data: lab.iter().map(|p| p[0]).collect() };
let (lo, hi) = (min_filter(&l, radius, false), min_filter(&l, radius, true));
for_rows(&mut img.data, w, |y, row| {
for (x, px) in row.iter_mut().enumerate() {
let i = y * w + x;
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more