mirror of
https://github.com/storytold/lightcraft.git
synced 2026-12-02 02:46:10 -06:00
Merge main into crystal-grain; the crystal grain moves to process V7
v0.19.0 shipped V4 to V6 with value-noise grain, so those stay frozen and the crystal grain becomes a process of its own. V7 is V6 plus the grain: without grain it renders as V6 (`without_grain_v7_renders_as_v6`), and the GPU equivalence cases now cover V6's value noise. Merged with main's float output (`deep`, `hdr`): the value noise keeps its clamped luminance; the crystal grain already clamps, and fades out at and above SDR white. The finish kernel's failed-render check stays ahead of the aux upload. The test of unknown process numbers now takes one past the latest: 7 was hard-coded, and is a known process now. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,7 +13,7 @@ pub mod settings;
|
||||
|
||||
pub use controls::{CONTROLS, ControlSpec, Section, Track};
|
||||
pub use presets::{Preset, SettingsGroup, apply_partial, extract_groups};
|
||||
pub use segmask::SegMask;
|
||||
pub use segmask::{SegMask, with_grid_interner};
|
||||
pub use settings::*;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
+310
-16
@@ -1,8 +1,12 @@
|
||||
//! Presets and copy/paste subsets.
|
||||
//!
|
||||
//! A preset is a *partial* settings object (JSON) — only the groups it includes. Applying merges it
|
||||
//! into the photo's settings; `amount` (0..200 %) interpolates numeric values between the current
|
||||
//! settings and the preset's. Copy/paste/sync use the same group selection ([`SettingsGroup`]).
|
||||
//! A preset is a *partial* settings object (JSON) — only the settings it names. Applying it changes
|
||||
//! exactly the settings it names (a leaf: a number, a flag, a name; an array is one leaf): each is
|
||||
//! computed from the photo's *original* state (its import settings, when known) and the preset's
|
||||
//! value, and replaces the photo's value; every other setting keeps the photo's value (issue
|
||||
//! #2159). `amount` (0..200 %) moves each named number between the original and the preset's
|
||||
//! value. Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the
|
||||
//! current settings as before.
|
||||
//!
|
||||
//! The rendering process ([`crate::ProcessVersion`]) is in no group: copy, paste, sync and presets
|
||||
//! made from a photo never carry it, so the photos they change keep their own. A partial that names
|
||||
@@ -191,6 +195,74 @@ pub fn apply_partial(s: &DevelopSettings, partial: &Value, amount: f64) -> Devel
|
||||
s.merged(&patch).unwrap_or_else(|_| s.clone())
|
||||
}
|
||||
|
||||
/// Top-level settings keys that hold per-photo pixel repairs: a preset's named repairs compose on
|
||||
/// the photo's own values instead of the original's (masks are added by [`Preset::apply_on`]), and
|
||||
/// a preset without them leaves the photo's alone.
|
||||
const REPAIR_KEYS: [&str; 3] = ["masks", "spots", "red_eye"];
|
||||
|
||||
/// The settings `settings` (a partial JSON object) names, applied to `current` at `amount`: each
|
||||
/// named setting is computed from `original` (the photo's import state) and the preset's value,
|
||||
/// and replaces the photo's value (issue #2159). Every setting the preset does not name keeps the
|
||||
/// photo's current value, edits included. Pixel repairs compose on the photo's own values, as they
|
||||
/// always have.
|
||||
fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings: &Value, amount: f64) -> DevelopSettings {
|
||||
// At 100 % the preset's own values apply as they are, and `original` is not read. The presets
|
||||
// panel calls this for every visible row on every frame, so the scaling base is built below only.
|
||||
if (amount - 1.0).abs() < 1e-9 {
|
||||
return current.merged(settings).unwrap_or_else(|_| current.clone());
|
||||
}
|
||||
let cur = current.to_json();
|
||||
let mut base = original.to_json();
|
||||
if let (Some(b), Some(c)) = (base.as_object_mut(), cur.as_object()) {
|
||||
for k in REPAIR_KEYS {
|
||||
if let Some(v) = c.get(k) {
|
||||
b.insert(k.to_string(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let composed = match settings.as_object() {
|
||||
Some(patch) => Value::Object(interpolate_object(base.as_object(), patch, amount)),
|
||||
None => Value::Object(Map::new()),
|
||||
};
|
||||
// `merged` deep-merges: the named settings replace, everything else stays as `current` has it
|
||||
current.merged(&composed).unwrap_or_else(|_| current.clone())
|
||||
}
|
||||
|
||||
/// The leaves of `patch` that apply at `t` (below 100 %), each computed from the same place in
|
||||
/// `base`. A leaf the amount does not reach is left out, so the photo keeps its own value there.
|
||||
fn interpolate_object(base: Option<&Map<String, Value>>, patch: &Map<String, Value>, t: f64) -> Map<String, Value> {
|
||||
let mut out = Map::new();
|
||||
for (k, pv) in patch {
|
||||
let bv = base.and_then(|b| b.get(k));
|
||||
let v = match pv {
|
||||
Value::Object(p) => Some(Value::Object(interpolate_object(bv.and_then(Value::as_object), p, t))),
|
||||
_ => interpolate_leaf(bv, pv, t),
|
||||
};
|
||||
if let Some(v) = v {
|
||||
out.insert(k.clone(), v);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One leaf at `t`. Numbers move from `base` towards `patch`. Other values switch to the preset's
|
||||
/// at half amount and up, and below it take the base's value. A null in the base is the baseline
|
||||
/// value the import state recorded (a cleared option, such as a free crop aspect): below half
|
||||
/// amount it applies and clears the photo's value, as the amount contract promises. A null the
|
||||
/// preset writes is a value like any other, so it applies at half amount and up (a preset can
|
||||
/// clear an option field such as a crop aspect).
|
||||
fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option<Value> {
|
||||
match (base, patch) {
|
||||
// integer fields (the grain seed, ids) are discrete like strings: see `scale_patch`
|
||||
(Some(Value::Number(b)), Value::Number(p)) if b.is_f64() || p.is_f64() => {
|
||||
let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0));
|
||||
serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number)
|
||||
}
|
||||
_ if t >= 0.5 => Some(patch.clone()),
|
||||
_ => base.cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Preset {
|
||||
pub id: String,
|
||||
@@ -209,30 +281,49 @@ impl Preset {
|
||||
pub fn from_settings(id: &str, name: &str, group: &str, s: &DevelopSettings, groups: &[SettingsGroup]) -> Preset {
|
||||
Preset { id: id.into(), name: name.into(), group: group.into(), settings: extract_groups(s, groups), favorite: false, builtin: false }
|
||||
}
|
||||
/// Apply at `amount` (1.0 = 100 %). Masks in the preset are added to the photo's own (ones it
|
||||
/// already has are skipped), their effect scaled by the amount.
|
||||
/// Apply at `amount` (1.0 = 100 %), with `s` as both the photo's current and its original
|
||||
/// settings (see [`Preset::apply_on`]): right for the import default preset and for scratch
|
||||
/// bases. Masks in the preset are added to the photo's own (ones it already has are skipped),
|
||||
/// their effect scaled by the amount.
|
||||
pub fn apply(&self, s: &DevelopSettings, amount: f64) -> DevelopSettings {
|
||||
self.apply_on(s, s, amount)
|
||||
}
|
||||
/// Apply at `amount` (1.0 = 100 %), composing on `original` (the photo's import state, or the
|
||||
/// photo's current settings when that is not known): each setting the preset names is computed
|
||||
/// from `original` and the preset's value, `amount` moving it between the two, and replaces the
|
||||
/// photo's value. Every setting the preset does not name keeps `current`'s value, and so do
|
||||
/// the photo's pixel repairs (masks, spots, red eye), which the preset patches; masks in the
|
||||
/// preset are added to the photo's own (ones it already has are skipped), their effect scaled
|
||||
/// by the amount. A second preset therefore restores what the first one changed in the
|
||||
/// settings it names (issue #2159), and nothing it leaves out.
|
||||
pub fn apply_on(&self, current: &DevelopSettings, original: &DevelopSettings, amount: f64) -> DevelopSettings {
|
||||
let Some(masks) = self.settings.get("masks").and_then(Value::as_array).filter(|m| !m.is_empty()) else {
|
||||
return apply_partial(s, &self.settings, amount);
|
||||
return compose_named(current, original, &self.settings, amount);
|
||||
};
|
||||
let mut rest = self.settings.clone();
|
||||
if let Some(o) = rest.as_object_mut() {
|
||||
o.remove("masks");
|
||||
}
|
||||
let mut out = apply_partial(s, &rest, amount);
|
||||
for m in masks {
|
||||
let Ok(mut m) = serde_json::from_value::<crate::Mask>(m.clone()) else { continue };
|
||||
if out.masks.iter().any(|q| q.name == m.name && q.components == m.components) {
|
||||
continue;
|
||||
}
|
||||
m.id = out.next_mask_id();
|
||||
m.adjust.amount = (m.adjust.amount * amount).clamp(0.0, 200.0);
|
||||
out.masks.push(m);
|
||||
}
|
||||
let mut out = compose_named(current, original, &rest, amount);
|
||||
add_masks(&mut out, masks, amount);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The preset's masks, added to the photo's own (ones it already has are skipped), their effect
|
||||
/// scaled by the amount.
|
||||
fn add_masks(out: &mut DevelopSettings, masks: &[Value], amount: f64) {
|
||||
for m in masks {
|
||||
let Ok(mut m) = serde_json::from_value::<crate::Mask>(m.clone()) else { continue };
|
||||
if out.masks.iter().any(|q| q.name == m.name && q.components == m.components) {
|
||||
continue;
|
||||
}
|
||||
m.id = out.next_mask_id();
|
||||
m.adjust.amount = (m.adjust.amount * amount).clamp(0.0, 200.0);
|
||||
out.masks.push(m);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -285,6 +376,209 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset changes only the settings it names: a setting in a group it styles but does not
|
||||
/// name keeps the photo's value, and so does a whole group it leaves out.
|
||||
#[test]
|
||||
fn apply_on_changes_only_the_settings_it_names() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.light.exposure = 2.0;
|
||||
current.light.blacks = -30.0;
|
||||
current.effects.clarity = 30.0;
|
||||
let original = DevelopSettings::default();
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"light": {"contrast": 12.0}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = p.apply_on(¤t, &original, 1.0);
|
||||
assert_eq!(out.light.contrast, 12.0);
|
||||
assert_eq!(out.light.exposure, 2.0, "a setting the preset doesn't name keeps the photo's value");
|
||||
assert_eq!(out.light.blacks, -30.0, "a setting in the same group, not named, keeps the photo's value");
|
||||
assert_eq!(out.effects.clarity, 30.0, "a group the preset doesn't name is untouched");
|
||||
}
|
||||
|
||||
/// A partial preset that names one colour of the mixer leaves the other colours, and the
|
||||
/// unnamed settings of the colour it names, as the photo has them.
|
||||
#[test]
|
||||
fn apply_on_keeps_the_mixer_colours_it_does_not_name() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.mixer.red.sat = 20.0;
|
||||
current.mixer.blue.hue = 15.0;
|
||||
current.mixer.blue.sat = 5.0;
|
||||
let original = DevelopSettings::default();
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"mixer": {"blue": {"sat": 15.0, "lum": -25.0}}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = p.apply_on(¤t, &original, 1.0);
|
||||
assert_eq!(out.mixer.red.sat, 20.0, "a colour the preset doesn't name");
|
||||
assert_eq!(out.mixer.blue.hue, 15.0, "a setting of a named colour that the preset doesn't name");
|
||||
assert_eq!((out.mixer.blue.sat, out.mixer.blue.lum), (15.0, -25.0));
|
||||
}
|
||||
|
||||
/// The white balance is not one setting: a preset that names only the temperature keeps the
|
||||
/// photo's tint.
|
||||
#[test]
|
||||
fn apply_on_keeps_the_white_balance_fields_it_does_not_name() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.wb.temp = 6000.0;
|
||||
current.wb.tint = 12.0;
|
||||
let original = DevelopSettings::default();
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"wb": {"temp": 5000.0}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = p.apply_on(¤t, &original, 1.0);
|
||||
assert_eq!((out.wb.temp, out.wb.tint), (5000.0, 12.0));
|
||||
}
|
||||
|
||||
/// A preset's amount 0 changes nothing when the original is the photo's current settings (no
|
||||
/// import state is recorded for the photo), and any other amount moves the named settings
|
||||
/// from where the photo has them.
|
||||
#[test]
|
||||
fn apply_on_without_an_import_state_scales_from_the_current_settings() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.light.exposure = 2.0;
|
||||
current.light.blacks = -30.0;
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"light": {"exposure": 0.45, "contrast": 12.0}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
assert_eq!(p.apply_on(¤t, ¤t, 0.0), current, "amount 0 applies nothing");
|
||||
let half = p.apply_on(¤t, ¤t, 0.5);
|
||||
assert!((half.light.exposure - 1.225).abs() < 1e-9, "{}", half.light.exposure);
|
||||
assert_eq!(half.light.blacks, -30.0);
|
||||
}
|
||||
|
||||
/// An unresolved `crs:Look` reference (its profile object has no id; the importer leaves
|
||||
/// `look` in it) changes nothing: the photo keeps its own profile.
|
||||
#[test]
|
||||
fn an_unresolved_profile_reference_keeps_the_photos_profile() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.profile.id = "lc.vivid".into();
|
||||
current.profile.amount = 60.0;
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"profile": {"look": {"name": "Not imported", "amount": 100.0}}, "light": {"contrast": 12.0}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
for amount in [1.0, 0.5] {
|
||||
let out = p.apply_on(¤t, ¤t, amount);
|
||||
assert_eq!((out.profile.id.as_str(), out.profile.amount), ("lc.vivid", 60.0), "amount {amount}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The amount interpolates between the original and the preset, not between the visible
|
||||
/// values and the preset: a preset at 50 % looks the same however the photo was edited before.
|
||||
#[test]
|
||||
fn apply_on_scales_against_the_original() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.light.exposure = 2.0;
|
||||
let original = DevelopSettings::default();
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"light": {"exposure": 0.45}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = p.apply_on(¤t, &original, 0.5);
|
||||
assert!((out.light.exposure - 0.225).abs() < 1e-9, "{}", out.light.exposure);
|
||||
}
|
||||
|
||||
/// Pixel repairs are the photo's own: a preset's are patched in, and one without them never
|
||||
/// restores the original's.
|
||||
#[test]
|
||||
fn apply_on_patches_pixel_repairs_into_the_current_ones() {
|
||||
let current = DevelopSettings {
|
||||
spots: serde_json::from_value(json!([{"mode": "heal", "points": [[0.5, 0.5]], "size": 0.05, "feather": 50.0, "opacity": 100.0}]))
|
||||
.unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
let original = DevelopSettings::default();
|
||||
let none = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"light": {"contrast": 10.0}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = none.apply_on(¤t, &original, 1.0);
|
||||
assert_eq!(out.spots.len(), 1, "the photo's spot survives a preset without spots");
|
||||
let clearing = Preset {
|
||||
id: "q".into(),
|
||||
name: "Q".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"light": {"contrast": 10.0}, "spots": []}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = clearing.apply_on(¤t, &original, 1.0);
|
||||
assert_eq!(out.spots.len(), 0, "a preset that names spots replaces them, as before");
|
||||
}
|
||||
|
||||
/// A null a preset writes into an option field (here a crop aspect: null is "free") is the
|
||||
/// preset's value, so it clears the photo's aspect from half amount up, as any value of the
|
||||
/// preset does; below half amount the import baseline applies, which here is null as well.
|
||||
#[test]
|
||||
fn a_preset_null_clears_an_option_field_from_half_amount() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.crop.aspect = Some((3, 2));
|
||||
let original = DevelopSettings::default(); // the import state has no aspect
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"crop": {"aspect": null}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
for amount in [1.0, 0.7, 0.5] {
|
||||
assert_eq!(p.apply_on(¤t, &original, amount).crop.aspect, None, "amount {amount}: the preset's null clears the aspect");
|
||||
}
|
||||
assert_eq!(p.apply_on(¤t, &original, 0.3).crop.aspect, None, "below half amount the import baseline (no aspect) applies");
|
||||
}
|
||||
|
||||
/// The import state has no aspect, and that null is the baseline below half amount (the amount
|
||||
/// contract: a named setting moves between the import state and the preset's value); from half
|
||||
/// amount the preset's aspect applies.
|
||||
#[test]
|
||||
fn a_null_in_the_original_is_the_baseline_below_half_amount() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.crop.aspect = Some((3, 2));
|
||||
let original = DevelopSettings::default();
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"crop": {"aspect": [16, 9]}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
assert_eq!(p.apply_on(¤t, &original, 0.4).crop.aspect, None, "40 %: the import baseline (no aspect) applies");
|
||||
assert_eq!(p.apply_on(¤t, &original, 0.6).crop.aspect, Some((16, 9)), "60 %: the preset's aspect applies");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_merge_objects() {
|
||||
let mut a = json!({"x": {"a": 1, "b": 2}, "y": [1]});
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Model segmentations stored with a mask ([`SegMask`]), so rendering never needs the model.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::{Deserialize, Serialize, Serializer};
|
||||
|
||||
/// Logits are stored in steps of 1/`SCALE`, clamped to ±127/`SCALE` (≈ ±15.9: a sigmoid of
|
||||
/// 1 − 1.2e-7, i.e. fully in or out).
|
||||
@@ -13,15 +16,26 @@ pub const MAX_SIDE: usize = 1024;
|
||||
/// normalized `((x + 0.5) / side, (y + 0.5) / side)`), quantized to `i8`, deflated and base64
|
||||
/// encoded. Coverage at a point is the sigmoid of the bilinearly sampled logit, so edges stay
|
||||
/// smooth at any output size.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
pub struct SegMask {
|
||||
pub side: u32,
|
||||
/// The grid's bytes (quantized, deflated, base64), unless this is a reference into the
|
||||
/// snapshot's shared grid table (`grid` is set and `data` is empty).
|
||||
#[serde(default)]
|
||||
pub data: String,
|
||||
/// The part of the image the grid covers, normalized `[x0, y0, x1, y1]` (`None` = all of
|
||||
/// it). A zoomed-in pass over one object covers just its surroundings, at a higher
|
||||
/// resolution than a pass over the whole photo.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub rect: Option<[f64; 4]>,
|
||||
/// Index into the catalog snapshot's shared grid table (`Catalog::grids`) this mask refers
|
||||
/// to instead of carrying its own `data`. A serialization detail of snapshots only: the
|
||||
/// snapshot writer sets it (through the interner, into its own table), `Catalog::repair`
|
||||
/// resolves it when a snapshot is read, and no other serialization writes it. A `grid` that
|
||||
/// arrives from any other document (a command, a preset, XMP, a log record) is read but
|
||||
/// never written back, so it cannot point a snapshot at another mask's grid.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub grid: Option<u32>,
|
||||
}
|
||||
|
||||
impl SegMask {
|
||||
@@ -29,7 +43,7 @@ impl SegMask {
|
||||
pub fn from_logits(side: usize, logits: &[f32]) -> SegMask {
|
||||
let q: Vec<u8> = logits.iter().take(side * side).map(|l| ((l * SCALE).round().clamp(-127.0, 127.0) as i8) as u8).collect();
|
||||
let z = miniz_oxide::deflate::compress_to_vec(&q, 8);
|
||||
SegMask { side: side as u32, data: base64_encode(&z), rect: None }
|
||||
SegMask { side: side as u32, data: base64_encode(&z), rect: None, grid: None }
|
||||
}
|
||||
|
||||
/// From `side × side` logits over the part `rect` of the image.
|
||||
@@ -55,6 +69,63 @@ impl SegMask {
|
||||
}
|
||||
}
|
||||
|
||||
// The grid table a snapshot serialization refers to: each distinct grid's data → its index.
|
||||
thread_local! {
|
||||
static INTERNER: RefCell<Option<HashMap<String, u32>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Serializes masks as references into a shared grid table (`grid` = index, `data` omitted)
|
||||
/// while `f` runs, one thread at a time (snapshot writes). Nested calls are ignored (`None`):
|
||||
/// the outermost writer owns the table.
|
||||
pub fn with_grid_interner<T>(map: HashMap<String, u32>, f: impl FnOnce() -> T) -> Option<T> {
|
||||
INTERNER.with(|i| {
|
||||
if i.borrow().is_some() {
|
||||
return None;
|
||||
}
|
||||
struct Guard;
|
||||
impl Drop for Guard {
|
||||
fn drop(&mut self) {
|
||||
INTERNER.with(|j| *j.borrow_mut() = None);
|
||||
}
|
||||
}
|
||||
*i.borrow_mut() = Some(map);
|
||||
let _guard = Guard;
|
||||
Some(f())
|
||||
})
|
||||
}
|
||||
|
||||
impl Serialize for SegMask {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
use serde::ser::SerializeMap;
|
||||
// While a snapshot is being written with a shared grid table, a mask whose exact bytes
|
||||
// are in the table refers to it by index instead of repeating the blob (issue #2154).
|
||||
if !self.data.is_empty()
|
||||
&& let Some(id) = INTERNER.with(|i| i.borrow().as_ref().and_then(|m| m.get(&self.data).copied()))
|
||||
{
|
||||
let len = if self.rect.is_some() { 3 } else { 2 };
|
||||
let mut map = serializer.serialize_map(Some(len))?;
|
||||
map.serialize_entry("side", &self.side)?;
|
||||
map.serialize_entry("grid", &id)?;
|
||||
if let Some(rect) = self.rect {
|
||||
map.serialize_entry("rect", &rect)?;
|
||||
}
|
||||
return map.end();
|
||||
}
|
||||
// Without a table hit: exactly the pre-v10 derived form (field order and skips included),
|
||||
// so every serialization that doesn't dedup keeps its bytes (`hash64`, cache keys). `grid`
|
||||
// is never written here: a value read from some document is dropped on save, and only the
|
||||
// interner above can write a reference (into the table of the snapshot being written).
|
||||
let len = 2 + usize::from(self.rect.is_some());
|
||||
let mut map = serializer.serialize_map(Some(len))?;
|
||||
map.serialize_entry("side", &self.side)?;
|
||||
map.serialize_entry("data", &self.data)?;
|
||||
if let Some(rect) = self.rect {
|
||||
map.serialize_entry("rect", &rect)?;
|
||||
}
|
||||
map.end()
|
||||
}
|
||||
}
|
||||
|
||||
/// Most zoomed-in detail patches one AI mask component keeps (the app makes one; each costs a
|
||||
/// decode per render, so a hostile document can't make rendering explode).
|
||||
pub const MAX_DETAIL: usize = 4;
|
||||
@@ -189,7 +260,51 @@ mod tests {
|
||||
assert!(m.logits().is_none(), "size mismatch");
|
||||
m.side = 100_000;
|
||||
assert!(m.logits().is_none(), "absurd size");
|
||||
assert!(SegMask { side: 8, data: "not base64 !".into(), rect: None }.logits().is_none());
|
||||
assert!(SegMask { side: 8, data: "not base64 !".into(), rect: None, grid: None }.logits().is_none());
|
||||
assert!(SegMask { rect: Some([0.5, 0.0, 0.2, 1.0]), ..SegMask::from_logits(2, &[0.0; 4]) }.bounds().is_none());
|
||||
}
|
||||
|
||||
/// A `grid` read from a document is never written outside the snapshot interner, with or
|
||||
/// without data: the bytes stay the pre-v10 form, so `hash64` and cache keys don't depend on
|
||||
/// a stray value (issue #2154).
|
||||
#[test]
|
||||
fn stray_grid_is_never_written_outside_the_interner() {
|
||||
let empty = SegMask { side: 4, data: String::new(), rect: None, grid: None };
|
||||
let stray = SegMask { grid: Some(3), ..empty.clone() };
|
||||
assert_eq!(serde_json::to_string(&stray).unwrap(), "{\"side\":4,\"data\":\"\"}");
|
||||
assert_eq!(serde_json::to_string(&stray).unwrap(), serde_json::to_string(&empty).unwrap());
|
||||
let with_data = SegMask { grid: Some(3), ..SegMask::from_logits(4, &[1.0; 16]) };
|
||||
assert!(!serde_json::to_string(&with_data).unwrap().contains("grid"), "no grid key outside the interner");
|
||||
}
|
||||
|
||||
/// Without the snapshot interner the JSON is exactly the derived form it always was; with
|
||||
/// it, a pooled grid serializes as an index and the data is left to the table (issue #2154).
|
||||
#[test]
|
||||
fn serialization_refs_only_under_the_interner() {
|
||||
let m = SegMask::from_logits(4, &[1.0; 16]);
|
||||
let plain = serde_json::to_string(&m).unwrap();
|
||||
assert_eq!(plain, format!("{{\"side\":4,\"data\":\"{}\"}}", m.data), "no interner: unchanged bytes");
|
||||
let with_rect = SegMask { rect: Some([0.0, 0.0, 0.5, 0.5]), ..m.clone() };
|
||||
assert_eq!(serde_json::to_string(&with_rect).unwrap(), format!("{{\"side\":4,\"data\":\"{}\",\"rect\":[0.0,0.0,0.5,0.5]}}", m.data));
|
||||
|
||||
let mut table = std::collections::HashMap::new();
|
||||
table.insert(m.data.clone(), 3u32);
|
||||
let referenced = with_grid_interner(table, || serde_json::to_string(&m).unwrap()).unwrap();
|
||||
assert_eq!(referenced, "{\"side\":4,\"grid\":3}", "pooled grid: an index, no data");
|
||||
// a grid the table doesn't hold, and an empty-data mask, stay inline
|
||||
let other = SegMask::from_logits(2, &[0.0; 4]);
|
||||
let mixed = with_grid_interner(std::collections::HashMap::new(), || serde_json::to_string(&other).unwrap()).unwrap();
|
||||
assert_eq!(mixed, format!("{{\"side\":2,\"data\":\"{}\"}}", other.data));
|
||||
// the interner is gone afterwards: serialization is inline again
|
||||
assert_eq!(serde_json::to_string(&m).unwrap(), plain);
|
||||
// nested calls are ignored: the outer writer keeps its table
|
||||
let outer_table = std::collections::HashMap::from([(m.data.clone(), 0u32)]);
|
||||
let nested = with_grid_interner(outer_table, || {
|
||||
let inner_table = std::collections::HashMap::from([(other.data.clone(), 1u32)]);
|
||||
(with_grid_interner(inner_table, || serde_json::to_string(&other).unwrap()), serde_json::to_string(&m).unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(nested.0, None, "the nested writer is refused");
|
||||
assert_eq!(nested.1, "{\"side\":4,\"grid\":0}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,16 +88,23 @@ pub enum Process {
|
||||
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`). Film grain comes from a stack of
|
||||
/// crystal layers (after Aurélien Pierre's model): resolution independent, fading out at black
|
||||
/// and white; V1 to V3 keep their value noise.
|
||||
/// (`lightcraft_pipeline::light_v3`, `docs/light-v3.md`).
|
||||
V4,
|
||||
/// V4, with a raw's tone curve rolling off into white in stops past its last fitted knot, so
|
||||
/// highlights the sensor recorded keep their detail when Exposure lifts them (issue #1632).
|
||||
V5,
|
||||
/// V5, with colour noise reduction on the linear colour differences R−Y and B−Y, leaving Y alone, with
|
||||
/// edge-aware weights from a denoised guide and a brake for isolated colour specks (issue #815).
|
||||
V6,
|
||||
/// V6, with film grain from a stack of crystal layers (after Aurélien Pierre's model): resolution
|
||||
/// independent, fading out at black and white; V1 to V6 keep their value noise.
|
||||
V7,
|
||||
}
|
||||
|
||||
impl Process {
|
||||
/// Every process, oldest first.
|
||||
pub const ALL: [Process; 4] = [Process::V1, Process::V2, Process::V3, Process::V4];
|
||||
pub const LATEST: Process = Process::V4;
|
||||
pub const ALL: [Process; 7] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7];
|
||||
pub const LATEST: Process = Process::V7;
|
||||
|
||||
pub const fn version(self) -> ProcessVersion {
|
||||
match self {
|
||||
@@ -105,6 +112,9 @@ impl Process {
|
||||
Process::V2 => ProcessVersion(2),
|
||||
Process::V3 => ProcessVersion(3),
|
||||
Process::V4 => ProcessVersion(4),
|
||||
Process::V5 => ProcessVersion(5),
|
||||
Process::V6 => ProcessVersion(6),
|
||||
Process::V7 => ProcessVersion(7),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1125,6 +1135,72 @@ impl Default for Mask {
|
||||
}
|
||||
}
|
||||
|
||||
impl DevelopSettings {
|
||||
/// Calls `f` for every segmentation grid stored in these settings (the `seg` and `detail`
|
||||
/// of Object and Prompt mask shapes).
|
||||
pub fn visit_seg_masks(&self, f: &mut impl FnMut(&crate::SegMask)) {
|
||||
for mask in &self.masks {
|
||||
for component in &mask.components {
|
||||
visit_shape(&component.shape, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`DevelopSettings::visit_seg_masks`] with mutable access (resolving references into a
|
||||
/// snapshot's grid table).
|
||||
pub fn visit_seg_masks_mut(&mut self, f: &mut impl FnMut(&mut crate::SegMask)) {
|
||||
for mask in &mut self.masks {
|
||||
for component in &mut mask.components {
|
||||
visit_shape_mut(&mut component.shape, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_shape(shape: &MaskShape, f: &mut impl FnMut(&crate::SegMask)) {
|
||||
match shape {
|
||||
MaskShape::Object { seg, detail, .. } => {
|
||||
if let Some(seg) = seg {
|
||||
f(seg);
|
||||
}
|
||||
for d in detail {
|
||||
f(d);
|
||||
}
|
||||
}
|
||||
MaskShape::Prompt { seg, detail, .. } => {
|
||||
if let Some(seg) = seg {
|
||||
f(seg);
|
||||
}
|
||||
for d in detail {
|
||||
f(d);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_shape_mut(shape: &mut MaskShape, f: &mut impl FnMut(&mut crate::SegMask)) {
|
||||
match shape {
|
||||
MaskShape::Object { seg, detail, .. } => {
|
||||
if let Some(seg) = seg.as_mut() {
|
||||
f(seg);
|
||||
}
|
||||
for d in detail {
|
||||
f(d);
|
||||
}
|
||||
}
|
||||
MaskShape::Prompt { seg, detail, .. } => {
|
||||
if let Some(seg) = seg.as_mut() {
|
||||
f(seg);
|
||||
}
|
||||
for d in detail {
|
||||
f(d);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Heal / remove / red eye
|
||||
|
||||
|
||||
@@ -89,13 +89,14 @@ fn v1_is_left_out_when_saving_and_other_processes_are_kept() {
|
||||
#[test]
|
||||
fn unknown_process_numbers_load_and_render_with_the_newest_known() {
|
||||
// written by a newer LightCraft: kept as it is, rendered with the latest process this build has
|
||||
let s = DevelopSettings::from_json(&json!({"process": 7, "light": {"exposure": 0.5}})).unwrap();
|
||||
assert_eq!(s.process, ProcessVersion(7));
|
||||
let newer = Process::LATEST.version().0 + 1;
|
||||
let s = DevelopSettings::from_json(&json!({"process": newer, "light": {"exposure": 0.5}})).unwrap();
|
||||
assert_eq!(s.process, ProcessVersion(newer));
|
||||
assert_eq!(s.process.process(), Process::LATEST);
|
||||
assert!(!s.process.is_known());
|
||||
assert!(!s.process.is_outdated(), "never downgraded by Update to Current Process");
|
||||
assert_eq!(s.to_json()["process"], json!(7));
|
||||
assert_eq!(s.merged(&json!({"light": {"exposure": 1.0}})).unwrap().process, ProcessVersion(7));
|
||||
assert_eq!(s.to_json()["process"], json!(newer));
|
||||
assert_eq!(s.merged(&json!({"light": {"exposure": 1.0}})).unwrap().process, ProcessVersion(newer));
|
||||
// below V1 (no LightCraft writes it): rendered as V1, and updatable
|
||||
let zero = DevelopSettings::from_json(&json!({"process": 0})).unwrap().process;
|
||||
assert_eq!((zero.process(), zero.is_known(), zero.is_outdated()), (Process::V1, false, true));
|
||||
|
||||
Reference in New Issue
Block a user