From 39e0b73f80c80f216cdcaad3a044a9f6069d7d45 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Thu, 5 Nov 2026 07:25:18 +0100 Subject: [PATCH 01/14] LR-EDIT-OPTICS-PROFILE: add Nikon lens measurement probes Add NikonNEFInfo inspection, patch-matching geometry measurements, radial brightness model comparisons, and synthetic checks for the measurements. Rendering changes remain gated on checkpoint A review. Co-authored-by: Codex --- crates/engine/examples/nikon_lens_probe.rs | 95 ++++ docs/raw/nikon_lens_probe.py | 558 +++++++++++++++++++++ docs/raw/test_nikon_lens_probe.py | 100 ++++ 3 files changed, 753 insertions(+) create mode 100644 crates/engine/examples/nikon_lens_probe.rs create mode 100644 docs/raw/nikon_lens_probe.py create mode 100644 docs/raw/test_nikon_lens_probe.py diff --git a/crates/engine/examples/nikon_lens_probe.rs b/crates/engine/examples/nikon_lens_probe.rs new file mode 100644 index 00000000000..80ecaa8790b --- /dev/null +++ b/crates/engine/examples/nikon_lens_probe.rs @@ -0,0 +1,95 @@ +//! Measurement only: dump an uncorrected quarter-size camera-RGB proxy and render the current source. +//! +//! `cargo run --release -p lightcraft-engine --example nikon_lens_probe -- IN OUT_DIR [OPCODES.json]` +//! Optional JSON is an array of experimental `OpcodeList3` lens opcodes. It replaces the lens description +//! after source loading, without changing the decoder, saved settings, or camera-look fit. Candidate renders +//! therefore isolate optics; they do not predict a future camera-look refit. See docs/raw/nikon_lens_probe.py. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::io::Write; +use std::path::Path; + +use lightcraft_develop::DevelopSettings; +use lightcraft_engine::files; +use lightcraft_pipeline::{RenderRequest, SourceInfo}; +use lightcraft_raster::Rgb32f; + +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args_os().skip(1).collect(); + let input = args.first().ok_or("usage: nikon_lens_probe IN OUT_DIR [OPCODES.json]")?; + let dir = Path::new(args.get(1).ok_or("missing OUT_DIR")?); + std::fs::create_dir_all(dir)?; + let bytes = std::fs::read(input)?; + let mut raw = lightcraft_raw::decode(&bytes)?; + let mut header = raw.info(); + std::fs::write(dir.join("raw.json"), serde_json::to_vec_pretty(&header)?)?; + raw.opcodes.list3.clear(); + let proxy = raw.develop_binned(4, 1.0)?.ok_or("cannot bin this raw")?; + let mut out = std::io::BufWriter::new(std::fs::File::create(dir.join("camera-rgb.f32"))?); + out.write_all(&u32::try_from(proxy.width)?.to_le_bytes())?; + out.write_all(&u32::try_from(proxy.height)?.to_le_bytes())?; + for pixel in &proxy.data { + for value in pixel { + out.write_all(&value.to_le_bytes())?; + } + } + out.flush()?; + drop(raw); + let (source, mut info) = files::load_bytes(&bytes, 1200)?; + let mut settings = DevelopSettings::default(); + settings.wb.temp = info.as_shot_temp; + settings.wb.tint = info.as_shot_tint; + settings.optics.lens_profile = info.lens.is_some(); + render(&source, &info, &settings, &dir.join("baseline.png"))?; + if let Some(path) = args.get(2) { + let data = std::fs::read(path)?; + if data.len() > 64 * 1024 { + return Err("candidate opcodes exceed 64 KiB".into()); + } + header.opcodes.list3 = serde_json::from_slice(&data)?; + validate_candidates(&header.opcodes.list3)?; + info.lens = files::embedded_lens(&header); + settings.optics.lens_profile = info.lens.is_some(); + render(&source, &info, &settings, &dir.join("candidate.png"))?; + } + Ok(()) +} + +/// Diagnostic inputs have a deliberately small range; reject arbitrary operations and invalid gains. +fn validate_candidates(ops: &[lightcraft_raw::Opcode]) -> Result<(), &'static str> { + use lightcraft_raw::Opcode; + if ops.is_empty() || ops.len() > 2 { + return Err("provide one or two lens opcodes"); + } + for op in ops { + let center = match op { + Opcode::WarpRectilinear { planes, center } if planes.len() == 1 && planes.iter().flatten().all(|v| v.is_finite() && v.abs() <= 16.0) => { + center + } + Opcode::FixVignetteRadial { k, center } if k.iter().all(|v| v.is_finite() && v.abs() <= 16.0) => { + for i in 0..=256 { + let r2 = (f64::from(i) / 256.0).powi(2); + let gain = 1.0 + r2 * (k[0] + r2 * (k[1] + r2 * (k[2] + r2 * (k[3] + r2 * k[4])))); + if !gain.is_finite() || !(0.01..=16.0).contains(&gain) { + return Err("candidate vignette gain is outside 0.01 to 16"); + } + } + center + } + _ => return Err("candidate must be a bounded single-plane warp or radial vignette"), + }; + if !center.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)) { + return Err("candidate center must be inside the active area"); + } + } + Ok(()) +} + +/// Use the same CPU renderer and PNG encoder as the app, with no catalog or filesystem hooks. +fn render(source: &Rgb32f, info: &SourceInfo, settings: &DevelopSettings, path: &Path) -> Result<(), Box> { + let rendered = lightcraft_pipeline::render(source, info, settings, &RenderRequest::fit(1200, 1200)); + let image = lightcraft_codecs::encode::EncodeImage::rgba8(&rendered.image); + std::fs::write(path, lightcraft_codecs::encode::encode_png(&image, &Default::default())?)?; + Ok(()) +} diff --git a/docs/raw/nikon_lens_probe.py b/docs/raw/nikon_lens_probe.py new file mode 100644 index 00000000000..1ff3bd3bc16 --- /dev/null +++ b/docs/raw/nikon_lens_probe.py @@ -0,0 +1,558 @@ +#!/usr/bin/env python3 +"""Measure Nikon optics without changing LightCraft's decoder or saved edits. + +Requires Python with numpy, scipy and Pillow, plus exiftool. Build the companion: + CARGO_TARGET_DIR=target/agent-nikon-lens cargo build --release -p lightcraft-engine \ + --example nikon_lens_probe +Run on SHA-256-verified, local CC0 corpus files: + python3 docs/raw/nikon_lens_probe.py --binary target/agent-nikon-lens/release/examples/nikon_lens_probe \ + --out corpus/nikon-lens corpus/raw/coverage-3584.nef + +Outputs contain camera images and must remain outside version control. Never point +this at private originals when sharing the output folder. TIFF fields are read +here directly. Only tag identities/offsets come from ExifTool's tag-name docs; +no external decoder implementation is used. Models are hypotheses, not production +corrections. The default render uses the existing camera look; replacing optics +after source loading deliberately does not refit that look. +""" +import argparse +import hashlib +import json +import math +from pathlib import Path +import struct +import subprocess +import sys + +import numpy as np +from PIL import Image +from scipy import ndimage, optimize, signal + + +def tiff_entries(data, offset, order): + """Read one bounded classic-TIFF IFD, without following arbitrary pointers.""" + if offset < 0 or offset + 2 > len(data): + raise ValueError("invalid IFD offset") + count = struct.unpack_from(order + "H", data, offset)[0] + if count > 4096 or offset + 2 + count * 12 > len(data): + raise ValueError("invalid IFD length") + sizes = {1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8} + result = {} + for i in range(count): + at = offset + 2 + i * 12 + tag, kind, n, value = struct.unpack_from(order + "HHII", data, at) + if kind not in sizes: + raise ValueError("unsupported TIFF entry type") + length = sizes[kind] * n + start = at + 8 if length <= 4 else value + if length > 16 * 1024 * 1024 or start + length > len(data): + raise ValueError("invalid TIFF entry range") + result[tag] = data[start : start + length] + return result + + +def nef_blocks(path): + """Read NikonNEFInfo through the raw SubIFD, not a decoder's interpretation.""" + data = path.read_bytes() + order = "<" if data[:2] == b"II" else ">" + root = tiff_entries(data, struct.unpack_from(order + "I", data, 4)[0], order) + offsets = root.get(330, b"") + if len(offsets) % 4 or len(offsets) > 128: + raise ValueError("invalid SubIFD offsets") + for at in struct.unpack(order + "I" * (len(offsets) // 4), offsets): + blob = tiff_entries(data, at, order).get(0xC7D5) + if blob is not None: + if not blob.startswith(b"Nikon\0"): + raise ValueError("unrecognized NikonNEFInfo") + inner = blob[10:] + order = "<" if inner[:2] == b"II" else ">" + entries = tiff_entries( + inner, struct.unpack_from(order + "I", inner, 4)[0], order + ) + + def rat(block, at): + n, d = struct.unpack_from(order + "ii", block, at) + if d <= 0: + raise ValueError("invalid signed rational") + return n / d + + distortion, vignette, center = (entries[k] for k in (5, 6, 8)) + return dict( + distortion_version=distortion[:4].decode("ascii"), + distortion_mode=distortion[4], + distortion_radius=rat(distortion, 8), + distortion_k=[rat(distortion, at) for at in (20, 28, 36)], + zoom=rat(distortion, 64), + center=[rat(center, at) for at in (4, 12)], + vignette_version=vignette[:4].decode("ascii"), + vignette_mode=vignette[4], + vignette_radius=rat(vignette, 8), + vignette_terms=struct.unpack_from(order + "I", vignette, 16)[0], + vignette_polynomial=[rat(vignette, at) for at in range(20, 92, 8)], + vignette_tail=rat(vignette, 96), + blocks={str(k): entries[k].hex() for k in (5, 6, 8)}, + ) + raise ValueError("NikonNEFInfo absent") + + +def proxy(folder): + """Read the companion example's little-endian camera RGB float dump.""" + data = (folder / "camera-rgb.f32").read_bytes() + w, h = struct.unpack_from(" 16_000_000 or len(data) != 8 + w * h * 12: + raise ValueError("invalid proxy dimensions or length") + return np.frombuffer(data, " 216 / 24389, 116 * np.cbrt(y) - 16, y * 24389 / 27) + + +def score(render, reference): + """Pearson and signed render-minus-reference dL, all pixels and outer ring.""" + # The old sweep's alignment script is absent from this checkout. Here both frames have + # the camera's aspect ratio, normal orientation, and are resized directly. + size = (200, round(reference.height * 200 / reference.width)) + a = lstar(render.convert("RGB").resize(size, Image.Resampling.LANCZOS)) + b = lstar(reference.convert("RGB").resize(size, Image.Resampling.LANCZOS)) + y, x = np.mgrid[: a.shape[0], : a.shape[1]] + rho = ( + np.hypot((x + 0.5 - a.shape[1] / 2), (y + 0.5 - a.shape[0] / 2)) + / math.hypot(*a.shape) + * 2 + ) + ring = rho >= 0.75 + if np.std(a) < 1e-8 or np.std(b) < 1e-8: + raise ValueError("cannot correlate a constant image") + delta = a - b + return dict( + r=float(np.corrcoef(a.ravel(), b.ravel())[0, 1]), + mean_dl=float(delta.mean()), + outer_mean_dl=float(delta[ring].mean()), + outer_mae_dl=float(np.abs(delta[ring]).mean()), + outer_pixels=int(ring.sum()), + ) + + +def patches(camera, jpeg, raw, meta): + """NCC patch matches with subpixel peaks; no fitted geometry parameters.""" + h, w = camera.shape[:2] + reference = np.asarray(jpeg.resize((w, h), Image.Resampling.LANCZOS), float)[..., 1] + source = np.log(np.maximum(camera[..., 1], 1e-6)) + reference = np.log(np.maximum(reference, 1)) + sx, sy, _ = coordinates(raw, meta, camera.shape) + records = [] + radius, search = 9, 12 + for y in np.linspace(24, h - 25, 19).astype(int): + for x in np.linspace(24, w - 25, 27).astype(int): + px, py = (sx[y, x] + 0.5) / 4 - 0.5, (sy[y, x] + 0.5) / 4 - 0.5 + ix, iy = round(px), round(py) + if ( + ix - search - radius < 0 + or iy - search - radius < 0 + or ix + search + radius >= w + or iy + search + radius >= h + ): + continue + template = reference[ + y - radius : y + radius + 1, x - radius : x + radius + 1 + ] + template = template - template.mean() + if np.std(template) < 0.025: + continue + region = source[ + iy - search - radius : iy + search + radius + 1, + ix - search - radius : ix + search + radius + 1, + ] + n = template.size + ones = np.ones(template.shape) + sums = signal.correlate2d(region, ones, mode="valid") + squares = signal.correlate2d(region**2, ones, mode="valid") + cc = signal.correlate2d(region, template, mode="valid") / np.sqrt( + np.maximum((squares - sums**2 / n) * np.sum(template**2), 1e-20) + ) + by, bx = np.unravel_index(np.argmax(cc), cc.shape) + peak = cc[by, bx] + cc_other = cc.copy() + cc_other[max(0, by - 3) : by + 4, max(0, bx - 3) : bx + 4] = -1 + if ( + peak < 0.9 + or peak - cc_other.max() < 0.02 + or bx in (0, 2 * search) + or by in (0, 2 * search) + ): + continue + + def sub(a, b, c): + denominator = a - 2 * b + c + return ( + float(np.clip(0.5 * (a - c) / denominator, -0.5, 0.5)) + if denominator < -1e-8 + else 0 + ) + + dx = sub(cc[by, bx - 1], peak, cc[by, bx + 1]) + dy = sub(cc[by - 1, bx], peak, cc[by + 1, bx]) + mx, my = ix + bx - search + dx, iy + by - search + dy + records.append([x, y, px, py, mx, my, float(peak)]) + points = np.asarray(records) + if len(points) < 12: + raise ValueError("too few reliable patch matches") + errors = np.hypot(points[:, 4] - points[:, 2], points[:, 5] - points[:, 3]) * 4 + before = np.hypot(points[:, 4] - points[:, 0], points[:, 5] - points[:, 1]) * 4 + return dict( + matches=len(points), + before_median_px=float(np.median(before)), + before_p95_px=float(np.quantile(before, 0.95)), + after_median_px=float(np.median(errors)), + after_p95_px=float(np.quantile(errors, 0.95)), + points=points.tolist(), + **geometry_details(points, raw, meta), + ) + + +def geometry_details(points, raw, meta): + """Radial residuals, reversed-order control, and an independently fitted zoom.""" + cw, ch = raw["crop"]["width"] - 1, raw["crop"]["height"] - 1 + cx, cy = cw / 2 + meta["center"][0], ch / 2 + meta["center"][1] + dx = (points[:, 0] + 0.5) * 4 - 0.5 - cx + dy = (points[:, 1] + 0.5) * 4 - 0.5 - cy + mx = (points[:, 4] + 0.5) * 4 - 0.5 - cx + my = (points[:, 5] + 0.5) * 4 - 0.5 - cy + length = np.hypot(dx, dy) + rho = length / (math.hypot(cw, ch) / 2) + measured = (mx * dx + my * dy) / np.maximum(length, 1e-9) + k1, k2, k3 = meta["distortion_k"] + x = rho**2 + unscaled = length * (1 + x * (k3 + x * (k2 + x * k1))) + predicted = unscaled / (1 + meta["zoom"]) + reversed_order = length * (1 + x * (k1 + x * (k2 + x * k3))) / (1 + meta["zoom"]) + use = (rho > 0.15) & (rho < 0.95) + zoom = ( + 1 + / (np.dot(unscaled[use], measured[use]) / np.dot(unscaled[use], unscaled[use])) + - 1 + ) + radial = np.abs(measured[use] - predicted[use]) + return dict( + before_radial_median_px=float(np.median(np.abs(measured[use] - length[use]))), + before_radial_p95_px=float( + np.quantile(np.abs(measured[use] - length[use]), 0.95) + ), + radial_median_px=float(np.median(radial)), + radial_p95_px=float(np.quantile(radial, 0.95)), + reversed_order_radial_median_px=float( + np.median(np.abs(measured[use] - reversed_order[use])) + ), + stored_zoom=meta["zoom"], + fitted_zoom=float(zoom), + radius_min=float(rho.min()), + radius_max=float(rho.max()), + ) + + +def vignette_fit(camera, jpeg, raw, meta): + """Compare gain hypotheses with a nuisance tone curve and spatial holdout. + + A spline absorbs global Picture Control contrast. Colour ratios absorb the + first-order camera-to-JPEG colour transform. No radial term enters that fit. + Alternate 24-pixel tiles are withheld. The fitted gain strength is diagnostic + only, never a per-file production adjustment. Scene/radius confounding remains + possible, especially on the Auto Picture Control samples. + """ + w = 480 + h = round(jpeg.height * w / jpeg.width) + sx, sy, r2 = coordinates(raw, meta, (h, w)) + sensor = sample(camera, sx, sy) + rgb = np.asarray(jpeg.resize((w, h), Image.Resampling.LANCZOS), float) / 255 + target = np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4) + yy, xx = np.mgrid[:h, :w] + mask = ( + (rgb.min(axis=-1) > 0.04) + & (rgb.max(axis=-1) < 0.95) + & (sensor.min(axis=-1) > 0.0002) + & (sensor.max(axis=-1) < 0.9) + & (r2 < 0.95**2) + ) + # Smooth edges can compare different subjects when geometry is imperfect. + grad = np.hypot( + ndimage.sobel(np.log(np.maximum(target[..., 1], 1e-5)), 0), + ndimage.sobel(np.log(np.maximum(target[..., 1], 1e-5)), 1), + ) + mask &= grad < 1.0 + train = ((xx // 24 + yy // 24) % 2 == 0)[mask] + radius = np.sqrt(r2[mask]) + green = np.log(sensor[..., 1][mask]) + response = np.log(target[..., 1][mask]) + colours = np.log( + np.maximum(sensor[..., [0, 2]][mask], 1e-8) / sensor[..., 1][mask, None] + ) + red, blue = colours.T + poly = meta["vignette_polynomial"] + x = r2[mask] + complete = np.polyval(poly, np.sqrt(x)) + named = 1 + x * (poly[6] + x * (poly[4] + x * poly[2])) + if len(green) < 500 or not np.all(complete > 0): + raise ValueError("not enough valid brightness pairs or nonpositive gain") + + def fit(gain): + corrected = green + np.log(np.maximum(gain, 1e-5)) + knots = np.linspace(-11, 1, 17) + design = np.stack( + [np.ones_like(green), corrected] + + [np.maximum(corrected - k, 0) for k in knots[1:-1]] + + [red, blue, red * blue, red**2, blue**2], + axis=-1, + ) + coef = np.linalg.lstsq(design[train], response[train], rcond=1e-8)[0] + residual = response - design @ coef + test = ~train + ring = test & (radius >= 0.75) + inner = test & (radius <= 0.35) + return dict( + training_log_rmse=float(np.sqrt(np.mean(residual[train] ** 2))), + heldout_log_rmse=float(np.sqrt(np.mean(residual[test] ** 2))), + outer_log_bias=float(np.mean(residual[ring])), + inner_log_bias=float(np.mean(residual[inner])), + outer_minus_inner=float(np.mean(residual[ring]) - np.mean(residual[inner])), + ) + + candidates = { + "none": np.ones_like(x), + "complete": complete, + "named_three": named, + "reciprocal": 1 / complete, + "sqrt": np.sqrt(complete), + "squared": complete**2, + "tail_strength": 1 + meta["vignette_tail"] * (complete - 1), + "stops": 2 ** (complete - 1), + } + result = {name: fit(gain) for name, gain in candidates.items()} + fitted = optimize.minimize_scalar( + lambda a: fit(1 + a * (complete - 1))["training_log_rmse"], + bounds=(0, 2), + method="bounded", + options={"xatol": 0.01}, + ) + result["fitted_strength"] = dict( + alpha=float(fitted.x), **fit(1 + fitted.x * (complete - 1)) + ) + result["samples"] = len(green) + result["outer_samples"] = int(np.sum((~train) & (radius >= 0.75))) + result["gains_at_rho"] = { + str(r): float(np.polyval(poly, r)) for r in (0.25, 0.5, 0.75, 1) + } + return result + + +def opcodes(raw, meta, vignette=False, strength=1.0): + """Convert candidate models to the existing active-area OpcodeList3 convention.""" + crop, active = raw["crop"], raw["active_area"] + cw, ch = crop["width"] - 1, crop["height"] - 1 + ax, ay = active["width"] - 1, active["height"] - 1 + cx, cy = ( + crop["x"] + cw / 2 + meta["center"][0], + crop["y"] + ch / 2 + meta["center"][1], + ) + half = math.hypot(cw, ch) / 2 + a = math.hypot(max(cx, ax - cx), max(cy, ay - cy)) / half + k1, k2, k3 = meta["distortion_k"] + s = 1 / (1 + meta["zoom"]) + result = [ + { + "WarpRectilinear": dict( + planes=[[s, k3 * a * a * s, k2 * a**4 * s, k1 * a**6 * s, 0, 0]], + center=[cx / ax, cy / ay], + ) + } + ] + if vignette: + poly = meta["vignette_polynomial"] + result.insert( + 0, + { + "FixVignetteRadial": dict( + k=[ + strength * poly[6] * a * a, + strength * poly[4] * a**4, + strength * poly[2] * a**6, + strength * poly[0] * a**8, + 0, + ], + center=[cx / ax, cy / ay], + ) + }, + ) + return result + + +def prepare(path, folder, binary): + """Write diagnostics beside verified public inputs, without touching originals.""" + folder.mkdir(parents=True, exist_ok=True) + previous = folder / "metadata.json" + digest = hashlib.sha256(path.read_bytes()).hexdigest() + if previous.exists() and json.loads(previous.read_text()).get("sha256") != digest: + raise ValueError("output folder belongs to another input; use a fresh folder") + subprocess.run([str(binary), str(path), str(folder)], check=True) + tags = [ + "Model", + "LensModel", + "FocalLength", + "FNumber", + "DateTimeOriginal", + "ShutterCount", + "VignetteControl", + "PictureControlName", + "ActiveD-Lighting", + "AutoDistortionControl", + "ColorSpace", + ] + exif = json.loads( + subprocess.check_output( + ["exiftool", "-j", "-n"] + ["-" + t for t in tags] + [str(path)] + ) + )[0] + exif.pop("SourceFile", None) + if exif.get("ColorSpace") != 1: + raise ValueError("this probe currently requires an sRGB camera JPEG") + meta = nef_blocks(path) + meta.update(exif=exif, sha256=hashlib.sha256(path.read_bytes()).hexdigest()) + (folder / "metadata.json").write_text(json.dumps(meta, indent=2) + "\n") + if not (folder / "camera.jpg").exists(): + data = subprocess.check_output(["exiftool", "-b", "-JpgFromRaw", str(path)]) + if not data: + raise ValueError("full-size embedded camera JPEG absent") + (folder / "camera.jpg").write_bytes(data) + raw = json.loads((folder / "raw.json").read_text()) + crop = raw["crop"] + if crop["width"] % 4 or crop["height"] % 4: + raise ValueError("this probe requires crop dimensions divisible by four") + if raw["orientation"] != "Normal": + raise ValueError("this probe currently requires normal EXIF orientation") + with Image.open(folder / "camera.jpg") as jpeg: + if jpeg.size != (crop["width"], crop["height"]): + raise ValueError("camera JPEG does not cover the full default crop") + for name, vig, strength in [ + ("distortion", False, 1), + ("vignette", True, 1), + ("vignette-tail", True, meta["vignette_tail"]), + ]: + ops = folder / (name + ".json") + ops.write_text(json.dumps(opcodes(raw, meta, vig, strength), indent=2) + "\n") + return raw, meta + + +def main(): + """Prepare data and report baseline and geometry, leaving production untouched.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument( + "--render-candidates", + action="store_true", + help="render the stored polynomial hypotheses after source loading", + ) + parser.add_argument("files", type=Path, nargs="+") + args = parser.parse_args() + for path in args.files: + folder = args.out / path.stem + manifest = Path(__file__).with_name("coverage-sweep.tsv") + for line in manifest.read_text().splitlines(): + cols = line.split("\t") + if ( + len(cols) == 14 + and cols[3] == path.name + and hashlib.sha256(path.read_bytes()).hexdigest() != cols[5] + ): + raise ValueError("input differs from pinned coverage-sweep SHA-256") + raw, meta = prepare(path, folder, args.binary) + camera = proxy(folder) + jpeg = Image.open(folder / "camera.jpg").convert("RGB") + result = dict( + sha256=meta["sha256"], + exif=meta["exif"], + baseline=score(Image.open(folder / "baseline.png"), jpeg), + distortion=patches(camera, jpeg, raw, meta), + vignette=vignette_fit(camera, jpeg, raw, meta), + ) + if args.render_candidates: + scores = {} + for name in ("distortion", "vignette", "vignette-tail"): + subprocess.run( + [ + str(args.binary), + str(path), + str(folder), + str(folder / (name + ".json")), + ], + check=True, + ) + (folder / "candidate.png").replace(folder / (name + ".png")) + scores[name] = score(Image.open(folder / (name + ".png")), jpeg) + result["experimental_renders_no_look_refit"] = scores + (folder / "measurements.json").write_text(json.dumps(result, indent=2) + "\n") + print( + path.name, + json.dumps( + dict( + baseline=result["baseline"], + fitted_strength=result["vignette"]["fitted_strength"], + ) + ), + flush=True, + ) + print( + "distortion", + json.dumps( + {k: v for k, v in result["distortion"].items() if k != "points"} + ), + flush=True, + ) + + +if __name__ == "__main__": + try: + main() + except ( + ValueError, + OSError, + KeyError, + struct.error, + subprocess.CalledProcessError, + ) as error: + print(f"nikon_lens_probe: {error}", file=sys.stderr) + sys.exit(1) diff --git a/docs/raw/test_nikon_lens_probe.py b/docs/raw/test_nikon_lens_probe.py new file mode 100644 index 00000000000..7fa2a48ff6b --- /dev/null +++ b/docs/raw/test_nikon_lens_probe.py @@ -0,0 +1,100 @@ +"""Synthetic checks for the Nikon measurement tool, with no media fixtures. + +Run: python3 -m unittest discover -s docs/raw -p 'test_nikon_lens_probe.py' +""" + +import struct +import unittest + +import numpy as np +from PIL import Image + +import nikon_lens_probe as probe + + +class Measurements(unittest.TestCase): + def test_lab_score_sign_and_outer_ring(self): + """An identical ramp has zero error; a darker render has negative dL.""" + ramp = np.tile(np.arange(32, 232, dtype=np.uint8), (133, 1)) + reference = Image.fromarray(np.repeat(ramp[..., None], 3, axis=-1)) + score = probe.score(reference, reference) + self.assertAlmostEqual(score["r"], 1) + self.assertEqual(score["mean_dl"], 0) + self.assertEqual(score["outer_mae_dl"], 0) + self.assertEqual(score["outer_pixels"], 5040) + darker = Image.fromarray(np.repeat((ramp - 10)[..., None], 3, axis=-1)) + self.assertLess(probe.score(darker, reference)["mean_dl"], 0) + with self.assertRaisesRegex(ValueError, "constant image"): + probe.score(Image.new("RGB", (200, 133)), reference) + + def test_ifd_ranges_are_bounded(self): + """A truncated directory or out-of-file entry fails before unpacking it.""" + for data, offset in [(b"", 0), (b"\0\0", -1), (b"\1\0", 0)]: + with self.assertRaises(ValueError): + probe.tiff_entries(data, offset, "<") + directory = struct.pack(" Date: Thu, 5 Nov 2026 07:55:30 +0100 Subject: [PATCH 02/14] LR-EDIT-OPTICS-PROFILE: bound and validate Nikon measurement inputs Reject truncated Nikon blocks, incomplete spatial splits and radial bins, and non-finite fit statistics. Write strict JSON and bound opcode reads to 65,537 bytes. Add synthetic regressions for the review findings. Co-authored-by: Codex --- crates/engine/examples/nikon_lens_probe.rs | 33 ++++++++-- docs/raw/nikon_lens_probe.py | 54 ++++++++++++--- docs/raw/test_nikon_lens_probe.py | 76 ++++++++++++++++++++++ 3 files changed, 148 insertions(+), 15 deletions(-) diff --git a/crates/engine/examples/nikon_lens_probe.rs b/crates/engine/examples/nikon_lens_probe.rs index 80ecaa8790b..eb31a5909b2 100644 --- a/crates/engine/examples/nikon_lens_probe.rs +++ b/crates/engine/examples/nikon_lens_probe.rs @@ -7,7 +7,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use std::io::Write; +use std::io::{Read, Write}; use std::path::Path; use lightcraft_develop::DevelopSettings; @@ -43,10 +43,7 @@ fn main() -> Result<(), Box> { settings.optics.lens_profile = info.lens.is_some(); render(&source, &info, &settings, &dir.join("baseline.png"))?; if let Some(path) = args.get(2) { - let data = std::fs::read(path)?; - if data.len() > 64 * 1024 { - return Err("candidate opcodes exceed 64 KiB".into()); - } + let data = read_candidates(std::fs::File::open(path)?)?; header.opcodes.list3 = serde_json::from_slice(&data)?; validate_candidates(&header.opcodes.list3)?; info.lens = files::embedded_lens(&header); @@ -56,6 +53,16 @@ fn main() -> Result<(), Box> { Ok(()) } +/// Read one byte beyond the limit to distinguish a complete input from an oversized one. +fn read_candidates(reader: impl Read) -> std::io::Result> { + let mut data = Vec::new(); + reader.take(65_537).read_to_end(&mut data)?; + if data.len() > 65_536 { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "candidate opcodes exceed 64 KiB")); + } + Ok(data) +} + /// Diagnostic inputs have a deliberately small range; reject arbitrary operations and invalid gains. fn validate_candidates(ops: &[lightcraft_raw::Opcode]) -> Result<(), &'static str> { use lightcraft_raw::Opcode; @@ -93,3 +100,19 @@ fn render(source: &Rgb32f, info: &SourceInfo, settings: &DevelopSettings, path: std::fs::write(path, lightcraft_codecs::encode::encode_png(&image, &Default::default())?)?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A hostile stream must be rejected after at most limit + 1 bytes, without reading to EOF. + #[test] + fn candidate_reader_bounds_the_read_and_accepts_the_exact_limit() { + let mut endless = std::io::repeat(b' '); + let mut counted = (&mut endless).take(1_000_000); + let error = read_candidates(&mut counted).unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::InvalidData); + assert_eq!(counted.limit(), 1_000_000 - 65_537); + assert_eq!(read_candidates(std::io::repeat(b' ').take(65_536)).unwrap().len(), 65_536); + } +} diff --git a/docs/raw/nikon_lens_probe.py b/docs/raw/nikon_lens_probe.py index 1ff3bd3bc16..2181ba7b6d4 100644 --- a/docs/raw/nikon_lens_probe.py +++ b/docs/raw/nikon_lens_probe.py @@ -29,6 +29,25 @@ from scipy import ndimage, optimize, signal +def json_text(value, **kwargs): + """Reject non-finite output instead of writing nonstandard JSON NaN/Infinity.""" + return json.dumps(value, allow_nan=False, **kwargs) + + +def validate_fit_samples(train, radius): + """Require both tile parities and radial coverage before fitting or averaging. + + At least 250 pairs in each split, and 32 in each inner/middle/outer bin + of each split, keep empty or tiny regions from masquerading as evidence. + """ + for name, split in (("training", train), ("validation", ~train)): + if np.count_nonzero(split) < 250: + raise ValueError(f"not enough {name} brightness pairs") + for lo, hi in ((0, 0.35), (0.35, 0.75), (0.75, 0.95)): + if np.count_nonzero(split & (radius >= lo) & (radius < hi)) < 32: + raise ValueError(f"not enough {name} pairs in radial bin {lo} to {hi}") + + def tiff_entries(data, offset, order): """Read one bounded classic-TIFF IFD, without following arbitrary pointers.""" if offset < 0 or offset + 2 > len(data): @@ -77,6 +96,13 @@ def rat(block, at): return n / d distortion, vignette, center = (entries[k] for k in (5, 6, 8)) + for name, block, minimum in ( + ("DistortionInfo", distortion, 72), + ("VignetteInfo", vignette, 104), + ("optical center", center, 20), + ): + if len(block) < minimum: + raise ValueError(f"truncated {name} block: need {minimum} bytes") return dict( distortion_version=distortion[:4].decode("ascii"), distortion_mode=distortion[4], @@ -326,11 +352,16 @@ def vignette_fit(camera, jpeg, raw, meta): x = r2[mask] complete = np.polyval(poly, np.sqrt(x)) named = 1 + x * (poly[6] + x * (poly[4] + x * poly[2])) - if len(green) < 500 or not np.all(complete > 0): + validate_fit_samples(train, radius) + if not all(np.isfinite(a).all() for a in (green, response, colours, complete)): + raise ValueError("non-finite brightness pairs or gain") + if not np.all(complete > 0): raise ValueError("not enough valid brightness pairs or nonpositive gain") def fit(gain): - corrected = green + np.log(np.maximum(gain, 1e-5)) + if not np.isfinite(gain).all() or not np.all(gain > 0): + raise ValueError("non-finite or nonpositive candidate gain") + corrected = green + np.log(gain) knots = np.linspace(-11, 1, 17) design = np.stack( [np.ones_like(green), corrected] @@ -343,13 +374,16 @@ def fit(gain): test = ~train ring = test & (radius >= 0.75) inner = test & (radius <= 0.35) - return dict( + statistics = dict( training_log_rmse=float(np.sqrt(np.mean(residual[train] ** 2))), heldout_log_rmse=float(np.sqrt(np.mean(residual[test] ** 2))), outer_log_bias=float(np.mean(residual[ring])), inner_log_bias=float(np.mean(residual[inner])), outer_minus_inner=float(np.mean(residual[ring]) - np.mean(residual[inner])), ) + if not all(math.isfinite(value) for value in statistics.values()): + raise ValueError("non-finite brightness fit statistics") + return statistics candidates = { "none": np.ones_like(x), @@ -368,6 +402,8 @@ def fit(gain): method="bounded", options={"xatol": 0.01}, ) + if not fitted.success or not math.isfinite(fitted.x): + raise ValueError("brightness strength optimization did not converge") result["fitted_strength"] = dict( alpha=float(fitted.x), **fit(1 + fitted.x * (complete - 1)) ) @@ -451,7 +487,7 @@ def prepare(path, folder, binary): raise ValueError("this probe currently requires an sRGB camera JPEG") meta = nef_blocks(path) meta.update(exif=exif, sha256=hashlib.sha256(path.read_bytes()).hexdigest()) - (folder / "metadata.json").write_text(json.dumps(meta, indent=2) + "\n") + (folder / "metadata.json").write_text(json_text(meta, indent=2) + "\n") if not (folder / "camera.jpg").exists(): data = subprocess.check_output(["exiftool", "-b", "-JpgFromRaw", str(path)]) if not data: @@ -472,7 +508,7 @@ def prepare(path, folder, binary): ("vignette-tail", True, meta["vignette_tail"]), ]: ops = folder / (name + ".json") - ops.write_text(json.dumps(opcodes(raw, meta, vig, strength), indent=2) + "\n") + ops.write_text(json_text(opcodes(raw, meta, vig, strength), indent=2) + "\n") return raw, meta @@ -524,10 +560,10 @@ def main(): (folder / "candidate.png").replace(folder / (name + ".png")) scores[name] = score(Image.open(folder / (name + ".png")), jpeg) result["experimental_renders_no_look_refit"] = scores - (folder / "measurements.json").write_text(json.dumps(result, indent=2) + "\n") + (folder / "measurements.json").write_text(json_text(result, indent=2) + "\n") print( path.name, - json.dumps( + json_text( dict( baseline=result["baseline"], fitted_strength=result["vignette"]["fitted_strength"], @@ -537,9 +573,7 @@ def main(): ) print( "distortion", - json.dumps( - {k: v for k, v in result["distortion"].items() if k != "points"} - ), + json_text({k: v for k, v in result["distortion"].items() if k != "points"}), flush=True, ) diff --git a/docs/raw/test_nikon_lens_probe.py b/docs/raw/test_nikon_lens_probe.py index 7fa2a48ff6b..924fe72af2c 100644 --- a/docs/raw/test_nikon_lens_probe.py +++ b/docs/raw/test_nikon_lens_probe.py @@ -5,6 +5,8 @@ import struct import unittest +from pathlib import Path +from unittest import mock import numpy as np from PIL import Image @@ -36,6 +38,80 @@ def test_ifd_ranges_are_bounded(self): with self.assertRaisesRegex(ValueError, "entry range"): probe.tiff_entries(directory, 0, "<") + def test_truncated_nef_blocks_fail_before_indexing(self): + """A version-only block must raise a useful error, not IndexError.""" + header = b"II*\0" + struct.pack(" Date: Thu, 5 Nov 2026 08:03:06 +0100 Subject: [PATCH 03/14] LR-EDIT-OPTICS-PROFILE: respect Nikon distortion correction modes Accept only modes 1 and 3. Mode 2 is Off; no-lens and unknown modes also leave the source without a warp. Exercise every case through the public header probe and full decode with a synthetic NEF. Co-authored-by: Codex --- crates/raw/src/vendor/nef.rs | 68 +++++++++++++++++++------------ crates/raw/src/vendor/nef_lens.rs | 9 ++-- 2 files changed, 47 insertions(+), 30 deletions(-) diff --git a/crates/raw/src/vendor/nef.rs b/crates/raw/src/vendor/nef.rs index 10bb24d501e..661064dc2f8 100644 --- a/crates/raw/src/vendor/nef.rs +++ b/crates/raw/src/vendor/nef.rs @@ -688,36 +688,38 @@ mod tests { TiffWriter::new(order, false).write(&[ifd0]).unwrap() } + /// A small uncompressed NEF with a real NikonNEFInfo TIFF block, without binary fixtures. + fn nikon_distortion_file(model: &str, mode: u8) -> Vec { + use super::super::nef_lens::tests::{distortion_block, nef_info_blob, offset_block}; + let (w, h) = (48u32, 32u32); + let words: Vec = (0..w * h).flat_map(|i| (600 + (i % 97) as u16 * 50).to_be_bytes()).collect(); + let mut raw = IfdBuilder::new(); + raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![14])); + raw.set(t::COMPRESSION, Value::Short(vec![1])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); + let info = nef_info_blob(&[ + (0x0005, distortion_block(mode, 21.6, 4, [0.039895, 0.019211, -0.127218], -0.025043)), + (0x0008, offset_block(1.5, -0.75)), + ]); + raw.set(0xc7d5, Value::Undefined(info)); + raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![words] }); + let mut ifd0 = IfdBuilder::new(); + ifd0.set(t::MAKE, Value::Ascii("NIKON CORPORATION".into())); + ifd0.set(t::MODEL, Value::Ascii(model.into())); + ifd0.add_sub_ifd(raw); + TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() + } + /// A Z 6II NEF carrying NikonNEFInfo gets Nikon's distortion correction as one warp, in the header probe and /// the full decode alike, and keeps it through DNG export; another body with the same data gets none. #[test] fn nikon_in_file_distortion_becomes_a_warp() { - use super::super::nef_lens::tests::{distortion_block, nef_info_blob, offset_block}; - let (w, h) = (48u32, 32u32); - let file = |model: &str| { - let words: Vec = (0..w * h).flat_map(|i| (600 + (i % 97) as u16 * 50).to_be_bytes()).collect(); - let mut raw = IfdBuilder::new(); - raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); - raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![14])); - raw.set(t::COMPRESSION, Value::Short(vec![1])); - raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); - raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); - raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); - let info = nef_info_blob(&[ - (0x0005, distortion_block(3, 21.6, 4, [0.039895, 0.019211, -0.127218], -0.025043)), - (0x0008, offset_block(1.5, -0.75)), - ]); - raw.set(0xc7d5, Value::Undefined(info)); - raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![words] }); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("NIKON CORPORATION".into())); - ifd0.set(t::MODEL, Value::Ascii(model.into())); - ifd0.add_sub_ifd(raw); - TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() - }; - let bytes = file("NIKON Z 6_2"); + let bytes = nikon_distortion_file("NIKON Z 6_2", 3); let header = decode(&bytes, Mode::Header).unwrap(); let full = decode(&bytes, Mode::Full).unwrap(); assert_eq!(header.info(), full.info()); @@ -728,7 +730,19 @@ mod tests { let dng = crate::write_dng(&full, &Default::default()).unwrap(); assert_eq!(crate::decode(&dng).unwrap().opcodes.list3, full.opcodes.list3); full.develop(crate::Method::Bilinear).unwrap(); - assert!(decode(&file("NIKON D850"), Mode::Full).unwrap().opcodes.list3.is_empty()); + assert!(decode(&nikon_distortion_file("NIKON D850", 3), Mode::Full).unwrap().opcodes.list3.is_empty()); + } + + /// Off, no-lens and unrecognized modes must not create a source correction through either public path. + #[test] + fn nikon_distortion_modes_are_respected_by_probe_and_full_decode() { + for mode in [0, 1, 2, 3, 4, 128, 255] { + let bytes = nikon_distortion_file("NIKON Z 6_2", mode); + let header = crate::probe_info(&bytes).unwrap(); + let full = crate::decode(&bytes).unwrap(); + assert_eq!(header, full.info(), "mode {mode}: header/full agreement"); + assert_eq!(!header.opcodes.list3.is_empty(), matches!(mode, 1 | 3), "mode {mode}"); + } } #[test] diff --git a/crates/raw/src/vendor/nef_lens.rs b/crates/raw/src/vendor/nef_lens.rs index c5e9490ebde..1d828cebddc 100644 --- a/crates/raw/src/vendor/nef_lens.rs +++ b/crates/raw/src/vendor/nef_lens.rs @@ -45,10 +45,10 @@ fn nef_info(raw: &Ifd) -> Option<(Ifd, ByteOrder)> { Some((ifd, order)) } -/// DistortionInfo: `"0100"`, the correction mode (0 none), the normalisation radius (mm) at 8, the term count (4) -/// at 16, the coefficients at 20 / 28 / 36 and the zoom at 64, each a signed rational. +/// DistortionInfo: `"0100"`, mode (1 optional on, 3 required on; 0 no lens, 2 off), radius (mm) at 8, +/// term count (4) at 16, coefficients at 20 / 28 / 36 and zoom at 64, each a signed rational. fn distortion_info(b: &[u8], order: ByteOrder) -> Option { - if b.get(0..4)? != b"0100" || *b.get(4)? == 0 { + if b.get(0..4)? != b"0100" || !matches!(*b.get(4)?, 1 | 3) { return None; } let norm = rational(b, 8, order)?; @@ -231,6 +231,9 @@ pub(in crate::vendor) mod tests { // correction off, a DX radius, another term count, a wild coefficient or zoom, no NEFInfo at all for bad in [ distortion_block(0, 21.6, 4, WIDE.0, WIDE.1), + distortion_block(2, 21.6, 4, WIDE.0, WIDE.1), + distortion_block(4, 21.6, 4, WIDE.0, WIDE.1), + distortion_block(255, 21.6, 4, WIDE.0, WIDE.1), distortion_block(3, 14.2, 4, WIDE.0, WIDE.1), distortion_block(3, 21.6, 3, WIDE.0, WIDE.1), distortion_block(3, 21.6, 4, [0.0, 0.0, 1.5], 0.0), From 374f0c5ae927ffb715bc4c2bfda835dc55f14737 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Thu, 5 Nov 2026 10:35:51 +0100 Subject: [PATCH 04/14] LR-EDIT-OPTICS-PROFILE: enable validated Nikon Z 6 and Z 7 distortion Use the existing embedded warp, profile controls and DNG path for the two validated bodies. Keep Nikon vignetting and fitted strengths unshipped. Advance camera-look and render-cache versions for this source change, with coverage for offline previews, online rebuilds and edited library reloads. Record fresh production comparisons for all 40 pinned sweep files. The six Nikon outputs improve; the other 34 RGB outputs are byte-identical. Preserve the sweep provenance and bound the claim to two scenes and two focal lengths. Repair existing dither assumptions in CPU/GPU tests after confirming the golden hashes on clean main. Isolate the Find Similar signature-cache test from loupe pixel-cache timing without relaxing its read-count assertions. Align the dialog accessibility harness with the existing optional-font policy, and keep the wire round-trip comparison exact by using the same CPU backend. Co-authored-by: Codex --- apps/lightcraft-web/src/wire.rs | 7 +- crates/engine/src/camera_preview.rs | 3 +- crates/engine/src/media/source.rs | 2 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/nikon_lens.rs | 323 +++++++++++++++++++++++ crates/gpu/tests/it/equivalence.rs | 13 +- crates/gpu/tests/mask_geometry.rs | 9 +- crates/pipeline/src/tests_light.rs | 28 +- crates/raw/src/vendor/nef_lens.rs | 8 +- crates/ui-egui/src/tests/find_similar.rs | 2 + crates/ui-egui/tests/it/dialog_role.rs | 7 +- docs/gaps.md | 5 +- docs/nikon-lens-corrections.md | 138 +++++++++- docs/parity-checklist.md | 5 +- docs/raw/coverage-sweep.tsv | 14 +- docs/raw/coverage_render_sweep.py | 196 ++++++++++++++ docs/raw/nikon-distortion-sweep.tsv | 46 ++++ 17 files changed, 769 insertions(+), 38 deletions(-) create mode 100644 crates/engine/src/tests/nikon_lens.rs create mode 100644 docs/raw/coverage_render_sweep.py create mode 100644 docs/raw/nikon-distortion-sweep.tsv diff --git a/apps/lightcraft-web/src/wire.rs b/apps/lightcraft-web/src/wire.rs index 53d389b6f77..ef35396d242 100644 --- a/apps/lightcraft-web/src/wire.rs +++ b/apps/lightcraft-web/src/wire.rs @@ -438,7 +438,7 @@ mod tests { } #[test] - fn wire_job_renders_like_the_engine() { + fn wire_job_renders_like_the_engine_cpu() { let mut s = Session::with_demo(); let id = s.visible_cloned()[0]; s.execute("library.select", &serde_json::json!({"ids": [id.0]})).unwrap(); @@ -451,7 +451,10 @@ mod tests { let mut core = WorkerCore::default(); assert_eq!(core.needs_original(&wire), None, "demo scenes are generated"); let a = core.render(&wire, None).unwrap(); - let b = job.run().rendered.unwrap(); + // Keep the wire round-trip comparison exact on the same backend. The window test above + // compares the worker with a native job, which can use the GPU and its rounding budget. + let source = job.source.load_source().unwrap(); + let b = lightcraft_engine::pipeline::render(&source.image, &source.info_or(job.info.clone()), &job.settings, &job.request); assert_eq!((a.image.width, a.image.height), (b.image.width, b.image.height)); assert_eq!(a.image.data, b.image.data); assert_eq!(a.histogram, b.histogram); diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index 014a7440800..0987518f05b 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -84,7 +84,8 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights}; /// 13: the sensor proxy of every per-file fit gets the embedded vignetting correction the render applies (Fujifilm /// RAF; other makes with a lens database), so the render no longer applies it twice, at the position a lens warp samples; /// the warped candidate's alignment leaves out the pixels outside the sensor instead of reading them as black. -pub const LOOK_VERSION: u32 = 13; +/// 14: Nikon Z 6 / Z 7 distortion enters the fitting geometry; Nikon mode 2 Off no longer supplies a warp. +pub const LOOK_VERSION: u32 = 14; #[derive(Clone, Debug)] pub(crate) struct CameraLook { diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index c1ee14ca89e..c31546a10c0 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -1,7 +1,7 @@ use super::{Arc, 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 = 75; +pub const RENDER_CACHE_VERSION: u64 = 76; /// 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]; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b5f08f6ae16..2c134b61e37 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -38,6 +38,7 @@ mod mask_effects; mod mask_geometry; mod merge; mod move_to_share; +mod nikon_lens; mod organize; mod persist; mod prefs; diff --git a/crates/engine/src/tests/nikon_lens.rs b/crates/engine/src/tests/nikon_lens.rs new file mode 100644 index 00000000000..8ae4753348e --- /dev/null +++ b/crates/engine/src/tests/nikon_lens.rs @@ -0,0 +1,323 @@ +//! Nikon source corrections across the decoder, optics controls, export and existing libraries. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use lightcraft_catalog::Op; +use lightcraft_develop::DevelopSettings; +use lightcraft_geom::Orientation; +use lightcraft_pipeline::{RenderRequest, SourceInfo}; +use lightcraft_raster::{Rgb32f, Rgba8}; +use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags}; +use serde_json::json; + +use crate::{Session, files}; + +/// Original procedural sensor data and NikonNEFInfo records, with no external media fixture. +fn nef(model: &str, orientation: Orientation) -> Vec { + fn rational(value: f64, denominator: i32) -> Vec { + let numerator = (value * f64::from(denominator)).round() as i32; + [numerator.to_le_bytes(), denominator.to_le_bytes()].concat() + } + let mut distortion = b"0100\x03\x01\0\0".to_vec(); + distortion.extend(rational(21.6, 4096)); + distortion.extend(4u32.to_le_bytes()); + for value in [0.039895, 0.019211, -0.127218, 0.0, 0.0] { + distortion.extend(rational(value, 1 << 20)); + } + distortion.extend([0u8; 4]); + distortion.extend(rational(-0.025043, 1 << 20)); + distortion.resize(84, 0); + let mut center = b"0100".to_vec(); + center.extend(rational(1.5, 256)); + center.extend(rational(-0.75, 256)); + center.resize(24, 0); + let mut info = IfdBuilder::new(); + info.set(5, Value::Undefined(distortion)); + info.set(8, Value::Undefined(center)); + let mut blob = b"Nikon\0\x01\x03\0\0".to_vec(); + blob.extend(TiffWriter::default().write(&[info]).unwrap()); + let (w, h) = (192u32, 128u32); + let mut samples = Vec::new(); + for y in 0..h { + for x in 0..w { + let rgb = [2200 + x * 25, 3000 + y * 30, 2600 + (x + y) * 10]; + let channel = [[0, 1], [1, 2]][y as usize % 2][x as usize % 2]; + samples.extend((rgb[channel] as u16).to_le_bytes()); + } + } + let mut raw = IfdBuilder::new(); + raw.set(tags::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + raw.set(tags::IMAGE_WIDTH, Value::Long(vec![w])); + raw.set(tags::IMAGE_LENGTH, Value::Long(vec![h])); + raw.set(tags::BITS_PER_SAMPLE, Value::Short(vec![14])); + raw.set(tags::COMPRESSION, Value::Short(vec![1])); + raw.set(tags::PHOTOMETRIC, Value::Short(vec![tags::photometric::CFA])); + raw.set(tags::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(tags::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); + raw.set(0xc7d5, Value::Undefined(blob)); + raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![samples] }); + let mut root = IfdBuilder::new(); + root.set(tags::MAKE, Value::Ascii("NIKON CORPORATION".into())); + root.set(tags::MODEL, Value::Ascii(model.into())); + root.set(tags::ORIENTATION, Value::Short(vec![orientation.to_exif()])); + root.add_sub_ifd(raw); + TiffWriter::new(ByteOrder::Little, false).write(&[root]).unwrap() +} + +fn settings(info: &SourceInfo) -> DevelopSettings { + let mut s = DevelopSettings::default(); + s.wb.temp = info.as_shot_temp; + s.wb.tint = info.as_shot_tint; + s.optics.lens_profile = true; + s +} + +fn render(source: &Rgb32f, info: &SourceInfo, settings: &DevelopSettings, edge: usize) -> Rgba8 { + lightcraft_pipeline::render(source, info, settings, &RenderRequest::fit(edge, edge)).image +} + +fn difference(a: &Rgba8, b: &Rgba8) -> (f64, u8) { + assert_eq!((a.width, a.height), (b.width, b.height)); + let values: Vec<_> = a.data.iter().zip(&b.data).flat_map(|(a, b)| (0..3).map(move |c| a[c].abs_diff(b[c]))).collect(); + (values.iter().map(|&v| f64::from(v)).sum::() / values.len() as f64, values.into_iter().max().unwrap()) +} + +/// New body recognition must reach both public decode paths and the existing toggle/strength controls. +#[test] +fn nikon_z6_z7_probe_decode_toggle_amount_and_dng_agree() { + for model in ["NIKON Z 6", "NIKON Z 7"] { + let bytes = nef(model, Orientation::Normal); + let header = lightcraft_raw::probe_info(&bytes).unwrap(); + let raw = lightcraft_raw::decode(&bytes).unwrap(); + assert_eq!(header, raw.info()); + assert!(matches!(&raw.data,lightcraft_raw::RawData::U16(samples) if samples.iter().all(|&v|v<16384)), "the fixture is valid 14-bit data"); + assert_eq!(raw.opcodes.list3.len(), 1); + let lens = files::embedded_lens(&header).unwrap(); + assert!(lens.warp.is_some() && lens.vignette.is_none()); + let dng = lightcraft_raw::write_dng(&raw, &Default::default()).unwrap(); + let back = lightcraft_raw::decode(&dng).unwrap(); + assert_eq!(back.opcodes.list3, raw.opcodes.list3); + assert_eq!(back.data, raw.data); + assert_eq!(files::embedded_lens(&back.info()), Some(lens)); + let (source, info) = files::load_bytes(&bytes, 192).unwrap(); + assert_eq!(info.lens, Some(lens)); + let mut s = settings(&info); + let on = render(&source, &info, &s, 192); + s.optics.lens_profile = false; + let off = render(&source, &info, &s, 192); + assert_ne!(on.data, off.data); + s.optics.lens_profile = true; + s.optics.profile_distortion = 0.0; + assert_eq!(render(&source, &info, &s, 192).data, off.data); + s.optics.profile_distortion = 50.0; + let half = render(&source, &info, &s, 192); + assert_ne!(half.data, off.data); + assert_ne!(half.data, on.data); + s.disabled_sections.push("optics".into()); + assert_eq!(render(&source, &info, &s, 192).data, off.data); + } +} + +/// A sensor-shifted warp must rotate with the sensor, and reduced development must retain its geometry. +#[test] +fn nikon_orientation_and_preview_export_geometry_agree() { + for model in ["NIKON Z 6", "NIKON Z 7"] { + let (source, info) = files::load_bytes(&nef(model, Orientation::Normal), 192).unwrap(); + let s = settings(&info); + let full = render(&source, &info, &s, 192); + for exif in 1..=8 { + let orientation = Orientation::from_exif(exif); + let (source, info) = files::load_bytes(&nef(model, orientation), 192).unwrap(); + let actual = render(&source, &info, &s, 192); + let expected = full.oriented(orientation); + let (mean, max) = difference(&actual, &expected); + assert!(mean <= 0.5 && max <= 3, "{model} {orientation:?}: mean {mean}, max {max}"); + } + let (preview, preview_info) = files::load_bytes(&nef(model, Orientation::Normal), 96).unwrap(); + let actual = render(&preview, &preview_info, &s, 96); + let expected = lightcraft_raster::resample::resize( + &full.map(|p| p.map(f32::from)), + actual.width, + actual.height, + lightcraft_raster::resample::Filter::Lanczos3, + ) + .map(|p| p.map(|v| v.round().clamp(0.0, 255.0) as u8)); + let (mean, max) = difference(&actual, &expected); + eprintln!("{model} preview/full: mean {mean}, max {max}"); + assert!(mean <= 1.0 && max <= 8, "{model} preview/full: mean {mean}, max {max}"); + let full_warp = lightcraft_pipeline::optics::Warp::from_settings(source.width as f64, source.height as f64, &s, info.lens.as_ref()); + let preview_warp = + lightcraft_pipeline::optics::Warp::from_settings(preview.width as f64, preview.height as f64, &s, preview_info.lens.as_ref()); + for x in [0.025, 0.5, 0.975] { + for y in [0.025, 0.5, 0.975] { + let a = full_warp.to_source(lightcraft_geom::Point::new(x * full_warp.w, y * full_warp.h), 1); + let b = preview_warp.to_source(lightcraft_geom::Point::new(x * preview_warp.w, y * preview_warp.h), 1); + assert!((a.x / full_warp.w - b.x / preview_warp.w).abs() < 1e-12); + assert!((a.y / full_warp.h - b.y / preview_warp.h).abs() < 1e-12); + } + } + } +} + +/// Exercise the exact Nikon-derived profile on the GPU as well as the CPU reference. +#[test] +fn nikon_distortion_cpu_gpu_agree() { + if !lightcraft_gpu::available() { + let reason = lightcraft_gpu::unavailable_reason().unwrap_or_default(); + assert!(!reason.contains("kernels failed to build"), "{reason}"); + lightcraft_testkit::skip!(Gpu, "no GPU adapter for Nikon optics comparison: {reason}"); + return; + } + eprintln!("Nikon optics GPU: {}", lightcraft_gpu::adapter_name().unwrap_or_default()); + for model in ["NIKON Z 6", "NIKON Z 7"] { + let (source, info) = files::load_bytes(&nef(model, Orientation::Rotate90), 192).unwrap(); + let source = Arc::new(source); + let mut s = settings(&info); + for amount in [0.0, 50.0, 100.0] { + s.optics.profile_distortion = amount; + let request = RenderRequest::fit(192, 192); + let cpu = lightcraft_pipeline::render(&source, &info, &s, &request); + let gpu = lightcraft_gpu::render(&source, &info, &s, &request, None).expect("available GPU must render Nikon optics"); + let (mean, max) = difference(&cpu.image, &gpu.image); + assert!(mean <= 0.5 && max <= 3, "{model} {amount}: mean {mean}, max {max}"); + } + } +} + +struct Scratch(PathBuf); +impl Scratch { + fn new(model: &str) -> Self { + let p = std::env::temp_dir().join(format!("lc-nikon-lens-{}-{}", std::process::id(), model.replace(' ', "_"))); + std::fs::create_dir_all(&p).unwrap(); + Self(p) + } +} +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Give a synthetic old preview its actual pre-change look version, preserving the JPEG and facts tail. +fn old_header(bytes: &[u8]) -> Vec { + let start = b"LCSP1\n".len(); + let end = start + bytes[start..].iter().position(|&b| b == b'\n').unwrap(); + let mut header: serde_json::Value = serde_json::from_slice(&bytes[start..end]).unwrap(); + header["look_version"] = json!(13); + let mut out = bytes[..start].to_vec(); + out.extend(serde_json::to_vec(&header).unwrap()); + out.extend(&bytes[end..]); + out +} + +/// Reopen a pre-correction library, preserve edited settings, and migrate stored pixels and lens facts only online. +#[test] +fn nikon_existing_library_and_smart_preview_refresh_preserve_edits() { + const { assert!(crate::media::RENDER_CACHE_VERSION > 75, "the source change must invalidate old renders") }; + for model in ["NIKON Z 6", "NIKON Z 7"] { + let scratch = Scratch::new(model); + let original = scratch.0.join("photo.nef"); + let library = scratch.0.join("library"); + let bytes = nef(model, Orientation::Normal); + std::fs::write(&original, &bytes).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(&library, false).unwrap(); + s.execute("library.import", &json!({"paths":[original]})).unwrap(); + let id = s.active().unwrap(); + let mut edited = (*s.catalog.photo(id).unwrap().develop).clone(); + edited.light.exposure = 0.7; + edited.optics.lens_profile = false; + s.commit( + "Old edit", + Op::Batch { + ops: vec![ + Op::SetEmbeddedLens { id, lens: None }, + Op::SetDevelop { id, settings: Arc::new(edited.clone()), label: "Old edit".into(), edited: Some("2026-10-12T00:00:00".into()) }, + ], + }, + ) + .unwrap(); + s.persist_if_dirty(); + s.flush_log().unwrap(); + drop(s); + let mut s = Session::new().with_fs(); + s.open_library(&library, false).unwrap(); + assert_eq!(*s.catalog.photo(id).unwrap().develop, edited); + assert!(s.catalog.photo(id).unwrap().embedded_lens.is_none()); + let (source, mut info) = files::load_bytes(&bytes, 192).unwrap(); + let new_lens = info.lens; + assert!(new_lens.is_some()); + info.lens = None; + let old_tone = lightcraft_pipeline::tone::CameraTone::new(std::array::from_fn(|i| { + let x = 0.004 * 1.17f32.powi(i as i32); + [x, 0.95 * (1.0 - (-1.5 * x).exp())] + })) + .unwrap(); + info.camera_tone = Some(old_tone); + let old_source = source.map(|p| p.map(|v| v * 0.5)); + let old = old_header(&crate::smart::encode(&old_source, Some(&info)).unwrap()); + let preview = crate::smart::sharded_file_path(s.media.smart_dir.as_ref().unwrap(), s.catalog.photo(id).unwrap()); + std::fs::create_dir_all(preview.parent().unwrap()).unwrap(); + std::fs::write(&preview, &old).unwrap(); + assert!(crate::smart::is_stale(&preview), "look version 13 must be older than this correction"); + let offline = scratch.0.join("offline.nef"); + std::fs::rename(&original, &offline).unwrap(); + s.media.forget(id); + let result = s.execute("library.smartPreviews", &json!({"ids":[id.0]})).unwrap(); + assert_eq!(result["staleKept"], 1, "{result}"); + assert_eq!(std::fs::read(&preview).unwrap(), old); + let (_, tone, stored) = crate::smart::decode(&old).unwrap(); + assert_eq!(tone, Some(old_tone)); + assert!(stored.unwrap().lens.is_none()); + let offline_render = s.render_now(id, 96, 96).unwrap(); + assert!(!offline_render.image.data.is_empty()); + std::fs::rename(&offline, &original).unwrap(); + s.media.forget(id); + let result = s.execute("library.smartPreviews", &json!({"ids":[id.0]})).unwrap(); + assert_eq!(result["refreshed"], 1, "{result}"); + assert!(!crate::smart::is_stale(&preview)); + let fresh = std::fs::read(&preview).unwrap(); + let (fresh_pixels, tone, stored) = crate::smart::decode(&fresh).unwrap(); + let (old_pixels, _, _) = crate::smart::decode(&old).unwrap(); + let error = |image: &Rgb32f| { + image.data.iter().zip(&source.data).flat_map(|(a, b)| (0..3).map(move |c| (a[c] - b[c]).abs() as f64)).sum::() + / (source.data.len() * 3) as f64 + }; + assert!(error(&fresh_pixels) < error(&old_pixels) / 4.0, "online rebuild replaces fitted pixels as well as header facts"); + assert_ne!(tone, Some(old_tone)); + assert_eq!(stored.unwrap().lens, new_lens); + s.execute("photo.reload", &json!({"ids":[id.0]})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().embedded_lens, new_lens); + assert_eq!(*s.catalog.photo(id).unwrap().develop, edited, "reloading lens data preserves the entire edited settings value"); + s.persist_if_dirty(); + s.flush_log().unwrap(); + drop(s); + let mut s = Session::new().with_fs(); + s.open_library(&library, false).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().embedded_lens, new_lens); + assert_eq!(*s.catalog.photo(id).unwrap().develop, edited); + let options = crate::export::ExportOptions { format: crate::export::ExportFormat::Dng, ..Default::default() }; + let exported = crate::export::export_photo(&mut s, id, &options, 1).unwrap(); + let dng = lightcraft_raw::decode(&exported.bytes).unwrap(); + assert_eq!(files::embedded_lens(&dng.info()), new_lens); + } +} + +/// The public real files agree with their header probes and contain no shipped vignette opcode. +#[test] +fn nikon_z6_z7_corpus_headers_and_full_decodes_agree() { + let corpus = + std::env::var_os("LIGHTCRAFT_CORPUS").map(PathBuf::from).unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus")); + for id in [3584, 3581, 3582, 2792, 2789, 2790] { + let path = corpus.join(format!("raw/coverage-{id}.nef")); + if !path.exists() { + lightcraft_testkit::skip!(Corpus, "Nikon coverage sample {id} absent"); + continue; + } + let bytes = std::fs::read(path).unwrap(); + let raw = lightcraft_raw::decode(&bytes).unwrap(); + assert_eq!(lightcraft_raw::probe_info(&bytes).unwrap(), raw.info()); + assert!(matches!(raw.opcodes.list3.as_slice(), [lightcraft_raw::Opcode::WarpRectilinear { .. }])); + } +} diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 7a21768de1d..9c3e4cf2d64 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -53,9 +53,16 @@ fn check_v3_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) { 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]); + // Ordered dithering can vary a uniform source by one quantization level. + for channel in 0..4 { + let min = image.data.iter().map(|p| p[channel]).min().unwrap(); + let max = image.data.iter().map(|p| p[channel]).max().unwrap(); + assert!(max - min <= 1, "chroma {chroma}: channel {channel} spans {min}..{max}"); + } + for pixel in &image.data { + for (actual, expected) in pixel.iter().zip(expected) { + assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {pixel:?}, expected {expected}"); + } } } let (_, max, _) = diff(&cpu, &gpu); diff --git a/crates/gpu/tests/mask_geometry.rs b/crates/gpu/tests/mask_geometry.rs index 1cbd741a0e3..67cbcffd4fc 100644 --- a/crates/gpu/tests/mask_geometry.rs +++ b/crates/gpu/tests/mask_geometry.rs @@ -108,6 +108,11 @@ fn luma(img: &Rgba8, i: usize) -> f64 { (p[0] as f64 + p[1] as f64 + p[2] as f64) / 3.0 } +/// Match the CPU geometry test's exclusion of differences at the 8-bit dither floor. +fn above_dither(d: f64) -> f64 { + (d - 1.5).max(0.0) +} + fn centroid(w: usize, weights: impl Iterator) -> (f64, f64) { let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0); for (i, v) in weights.enumerate() { @@ -140,9 +145,9 @@ fn masks_stay_on_the_content_under_every_geometry_change_on_the_gpu() { let plain = on_gpu(&src, &unmasked, None); // (where the marked photo differs from an unmarked one: a warp leaves light blank canvas) let bare = on_gpu(&Arc::new(marked(false)), &unmasked, None); - let mark = centroid(plain.width, (0..plain.data.len()).map(|i| (luma(&plain, i) - luma(&bare, i)).max(0.0))); + let mark = centroid(plain.width, (0..plain.data.len()).map(|i| above_dither(luma(&plain, i) - luma(&bare, i)))); for (how, m) in [("fresh", on_gpu(&src, &s, None)), ("cached", on_gpu(&src, &s, Some(&cache)))] { - let at = centroid(m.width, (0..m.data.len()).map(|i| (luma(&m, i) - luma(&plain, i)).max(0.0))); + let at = centroid(m.width, (0..m.data.len()).map(|i| above_dither(luma(&m, i) - luma(&plain, i)))); let d = ((at.0 - mark.0).powi(2) + (at.1 - mark.1).powi(2)).sqrt(); assert!(d < 2.0, "{name} after {what} ({how}): the mask's effect is at {at:?}, the mark at {mark:?}"); } diff --git a/crates/pipeline/src/tests_light.rs b/crates/pipeline/src/tests_light.rs index 2b85a980435..ec5e76aef51 100644 --- a/crates/pipeline/src/tests_light.rs +++ b/crates/pipeline/src/tests_light.rs @@ -38,9 +38,16 @@ fn check_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) { s.light.contrast = 100.0; s.light.blacks = 80.0; let image = render(&src, &info, &s, &RenderRequest::fit(64, 64)).image; - 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]); + // Ordered dithering can vary a uniform source by one quantization level. + for channel in 0..4 { + let min = image.data.iter().map(|p| p[channel]).min().unwrap(); + let max = image.data.iter().map(|p| p[channel]).max().unwrap(); + assert!(max - min <= 1, "chroma {chroma}: channel {channel} spans {min}..{max}"); + } + for pixel in &image.data { + for (actual, expected) in pixel.iter().zip(expected) { + assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {pixel:?}, expected {expected}"); + } } } @@ -128,11 +135,11 @@ fn golden(process: ProcessVersion) -> u64 { h } -/// V1 and V2 render byte for byte as they do on main before adding process V3. The hashes were captured -/// on main at e2d18b5fb (before `light_v3`) on macOS aarch64, where they are checked: the renders -/// call the platform's `powf` / `exp2` / `log2`, whose last bit can differ on other platforms, so -/// elsewhere the test only prints them. Before updating them during a rebase, run this exact fixture -/// on main and confirm that both hashes match. This PR must not change V1 or V2 rendering. +/// V1 and V2 render byte for byte as on main. The hashes originally captured before `light_v3` +/// at e2d18b5fb were refreshed by running this exact fixture on clean main at 56d1cc2865, +/// after the shared 8-bit Bayer quantization change. They are checked on macOS aarch64: the +/// renders call the platform's `powf` / `exp2` / `log2`, whose last bit can differ elsewhere. +/// Before updating them during a rebase, run this exact fixture on main and confirm both hashes. #[test] fn v1_and_v2_render_as_before_v3() { let got = [golden(ProcessVersion(1)), golden(ProcessVersion(2))]; @@ -142,7 +149,7 @@ fn v1_and_v2_render_as_before_v3() { } } -const GOLDEN: [u64; 2] = [0x5bf0_a7c8_579f_3f34, 0x87a3_598c_1597_9e4d]; +const GOLDEN: [u64; 2] = [0x4830_59a3_ad92_326c, 0x9653_aed0_ea32_aff3]; fn on(process: Process, s: &DevelopSettings) -> DevelopSettings { DevelopSettings { process: process.version(), ..s.clone() } @@ -311,7 +318,8 @@ fn v3_sliders_move_a_grey_ramp_their_way() { ("light.blacks", -60.0), ] { let r = shot(id, v); - assert!(r.windows(2).all(|w| luma(w[1]) >= luma(w[0])), "{id} {v}: the ramp is no longer increasing"); + // Adjacent ordered-dither thresholds can lower a sample by one 8-bit level. + assert!(r.windows(2).all(|w| luma(w[1]) + 1 >= luma(w[0])), "{id} {v}: the ramp decreases beyond the dither floor"); assert!(r.iter().all(|p| p[0].abs_diff(p[1]) <= 1 && p[1].abs_diff(p[2]) <= 1), "{id} {v}: the ramp is no longer grey"); let diff = |lo: usize, hi: usize| (lo..hi).map(|x| luma(r[x]) - luma(plain[x])).sum::(); let (dark, light) = (diff(40, 90), diff(170, 220)); diff --git a/crates/raw/src/vendor/nef_lens.rs b/crates/raw/src/vendor/nef_lens.rs index 1d828cebddc..3ba753a77da 100644 --- a/crates/raw/src/vendor/nef_lens.rs +++ b/crates/raw/src/vendor/nef_lens.rs @@ -15,7 +15,7 @@ const DISTORTION_INFO: u16 = 0x0005; const CENTRE_OFFSET: u16 = 0x0008; /// Bodies whose files were checked against the camera's JPEG (docs/nikon-lens-corrections.md). Matching tags on /// another body do not establish its pixel pitch or image area; add a body only after checking its files. -const VALIDATED: &[&str] = &["NIKON Z 6_2", "NIKON Z 8", "NIKON Z f"]; +const VALIDATED: &[&str] = &["NIKON Z 6", "NIKON Z 7", "NIKON Z 6_2", "NIKON Z 8", "NIKON Z f"]; /// The normalisation radius every checked file stores: the FX half-diagonal in millimetres. const FX_HALF_DIAGONAL_MM: f64 = 21.6; const SAMPLES: usize = 256; @@ -222,10 +222,12 @@ pub(in crate::vendor) mod tests { #[test] fn refuses_unvalidated_bodies_and_unknown_layouts() { let good = distortion_block(3, 21.6, 4, WIDE.0, WIDE.1); - assert!(warp("NIKON Z 6_2", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); + for model in ["NIKON Z 6", "NIKON Z 7", "NIKON Z 6_2"] { + assert!(warp(model, &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some(), "{model}"); + } assert!(warp("NIKON Z f", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); assert!(warp("NIKON Z 8", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); - for model in ["", "NIKON Z 6", "NIKON Z 6_3", "NIKON Z 9", "NIKON D850", "NIKON Z 6_2 x"] { + for model in ["", "NIKON Z 7_2", "NIKON Z 6_3", "NIKON Z 9", "NIKON D850", "NIKON Z 6_2 x"] { assert!(warp(model, &raw_with(&[(DISTORTION_INFO, good.clone())])).is_none(), "{model}"); } // correction off, a DX radius, another term count, a wild coefficient or zoom, no NEFInfo at all diff --git a/crates/ui-egui/src/tests/find_similar.rs b/crates/ui-egui/src/tests/find_similar.rs index 4ac537dc281..ca9b170c22d 100644 --- a/crates/ui-egui/src/tests/find_similar.rs +++ b/crates/ui-egui/src/tests/find_similar.rs @@ -158,6 +158,8 @@ fn stopping_leaves_the_view_alone_and_the_next_search_reads_only_the_rest() { assert!(h.app.ui.toast.is_none(), "{:?}", h.app.ui.toast); assert_eq!(drive.reads.load(Ordering::SeqCst), 1); + // The loupe can have decoded a photo meanwhile. Measure signature reuse without its pixel cache. + h.app.session.media.clear_sources(); let r = h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); assert_eq!(r["count"], PHOTOS - 1, "what was read isn't read again"); until_done(&mut h); diff --git a/crates/ui-egui/tests/it/dialog_role.rs b/crates/ui-egui/tests/it/dialog_role.rs index a36cc96fe97..7332fa56807 100644 --- a/crates/ui-egui/tests/it/dialog_role.rs +++ b/crates/ui-egui/tests/it/dialog_role.rs @@ -7,7 +7,12 @@ use lightcraft_ui_egui::{LightcraftApp, Services}; fn harness() -> Harness<'static, LightcraftApp> { let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, ..Default::default() }); - let mut h = Harness::builder().with_size(vec2(1500.0, 950.0)).build_ui_state( + let mut builder = Harness::builder().with_size(vec2(1500.0, 950.0)); + // Like the accessibility audit, this checks semantics without requiring optional font glyphs. + if lightcraft_engine::CRAFT_FONTS.is_empty() { + builder = builder.allow_missing_glyphs(); + } + let mut h = builder.build_ui_state( |ui, app: &mut LightcraftApp| { app.logic(&ui.ctx().clone()); app.ui(ui); diff --git a/docs/gaps.md b/docs/gaps.md index 566786a5f02..30c371beed7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps: where LightCraft falls short of Lightroom -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-05 · **Change:** minor (Contrast and Blacks calibrated in process V4, #523; PERF-STEP-STALL: flags, ratings and edits never wait for the drive; before: gap 1: the Canon EOS D60 is the first chart-calibrated model, its matrices from our own ColorChecker shots give its white balance a Kelvin scale; gap 20: Canon CRW decodes; LR-LIB-VIRTUALCOPY: default number exhaustion is validated before copy creation; gap 8: lens profile work is tracked in #329; gap 8: lensfun's lens database offered on the first launch and downloaded on request, looked up for the library; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; typed GPS input now rejects malformed coordinates before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in coordinates, elevations and timestamps; malformed references error; CDATA stays literal; ranked gaps unchanged; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; import: checked rename-sequence exhaustion; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: Sony ILCE-7RM6 in-file distortion conversion extends to the APS-C ILCE-6700; LR-META-EXIF-FULL rejects extra EXIF clock components and preserves date fallbacks; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; JPEG ICC APP2 sequence validation; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 24: extreme brush segments skip the intermediate dabs; **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-20 · **Change:** minor (gap 15: Print Page Options — page numbers, page info, crop marks) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-05 · **Change:** minor (Nikon Z 6 / Z 7 distortion and cache migration, Nikon vignette model remains unshipped; Contrast and Blacks calibrated in process V4, #523; PERF-STEP-STALL: flags, ratings and edits never wait for the drive; before: gap 1: the Canon EOS D60 is the first chart-calibrated model, its matrices from our own ColorChecker shots give its white balance a Kelvin scale; gap 20: Canon CRW decodes; LR-LIB-VIRTUALCOPY: default number exhaustion is validated before copy creation; gap 8: lens profile work is tracked in #329; gap 8: lensfun's lens database offered on the first launch and downloaded on request, looked up for the library; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; typed GPS input now rejects malformed coordinates before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in coordinates, elevations and timestamps; malformed references error; CDATA stays literal; ranked gaps unchanged; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; import: checked rename-sequence exhaustion; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 9: CI runs the tests on Linux x64 since #2667; macOS, Windows and the GPU equivalence tests still don't; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: Sony ILCE-7RM6 in-file distortion conversion extends to the APS-C ILCE-6700; LR-META-EXIF-FULL rejects extra EXIF clock components and preserves date fallbacks; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; JPEG ICC APP2 sequence validation; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 8: lens profile work is tracked in #329; gap 30: the Info panel shows the selected photos' shared metadata and marks mixed fields; gap 28: ⌘⌥⇧C / ⌘⌥⇧V copy and paste metadata; gap 13: before a Lightroom catalog import the app asks merge or new library, #2672; gap 28: F8 shows / hides the right panel; import review album hierarchy, #2362; gap 20: Minolta MRW decodes; gap 10: 557 models verified with CRW and MRW; gap 15: Print Page Options — page numbers, page info, crop marks; gap 28: `\` shows / hides the Filter Bar in the grids; gap 21: Indonesian interface shipped, every message but What's New; gap 27: the Windows x64 installer verified on Windows 11; the Settings → Apps uninstall confirmation remains; gap 28: ⌘L Enable Filters switches the filter off and on; gap 15: Japanese photo and postcard paper sizes in the Print page setup and PDF; gap 24: extreme brush segments skip the intermediate dabs; **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-20 · **Change:** minor (gap 15: Print Page Options — page numbers, page info, crop marks) Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, and how hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is @@ -22,7 +22,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 5 B | **AI masks: Subject, Sky, People, Background, Landscape** are heuristics; Object / Describe run SAM 3 but its download has no mirror configured | `crates/segment`; ai-masks.md; MASK rows 67% | masking is how most Lightroom users edit today | 40–70 + model decision | [target-app-parity](target-app-parity.md#ai) | | 6 B | **Compressed ORF** (every Olympus / OM body since ~2008) | measured: 66 of 78 Olympus / OM models preview-only; `orf.rs` refuses; OM bucket 3% of photographers, 3% of them fully work | +2.6 points; best gain per hour of any raw gap (~0.2) | 8–15 | [raw-parity](raw-parity.md#compressed-orf-a-clean-room-starting-point) (the two Olympus patents that describe the method) | | 7 | **Nikon High Efficiency NEF** (HE / HE★ on Z 8, Z 9, Z 6III, Z f, Z50II, Z5II when set to HE) | named and preview only (#193); needs a pure-Rust JPEG XS decoder | +1.1 points (only shots taken in HE; lossless works on the same bodies); low gain per hour (~0.04), so not a beta blocker | 20–40 | [raw-parity](raw-parity.md) | -| 8 B | **Lens profiles: lensfun only, no picker, no own calibration** (LR-EDIT-OPTICS-PROFILE): the desktop app offers lensfun's database (CC BY-SA 3.0, pinned, never bundled) once on the first launch and downloads it on that click or from Settings, then looks every raw up by its lens ([lens-profiles.md](lens-profiles.md)), but those profiles are not validated against Lightroom, there is no profile picker (in the file / lens database / own calibration) and no calibration wizard; in-file corrections: DNG opcodes, RW2 in-file distortion, Sony ILCE-7RM4A, ILCE-7M3, full-frame ILCE-7CR distortion (Auto only) and ILCE-7RM6 and ILCE-6700 distortion (`docs/sony-ilce7rm6-lens-corrections.md`) and Nikon Z 6II / Z 8 / Z f distortion (`docs/nikon-lens-corrections.md`); tracked in #329 | Adobe ships 3,635 lens profiles; we never use them | distortion / vignetting correction is a default step for many | 40–80 + calibration shots | [raw-parity](raw-parity.md#lens-profiles) | +| 8 B | **Lens profiles: lensfun only, no picker, no own calibration** (LR-EDIT-OPTICS-PROFILE): the desktop app offers lensfun's database (CC BY-SA 3.0, pinned, never bundled) once on the first launch and downloads it on that click or from Settings, then looks every raw up by its lens ([lens-profiles.md](lens-profiles.md)), but those profiles are not validated against Lightroom, there is no profile picker (in the file / lens database / own calibration) and no calibration wizard; in-file corrections: DNG opcodes, RW2 in-file distortion, Sony ILCE-7RM4A, ILCE-7M3, full-frame ILCE-7CR distortion (Auto only) and ILCE-7RM6 and ILCE-6700 distortion (`docs/sony-ilce7rm6-lens-corrections.md`) and Nikon Z 6 / Z 7 / Z 6II / Z 8 / Z f distortion (`docs/nikon-lens-corrections.md`); Z 6 / Z 7 evidence is limited to two scenes at 52/56 mm, with extreme corners unvalidated; Nikon vignette correction remains unfinished (the provisional eight-power model and its strength are not validated across captures or correction settings); tracked in #329 | Adobe ships 3,635 lens profiles; we never use them | distortion / vignetting correction is a default step for many | 40–80 + calibration shots | [raw-parity](raw-parity.md#lens-profiles) | | 9 B | **Tests don't run in CI on macOS or Windows, and no CI job runs the GPU equivalence tests**: the CI gate (`ci.yml`, #2667) runs `cargo xtask ci`, which includes `cargo test`, on Linux x64 for every push to `main` and every pull request; FreeBSD runs `cargo test` nightly, on pushes to `release` and on PRs that change its workflow or `packaging/freebsd/`; the macOS and Windows jobs build packages | `.github/workflows/` (ci, freebsd, packaging-lint, release, sonarcloud, windows-arm64); the gate's runner has Mesa software Vulkan drivers installed, but `Gpu::new` refuses software adapters (`crates/gpu/src/ctx.rs`), so the CPU ↔ GPU equivalence tests skip; the linux-riscv64 release job added in 0.6.0 (#844) runs only `lightcraft-cli --version` under QEMU; #1148 (open, not merged; #2667 names it superseded) has the macOS and Windows test legs and a `LIGHTCRAFT_GPU_ALLOW_SOFTWARE` opt-in that runs the GPU tests on lavapipe, Metal and WARP | a regression that only shows on macOS or Windows, or only on a GPU, reaches users; `cargo xtask ci` runs only on Linux in CI | 6–12 | [target-app-parity](target-app-parity.md#by-dimension) | | 10 B | **Per-model verification thin, plus cheap per-body decode fixes**: 557 of 1,446 Adobe models verified (39%), ~86% of photographers on a verified body; Nikon 5 bodies verified, Canon 34, Leica 14 (the Q3 by a recorded check of 38 private DNGs). Cheap fixes: Z 6II packed 14-bit NEF (#769, PR #671), Sony A100 regression (#702); F828 SRF now discovered and imported as preview-only, sensor decoding still missing, DSLR-A200…A390 / A850 12-bit ARW (#535) | measured: [raw/coverage.tsv](raw/coverage.tsv) | per-body bugs (levels, crops, WB) surface only from users | 25–45 | [raw-parity](raw-parity.md#by-maker-measured) | | 11 | **Enhance: Raw Details, Super Resolution; AI denoise without shippable weights or X-Trans** | ENH rows 0%; denoise Bayer only, RawNIND weights GPL and opt-in | Fujifilm users get no AI denoise; nobody gets it out of the box | 30–60 + model decision | [raw-parity](raw-parity.md#demosaic-levels-crops-and-lens-metadata) | @@ -90,6 +90,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | LR-EDIT-OPTICS-PROFILE: Nikon Z 6 / Z 7 in-file distortion validated on six exposures of two scenes at 52/56 mm; mode 2 Off rejected; smart previews and cached renders invalidated; Nikon vignetting remains unfinished; status unchanged | | 2026-11-02 | minor | PERF-STEP-STALL: the catalog log is written and synced off the UI thread, so stepping and flagging never wait for the drive (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, counted as unsaved, never dropped; gap 26 not closed | | 2026-10-28 | minor | Gap 8 shrinks: the desktop app offers lensfun's lens database (CC BY-SA, pinned) once on the first launch and downloads it on request and looks the library's raws up when it arrives; validation, a profile picker and own calibration remain | | 2026-10-23 | patch | Gap 8: the Sigma 10–18 mm on the ILCE-6700 gets a measured lens exception at 10–10.5 mm (0.55 px worst over 99 photos, was about 1.4 px) | diff --git a/docs/nikon-lens-corrections.md b/docs/nikon-lens-corrections.md index 2431cd6dbde..eeccef2f841 100644 --- a/docs/nikon-lens-corrections.md +++ b/docs/nikon-lens-corrections.md @@ -1,10 +1,12 @@ # Nikon embedded distortion corrections +> Last updated: 2026-11-05. Z 6 / Z 7 distortion validation; vignetting remains unfinished. + Nikon writes its own distortion correction into NEFs from its mirrorless bodies, in the raw SubIFD tag `0xc7d5` -(NikonNEFInfo). LightCraft reads it for the NIKON Z 6_2 (Z 6II), the NIKON Z 8 and the NIKON Z f and turns it into an +(NikonNEFInfo). LightCraft reads it for the NIKON Z 6, NIKON Z 7, NIKON Z 6_2 (Z 6II), NIKON Z 8 and NIKON Z f and turns it into an `OpcodeList3` `WarpRectilinear`, so it goes through the same profile correction control, optics path, orientation handling and DNG export as the other embedded corrections. Other bodies are left alone for now even if they have the -same tag, because I've only checked files from these three. +same tag. Body recognition is limited to files checked against their camera JPEGs. This is distortion only. The vignetting block (`0x0006`) and what looks like lateral CA (`0x0007`) aren't applied yet. Like the Sony, Fujifilm and Panasonic corrections it's on by default and can be turned off under Lens @@ -24,7 +26,7 @@ NikonNEFInfo starts with `"Nikon\0"` and a 4-byte version, followed by a small T | Entry | Bytes | What it holds | |---|---|---| | `0x0005` DistortionInfo | 0–3 | `"0100"` | -| | 4 | correction mode: 1 "On (Optional)", 3 "On (Required)", 0 none | +| | 4 | correction mode: 1 "On (Optional)", 3 "On (Required)"; 0 none, 2 "Off" and unknown modes are skipped | | | 8–15 | normalisation radius in mm, a signed rational. It's 21.6 (the FX half diagonal) in every file I looked at | | | 16–19 | number of terms, 4 | | | 20, 28, 36 | the three coefficients, called `k1`, `k2`, `k3` here after ExifTool's names | @@ -84,12 +86,132 @@ extra correction for Z lenses that isn't in the readable coefficients. NikonNEFI didn't try to decode it. Even so, the readable correction takes most of the distortion out. At 24 mm the error at 0.7 half diagonals goes from −82 px to +25 px, and at 70 mm from about −137 px to under 4 px. +## Z 6 and Z 7 validation + +The six CC0 raw.pixls.us files in `docs/raw/coverage-sweep.tsv` are six exposures +of two repeated scenes, with one NIKKOR Z 24-70mm f/4 S. The Z 6 files (3584, +3581, 3582) are at 52 mm and f/6.7; the Z 7 files (2792, 2789, 2790) are at +56 mm and f/5.6. They do not establish coverage at other focal lengths or lenses. +All six file SHA-256 hashes were checked before decoding. + +`docs/raw/nikon_lens_probe.py` matches log-green patches in a quarter-size sensor +proxy against the full-size embedded JPEG. It requires normalized correlation +at least 0.90 and a peak at least 0.02 above competing matches outside its +7-by-7 neighborhood. The stored coefficients, zoom and optical center are used +without fitting a correction to each photo. Radial errors below are full-size +pixels over reliable matches between 0.15 and 0.95 image half-diagonals. + +| Body | Files | Uncorrected radial median | Corrected radial median | Corrected radial p95 | +|---|---:|---:|---:|---:| +| Z 6 | 3 | 82.84-84.00 px | 0.88-0.96 px | 4.69-4.99 px | +| Z 7 | 3 | 124.21-124.80 px | 1.37-1.46 px | 6.18-6.38 px | + +Reliable patches reach about 0.90-0.91 half-diagonals on the Z 6 and 0.94 on +the Z 7. The extreme corners remain unvalidated geometrically. The remaining +smooth edge error is consistent with the native Z lens residual described +above. These results support extending the existing model to these bodies, +with the same full-frame crop, layout, radius and mapping guards. + +Fresh production exports, including the refitted camera look, were compared +against the same references across all 40 coverage-sweep rows. The measurement +method, base/candidate results and unchanged-image hashes are recorded in +[`raw/nikon-distortion-sweep.tsv`](raw/nikon-distortion-sweep.tsv). The historical file and sensor-hash provenance +in the TSV is retained. Only rows whose rendered pixels change are updated. + +The production comparison uses CPU CLI exports at a 1200 px long edge, the +recorded reference orientation and a center crop to the camera reference aspect, +then Lab L* at 200 px. The outer ring starts at 0.75 image half-diagonals. +A lens database is disabled for both runs. The camera look is refitted by each +binary, and all settings remain at their import defaults. + +| File ID | Base r | Corrected r | Base mean dL | Corrected mean dL | Base outer mean dL | Corrected outer mean dL | +|---|---:|---:|---:|---:|---:|---:| +| 3584 | 0.8769 | 0.9964 | +0.299 | +0.173 | -3.479 | -1.609 | +| 3581 | 0.8772 | 0.9964 | +0.320 | +0.196 | -3.470 | -1.611 | +| 3582 | 0.8775 | 0.9964 | +0.430 | +0.212 | -3.431 | -1.592 | +| 2792 | 0.7497 | 0.9914 | +1.924 | +1.215 | -2.982 | -2.068 | +| 2789 | 0.7483 | 0.9910 | +2.188 | +1.271 | -2.881 | -2.028 | +| 2790 | 0.7480 | 0.9910 | +2.240 | +1.251 | -2.868 | -2.073 | + +Here dL is LightCraft minus camera JPEG. All six improve in correlation, +absolute mean dL and outer-ring mean absolute error. The other 34 production +RGB outputs are byte-identical. Residual tone and corner brightness differences +remain; neither Auto Picture Control nor Nikon shading is reproduced exactly. + +## Vignetting remains unfinished + +No Nikon vignette correction or fitted per-body strength is applied. The +investigation used the six Z 6 / Z 7 files and one public file each from the +Z 6II, Z 8 and Z f. That is nine exposures, five scenes, four lenses and five +focal lengths in total; the repeated scenes are not independent lens evidence. + +The `0100` block at `0x0006` has a 21.600098 mm radius and a term count of eight +in these files. Nine signed rationals start at offset 20. A provisional model +reads them in descending polynomial order: odd terms are zero and the last +term is one. It includes an unnamed rational `a` at offset 20 as well as the +three named coefficients at offsets 36, 52 and 68: + +```text +P(rho) = 1 + c3*rho^2 + c2*rho^4 + c1*rho^6 + a*rho^8 +candidate gain = 1 + strength * (P(rho) - 1) +``` + +Here `rho` is the unwarped source radius over the image-area half diagonal, +about the recorded optical center. The ordering, powers, normalization and +strength are hypotheses derived from the files and camera-JPEG comparisons. +Only tag identities and the named coefficient offsets came from ExifTool's +tag-name documentation. No external decoder implementation was read. + +The unnamed term matters: at `rho = 1`, the named three alone give gains of +0.912 on the Z 6 and 2.790 on the Z 7; the complete polynomial gives 1.705 and +1.673. However, diagnostic renders that retain the old camera-look fit overbrighten +the corners at full strength and worsen the Z 8 and Z f comparison. Those +experiments do not predict production output after a camera-look refit. Treating the rational at offset 96 as the strength +also fails to establish one consistent interpretation across bodies and scenes. + +The diagnostic fitter uses a global log-tone spline and color-ratio terms, +with alternating spatial tiles reserved for validation. It rejects undersampled +splits and radial bins and non-finite statistics. Effective fitted strengths +vary among captures. Scene brightness correlated with radius, Auto Picture +Control on the Z 6, and Auto Active D-Lighting on the Z 6II sample limit the +inference. No contrast response was tuned to close those differences. + +Further investigation needs other lenses, apertures and focal lengths, whole +captures held out, flat or near-flat scenes where available, and different +correction settings. Private pairs must stay in place, with diagnostics outside +the repository and anonymous results. Vignetting requires a later review. +If validated, `FixVignetteRadial` before the warp in `OpcodeList3` would use the +existing profile toggle, amount, orientation and DNG path. A `GainMap` would +be baked into the source and would not provide that lens toggle. + +## Existing libraries and process versions + +These are source corrections under `docs/process-versions.md`; they do not +introduce a rendering process. Qualifying Z 6 / Z 7 NEFs can acquire the warp, +and mode-2 NEFs on previously validated bodies lose the unwanted warp. Modes +1 (On Optional) and 3 (On Required) are accepted; 0, 2 and unknown modes are skipped. + +The camera-look fit uses the recognized geometry even when profile corrections +are switched off, so existing edited photos on any process can change tone or +color when decoded again. `LOOK_VERSION` and `RENDER_CACHE_VERSION` are advanced +together. Old smart previews are rebuilt from online originals and retained +with their stored pixels, tone and lens data while originals are offline. + +Reload from Disk refreshes catalog lens metadata. It enables a newly found +profile for an untouched photo without an import preset; an edited photo keeps +its settings, including an explicit off switch. Reload is required to update +an older catalog's Optics metadata. A file profile takes precedence over a +lens-database profile, so a Z 6 / Z 7 photo previously using database corrections +can also change when its embedded profile is recognized. The production sweep +above disables the optional database in both runs. Existing DNGs without these +opcodes, other bodies and preview-only raw variants do not acquire this NEF correction. + ## What's left out -Only `NIKON Z 6_2`, `NIKON Z 8` and `NIKON Z f` are corrected, matched exactly. A matching tag on another body doesn't tell us its +Only `NIKON Z 6`, `NIKON Z 7`, `NIKON Z 6_2`, `NIKON Z 8` and `NIKON Z f` are corrected, matched exactly. A matching tag on another body doesn't tell us its pixel pitch or image area, so other bodies can be added once someone checks their files. Only the full-frame 3:2 image area is corrected, because the stored 21.6 mm radius is the FX half diagonal, so DX and other crops are skipped. -The decoder also skips data it doesn't recognise (another layout, radius or term count, or no correction mode), +The decoder also skips data it doesn't recognise (another layout, radius or term count, or a correction mode other than 1 or 3), values that are clearly wrong (coefficients past ±1, a zoom past ±0.5, a sensor shift over 5% of the frame) and any mapping that folds back on itself before the farthest corner. @@ -99,3 +221,9 @@ and a DNG export. `nikon_in_file_distortion_is_limited_to_validated_bodies` chec warp and the D5100, D7000, D7500 and Coolpix B700 samples don't. None of my photos, crops or reference images are committed, only the numbers above. + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-11-05 | minor | Z 6 / Z 7 distortion, correction-mode guards, cache and library migration coverage; vignette model remains unshipped | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index ced72e47cf4..3231594543c 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (LRC-DEV-AUTOSYNC: white balance syncs on each photo's own scale, As Shot and Auto per photo; before: LR-LIB-FLAG: a flag or rating never waits for the drive, PERF-STEP-STALL; LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread, so a large library no longer freezes the window; LR-MASK-LINEAR: masks stay on the photo's content under lens corrections, Upright, Transform and Rotate; LR-IMP-FORMATS: the Canon CRW decoder is the shared craft-libs crate `craft-crw`; LR-PROF-CAMERACOLOR: chart-measured matrices for the Canon EOS D60, its white balance in Kelvin; CRW imports name their camera; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Nikon Z 6 / Z 7 distortion and cache migration, Nikon vignette model remains unshipped; LRC-DEV-AUTOSYNC: white balance syncs on each photo's own scale, As Shot and Auto per photo; before: LR-LIB-FLAG: a flag or rating never waits for the drive, PERF-STEP-STALL; LRC-LIB-VISUALSEARCH: Find Similar Photos reads the photos on a worker thread, so a large library no longer freezes the window; LR-MASK-LINEAR: masks stay on the photo's content under lens corrections, Upright, Transform and Rotate; LR-IMP-FORMATS: the Canon CRW decoder is the shared craft-libs crate `craft-crw`; LR-PROF-CAMERACOLOR: chart-measured matrices for the Canon EOS D60, its white balance in Kelvin; CRW imports name their camera; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -212,7 +212,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-DETAIL-SUPERRES | Super resolution | P2 | ⬜ | | | | LR-EDIT-DETAIL-AISHARPEN | AI sharpen | OOS | 🚫 | | | | LR-EDIT-OPTICS-CA | Remove chromatic aberration | P1 | ✅ | `crates/ui-egui/src/panels/edit.rs` (checkbox), `ctl:optics.caRed`, `ctl:optics.caBlue` | | -| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `crates/raw/src/vendor/rw2.rs`, `crates/raw/src/vendor/raf_lens.rs`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, ILCE-7M3 (FE 16–35 F4 ZA, FE 28–70, FE 50 F1.8; 26 shots within 0.06–0.44 px median of the camera JPEG at 6000 px, from up to 26 px uncorrected), and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `crates/raw/src/vendor/nef_lens.rs`, `docs/nikon-lens-corrections.md`) for the Z 6II, Z 8 and Z f, full-frame image area only: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `crates/raw/src/vendor/raf_lens.rs`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-T30 III, X-M5, X-T5 crops; X-S20 supported) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`crates/raw/src/lens_metadata.rs`), but only the ILCE-7RM4A, ILCE-7M3, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; lens database: the desktop app offers lensfun's `data/db` once on the first launch (Download / Not Now with its size; Settings ▸ General ▸ Lens profiles downloads it later; nothing is fetched without that click; CC BY-SA 3.0, pinned by commit, size and SHA-256, never bundled; `cmd:lens.downloadDatabase`, `crates/engine/src/lensfun_download.rs`) and downloads it with an activity row, and when it arrives every library raw whose lens it knows is looked up again in the background (`cmd:library.refreshLensProfiles`, `crates/engine/src/cmd/lens_refresh.rs`), as is a photo whose Enable Lens Corrections is ticked; the Optics panel names the loaded profile and its source, or says "No lens profile found for " (`crates/ui-egui/src/lens_db.rs`); presets, Copy / Paste and Sync carry only the switch and amounts, never a profile (`crates/engine/src/tests/lens_refresh.rs`); no source picker or own calibration yet | +| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `crates/raw/src/vendor/rw2.rs`, `crates/raw/src/vendor/raf_lens.rs`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, ILCE-7M3 (FE 16–35 F4 ZA, FE 28–70, FE 50 F1.8; 26 shots within 0.06–0.44 px median of the camera JPEG at 6000 px, from up to 26 px uncorrected), and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `crates/raw/src/vendor/nef_lens.rs`, `docs/nikon-lens-corrections.md`) for the Z 6, Z 7, Z 6II, Z 8 and Z f, full-frame image area only (modes 1/3 on, mode 2 off and unknown modes skipped); the Z 6 / Z 7 extension is measured on six exposures of two scenes with the 24-70mm f/4 S at 52/56 mm, corrected radial medians 0.88-0.96 / 1.37-1.46 px, with extreme corners unvalidated; Nikon vignetting remains unfinished and no fitted body strength is applied; camera-look and render-cache versions advance together, old smart previews rebuild online and remain usable offline, Reload updates lens metadata while preserving edited settings: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `crates/raw/src/vendor/raf_lens.rs`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-T30 III, X-M5, X-T5 crops; X-S20 supported) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`crates/raw/src/lens_metadata.rs`), but only the ILCE-7RM4A, ILCE-7M3, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; lens database: the desktop app offers lensfun's `data/db` once on the first launch (Download / Not Now with its size; Settings ▸ General ▸ Lens profiles downloads it later; nothing is fetched without that click; CC BY-SA 3.0, pinned by commit, size and SHA-256, never bundled; `cmd:lens.downloadDatabase`, `crates/engine/src/lensfun_download.rs`) and downloads it with an activity row, and when it arrives every library raw whose lens it knows is looked up again in the background (`cmd:library.refreshLensProfiles`, `crates/engine/src/cmd/lens_refresh.rs`), as is a photo whose Enable Lens Corrections is ticked; the Optics panel names the loaded profile and its source, or says "No lens profile found for " (`crates/ui-egui/src/lens_db.rs`); presets, Copy / Paste and Sync carry only the switch and amounts, never a profile (`crates/engine/src/tests/lens_refresh.rs`); no source picker or own calibration yet | ) | LR-EDIT-OPTICS-DEFRINGE | Defringe | P1 | ✅ | `ctl:optics.defringe*` | no fringe eyedropper | | LR-EDIT-OPTICS-MANUAL | Manual distortion / vignetting | P1 | ✅ | `ctl:optics.distortion`, `ctl:optics.vignetting`, `ctl:optics.vignettingMidpoint` | | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-11-05 | minor | LR-EDIT-OPTICS-PROFILE: Nikon Z 6 / Z 7 in-file distortion validated on six exposures of two scenes at 52/56 mm; mode 2 Off rejected; smart previews and cached renders invalidated; Nikon vignetting remains unfinished; status unchanged | | 2026-11-02 | minor | LRC-DEV-AUTOSYNC (N-A3, note 18): Auto Sync carries white balance as a mode or on each photo's own scale: As Shot and Auto per photo (were the active photo's numbers), a Temp move keeps each photo's tint, the same number on photos of the same scale, a photo of another scale (a JPEG beside a raw) moves by as much; Sync Settings unchanged; status unchanged | | 2026-11-02 | minor | LR-LIB-FLAG (PERF-STEP-STALL): flags, ratings and edits are written and synced to the catalog log off the UI thread (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, never dropped | | 2026-10-28 | minor | LR-EDIT-OPTICS-PROFILE: lensfun's database offered once on the first launch and downloaded on request (Download / Not Now, Settings) (pinned, CC BY-SA, never bundled), the library looked up when it arrives or Enable Lens Corrections is ticked, the Optics panel names the profile or the lens without one; status unchanged (🟡) | diff --git a/docs/raw/coverage-sweep.tsv b/docs/raw/coverage-sweep.tsv index 8e3b2449aeb..711a7fbf628 100644 --- a/docs/raw/coverage-sweep.tsv +++ b/docs/raw/coverage-sweep.tsv @@ -2,6 +2,8 @@ # FNV-1a-64 pins LightCraft's own complete decoded samples, row-major little-endian, including masked borders. # Default renders at up to 1200 px; Pearson r on Lab L* at 200 px after orientation/aspect alignment, threshold 0.6. # Hasselblad PreviewTIFF references check image structure only. Own-matrix DNG tone remains subject to issue #1277. +# 2026-11-05: six Z 6/Z 7 render scores/mean dL refreshed after distortion and camera-look refit; original file/sensor provenance and every other row retained. +# Fresh base/candidate production renders over all 40 rows: docs/raw/nikon-distortion-sweep.tsv (34 RGB outputs unchanged). maker camera id file url sha256 width height cpp samples fnv1a64 luma_r reference notes Apple iPhone 6s Plus 915 coverage-915.dng https://raw.pixls.us/getfile.php/915/nice/Apple%20-%20iPhone%206s%20Plus%20-%2016bit%20%284:3%29.DNG 845fee4f09c832af3728778737f5ae9b99124debb821b6e2066b94aed1daa91c 4032 3024 1 u16 17e4d3c620d593c9 0.9712 embedded JPEG 16bit (4:3); comparison Normal/crop-render; mean dL -10.109 Apple iPhone 7 Plus 939 coverage-939.dng https://raw.pixls.us/getfile.php/939/nice/Apple%20-%20iPhone%207%20Plus%20-%2016bit%20%284:3%29.DNG e8c7ebd8f22f7281d165496b91c8fea8a8e79c8113172fb499e1d66d6045332e 4032 3024 1 u16 d0095a8b553f0f8a 0.9904 embedded JPEG 16bit (4:3); comparison Normal/crop-render; mean dL -11.913 @@ -27,12 +29,12 @@ Hasselblad X2D 100C 6565 coverage-6565.3fr https://raw.pixls.us/getfile.php/6565 Nikon D6 4726 coverage-4726.nef https://raw.pixls.us/getfile.php/4726/nice/Nikon%20-%20D6%20-%2012bit%2012bit%20compressed%20%28Lossy%20%28type%202%29%29%20%283:2%29.NEF 3a098e704d0e1af97efc37541b43a37e5b3457d2f4e7828c0d8d9af37332f233 5584 3728 1 u16 272425c271bb0d76 0.9557 embedded JPEG 12bit 12bit compressed (Lossy (type 2)) (3:2); comparison Normal/crop-render; mean dL 0.037 Nikon D6 4720 coverage-4720.nef https://raw.pixls.us/getfile.php/4720/nice/Nikon%20-%20D6%20-%2014bit%2014bit%20compressed%20%28Lossless%29%20%283:2%29.NEF 827bcfff8a3cd86278382c353e4542faab52cf12c365540f30753bb4c6fabc0f 5584 3728 1 u16 1d6a9f10a502fb14 0.9581 embedded JPEG 14bit 14bit compressed (Lossless) (3:2); comparison Normal/crop-render; mean dL 0.048 Nikon D6 4721 coverage-4721.nef https://raw.pixls.us/getfile.php/4721/nice/Nikon%20-%20D6%20-%2014bit%2014bit%20compressed%20%28Lossy%20%28type%202%29%29%20%283:2%29.NEF 081d5dbc1d6c97935020d33ffa486dcaa8d4564cbde280cfadcf26ff61da2838 5584 3728 1 u16 2d6c8af38e4a0ed4 0.9592 embedded JPEG 14bit 14bit compressed (Lossy (type 2)) (3:2); comparison Normal/crop-render; mean dL 0.043 -Nikon Z 6 3584 coverage-3584.nef https://raw.pixls.us/getfile.php/3584/nice/Nikon%20-%20Z%206%20-%2012bit%2012bit%20compressed%20%283:2%29.NEF 3cbd9acf9e9bfd7d0c62c46436109556a101f7535c5fd25f86dad6ea61bf3886 6064 4040 1 u16 a63b22e83bb7c82f 0.8749 embedded JPEG 12bit 12bit compressed (3:2); comparison Normal/crop-render; mean dL 0.327 -Nikon Z 6 3581 coverage-3581.nef https://raw.pixls.us/getfile.php/3581/nice/Nikon%20-%20Z%206%20-%2014bit%2014bit%20compressed%20%283:2%29.NEF 8ca94584578b35a422744c1a610174ce37df0691588edfdecaec3111b3fbbb02 6064 4040 1 u16 1e23d74a11c01a97 0.8752 embedded JPEG 14bit 14bit compressed (3:2); comparison Normal/crop-render; mean dL 0.353 -Nikon Z 6 3582 coverage-3582.nef https://raw.pixls.us/getfile.php/3582/nice/Nikon%20-%20Z%206%20-%2014bit%2014bit%20lossless%20compressed%20%283:2%29.NEF c079345fc93f53a4f0d322f8ddaae505f920c36015f25b58befccaa61db1af31 6064 4040 1 u16 0a0bc73568e125e0 0.8755 embedded JPEG 14bit 14bit lossless compressed (3:2); comparison Normal/crop-render; mean dL 0.464 -Nikon Z 7 2792 coverage-2792.nef https://raw.pixls.us/getfile.php/2792/nice/Nikon%20-%20Z%207%20-%2012bit%2012bit%20compressed%20%283:2%29.NEF c861546fbcf5826d5eb26d223e2143fa32968e89f7edbc5bb10c283ea5461ded 8288 5520 1 u16 c989690cb3e19ef9 0.7417 embedded JPEG 12bit 12bit compressed (3:2); comparison Normal/crop-render; mean dL 2.417 -Nikon Z 7 2789 coverage-2789.nef https://raw.pixls.us/getfile.php/2789/nice/Nikon%20-%20Z%207%20-%2012bit%2012bit%20compressed%20%283:2%29.NEF e54a6c4264bf685214f538036fd9d39088e510b2bfedf288e568f0db1897880e 8288 5520 1 u16 627867ac6a8dd4ad 0.7412 embedded JPEG 12bit 12bit compressed (3:2); comparison Normal/crop-render; mean dL 2.299 -Nikon Z 7 2790 coverage-2790.nef https://raw.pixls.us/getfile.php/2790/nice/Nikon%20-%20Z%207%20-%2012bit%2012bit%20compressed%20%283:2%29.NEF f0e756dbfd00f3b71cb3d8aa5b9e2e1be32f1052a6c4380e09ebc7c5e7748114 8288 5520 1 u16 8a52e6f3d8ff64dd 0.7389 embedded JPEG 12bit 12bit compressed (3:2); comparison Normal/crop-render; mean dL 2.585 +Nikon Z 6 3584 coverage-3584.nef https://raw.pixls.us/getfile.php/3584/nice/Nikon%20-%20Z%206%20-%2012bit%2012bit%20compressed%20%283:2%29.NEF 3cbd9acf9e9bfd7d0c62c46436109556a101f7535c5fd25f86dad6ea61bf3886 6064 4040 1 u16 a63b22e83bb7c82f 0.9964 embedded JPEG 12bit 12bit compressed (3:2); comparison Normal/crop-render; mean dL 0.173; 2026-11-05 production refit with Nikon distortion; outer mean dL -1.609; docs/raw/nikon-distortion-sweep.tsv +Nikon Z 6 3581 coverage-3581.nef https://raw.pixls.us/getfile.php/3581/nice/Nikon%20-%20Z%206%20-%2014bit%2014bit%20compressed%20%283:2%29.NEF 8ca94584578b35a422744c1a610174ce37df0691588edfdecaec3111b3fbbb02 6064 4040 1 u16 1e23d74a11c01a97 0.9964 embedded JPEG 14bit 14bit compressed (3:2); comparison Normal/crop-render; mean dL 0.196; 2026-11-05 production refit with Nikon distortion; outer mean dL -1.611; docs/raw/nikon-distortion-sweep.tsv +Nikon Z 6 3582 coverage-3582.nef https://raw.pixls.us/getfile.php/3582/nice/Nikon%20-%20Z%206%20-%2014bit%2014bit%20lossless%20compressed%20%283:2%29.NEF c079345fc93f53a4f0d322f8ddaae505f920c36015f25b58befccaa61db1af31 6064 4040 1 u16 0a0bc73568e125e0 0.9964 embedded JPEG 14bit 14bit lossless compressed (3:2); comparison Normal/crop-render; mean dL 0.212; 2026-11-05 production refit with Nikon distortion; outer mean dL -1.592; docs/raw/nikon-distortion-sweep.tsv +Nikon Z 7 2792 coverage-2792.nef https://raw.pixls.us/getfile.php/2792/nice/Nikon%20-%20Z%207%20-%2012bit%2012bit%20compressed%20%283:2%29.NEF c861546fbcf5826d5eb26d223e2143fa32968e89f7edbc5bb10c283ea5461ded 8288 5520 1 u16 c989690cb3e19ef9 0.9914 embedded JPEG 12bit 12bit compressed (3:2); comparison Normal/crop-render; mean dL 1.215; 2026-11-05 production refit with Nikon distortion; outer mean dL -2.068; docs/raw/nikon-distortion-sweep.tsv +Nikon Z 7 2789 coverage-2789.nef https://raw.pixls.us/getfile.php/2789/nice/Nikon%20-%20Z%207%20-%2012bit%2012bit%20compressed%20%283:2%29.NEF e54a6c4264bf685214f538036fd9d39088e510b2bfedf288e568f0db1897880e 8288 5520 1 u16 627867ac6a8dd4ad 0.9910 embedded JPEG 12bit 12bit compressed (3:2); comparison Normal/crop-render; mean dL 1.271; 2026-11-05 production refit with Nikon distortion; outer mean dL -2.028; docs/raw/nikon-distortion-sweep.tsv +Nikon Z 7 2790 coverage-2790.nef https://raw.pixls.us/getfile.php/2790/nice/Nikon%20-%20Z%207%20-%2012bit%2012bit%20compressed%20%283:2%29.NEF f0e756dbfd00f3b71cb3d8aa5b9e2e1be32f1052a6c4380e09ebc7c5e7748114 8288 5520 1 u16 8a52e6f3d8ff64dd 0.9910 embedded JPEG 12bit 12bit compressed (3:2); comparison Normal/crop-render; mean dL 1.251; 2026-11-05 production refit with Nikon distortion; outer mean dL -2.073; docs/raw/nikon-distortion-sweep.tsv Nikon Z 8 6617 coverage-6617.nef https://raw.pixls.us/getfile.php/6617/nice/Nikon%20-%20Z%208%20-%208bit%208bit%20compressed%20%283:2%29.NEF c13a8675294456b9c979e6c1e556951654f35377b2870af2874bfb556f21ce40 8280 5520 1 u16 716e1158bab28b76 0.9563 embedded JPEG 8bit 8bit compressed (3:2); comparison Normal/crop-render; mean dL 2.044 Parrot Anafi 2912 coverage-2912.dng https://raw.pixls.us/getfile.php/2912/nice/Parrot%20-%20Anafi%20-%2016bit%20%284:3%29.DNG a257a296047ff2d396109fd2e6947fa36aa7986695b6815f83979d59e98a84e6 5344 4016 1 u16 07a188c932a25a31 0.9895 embedded JPEG 16bit (4:3); comparison Normal/crop-render; mean dL -3.924 Samsung Galaxy S21 Ultra Rear Main Camera 6728 coverage-6728.dng https://raw.pixls.us/getfile.php/6728/nice/Samsung%20-%20Galaxy%20S21%20Ultra%20-%204:3.dng 5baeb5f0c4a125647df03b82c2d38b0f02784393bd39eff1a5b23d8f5308dc5e 4000 3000 3 u16 16c5d6faed83390d 0.9912 embedded JPEG 4:3; comparison Rotate180/crop-render; mean dL -10.83 diff --git a/docs/raw/coverage_render_sweep.py b/docs/raw/coverage_render_sweep.py new file mode 100644 index 00000000000..12ee2d0e46d --- /dev/null +++ b/docs/raw/coverage_render_sweep.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Compare production CLI exports across all 40 pinned coverage-sweep inputs. + +Run from the repository root with Python, numpy, scipy, Pillow and exiftool: + python3 docs/raw/coverage_render_sweep.py --cli BASE_CLI --out corpus/nikon-lens/base + python3 docs/raw/coverage_render_sweep.py --cli CANDIDATE_CLI --out corpus/nikon-lens/candidate \ + --compare corpus/nikon-lens/base/scores.json + +Use a fresh output directory per binary. The second run reuses the first run's +reference images and framing. Existing PNGs allow an interrupted run to resume. +Inputs are only the SHA-256-pinned public corpus rows. Images and binary copies +stay in gitignored corpus; commit the numerical evidence separately. PreviewTIFF +rows remain image-structure checks rather than display-ready colour references. +""" +import argparse, csv, hashlib, io, json, os, subprocess, sys +from pathlib import Path +from PIL import Image, ImageOps +from nikon_lens_probe import score + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--cli", type=Path, required=True) + p.add_argument("--out", type=Path, required=True) + p.add_argument("--compare", type=Path) + a = p.parse_args() + a.out.mkdir(parents=True, exist_ok=True) + rows = list( + csv.DictReader( + [ + l + for l in Path("docs/raw/coverage-sweep.tsv").read_text().splitlines() + if not l.startswith("#") + ], + delimiter="\t", + ) + ) + previous = json.loads(a.compare.read_text())["records"] if a.compare else None + empty = Path("corpus/nikon-lens/empty-lensdb").resolve() + empty.mkdir(exist_ok=True) + env = dict( + os.environ, + LIGHTCRAFT_GPU="0", + LIGHTCRAFT_LENSFUN_DIR=str(empty), + RAYON_NUM_THREADS="6", + ) + results = {} + cli_sha = hashlib.sha256(a.cli.read_bytes()).hexdigest() + record_path = a.out / "run.json" + configuration = dict( + cli_sha256=cli_sha, + compare=str(a.compare.resolve()) if a.compare else None, + rayon_threads=6, + gpu=False, + ) + if record_path.exists() and json.loads(record_path.read_text()) != configuration: + raise ValueError( + "output directory belongs to a different binary or comparison; use a fresh directory" + ) + record_path.write_text(json.dumps(configuration, indent=2, allow_nan=False) + "\n") + for row in rows: + raw = Path("corpus/raw") / row["file"] + digest = hashlib.sha256(raw.read_bytes()).hexdigest() + if digest != row["sha256"]: + raise ValueError("SHA-256 mismatch " + row["file"]) + out = a.out / (raw.stem + ".png") + ref = (a.compare.parent if a.compare else a.out) / (raw.stem + "-reference.png") + if not out.exists(): + with (a.out / (raw.stem + ".log")).open("w") as log: + subprocess.run( + [str(a.cli), "render", str(raw), "-o", str(out), "--size", "1200"], + env=env, + stdout=log, + stderr=log, + check=True, + ) + if not ref.exists(): + images = [] + for tag in ("JpgFromRaw", "PreviewImage", "PreviewTIFF"): + data = subprocess.check_output( + ["exiftool", "-b", "-" + tag, str(raw)], stderr=subprocess.DEVNULL + ) + if data: + im = Image.open(io.BytesIO(data)) + im.load() + images.append((im.width * im.height, tag, im.convert("RGB"))) + if not images: + tags = json.loads( + subprocess.check_output( + [ + "exiftool", + "-j", + "-n", + "-G1", + "-StripOffsets", + "-StripByteCounts", + "-Compression", + str(raw), + ] + ) + )[0] + for key, compression in tags.items(): + if not key.endswith(":Compression") or compression not in (6, 7): + continue + group = key.rsplit(":", 1)[0] + offset = tags.get(group + ":StripOffsets") + length = tags.get(group + ":StripByteCounts") + if ( + not isinstance(offset, int) + or not isinstance(length, int) + or length <= 0 + or length > 64 * 1024 * 1024 + or offset < 0 + or offset + length > raw.stat().st_size + ): + continue + with raw.open("rb") as stream: + stream.seek(offset) + data = stream.read(length) + im = Image.open(io.BytesIO(data)) + im.load() + images.append( + (im.width * im.height, group + " JPEG strip", im.convert("RGB")) + ) + if not images: + raise ValueError("no camera reference in " + row["file"]) + _, tag, reference = max(images, key=lambda x: x[0]) + reference.save(ref) + else: + reference = Image.open(ref).convert("RGB") + tag = "cached" + rendered = Image.open(out).convert("RGB") + pixel_sha = hashlib.sha256( + f"{rendered.width}x{rendered.height}:RGB:".encode() + rendered.tobytes() + ).hexdigest() + rotation = 180 if "comparison Rotate180/" in row["notes"] else 0 + if rotation: + rendered = rendered.rotate(rotation, expand=True) + # The historical records use crop-render: retain the camera's reference aspect and center-crop the render. + framed = ImageOps.fit( + rendered, + (200, round(reference.height * 200 / reference.width)), + method=Image.Resampling.LANCZOS, + centering=(0.5, 0.5), + ) + measured = score(framed, reference) + record = dict( + file_sha256=digest, + pixel_sha256=pixel_sha, + render_size=rendered.size, + reference=row["reference"], + reference_sha256=hashlib.sha256(reference.tobytes()).hexdigest(), + reference_size=reference.size, + rotation=rotation, + **measured, + ) + if previous: + base = previous[row["file"]] + record["pixels_changed"] = pixel_sha != base["pixel_sha256"] + record["delta_r"] = record["r"] - base["r"] + record["delta_abs_mean_dl"] = abs(record["mean_dl"]) - abs(base["mean_dl"]) + results[row["file"]] = record + (a.out / "scores.json").write_text( + json.dumps( + dict( + cli_sha256=cli_sha, + method="CLI PNG 1200px; CPU; 6 Rayon threads; no lens database; largest embedded reference; recorded rotation; center crop-render; Lab L* 200px; outer rho>=0.75; pixel SHA256 includes WxH:RGB: and row-major RGB bytes", + records=results, + ), + indent=2, + allow_nan=False, + ) + + "\n" + ) + print(row["file"], json.dumps(record, allow_nan=False), flush=True) + + if previous: + regressions = [ + name + for name, record in results.items() + if record["r"] < previous[name]["r"] - 1e-9 + or abs(record["mean_dl"]) > abs(previous[name]["mean_dl"]) + 1e-9 + or record["outer_mae_dl"] > previous[name]["outer_mae_dl"] + 1e-9 + ] + if regressions: + raise ValueError( + "render/reference metrics regressed: " + ", ".join(regressions) + ) + + +if __name__ == "__main__": + try: + main() + except (ValueError, OSError, subprocess.CalledProcessError) as error: + print(f"coverage_render_sweep: {error}", file=sys.stderr) + sys.exit(1) diff --git a/docs/raw/nikon-distortion-sweep.tsv b/docs/raw/nikon-distortion-sweep.tsv new file mode 100644 index 00000000000..f52a3610b1c --- /dev/null +++ b/docs/raw/nikon-distortion-sweep.tsv @@ -0,0 +1,46 @@ +# 2026-11-05 LR-EDIT-OPTICS-PROFILE production comparison; source behavior before/after Z 6 / Z 7 recognition. +# Base CLI SHA-256 e301181ff094a92827c2bc9ff5c87e1d2e6ea422bbff05a6fbc228dc58b17773; candidate CLI SHA-256 52fe2940ef26a0b3e3ca96c9d724dc887d0decb6487f036b369bd262015510bc +# CLI PNG 1200px; CPU; 6 Rayon threads; no lens database; largest embedded reference; recorded rotation; center crop-render; Lab L* 200px; outer rho>=0.75; pixel SHA256 includes WxH:RGB: and row-major RGB bytes; same frozen camera references for both runs. +# File and complete sensor hashes remain pinned in coverage-sweep.tsv. PreviewTIFF references are structural checks. +# 40 rows measured; six Z 6/Z 7 RGB outputs changed; other 34 dimensions and RGB bytes identical. +file file_sha256 base_rgb_sha256 candidate_rgb_sha256 reference_rgb_sha256 base_r candidate_r base_mean_dL candidate_mean_dL base_outer_mean_dL candidate_outer_mean_dL base_outer_mae_dL candidate_outer_mae_dL pixels_changed +coverage-915.dng 845fee4f09c832af3728778737f5ae9b99124debb821b6e2066b94aed1daa91c 7a209e6abf2f559079971fb5415eb1cfe114c3bbdee5eed1cc5b699e9e21dca5 7a209e6abf2f559079971fb5415eb1cfe114c3bbdee5eed1cc5b699e9e21dca5 025750081518c08900bae38bb90269981034b9da292b08899b0a689b11c38482 0.994525 0.994525 0.023243 0.023243 1.349133 1.349133 1.940318 1.940318 false +coverage-939.dng e8c7ebd8f22f7281d165496b91c8fea8a8e79c8113172fb499e1d66d6045332e dcce0cebb566f50a1abbf61ff6907771f14bf0ed7200e10b9d446129df10e8a4 dcce0cebb566f50a1abbf61ff6907771f14bf0ed7200e10b9d446129df10e8a4 68a7b1fc5aa21fd4ae6734779b4f39ed3e0512a7e93b82df30ebf5382968a599 0.992590 0.992590 0.064747 0.064747 0.874884 0.874884 2.152766 2.152766 false +coverage-3372.dng 50bc64ee8cfbbfb6c0531e29ab428ff985506a16fe2d1d2e74656f21b54505f6 a5cfa191df69bc333395e6850ebd38a0a01bfa58afad2731302d60e8a7838c52 a5cfa191df69bc333395e6850ebd38a0a01bfa58afad2731302d60e8a7838c52 b8f06d84b64cb320ded02fd2d1bf1277d5c21ef189633e7b591fb688d2f92e9c 0.990041 0.990041 -0.013535 -0.013535 -2.592615 -2.592615 2.761213 2.761213 false +coverage-3009.dng 7afecae0db80d832941eeeb3c0eb2dc03f5696637b6e78b3c592e8c002dce4ec 108f80dc0fad11fc8acd09bf7deaa7bfddd37deb6866d4fbcfd7b4b6a3e7f12d 108f80dc0fad11fc8acd09bf7deaa7bfddd37deb6866d4fbcfd7b4b6a3e7f12d 9bb7d66e80d1d1c455ad93b9d6985ffc737d4ced5ee9b3f21bdf0fd6e626e4df 0.986272 0.986272 0.074410 0.074410 0.427961 0.427961 2.322285 2.322285 false +coverage-5140.dng dbe98cb202f884ff11e0144899613b26d33cf9cddd9f1a62226f4352397f18e4 6d8f9f3156ae3b963a58f1fb4e660183f1c0c63b5b6f36e2917c96d5c15c71cd 6d8f9f3156ae3b963a58f1fb4e660183f1c0c63b5b6f36e2917c96d5c15c71cd ad4f9d1ada942aaaa9034ab49571f7c041fca3cf1e38ef6cf026ce42c120ee5e 0.867378 0.867378 0.412393 0.412393 1.767910 1.767910 13.341056 13.341056 false +coverage-8041.dng 901b7970f02f7197c782f111363feef02108f75811342d8cc4a2b66757bb7af0 5f8a433cd375e4043fb4bff8dd67dada28dc9565edd12c5104d3b14b02cd73dc 5f8a433cd375e4043fb4bff8dd67dada28dc9565edd12c5104d3b14b02cd73dc 3855315af444ab977dd003bfacfa711ed390ae6025ceb6d2af20c3dcfdff616b 0.684543 0.684543 2.559364 2.559364 0.909967 0.909967 14.285771 14.285771 false +coverage-4785.dng 21a49e63966f82391ca1188c7559c3acc01a35a89a70194fda4bf44cbd64a851 893e9cfe474a50b982c1fa23bdb0c1374ab5d967293a981f9d2b84fd3d22d28c 893e9cfe474a50b982c1fa23bdb0c1374ab5d967293a981f9d2b84fd3d22d28c 1d1ed98a0aad10449d1a1f2ddcf3125b3c504899c06cecbf32d6cf274db1e054 0.945065 0.945065 0.050662 0.050662 5.515994 5.515994 5.622163 5.622163 false +coverage-4898.dng fb4f294e12cab7b507fd0b7c07f24e5d13e7c0dd127b534ce12c48d644c9363d 8db8d6d620bdb3b6c7cc2b235e51749c4da540f77ca862fa8c193daea37fa70c 8db8d6d620bdb3b6c7cc2b235e51749c4da540f77ca862fa8c193daea37fa70c cb615ea124f3c5f9bc629d452447d1c4d14612b1636ed160c9a06431467ed9ab 0.983566 0.983566 0.060258 0.060258 2.427187 2.427187 2.930057 2.930057 false +coverage-3502.dng 0c03a6c93b4b8593cd0e4426166e6389710007238b82eb23861ef191322f0c54 b3c974f763f8e7777b6427e75a31fef742c0f427b1706a3da891a567b1e67766 b3c974f763f8e7777b6427e75a31fef742c0f427b1706a3da891a567b1e67766 1c864a9158ba114a7d3de6f369b861ff9bf9f10a4442ab1b1c1b18423b12ced3 0.947816 0.947816 0.570854 0.570854 0.216759 0.216759 3.516492 3.516492 false +coverage-4176.dng 11b38186ee3455376291bcdb3049728a3f9dcd94b9e82ff76855d9f3430e44be 8b2ce53b166c811fe88afed2e3fa110216f3ad8e565fe2e58ae7f701e7f7286b 8b2ce53b166c811fe88afed2e3fa110216f3ad8e565fe2e58ae7f701e7f7286b 84e23a04f63c5e7e43c9d7cb6b11814007c9419579a9595554dbce328687a461 0.968793 0.968793 1.163139 1.163139 1.424981 1.424981 5.727719 5.727719 false +coverage-5961.dng 3a859e917a91698a3e15ce3b3721a48a1fb1296873e0697d3bf7c2793297200d 7e6b2644160ee45f2c3da2a088d0e7e0554808be6582bad72390a893c2b0d4ac 7e6b2644160ee45f2c3da2a088d0e7e0554808be6582bad72390a893c2b0d4ac 31163985c5c6403dd75c5cadf7df512cbec56cc89045cf4b7bd8fa5d9b27b7fb 0.936571 0.936571 0.940841 0.940841 -0.299343 -0.299343 3.948523 3.948523 false +coverage-7751.dng 45420c595401547cca950ae58d552bc82b32d31ce1d58c082df33004016197f5 ee7ae0cf2fd093730a6e815f3456310f2efd1473c31fce8f1c47982306d710a6 ee7ae0cf2fd093730a6e815f3456310f2efd1473c31fce8f1c47982306d710a6 5fb260934ea749b272a8adb377c463fc00f1b9a4ac2018269b28117cc1c73ba4 0.967367 0.967367 -4.971174 -4.971174 -5.999716 -5.999716 6.089165 6.089165 false +coverage-7217.3fr e27ff177519298fe7bae64506b975190789dc0e6ad70bea58be7c78fd094eae0 35323b43a62a63645d6cf36fd4615f174d1771280227786c2abf3413aa0a3b1a 35323b43a62a63645d6cf36fd4615f174d1771280227786c2abf3413aa0a3b1a 54f4debd2642c16e61f59cd5192ddb103e3950f4fcde1dc84b28f193a35212d6 0.998485 0.998485 -14.212307 -14.212307 -14.035583 -14.035583 14.221253 14.221253 false +coverage-7218.fff c8d78912ae725a59acff42a4b4731350bbddd4a600423f319579261bd41da932 fda47ceeaec659e22fd1b7574dceb0f8bc0fa04ab13a9b603636130a49ac8e63 fda47ceeaec659e22fd1b7574dceb0f8bc0fa04ab13a9b603636130a49ac8e63 c0f369382f80118d5104e634970276b7dabf59198884284e75f61f8f09cfcb87 0.944791 0.944791 28.791157 28.791157 29.071434 29.071434 29.071434 29.071434 false +coverage-1640.fff 209d464e13702de5f4fdb830ac26ac140c98a8d0dc3e81c5ba61d93677330832 becd65d57b8d510029753e610bf16a9cbbee60ec4ca89188c13c78ac00afdb88 becd65d57b8d510029753e610bf16a9cbbee60ec4ca89188c13c78ac00afdb88 0fbdbebafe94faa3ee33c298dbc615ed74c3a468dfbbcb90083acf069a3be7d3 0.958222 0.958222 29.453605 29.453605 32.723201 32.723201 32.723201 32.723201 false +coverage-1639.fff 1aad9319fcbab81b851a74c3eeaa2a07fc5013bf2c4e272fd31d6419b6b9adb0 a1f8d7ce8ff254c3d0b23be4a8462a42451169b9fb84ea53cfbe6fd763cd3650 a1f8d7ce8ff254c3d0b23be4a8462a42451169b9fb84ea53cfbe6fd763cd3650 5513970776b1ea5c16963cb9e046ac60ec03da6123a5e33fa6445feda3555fa6 0.946932 0.946932 28.904472 28.904472 32.967622 32.967622 32.967622 32.967622 false +coverage-2058.3fr 395acb2c706dc10270c58ec261e42a5e36f6ac8c39d2a767e86e83648aa318a3 fed7a13cba1cd872b5586d6e682c5f70b6287fbd676bbbf90a110141e4084626 fed7a13cba1cd872b5586d6e682c5f70b6287fbd676bbbf90a110141e4084626 a73ed6b0caee244174f8bc1795b841e864b4086a246ce036613cc2903e9b91a1 0.977350 0.977350 -9.085600 -9.085600 -8.681743 -8.681743 9.397649 9.397649 false +coverage-3874.fff 8c2451b3478fb529b4e9bd51ed3267999ce26eb1fcb5c3b93c3ae7bc56267794 8afa3cd9159493673f3bce8173874d9d6e4c2b1deadef937abee40adfcccdddd 8afa3cd9159493673f3bce8173874d9d6e4c2b1deadef937abee40adfcccdddd 73822bd3d0f981beb0a3ec43b97d78b29d2a0f80095ee96f55cf9d2c0b12090a 0.943996 0.943996 22.447115 22.447115 22.000699 22.000699 22.000699 22.000699 false +coverage-3941.3fr 809d498263d6f07cbaa4b9a5be97933057b4ab21e7243bb7afbe3862f3b48b47 b2df3a195c3a0a049fdc1662ec16d5de09dac0c68b318fc5be44c5a83017d420 b2df3a195c3a0a049fdc1662ec16d5de09dac0c68b318fc5be44c5a83017d420 e18327d8683f48c59e88d9fd8471b8b0cdb0b52881b060b5faa5bd94757d2e89 0.998565 0.998565 -11.203822 -11.203822 -7.766498 -7.766498 8.314481 8.314481 false +coverage-6568.fff 44977fdaa3063eacbb2ac416dfb531bb4e3b96f3745d073dc49fb1ebcd78bedc 9d100472a075cf365d36c31518828645d44ac9f13fb8056eb173101cf639b410 9d100472a075cf365d36c31518828645d44ac9f13fb8056eb173101cf639b410 67c0c565242275455c393996145dfde6a6f007b095534be6b6ec07871ad458d1 0.919667 0.919667 26.519504 26.519504 23.618780 23.618780 23.618780 23.618780 false +coverage-6565.3fr dcc5a4abe3498e6f25e89bb491995fd12c3b669d9277c71b45b49210d3e56280 d93986c1ff36c4f7d25e9648b8274a84192fd12d3861da4bfabfabd235ac80a8 d93986c1ff36c4f7d25e9648b8274a84192fd12d3861da4bfabfabd235ac80a8 9d7c121e4c9bea513e8169c02bef5edcf4f7998d4e5a9411256a945a63975f82 0.996867 0.996867 -2.886130 -2.886130 -1.776552 -1.776552 6.132961 6.132961 false +coverage-4726.nef 3a098e704d0e1af97efc37541b43a37e5b3457d2f4e7828c0d8d9af37332f233 8d098d03b41f5fde10fde49ebb732a498074920d173ef9ac898afb7fa64d56c5 8d098d03b41f5fde10fde49ebb732a498074920d173ef9ac898afb7fa64d56c5 2b2a2b7f870d44f0292a33e38073eed219c102c92c40c48ae87530d9dfae2858 0.956144 0.956144 0.064876 0.064876 -2.685693 -2.685693 2.694906 2.694906 false +coverage-4720.nef 827bcfff8a3cd86278382c353e4542faab52cf12c365540f30753bb4c6fabc0f ffca536b76f824932a946718d5bb6bb2ce4076c970b4ab28f6fdc71c3d38dc31 ffca536b76f824932a946718d5bb6bb2ce4076c970b4ab28f6fdc71c3d38dc31 da9c3a96b7d1a0a5e9ac7c5570210c97485912d7c110ef3edfb427a6da56b4e0 0.959190 0.959190 0.056993 0.056993 -2.625904 -2.625904 2.630247 2.630247 false +coverage-4721.nef 081d5dbc1d6c97935020d33ffa486dcaa8d4564cbde280cfadcf26ff61da2838 b43c903ddfd3a1cd3e5cecaf25f8c4b2474ac55c561246af1006d1168e97e9ad b43c903ddfd3a1cd3e5cecaf25f8c4b2474ac55c561246af1006d1168e97e9ad 462a9b1967e75b8bd82e758a2ec48b3cff799f471b301a212107d2e3f0b41898 0.960036 0.960036 0.061219 0.061219 -2.706551 -2.706551 2.732903 2.732903 false +coverage-3584.nef 3cbd9acf9e9bfd7d0c62c46436109556a101f7535c5fd25f86dad6ea61bf3886 17c42ee6eba1f8d24eb72eae1a44ab93cf4f7efb4017840f72f43ac96ef105fe c4424647f0b6aa60d3e7af2f1adfaab7502b13946494a2e756e316181ce6bd83 29c387d28579714156eb5fbd3830b51ae629dd7f77381717a873c36edfe059ba 0.876903 0.996429 0.298957 0.173163 -3.478649 -1.608575 5.760813 1.807430 true +coverage-3581.nef 8ca94584578b35a422744c1a610174ce37df0691588edfdecaec3111b3fbbb02 9ce7b87b17a50d5bafbfa45629c89429ed4b86c80e7fd77f19854e3d21cd0f47 d2754186bee92f268fad485f776243b4f7b9329312db73c35dd97105dc0ae776 db8f4ab93ef278e3493942e28755bdd63fbba4fd6720589bf14c898a6af3804f 0.877158 0.996450 0.319627 0.196280 -3.470312 -1.610507 5.803838 1.813292 true +coverage-3582.nef c079345fc93f53a4f0d322f8ddaae505f920c36015f25b58befccaa61db1af31 5155b938b8b7d32bc6d14a1541115cc5336e396d3f309a2a41f76282a6bbac4a ed4916dbfd4c4506890c0b38517b0b332e583d26a5a535a3a3311e343ead36a2 6b1f9eca41d54dae3e1376a895edbb1148b9a4d243b711ef2ac1e5d289db843a 0.877491 0.996441 0.430047 0.212496 -3.431174 -1.591756 5.768369 1.802145 true +coverage-2792.nef c861546fbcf5826d5eb26d223e2143fa32968e89f7edbc5bb10c283ea5461ded b43d6cff9edef6b88a7195b74b2a77bf414c47aaa1a5ab7adfeb8dfa77b50fac a54d97b59794bfa3cf4addbd478e94d9755f97e1870ff24542c258bf3d9ec3cf 4671ff7911e5dc87ca8c6cd0be1243bf8e7bca0b0a876b84af1cb1b4827ec8a4 0.749706 0.991416 1.923504 1.214512 -2.982260 -2.068134 6.521320 2.357019 true +coverage-2789.nef e54a6c4264bf685214f538036fd9d39088e510b2bfedf288e568f0db1897880e 0c56854e80f00b1cf9d975573b7b0bea06afe7b831560ceadca7402f457298c5 e517bca9c4946627aaa46cc28098563ca23557baf423a941396399d853c57f90 c7477c44dae576b978f8dbefa14f04347a5f4cee48a0f1c1f5f986bf8ff62c94 0.748283 0.990996 2.187907 1.271131 -2.880651 -2.028002 6.456293 2.332397 true +coverage-2790.nef f0e756dbfd00f3b71cb3d8aa5b9e2e1be32f1052a6c4380e09ebc7c5e7748114 61af749d6152e9b3540b4a0f7e2e288e350d0b448903aa1fe3001e6e0dc26572 e2640a31f3e7d1deb8eed81387b62a8dce11f397138c8910cd26fdf37375adb0 3e2a0bf55ff59efcf72cd561ae8de0970e88f52190255214265778132146e044 0.748047 0.990970 2.239679 1.251089 -2.868331 -2.072744 6.472221 2.357066 true +coverage-6617.nef c13a8675294456b9c979e6c1e556951654f35377b2870af2874bfb556f21ce40 4f0756ffcae51fd896c73ee019d62cbd6a1a7e39b37c640c5e7bb89b732ac988 4f0756ffcae51fd896c73ee019d62cbd6a1a7e39b37c640c5e7bb89b732ac988 279cabf15e6ad15482453bf5d25117ba9a7b0c3fd85988939d429e12409f471a 0.996314 0.996314 1.493065 1.493065 -0.110194 -0.110194 1.171614 1.171614 false +coverage-2912.dng a257a296047ff2d396109fd2e6947fa36aa7986695b6815f83979d59e98a84e6 519395f487c52edaf368fb3f1a925372085abca790e4b07530edad1ca69ddcf2 519395f487c52edaf368fb3f1a925372085abca790e4b07530edad1ca69ddcf2 1f006eef44b6949f3669cd37b886f3ac0c44be0563f0184b78d6d136abee86dc 0.989430 0.989430 -3.942714 -3.942714 -5.085409 -5.085409 11.126564 11.126564 false +coverage-6728.dng 5baeb5f0c4a125647df03b82c2d38b0f02784393bd39eff1a5b23d8f5308dc5e 75ee31bf22b15c881961517fb73e645b628c48ecbd1bd7a6d2b8e5c34a52e9fe 75ee31bf22b15c881961517fb73e645b628c48ecbd1bd7a6d2b8e5c34a52e9fe 003dc9b81080222b8e6145afeac5bad87988cc1c6fb35a16a7f7b96da3eb8692 0.991086 0.991086 -10.932121 -10.932121 -9.837630 -9.837630 11.280033 11.280033 false +coverage-6261.dng 53e7f83a94c965495ba32d3ea6021ef08ed02244ce64d111d1329bbd01fd5581 1f4032f72781100b065f83500575218aa161fc9e0ae26e2f54fe62734f8f5e53 1f4032f72781100b065f83500575218aa161fc9e0ae26e2f54fe62734f8f5e53 0edff2c82bf144274cdbddd93a9acbb9a9719b62cd71fc78a2da204dd783f9a9 0.971932 0.971932 -20.542994 -20.542994 -22.129382 -22.129382 22.141729 22.141729 false +coverage-6697.dng 1c04574f32b5a139922f075291c52018b89d9981ee155a16958a231c1fdbb067 01e299e62d05538eaff576b5e724d9621d20123cbeef23518616d0e0e6de4e90 01e299e62d05538eaff576b5e724d9621d20123cbeef23518616d0e0e6de4e90 e40bf6a52bee99f9cdc81df6271b8f684895e685668f09320d4ac5d8c3fe9485 0.940795 0.940795 -6.648589 -6.648589 -6.678374 -6.678374 8.360162 8.360162 false +coverage-1297.dng 843617c8b572320b7badfb4ac2eda19479f5804a1dabb909c861bde23ed30561 106b451517956a4f3d21e1672dddc5b79bd63bc3a72e7441a258da1202dba5ec 106b451517956a4f3d21e1672dddc5b79bd63bc3a72e7441a258da1202dba5ec 355198c8da6c76081090e58aebd69a8b667e4fee6d031517305a736c468d9512 0.960372 0.960372 5.595697 5.595697 3.799795 3.799795 9.538383 9.538383 false +coverage-2645.dng 6abdd353094964eaadddf69bba3a0d551ecce1bc0ed013a434691df4f64dcbf2 cbf2aadcbea4d5cdb0331082f9e4e2408710c0ae7474e0021908dd61a4dd8a83 cbf2aadcbea4d5cdb0331082f9e4e2408710c0ae7474e0021908dd61a4dd8a83 3f50665d67fdc25aa7414f682b1e72d6a43f5c7d9b4fd49254589ec173e49c73 0.994782 0.994782 -4.198611 -4.198611 -6.485769 -6.485769 10.362222 10.362222 false +coverage-2310.dng 3cf5da4331d062bc6b31e0e8f5b7ff2cd21107de4262d79a2667f670516e8e8c abe8402607c962d21af883a9c997aae23cde0f1de48f918019437c3665a15ece abe8402607c962d21af883a9c997aae23cde0f1de48f918019437c3665a15ece 9a5a89387b45c8111b372a2c4950b7c91458182defa7fee8b70d650467e1fab2 0.989490 0.989490 2.369332 2.369332 -0.560246 -0.560246 12.247120 12.247120 false +coverage-7273.dng 0844bcf23a49e21b5c2f8489de55ce38fb7b594e3ed337d6b9af2dd9341354e9 d7fd47cfba2b95497754f59dbdb59d22c7fb8fe6aebdbea852761ef2a5e2af7f d7fd47cfba2b95497754f59dbdb59d22c7fb8fe6aebdbea852761ef2a5e2af7f 088b5ca56d6a6ce6fd3b4e7ae0eaa4c5a95932965b44350bf4da2f52b7b3a23b 0.974843 0.974843 7.036398 7.036398 8.006018 8.006018 8.044602 8.044602 false +coverage-6949.dng 8e7229f28be30bfa45289940eac04194af2b3474f6db286e4fa4070c145a0a70 ae75f7d9b6da146cc2a0803406a2407c0cc570d6e0e9eceb33c418ac079384fc ae75f7d9b6da146cc2a0803406a2407c0cc570d6e0e9eceb33c418ac079384fc b1e55b1ab3b856b21adb83908553c5df37c12680b8e8e3b5dc4b5db7612ace24 0.999881 0.999881 1.579304 1.579304 1.452400 1.452400 1.452400 1.452400 false From 622c34572ad902422ad186ea58f20769d0034b4e Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Thu, 5 Nov 2026 14:05:10 +0100 Subject: [PATCH 05/14] LR-EDIT-OPTICS-PROFILE: harden lens measurement tooling Reject duplicate candidate warp and vignette opcodes instead of silently measuring only the first. Create missing lens-database directory parents and validate cached PNGs before resuming a render sweep. Score PreviewTIFF references for structure without sRGB colour errors. Require matching baseline input identities and metric kinds before deltas, and retain colour regression gates for display-referred references. Add synthetic Python coverage and a Rust example regression. Production rendering is unchanged. Co-authored-by: Codex --- crates/engine/examples/nikon_lens_probe.rs | 18 ++ docs/raw/coverage_render_sweep.py | 100 +++++++++-- docs/raw/test_coverage_render_sweep.py | 198 +++++++++++++++++++++ 3 files changed, 300 insertions(+), 16 deletions(-) create mode 100644 docs/raw/test_coverage_render_sweep.py diff --git a/crates/engine/examples/nikon_lens_probe.rs b/crates/engine/examples/nikon_lens_probe.rs index eb31a5909b2..8214a9ce90d 100644 --- a/crates/engine/examples/nikon_lens_probe.rs +++ b/crates/engine/examples/nikon_lens_probe.rs @@ -69,6 +69,11 @@ fn validate_candidates(ops: &[lightcraft_raw::Opcode]) -> Result<(), &'static st if ops.is_empty() || ops.len() > 2 { return Err("provide one or two lens opcodes"); } + if ops.iter().filter(|op| matches!(op, Opcode::WarpRectilinear { .. })).count() > 1 + || ops.iter().filter(|op| matches!(op, Opcode::FixVignetteRadial { .. })).count() > 1 + { + return Err("provide at most one warp and one radial vignette"); + } for op in ops { let center = match op { Opcode::WarpRectilinear { planes, center } if planes.len() == 1 && planes.iter().flatten().all(|v| v.is_finite() && v.abs() <= 16.0) => { @@ -105,6 +110,19 @@ fn render(source: &Rgb32f, info: &SourceInfo, settings: &DevelopSettings, path: mod tests { use super::*; + #[test] + fn candidates_reject_duplicate_kinds_and_accept_one_of_each() { + use lightcraft_raw::Opcode; + let warp = Opcode::WarpRectilinear { planes: vec![[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }; + let vignette = Opcode::FixVignetteRadial { k: [0.0; 5], center: [0.5, 0.5] }; + assert!(validate_candidates(std::slice::from_ref(&warp)).is_ok()); + assert!(validate_candidates(std::slice::from_ref(&vignette)).is_ok()); + assert!(validate_candidates(&[warp.clone(), vignette.clone()]).is_ok()); + assert!(validate_candidates(&[vignette.clone(), warp.clone()]).is_ok()); + assert_eq!(validate_candidates(&[warp.clone(), warp]), Err("provide at most one warp and one radial vignette")); + assert_eq!(validate_candidates(&[vignette.clone(), vignette]), Err("provide at most one warp and one radial vignette")); + } + /// A hostile stream must be rejected after at most limit + 1 bytes, without reading to EOF. #[test] fn candidate_reader_bounds_the_read_and_accepts_the_exact_limit() { diff --git a/docs/raw/coverage_render_sweep.py b/docs/raw/coverage_render_sweep.py index 12ee2d0e46d..3a77589bb4d 100644 --- a/docs/raw/coverage_render_sweep.py +++ b/docs/raw/coverage_render_sweep.py @@ -10,14 +10,81 @@ reference images and framing. Existing PNGs allow an interrupted run to resume. Inputs are only the SHA-256-pinned public corpus rows. Images and binary copies stay in gitignored corpus; commit the numerical evidence separately. PreviewTIFF -rows remain image-structure checks rather than display-ready colour references. +rows use encoded-luminance correlation for structure only, with no sRGB transfer +or colour-error metrics. Older PreviewTIFF baseline scores must be regenerated +with this tool; valid cached PNGs can be reused. """ -import argparse, csv, hashlib, io, json, os, subprocess, sys +import argparse, csv, hashlib, io, json, math, os, subprocess, sys from pathlib import Path +import numpy as np from PIL import Image, ImageOps from nikon_lens_probe import score +def readable_png(path): + """Only a complete, decodable PNG can stand in for a completed render.""" + try: + with Image.open(path) as image: + if image.format != "PNG": + return False + image.verify() + with Image.open(path) as image: + image.load() + return True + except (OSError, ValueError, SyntaxError, Image.DecompressionBombError): + return False + + +def measure_pair(render, reference, structure_only): + if not structure_only: + return score(render, reference) + # Unknown TIFF encoding: compare spatial luminance without assuming an sRGB transfer function. + if reference.width <= 0 or reference.height <= 0: + raise ValueError("structure reference dimensions must be positive") + height = round(reference.height * 200 / reference.width) + if not 1 <= height <= 2000: + raise ValueError("structure reference aspect ratio exceeds the scoring limit") + size = (200, height) + a, b = [ + np.asarray(ImageOps.grayscale(image).resize(size, Image.Resampling.LANCZOS), dtype=float) + for image in (render, reference) + ] + if np.std(a) < 1e-8 or np.std(b) < 1e-8: + raise ValueError("cannot correlate a constant structure image") + return dict(r=float(np.corrcoef(a.ravel(), b.ravel())[0, 1])) + + +def compare_record(name, record, base): + """Compare scores only after confirming that both runs measured the same inputs.""" + if not isinstance(base, dict): + raise ValueError("baseline record missing or invalid: " + name) + for key in ("file_sha256", "reference_sha256", "reference_size", "reference", "rotation"): + if base.get(key) != record[key]: + raise ValueError("baseline " + key + " differs: " + name) + if base.get("metric_kind", "lab_lstar") != record["metric_kind"]: + raise ValueError("baseline metric_kind differs; regenerate baseline scores: " + name) + keys = ("r", "mean_dl", "outer_mae_dl") if record["metric_kind"] == "lab_lstar" else ("r",) + for key in keys: + value = base.get(key) + if type(value) not in (int, float) or not math.isfinite(value): + raise ValueError("baseline " + key + " is missing or non-finite: " + name) + if not isinstance(base.get("pixel_sha256"), str): + raise ValueError("baseline pixel_sha256 is missing or invalid: " + name) + record["pixels_changed"] = record["pixel_sha256"] != base["pixel_sha256"] + record["delta_r"] = record["r"] - base["r"] + if record["metric_kind"] == "lab_lstar": + record["delta_abs_mean_dl"] = abs(record["mean_dl"]) - abs(base["mean_dl"]) + + +def metrics_regressed(record, base): + if record["r"] < base["r"] - 1e-9: + return True + return record["metric_kind"] == "lab_lstar" and ( + abs(record["mean_dl"]) > abs(base["mean_dl"]) + 1e-9 + or record["outer_mae_dl"] > base["outer_mae_dl"] + 1e-9 + ) + + def main(): p = argparse.ArgumentParser() p.add_argument("--cli", type=Path, required=True) @@ -36,8 +103,12 @@ def main(): ) ) previous = json.loads(a.compare.read_text())["records"] if a.compare else None + if previous is not None and ( + not isinstance(previous, dict) or set(previous) != {row["file"] for row in rows} + ): + raise ValueError("baseline input files differ from the coverage manifest") empty = Path("corpus/nikon-lens/empty-lensdb").resolve() - empty.mkdir(exist_ok=True) + empty.mkdir(parents=True, exist_ok=True) env = dict( os.environ, LIGHTCRAFT_GPU="0", @@ -65,7 +136,7 @@ def main(): raise ValueError("SHA-256 mismatch " + row["file"]) out = a.out / (raw.stem + ".png") ref = (a.compare.parent if a.compare else a.out) / (raw.stem + "-reference.png") - if not out.exists(): + if not readable_png(out): with (a.out / (raw.stem + ".log")).open("w") as log: subprocess.run( [str(a.cli), "render", str(raw), "-o", str(out), "--size", "1200"], @@ -143,28 +214,27 @@ def main(): method=Image.Resampling.LANCZOS, centering=(0.5, 0.5), ) - measured = score(framed, reference) + structure_only = "PreviewTIFF" in row["reference"] + measured = measure_pair(framed, reference, structure_only) record = dict( file_sha256=digest, pixel_sha256=pixel_sha, render_size=rendered.size, reference=row["reference"], reference_sha256=hashlib.sha256(reference.tobytes()).hexdigest(), - reference_size=reference.size, + reference_size=list(reference.size), rotation=rotation, + metric_kind="structure_luma" if structure_only else "lab_lstar", **measured, ) - if previous: - base = previous[row["file"]] - record["pixels_changed"] = pixel_sha != base["pixel_sha256"] - record["delta_r"] = record["r"] - base["r"] - record["delta_abs_mean_dl"] = abs(record["mean_dl"]) - abs(base["mean_dl"]) + if previous is not None: + compare_record(row["file"], record, previous.get(row["file"])) results[row["file"]] = record (a.out / "scores.json").write_text( json.dumps( dict( cli_sha256=cli_sha, - method="CLI PNG 1200px; CPU; 6 Rayon threads; no lens database; largest embedded reference; recorded rotation; center crop-render; Lab L* 200px; outer rho>=0.75; pixel SHA256 includes WxH:RGB: and row-major RGB bytes", + method="CLI PNG 1200px; CPU; 6 Rayon threads; no lens database; largest embedded reference; recorded rotation; center crop-render; Lab L* 200px for display references, encoded-luminance r only for PreviewTIFF; outer rho>=0.75; pixel SHA256 includes WxH:RGB: and row-major RGB bytes", records=results, ), indent=2, @@ -174,13 +244,11 @@ def main(): ) print(row["file"], json.dumps(record, allow_nan=False), flush=True) - if previous: + if previous is not None: regressions = [ name for name, record in results.items() - if record["r"] < previous[name]["r"] - 1e-9 - or abs(record["mean_dl"]) > abs(previous[name]["mean_dl"]) + 1e-9 - or record["outer_mae_dl"] > previous[name]["outer_mae_dl"] + 1e-9 + if metrics_regressed(record, previous[name]) ] if regressions: raise ValueError( diff --git a/docs/raw/test_coverage_render_sweep.py b/docs/raw/test_coverage_render_sweep.py new file mode 100644 index 00000000000..801db9b093a --- /dev/null +++ b/docs/raw/test_coverage_render_sweep.py @@ -0,0 +1,198 @@ +"""Synthetic sweep-tool checks, with no corpus or external renderer required. + +Run: python3 -m unittest discover -s docs/raw -p 'test_*.py' +""" + +import copy +import csv +import hashlib +import io +import json +import os +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +import numpy as np +from PIL import Image + +import coverage_render_sweep as sweep + + +def gradient(): + values = np.tile(np.arange(20, 220, 4, dtype=np.uint8), (32, 1)) + return Image.fromarray(np.repeat(values[..., None], 3, axis=-1)) + + +class Measurements(unittest.TestCase): + def test_preview_tiff_uses_structure_without_srgb_colour_metrics(self): + image = gradient() + with mock.patch.object(sweep, "score", side_effect=AssertionError("colour scorer must not run")): + measured = sweep.measure_pair(image, image, True) + self.assertEqual(set(measured), {"r"}) + self.assertAlmostEqual(measured["r"], 1) + with self.assertRaisesRegex(ValueError, "constant structure"): + sweep.measure_pair(Image.new("RGB", (32, 32)), image, True) + with self.assertRaisesRegex(ValueError, "aspect ratio"): + sweep.measure_pair(image, Image.new("RGB", (1, 11)), True) + with self.assertRaisesRegex(ValueError, "dimensions"): + sweep.measure_pair(image, Image.new("RGB", (0, 1)), True) + + def test_display_references_keep_the_existing_colour_scorer(self): + image = gradient() + self.assertEqual(sweep.measure_pair(image, image, False), sweep.score(image, image)) + + def test_structure_gate_ignores_colour_errors_but_keeps_correlation(self): + base = dict(r=0.9, mean_dl=0, outer_mae_dl=0) + candidate = dict(metric_kind="structure_luma", r=0.95, mean_dl=100, outer_mae_dl=100) + self.assertFalse(sweep.metrics_regressed(candidate, base)) + self.assertTrue(sweep.metrics_regressed(dict(candidate, r=0.8), base)) + self.assertTrue(sweep.metrics_regressed(dict(candidate, metric_kind="lab_lstar"), base)) + self.assertTrue(sweep.metrics_regressed(dict(candidate, metric_kind="lab_lstar", mean_dl=0), base)) + + def test_baseline_inputs_are_checked_before_any_deltas(self): + current = dict( + file_sha256="a" * 64, + reference_sha256="b" * 64, + reference_size=[50, 32], + reference="embedded JPEG", + rotation=0, + metric_kind="lab_lstar", + pixel_sha256="c" * 64, + r=0.95, + mean_dl=0.1, + outer_mae_dl=0.2, + ) + changes = dict( + file_sha256="d" * 64, + reference_sha256="e" * 64, + reference_size=[32, 50], + reference="exiftool:PreviewTIFF", + rotation=180, + metric_kind="structure_luma", + ) + for key, wrong in changes.items(): + for value in (wrong, None): + with self.subTest(key=key, value=value): + record = copy.deepcopy(current) + base = dict(current, **{key: value}) + with self.assertRaisesRegex(ValueError, "baseline " + key + ".*sample.nef"): + sweep.compare_record("sample.nef", record, base) + self.assertNotIn("delta_r", record) + base = json.loads(json.dumps(current)) + del base["metric_kind"] # Existing display-reference baseline records remain compatible. + sweep.compare_record("sample.nef", current, base) + self.assertEqual(current["delta_r"], 0) + self.assertEqual(current["delta_abs_mean_dl"], 0) + self.assertFalse(current["pixels_changed"]) + + def test_old_tiff_metrics_and_nonfinite_baselines_are_rejected(self): + record = dict( + file_sha256="a", reference_sha256="b", reference_size=[50, 32], + reference="exiftool:PreviewTIFF", rotation=0, metric_kind="structure_luma", + pixel_sha256="c", r=1, + ) + old = dict(record) + del old["metric_kind"] + with self.assertRaisesRegex(ValueError, "regenerate baseline"): + sweep.compare_record("sample.fff", record, old) + for value in (float("nan"), float("inf"), None, "1"): + with self.subTest(value=value), self.assertRaisesRegex(ValueError, "baseline r"): + sweep.compare_record("sample.fff", record, dict(record, r=value)) + with self.assertRaisesRegex(ValueError, "baseline record missing"): + sweep.compare_record("sample.fff", record, None) + + +class Resume(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + previous = Path.cwd() + self.addCleanup(os.chdir, previous) + os.chdir(self.temp.name) + self.cli = Path("renderer") + self.cli.write_bytes(b"synthetic renderer identity") + self.output = Path("elsewhere/output") + self.fields = ["file", "sha256", "reference", "notes"] + Path("docs/raw").mkdir(parents=True) + + def manifest(self, rows): + with Path("docs/raw/coverage-sweep.tsv").open("w") as stream: + writer = csv.DictWriter(stream, fieldnames=self.fields, delimiter="\t") + writer.writeheader() + writer.writerows(rows) + + def invoke(self, extra=()): + with mock.patch("sys.argv", ["sweep", "--cli", str(self.cli), "--out", str(self.output), *extra]), mock.patch("builtins.print"): + sweep.main() + + def prepare_sample(self): + raw = Path("corpus/raw/sample.nef") + raw.parent.mkdir(parents=True) + raw.write_bytes(b"original synthetic input") + self.manifest([dict(file=raw.name, sha256=hashlib.sha256(raw.read_bytes()).hexdigest(), reference="embedded JPEG", notes="")]) + self.output.mkdir(parents=True) + gradient().save(self.output / "sample-reference.png") + return self.output / "sample.png" + + def test_missing_lens_database_parents_are_created_with_an_external_output(self): + self.manifest([]) + self.assertFalse(Path("corpus").exists()) + self.invoke() + self.assertTrue(Path("corpus/nikon-lens/empty-lensdb").is_dir()) + + def test_readable_png_rejects_partial_corrupt_and_non_png_files(self): + path = Path("cached.png") + buffer = io.BytesIO() + gradient().save(buffer, format="PNG") + data = buffer.getvalue() + self.assertFalse(sweep.readable_png(path)) + corrupt = bytearray(data) + corrupt[29] ^= 1 # Corrupt the IHDR CRC while preserving the pixel stream. + for bad in (b"", data[:24], data[:-12], bytes(corrupt)): + with self.subTest(length=len(bad)): + path.write_bytes(bad) + self.assertFalse(sweep.readable_png(path)) + gradient().save(path, format="JPEG") + self.assertFalse(sweep.readable_png(path)) + path.write_bytes(data) + self.assertTrue(sweep.readable_png(path)) + + def test_valid_cached_render_is_reused_and_empty_render_is_rebuilt(self): + output = self.prepare_sample() + gradient().save(output) + with mock.patch.object(sweep.subprocess, "run") as run: + self.invoke() + run.assert_not_called() + output.write_bytes(b"") + def render(args, **kwargs): + gradient().save(args[args.index("-o") + 1]) + with mock.patch.object(sweep.subprocess, "run", side_effect=render) as run: + self.invoke() + run.assert_called_once() + self.assertTrue(sweep.readable_png(output)) + + def test_preview_tiff_run_records_structure_only(self): + output = self.prepare_sample() + gradient().save(output) + raw = Path("corpus/raw/sample.nef") + self.manifest([dict(file=raw.name, sha256=hashlib.sha256(raw.read_bytes()).hexdigest(), reference="exiftool:PreviewTIFF", notes="")]) + with mock.patch.object(sweep, "score", side_effect=AssertionError("colour scorer must not run")): + self.invoke() + record = json.loads((self.output / "scores.json").read_text())["records"][raw.name] + self.assertEqual(record["metric_kind"], "structure_luma") + self.assertAlmostEqual(record["r"], 1) + self.assertNotIn("mean_dl", record) + self.assertNotIn("outer_mae_dl", record) + + def test_a_baseline_with_different_input_files_is_rejected(self): + self.manifest([]) + baseline = Path("baseline.json") + baseline.write_text(json.dumps(dict(records={"another.nef": {}}))) + with self.assertRaisesRegex(ValueError, "baseline input files differ"): + self.invoke(["--compare", str(baseline)]) + + +if __name__ == "__main__": + unittest.main() From d1ed0ac845f65bd886c9555598f2729ce7d38f24 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Thu, 5 Nov 2026 15:16:30 +0100 Subject: [PATCH 06/14] LR-EDIT-OPTICS-PROFILE: key sweep caches by input digest Include the full input SHA-256 in render, reference and log names so a new manifest pin cannot reuse pixels from another input with the same stem. Ignore legacy stem-only caches and preserve reuse for identical inputs. Add a synthetic regression for changed pins, same-stem files, unchanged input reuse and comparison-mode reference reuse. Production is unchanged. Co-authored-by: Codex --- docs/raw/coverage_render_sweep.py | 8 +++-- docs/raw/test_coverage_render_sweep.py | 48 ++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/docs/raw/coverage_render_sweep.py b/docs/raw/coverage_render_sweep.py index 3a77589bb4d..896a40e9f3a 100644 --- a/docs/raw/coverage_render_sweep.py +++ b/docs/raw/coverage_render_sweep.py @@ -13,6 +13,7 @@ rows use encoded-luminance correlation for structure only, with no sRGB transfer or colour-error metrics. Older PreviewTIFF baseline scores must be regenerated with this tool; valid cached PNGs can be reused. +Cache filenames include the input SHA-256. Legacy stem-only caches are ignored. """ import argparse, csv, hashlib, io, json, math, os, subprocess, sys from pathlib import Path @@ -134,10 +135,11 @@ def main(): digest = hashlib.sha256(raw.read_bytes()).hexdigest() if digest != row["sha256"]: raise ValueError("SHA-256 mismatch " + row["file"]) - out = a.out / (raw.stem + ".png") - ref = (a.compare.parent if a.compare else a.out) / (raw.stem + "-reference.png") + cache_stem = raw.stem + "-" + digest + out = a.out / (cache_stem + ".png") + ref = (a.compare.parent if a.compare else a.out) / (cache_stem + "-reference.png") if not readable_png(out): - with (a.out / (raw.stem + ".log")).open("w") as log: + with (a.out / (cache_stem + ".log")).open("w") as log: subprocess.run( [str(a.cli), "render", str(raw), "-o", str(out), "--size", "1200"], env=env, diff --git a/docs/raw/test_coverage_render_sweep.py b/docs/raw/test_coverage_render_sweep.py index 801db9b093a..cab68e39b86 100644 --- a/docs/raw/test_coverage_render_sweep.py +++ b/docs/raw/test_coverage_render_sweep.py @@ -133,8 +133,9 @@ def prepare_sample(self): raw.write_bytes(b"original synthetic input") self.manifest([dict(file=raw.name, sha256=hashlib.sha256(raw.read_bytes()).hexdigest(), reference="embedded JPEG", notes="")]) self.output.mkdir(parents=True) - gradient().save(self.output / "sample-reference.png") - return self.output / "sample.png" + cache_stem = raw.stem + "-" + hashlib.sha256(raw.read_bytes()).hexdigest() + gradient().save(self.output / (cache_stem + "-reference.png")) + return self.output / (cache_stem + ".png") def test_missing_lens_database_parents_are_created_with_an_external_output(self): self.manifest([]) @@ -173,6 +174,49 @@ def render(args, **kwargs): run.assert_called_once() self.assertTrue(sweep.readable_png(output)) + def test_changed_input_cannot_reuse_same_stem_pixels_or_references(self): + output = self.prepare_sample() + gradient().save(output) + self.invoke() + baseline = self.output / "scores.json" + for name in ("sample.nef", "sample.dng"): + with self.subTest(name=name): + raw = Path("corpus/raw") / name + raw.write_bytes(("replacement input " + name).encode()) + digest = hashlib.sha256(raw.read_bytes()).hexdigest() + self.manifest([dict(file=name, sha256=digest, reference="embedded JPEG", notes="")]) + image = gradient().transpose(Image.Transpose.FLIP_LEFT_RIGHT) + buffer = io.BytesIO() + image.save(buffer, format="PNG") + def render(args, **kwargs): + image.save(args[args.index("-o") + 1]) + def extract(args, **kwargs): + return buffer.getvalue() if "-JpgFromRaw" in args else b"" + with mock.patch.object(sweep.subprocess, "run", side_effect=render) as run, mock.patch.object(sweep.subprocess, "check_output", side_effect=extract) as extract_call: + self.invoke() + run.assert_called_once() + self.assertEqual(extract_call.call_count, 3) + self.assertEqual(Path(run.call_args.args[0][run.call_args.args[0].index("-o") + 1]).name, "sample-" + digest + ".png") + self.assertTrue((self.output / ("sample-" + digest + ".log")).is_file()) + reference = self.output / ("sample-" + digest + "-reference.png") + with Image.open(reference) as cached: + self.assertEqual(cached.tobytes(), image.tobytes()) + record = json.loads(baseline.read_text())["records"][name] + self.assertEqual(record["file_sha256"], digest) + self.assertEqual(record["reference_sha256"], hashlib.sha256(image.tobytes()).hexdigest()) + with mock.patch.object(sweep.subprocess, "run") as run, mock.patch.object(sweep.subprocess, "check_output") as extract_call: + self.invoke() + run.assert_not_called() + extract_call.assert_not_called() + self.output = Path("candidate") + with mock.patch.object(sweep.subprocess, "run", side_effect=render) as run, mock.patch.object(sweep.subprocess, "check_output") as extract_call: + self.invoke(["--compare", str(baseline)]) + run.assert_called_once() + extract_call.assert_not_called() + record = json.loads((self.output / "scores.json").read_text())["records"][name] + self.assertFalse(record["pixels_changed"]) + self.assertEqual(record["delta_r"], 0) + def test_preview_tiff_run_records_structure_only(self): output = self.prepare_sample() gradient().save(output) From eae8538756f6e8c2b4913b84d886306a3075ca77 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Fri, 6 Nov 2026 16:50:22 +0100 Subject: [PATCH 07/14] LR-EDIT-OPTICS-PROFILE: refresh the parity summary after the merge --- docs/parity-checklist.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index d77b506beb6..58810841323 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -31,7 +31,7 @@ cited here still exists. Formerly docs/parity.md. | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | -| F. Edit panel — global adjustments (EDIT) | 41 | 5 | 3 | 1 | 25/28 (89%) | 13/14 (93%) | +| F. Edit panel — global adjustments (EDIT) | 42 | 5 | 3 | 1 | 25/28 (89%) | 14/15 (93%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | | H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | @@ -51,11 +51,11 @@ cited here still exists. Formerly docs/parity.md. | W. Cloud & AI infrastructure (CLOUD / AI) | 1 | 0 | 1 | 2 | — | — | | X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) | | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | -| Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | +| Z. Keyboard shortcuts (desktop) | 77 | 5 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 41 | 26 | 21 | 8 | — | 24/27 (89%) | -| **Total** | 417 | 70 | 57 | 35 | 192/203 (95%) | 146/162 (90%) | +| **Total** | 419 | 70 | 57 | 35 | 193/203 (95%) | 147/163 (90%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.1%** of 544 in-scope rows — P0 97.3% of 203 · P1 94.1% of 162 · P2 56.7% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.2%** of 546 in-scope rows — P0 97.5% of 203 · P1 94.2% of 163 · P2 56.7% of 179. ## Top gaps and shortcut notes From ce0638aa854051de4059660b6ec21f686d3eda1b Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Fri, 6 Nov 2026 21:05:32 +0100 Subject: [PATCH 08/14] LR-EDIT-OPTICS-PROFILE: the wire job test is main's again, which #3782 changed the same way --- apps/lightcraft-web/src/wire.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/apps/lightcraft-web/src/wire.rs b/apps/lightcraft-web/src/wire.rs index 5a3028222c9..e7202bbc594 100644 --- a/apps/lightcraft-web/src/wire.rs +++ b/apps/lightcraft-web/src/wire.rs @@ -455,7 +455,7 @@ mod tests { } #[test] - fn wire_job_renders_like_the_engine_cpu() { + fn wire_job_renders_like_the_engine() { let mut s = Session::with_demo(); let id = s.visible_cloned()[0]; s.execute("library.select", &serde_json::json!({"ids": [id.0]})).unwrap(); @@ -468,10 +468,11 @@ mod tests { let mut core = WorkerCore::default(); assert_eq!(core.needs_original(&wire), None, "demo scenes are generated"); let a = core.render(&wire, None).unwrap(); - // Keep the wire round-trip comparison exact on the same backend. The window test above - // compares the worker with a native job, which can use the GPU and its rounding budget. + // The worker uses the CPU. A native thumbnail job may use an already initialized GPU, + // so exact serialization parity must use the engine's CPU reference (#3778), regardless + // of test order. The window test above separately checks native CPU/GPU equivalence. let source = job.source.load_source().unwrap(); - let b = lightcraft_engine::pipeline::render(&source.image, &source.info_or(job.info.clone()), &job.settings, &job.request); + let b = lightcraft_engine::pipeline::render(&source.image, &source.info_or(job.info), &job.settings, &job.request); assert_eq!((a.image.width, a.image.height), (b.image.width, b.image.height)); assert_eq!(a.image.data, b.image.data); assert_eq!(a.histogram, b.histogram); From 44b3d91ab60c7e4c28421a9e7aba7d7cb56587b9 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Wed, 11 Nov 2026 13:52:13 +0100 Subject: [PATCH 09/14] LR-EDIT-OPTICS-PROFILE: LOOK_VERSION 28, since open #3943 takes 26 and #3429 takes 27 --- crates/engine/src/camera_preview.rs | 6 +++--- docs/nikon-lens-corrections.md | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index 1576aa974a5..4bc15f2fd41 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -84,9 +84,9 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights}; /// 13: the sensor proxy of every per-file fit gets the embedded vignetting correction the render applies (Fujifilm /// RAF; other makes with a lens database), so the render no longer applies it twice, at the position a lens warp samples; /// the warped candidate's alignment leaves out the pixels outside the sensor instead of reading them as black. -/// 26: Nikon Z 6 / Z 7 distortion enters the fitting geometry; Nikon mode 2 Off no longer supplies a warp. -/// Versions through 25 are assigned by other open PRs. Later look changes must renumber above the landed version. -pub const LOOK_VERSION: u32 = 26; +/// 28: Nikon Z 6 / Z 7 distortion enters the fitting geometry; Nikon mode 2 Off no longer supplies a warp. +/// Versions through 27 are assigned by other open PRs. Later look changes must renumber above the landed version. +pub const LOOK_VERSION: u32 = 28; #[derive(Clone, Debug)] pub(crate) struct CameraLook { diff --git a/docs/nikon-lens-corrections.md b/docs/nikon-lens-corrections.md index 4e71aae2e04..8b8720caecf 100644 --- a/docs/nikon-lens-corrections.md +++ b/docs/nikon-lens-corrections.md @@ -203,7 +203,9 @@ so a proxy cached by the offline loupe cannot prevent rebuilding after reconnect The 2026-11-05 audit of all 747 open PR patches found a highest assigned `LOOK_VERSION` of 25 (#1206) and a highest `RENDER_CACHE_VERSION` of -8,589,934,600 (#160, `8 | (2 << 32)`). This change uses 26 and 8,589,934,601. +8,589,934,600 (#160, `8 | (2 << 32)`). A 2026-11-11 recheck found +`LOOK_VERSION` 26 in #3943 and 27 in #3429, so this change uses 28 and +8,589,934,601. Other PRs still assign 14 or 76, and #784 assigns 24 and 81. Whichever look or render change lands later must renumber above the versions already on main. From 09c9a68818701e9fb347537157836c30d35527b4 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Fri, 13 Nov 2026 07:56:09 +0100 Subject: [PATCH 10/14] LR-EDIT-OPTICS-PROFILE: the Nikon lens test uses craft_tiff (main moved crates/tiff to craft-libs, #4088) --- crates/engine/src/tests/nikon_lens.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/tests/nikon_lens.rs b/crates/engine/src/tests/nikon_lens.rs index fcfaa3c1da4..b8b19137371 100644 --- a/crates/engine/src/tests/nikon_lens.rs +++ b/crates/engine/src/tests/nikon_lens.rs @@ -3,12 +3,12 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; +use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags}; use lightcraft_catalog::Op; use lightcraft_develop::DevelopSettings; use lightcraft_geom::Orientation; use lightcraft_pipeline::{RenderRequest, SourceInfo}; use lightcraft_raster::{Rgb32f, Rgba8}; -use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags}; use serde_json::json; use crate::{Session, files}; From 19d6c7dc2e89cd4058a2d8db254394076bed79e8 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Sat, 14 Nov 2026 16:30:25 +0100 Subject: [PATCH 11/14] LR-EDIT-OPTICS-PROFILE: take craft-libs a207d20 for the Nikon Z 6 and Z 7 lens modes (storytold/craft-libs#1314) craft-raw, craft-tiff, craft-crw, craft-metadata and craft-image-codecs move together from f0f4758c0, because they share types. a207d20 is the merge of #1314; no craft-libs main commit has #1314 without the same-day changes before it, so these come along in the crates LightCraft uses: image-codecs keeps unmarked CMYK JPEG samples and fixes their polarity (#1317), adds jpeg_info and its coefficient counts, and lists InkSet and ExtraSamples on TiffPage (#1307); craft-jpeg gains an optimized baseline encoder (#1298). The b77af389f pins have no change up to a207d20 and stay. --- Cargo.lock | 12 ++++++------ Cargo.toml | 10 +++++----- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7db5f5a6347..8d714b46193 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1190,7 +1190,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=a207d20700e4575c5bb964b67f9c38238ecac195#a207d20700e4575c5bb964b67f9c38238ecac195" dependencies = [ "thiserror 2.0.21", ] @@ -1257,7 +1257,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=a207d20700e4575c5bb964b67f9c38238ecac195#a207d20700e4575c5bb964b67f9c38238ecac195" dependencies = [ "craft-jpeg", "craft-metadata", @@ -1280,7 +1280,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=a207d20700e4575c5bb964b67f9c38238ecac195#a207d20700e4575c5bb964b67f9c38238ecac195" dependencies = [ "thiserror 2.0.21", ] @@ -1298,7 +1298,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=a207d20700e4575c5bb964b67f9c38238ecac195#a207d20700e4575c5bb964b67f9c38238ecac195" dependencies = [ "brotli-decompressor 6.0.1", "chrono", @@ -1321,7 +1321,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=a207d20700e4575c5bb964b67f9c38238ecac195#a207d20700e4575c5bb964b67f9c38238ecac195" dependencies = [ "chrono", "craft-crw", @@ -1339,7 +1339,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=a207d20700e4575c5bb964b67f9c38238ecac195#a207d20700e4575c5bb964b67f9c38238ecac195" dependencies = [ "serde", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index c1eade14560..060ac8d2231 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,12 +13,12 @@ repository = "https://github.com/storytold/lightcraft" craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } # Canon CRW decoder shared with the other Craft apps -craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "a207d20700e4575c5bb964b67f9c38238ecac195" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b77af389f30bb10de10d8436ca9b39fe94e3bb67", features = ["frames"] } craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "b77af389f30bb10de10d8436ca9b39fe94e3bb67", default-features = false, features = ["decode", "encode"] } # Photo metadata: EXIF, IPTC-IIM, XMP packets and GPX track logs (craft-libs#949) -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "a207d20700e4575c5bb964b67f9c38238ecac195" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a207d20700e4575c5bb964b67f9c38238ecac195" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b77af389f30bb10de10d8436ca9b39fe94e3bb67" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } @@ -37,10 +37,10 @@ lightcraft-wincolor = { path = "crates/wincolor" } lightcraft-color = { path = "crates/color" } lightcraft-raster = { path = "crates/raster" } # TIFF/IFD: the shared reader and writer (moved from crates/tiff; craft-libs#783). -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a207d20700e4575c5bb964b67f9c38238ecac195" } # Camera raw files, the format layer: every maker but CR3, ARW, RAF, RW2 and ORF (craft-libs#862 and the maker PRs). # On the same commit as craft-tiff: its errors and IFDs are shared. -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "a207d20700e4575c5bb964b67f9c38238ecac195" } lightcraft-raw = { path = "crates/raw" } lightcraft-codecs = { path = "crates/codecs" } lightcraft-meta = { path = "crates/meta" } From 3c9764a5d9f033d446689057b7b2ecebca7393f9 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Sat, 14 Nov 2026 16:30:25 +0100 Subject: [PATCH 12/14] LR-EDIT-OPTICS-PROFILE: the Nikon doc drops its Last updated header and says the decoder lives in craft-raw --- docs/nikon-lens-corrections.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/nikon-lens-corrections.md b/docs/nikon-lens-corrections.md index 8b8720caecf..6a3f95cf6f8 100644 --- a/docs/nikon-lens-corrections.md +++ b/docs/nikon-lens-corrections.md @@ -1,7 +1,5 @@ # Nikon embedded distortion corrections -> Last updated: 2026-11-05. Z 6 / Z 7 distortion validation; vignetting remains unfinished. - Nikon writes its own distortion correction into NEFs from its mirrorless bodies, in the raw SubIFD tag `0xc7d5` (NikonNEFInfo). LightCraft reads it for the NIKON Z 6, NIKON Z 7, NIKON Z 6_2 (Z 6II), NIKON Z 8 and NIKON Z f and turns it into an `OpcodeList3` `WarpRectilinear`, so it goes through the same profile correction control, optics path, orientation @@ -227,10 +225,12 @@ The decoder also skips data it doesn't recognise (another layout, radius or term values that are clearly wrong (coefficients past ±1, a zoom past ±0.5, a sensor shift over 5% of the frame) and any mapping that folds back on itself before the farthest corner. -The tests in `nef_lens` cover the polynomial and zoom, the sensor-shift center and refusing other bodies, layouts -and crops. `nikon_in_file_distortion_becomes_a_warp` runs a synthetic Z 6II NEF through the header and full decode -and a DNG export. `nikon_in_file_distortion_is_limited_to_validated_bodies` checks the corpus: the Z f sample gets the -warp and the D5100, D7000, D7500 and Coolpix B700 samples don't. +The decoder and its unit tests live in craft-raw ([storytold/craft-libs](https://github.com/storytold/craft-libs), +`crates/raw`; the Z 6 / Z 7 change is storytold/craft-libs#1314). The tests in `nef_lens` cover the polynomial and zoom, +the sensor-shift center and refusing other bodies, layouts and crops. `nikon_in_file_distortion_becomes_a_warp` runs +a synthetic Z 6II NEF through the header and full decode and a DNG export. LightCraft's +`nikon_in_file_distortion_is_limited_to_validated_bodies` (`crates/raw/tests/it/corpus.rs`) checks the corpus: the Z f +sample gets the warp and the D5100, D7000, D7500 and Coolpix B700 samples don't. None of my photos, crops or reference images are committed, only the numbers above. From f26d2eb7409cbdc168eac39893c0f9364f88ee9c Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Sun, 15 Nov 2026 09:18:07 +0100 Subject: [PATCH 13/14] LR-EDIT-OPTICS-PROFILE: retry CI (the Linux gate's only failure was a denoise model-install timeout, unrelated to this change) From 9daf4370219ae0e0dff6f32178c953c83906a739 Mon Sep 17 00:00:00 2001 From: Alex Chambers Date: Wed, 25 Nov 2026 17:35:31 +0100 Subject: [PATCH 14/14] LR-EDIT-OPTICS-PROFILE: keep Nikon distortion decoding in craft-raw --- crates/engine/examples/nikon_lens_probe.rs | 136 ----- crates/engine/src/tests/nikon_lens.rs | 41 +- crates/gpu/tests/it/equivalence.rs | 14 +- crates/pipeline/src/tests_light.rs | 18 +- crates/ui-egui/src/tests/find_similar.rs | 2 - docs/gaps.md | 2 +- docs/nikon-lens-corrections.md | 254 +-------- docs/parity-checklist.md | 2 +- docs/raw/coverage_render_sweep.py | 266 --------- docs/raw/nikon_lens_probe.py | 612 --------------------- docs/raw/test_coverage_render_sweep.py | 242 -------- docs/raw/test_nikon_lens_probe.py | 199 ------- 12 files changed, 42 insertions(+), 1746 deletions(-) delete mode 100644 crates/engine/examples/nikon_lens_probe.rs delete mode 100644 docs/raw/coverage_render_sweep.py delete mode 100644 docs/raw/nikon_lens_probe.py delete mode 100644 docs/raw/test_coverage_render_sweep.py delete mode 100644 docs/raw/test_nikon_lens_probe.py diff --git a/crates/engine/examples/nikon_lens_probe.rs b/crates/engine/examples/nikon_lens_probe.rs deleted file mode 100644 index 8214a9ce90d..00000000000 --- a/crates/engine/examples/nikon_lens_probe.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! Measurement only: dump an uncorrected quarter-size camera-RGB proxy and render the current source. -//! -//! `cargo run --release -p lightcraft-engine --example nikon_lens_probe -- IN OUT_DIR [OPCODES.json]` -//! Optional JSON is an array of experimental `OpcodeList3` lens opcodes. It replaces the lens description -//! after source loading, without changing the decoder, saved settings, or camera-look fit. Candidate renders -//! therefore isolate optics; they do not predict a future camera-look refit. See docs/raw/nikon_lens_probe.py. -#![forbid(unsafe_code)] -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -use std::io::{Read, Write}; -use std::path::Path; - -use lightcraft_develop::DevelopSettings; -use lightcraft_engine::files; -use lightcraft_pipeline::{RenderRequest, SourceInfo}; -use lightcraft_raster::Rgb32f; - -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args_os().skip(1).collect(); - let input = args.first().ok_or("usage: nikon_lens_probe IN OUT_DIR [OPCODES.json]")?; - let dir = Path::new(args.get(1).ok_or("missing OUT_DIR")?); - std::fs::create_dir_all(dir)?; - let bytes = std::fs::read(input)?; - let mut raw = lightcraft_raw::decode(&bytes)?; - let mut header = raw.info(); - std::fs::write(dir.join("raw.json"), serde_json::to_vec_pretty(&header)?)?; - raw.opcodes.list3.clear(); - let proxy = raw.develop_binned(4, 1.0)?.ok_or("cannot bin this raw")?; - let mut out = std::io::BufWriter::new(std::fs::File::create(dir.join("camera-rgb.f32"))?); - out.write_all(&u32::try_from(proxy.width)?.to_le_bytes())?; - out.write_all(&u32::try_from(proxy.height)?.to_le_bytes())?; - for pixel in &proxy.data { - for value in pixel { - out.write_all(&value.to_le_bytes())?; - } - } - out.flush()?; - drop(raw); - let (source, mut info) = files::load_bytes(&bytes, 1200)?; - let mut settings = DevelopSettings::default(); - settings.wb.temp = info.as_shot_temp; - settings.wb.tint = info.as_shot_tint; - settings.optics.lens_profile = info.lens.is_some(); - render(&source, &info, &settings, &dir.join("baseline.png"))?; - if let Some(path) = args.get(2) { - let data = read_candidates(std::fs::File::open(path)?)?; - header.opcodes.list3 = serde_json::from_slice(&data)?; - validate_candidates(&header.opcodes.list3)?; - info.lens = files::embedded_lens(&header); - settings.optics.lens_profile = info.lens.is_some(); - render(&source, &info, &settings, &dir.join("candidate.png"))?; - } - Ok(()) -} - -/// Read one byte beyond the limit to distinguish a complete input from an oversized one. -fn read_candidates(reader: impl Read) -> std::io::Result> { - let mut data = Vec::new(); - reader.take(65_537).read_to_end(&mut data)?; - if data.len() > 65_536 { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "candidate opcodes exceed 64 KiB")); - } - Ok(data) -} - -/// Diagnostic inputs have a deliberately small range; reject arbitrary operations and invalid gains. -fn validate_candidates(ops: &[lightcraft_raw::Opcode]) -> Result<(), &'static str> { - use lightcraft_raw::Opcode; - if ops.is_empty() || ops.len() > 2 { - return Err("provide one or two lens opcodes"); - } - if ops.iter().filter(|op| matches!(op, Opcode::WarpRectilinear { .. })).count() > 1 - || ops.iter().filter(|op| matches!(op, Opcode::FixVignetteRadial { .. })).count() > 1 - { - return Err("provide at most one warp and one radial vignette"); - } - for op in ops { - let center = match op { - Opcode::WarpRectilinear { planes, center } if planes.len() == 1 && planes.iter().flatten().all(|v| v.is_finite() && v.abs() <= 16.0) => { - center - } - Opcode::FixVignetteRadial { k, center } if k.iter().all(|v| v.is_finite() && v.abs() <= 16.0) => { - for i in 0..=256 { - let r2 = (f64::from(i) / 256.0).powi(2); - let gain = 1.0 + r2 * (k[0] + r2 * (k[1] + r2 * (k[2] + r2 * (k[3] + r2 * k[4])))); - if !gain.is_finite() || !(0.01..=16.0).contains(&gain) { - return Err("candidate vignette gain is outside 0.01 to 16"); - } - } - center - } - _ => return Err("candidate must be a bounded single-plane warp or radial vignette"), - }; - if !center.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)) { - return Err("candidate center must be inside the active area"); - } - } - Ok(()) -} - -/// Use the same CPU renderer and PNG encoder as the app, with no catalog or filesystem hooks. -fn render(source: &Rgb32f, info: &SourceInfo, settings: &DevelopSettings, path: &Path) -> Result<(), Box> { - let rendered = lightcraft_pipeline::render(source, info, settings, &RenderRequest::fit(1200, 1200)); - let image = lightcraft_codecs::encode::EncodeImage::rgba8(&rendered.image); - std::fs::write(path, lightcraft_codecs::encode::encode_png(&image, &Default::default())?)?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn candidates_reject_duplicate_kinds_and_accept_one_of_each() { - use lightcraft_raw::Opcode; - let warp = Opcode::WarpRectilinear { planes: vec![[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }; - let vignette = Opcode::FixVignetteRadial { k: [0.0; 5], center: [0.5, 0.5] }; - assert!(validate_candidates(std::slice::from_ref(&warp)).is_ok()); - assert!(validate_candidates(std::slice::from_ref(&vignette)).is_ok()); - assert!(validate_candidates(&[warp.clone(), vignette.clone()]).is_ok()); - assert!(validate_candidates(&[vignette.clone(), warp.clone()]).is_ok()); - assert_eq!(validate_candidates(&[warp.clone(), warp]), Err("provide at most one warp and one radial vignette")); - assert_eq!(validate_candidates(&[vignette.clone(), vignette]), Err("provide at most one warp and one radial vignette")); - } - - /// A hostile stream must be rejected after at most limit + 1 bytes, without reading to EOF. - #[test] - fn candidate_reader_bounds_the_read_and_accepts_the_exact_limit() { - let mut endless = std::io::repeat(b' '); - let mut counted = (&mut endless).take(1_000_000); - let error = read_candidates(&mut counted).unwrap_err(); - assert_eq!(error.kind(), std::io::ErrorKind::InvalidData); - assert_eq!(counted.limit(), 1_000_000 - 65_537); - assert_eq!(read_candidates(std::io::repeat(b' ').take(65_536)).unwrap().len(), 65_536); - } -} diff --git a/crates/engine/src/tests/nikon_lens.rs b/crates/engine/src/tests/nikon_lens.rs index b8b19137371..2b26e47874e 100644 --- a/crates/engine/src/tests/nikon_lens.rs +++ b/crates/engine/src/tests/nikon_lens.rs @@ -1,6 +1,6 @@ //! Nikon source corrections across the decoder, optics controls, export and existing libraries. -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::sync::Arc; use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags}; @@ -83,23 +83,13 @@ fn difference(a: &Rgba8, b: &Rgba8) -> (f64, u8) { (values.iter().map(|&v| f64::from(v)).sum::() / values.len() as f64, values.into_iter().max().unwrap()) } -/// New body recognition must reach both public decode paths and the existing toggle/strength controls. +/// The import probe and the renderer must agree on the lens controlled by the Optics panel. #[test] -fn nikon_z6_z7_probe_decode_toggle_amount_and_dng_agree() { +fn nikon_z6_z7_profile_toggle_and_amount_control_the_imported_warp() { for model in ["NIKON Z 6", "NIKON Z 7"] { let bytes = nef(model, Orientation::Normal); - let header = lightcraft_raw::probe_info(&bytes).unwrap(); - let raw = lightcraft_raw::decode(&bytes).unwrap(); - assert_eq!(header, raw.info()); - assert!(matches!(&raw.data,lightcraft_raw::RawData::U16(samples) if samples.iter().all(|&v|v<16384)), "the fixture is valid 14-bit data"); - assert_eq!(raw.opcodes.list3.len(), 1); - let lens = files::embedded_lens(&header).unwrap(); + let lens = files::probe_bytes("photo.nef", &bytes).unwrap().embedded_lens.unwrap(); assert!(lens.warp.is_some() && lens.vignette.is_none()); - let dng = lightcraft_raw::write_dng(&raw, &Default::default()).unwrap(); - let back = lightcraft_raw::decode(&dng).unwrap(); - assert_eq!(back.opcodes.list3, raw.opcodes.list3); - assert_eq!(back.data, raw.data); - assert_eq!(files::embedded_lens(&back.info()), Some(lens)); let (source, info) = files::load_bytes(&bytes, 192).unwrap(); assert_eq!(info.lens, Some(lens)); let mut s = settings(&info); @@ -226,6 +216,7 @@ fn nikon_existing_library_and_smart_preview_refresh_preserve_edits() { s.execute("library.import", &json!({"paths":[original]})).unwrap(); let id = s.active().unwrap(); let mut edited = (*s.catalog.photo(id).unwrap().develop).clone(); + assert!(edited.optics.lens_profile, "import enables the embedded correction"); edited.light.exposure = 0.7; edited.optics.lens_profile = false; s.commit( @@ -282,6 +273,7 @@ fn nikon_existing_library_and_smart_preview_refresh_preserve_edits() { let (fresh_pixels, tone, stored) = crate::smart::decode(&fresh).unwrap(); let (old_pixels, _, _) = crate::smart::decode(&old).unwrap(); let error = |image: &Rgb32f| { + assert_eq!((image.width, image.height), (source.width, source.height)); image.data.iter().zip(&source.data).flat_map(|(a, b)| (0..3).map(move |c| (a[c] - b[c]).abs() as f64)).sum::() / (source.data.len() * 3) as f64 }; @@ -301,24 +293,9 @@ fn nikon_existing_library_and_smart_preview_refresh_preserve_edits() { let options = crate::export::ExportOptions { format: crate::export::ExportFormat::Dng, ..Default::default() }; let exported = crate::export::export_photo(&mut s, id, &options, 1).unwrap(); let dng = lightcraft_raw::decode(&exported.bytes).unwrap(); + let nef = lightcraft_raw::decode(&bytes).unwrap(); + assert_eq!(dng.opcodes.list3, nef.opcodes.list3); + assert_eq!(dng.data, nef.data); assert_eq!(files::embedded_lens(&dng.info()), new_lens); } } - -/// The public real files agree with their header probes and contain no shipped vignette opcode. -#[test] -fn nikon_z6_z7_corpus_headers_and_full_decodes_agree() { - let corpus = - std::env::var_os("LIGHTCRAFT_CORPUS").map(PathBuf::from).unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus")); - for id in [3584, 3581, 3582, 2792, 2789, 2790] { - let path = corpus.join(format!("raw/coverage-{id}.nef")); - if !path.exists() { - lightcraft_testkit::skip!(Corpus, "Nikon coverage sample {id} absent"); - continue; - } - let bytes = std::fs::read(path).unwrap(); - let raw = lightcraft_raw::decode(&bytes).unwrap(); - assert_eq!(lightcraft_raw::probe_info(&bytes).unwrap(), raw.info()); - assert!(matches!(raw.opcodes.list3.as_slice(), [lightcraft_raw::Opcode::WarpRectilinear { .. }])); - } -} diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 137d3446c6b..a8fa80f8120 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -56,16 +56,10 @@ fn check_v3_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) { 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] { - // Ordered dithering can vary a uniform source by one quantization level. - for channel in 0..4 { - let min = image.data.iter().map(|p| p[channel]).min().unwrap(); - let max = image.data.iter().map(|p| p[channel]).max().unwrap(); - assert!(max - min <= 1, "chroma {chroma}: channel {channel} spans {min}..{max}"); - } - for pixel in &image.data { - for (actual, expected) in pixel.iter().zip(expected) { - assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {pixel:?}, expected {expected}"); - } + // (8-bit output is dithered: a flat source varies by a level) + assert!(image.data.iter().all(|p| p.iter().zip(image.data[0]).all(|(a, b)| a.abs_diff(b) <= 1))); + 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); diff --git a/crates/pipeline/src/tests_light.rs b/crates/pipeline/src/tests_light.rs index 7f338eb987b..dd38bbf0460 100644 --- a/crates/pipeline/src/tests_light.rs +++ b/crates/pipeline/src/tests_light.rs @@ -38,16 +38,10 @@ fn check_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) { s.light.contrast = 100.0; s.light.blacks = 80.0; let image = render(&src, &info, &s, &RenderRequest::fit(64, 64)).image; - // Ordered dithering can vary a uniform source by one quantization level. - for channel in 0..4 { - let min = image.data.iter().map(|p| p[channel]).min().unwrap(); - let max = image.data.iter().map(|p| p[channel]).max().unwrap(); - assert!(max - min <= 1, "chroma {chroma}: channel {channel} spans {min}..{max}"); - } - for pixel in &image.data { - for (actual, expected) in pixel.iter().zip(expected) { - assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {pixel:?}, expected {expected}"); - } + // (8-bit output is dithered: a flat source varies by a level) + assert!(image.data.iter().all(|p| p.iter().zip(image.data[0]).all(|(a, b)| a.abs_diff(b) <= 1))); + for (actual, expected) in image.data[0].into_iter().zip(expected) { + assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {:?}, expected {expected}", image.data[0]); } } @@ -320,8 +314,8 @@ fn v3_sliders_move_a_grey_ramp_their_way() { ("light.blacks", -60.0), ] { let r = shot(id, v); - // Adjacent ordered-dither thresholds can lower a sample by one 8-bit level. - assert!(r.windows(2).all(|w| luma(w[1]) + 1 >= luma(w[0])), "{id} {v}: the ramp decreases beyond the dither floor"); + // (within a level of 8-bit dither) + assert!(r.windows(2).all(|w| luma(w[1]) >= luma(w[0]) - 1), "{id} {v}: the ramp is no longer increasing"); assert!(r.iter().all(|p| p[0].abs_diff(p[1]) <= 1 && p[1].abs_diff(p[2]) <= 1), "{id} {v}: the ramp is no longer grey"); let diff = |lo: usize, hi: usize| (lo..hi).map(|x| luma(r[x]) - luma(plain[x])).sum::(); let (dark, light) = (diff(40, 90), diff(170, 220)); diff --git a/crates/ui-egui/src/tests/find_similar.rs b/crates/ui-egui/src/tests/find_similar.rs index b37b8639225..ef70539578f 100644 --- a/crates/ui-egui/src/tests/find_similar.rs +++ b/crates/ui-egui/src/tests/find_similar.rs @@ -173,8 +173,6 @@ fn stopping_leaves_the_view_alone_and_the_next_search_reads_only_the_rest() { assert!(h.app.ui.toast.is_none(), "{:?}", h.app.ui.toast); assert_eq!(drive.reads.load(Ordering::SeqCst), 1); - // The loupe can have decoded a photo meanwhile. Measure signature reuse without its pixel cache. - h.app.session.media.clear_sources(); let r = h.app.run("library.findSimilar", json!({"id": 1})).unwrap(); assert_eq!(r["count"], PHOTOS - 1, "what was read isn't read again"); until_done(&mut h); diff --git a/docs/gaps.md b/docs/gaps.md index 7d542d13949..0e42226602c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -22,7 +22,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app | 5 B | **AI masks: Subject, Sky, People, Background, Landscape** are heuristics; Object / Describe run SAM 3 but its download has no mirror configured | `crates/segment`; ai-masks.md; MASK rows 67% | masking is how most Lightroom users edit today | 40–70 + model decision | [target-app-parity](target-app-parity.md#ai) | | 6 | **Compressed ORF** (support withdrawn) | #3775 decoder removed pending provenance review; uncompressed support remains | compressed files use embedded JPEG previews when available, not sensor data | pending review | [orf-compression](orf-compression.md) | | 7 | **Nikon High Efficiency NEF** (HE / HE★ on Z 8, Z 9, Z 6III, Z f, Z50II, Z5II when set to HE) | named and preview only (#193); needs a pure-Rust JPEG XS decoder | +1.1 points (only shots taken in HE; lossless works on the same bodies); low gain per hour (~0.04), so not a beta blocker | 20–40 | [raw-parity](raw-parity.md) | -| 8 B | **Lens profiles: lensfun only, no picker, no own calibration** (LR-EDIT-OPTICS-PROFILE): the desktop app offers lensfun's database (CC BY-SA 3.0, pinned, never bundled) once on the first launch and downloads it on that click or from Settings, then looks every raw up by its lens ([lens-profiles.md](lens-profiles.md)), but those profiles are not validated against Lightroom, there is no profile picker (in the file / lens database / own calibration) and no calibration wizard; in-file corrections: DNG opcodes, RW2 in-file distortion, Sony ILCE-7RM4A, ILCE-7M3, full-frame ILCE-7CR distortion (Auto only) and ILCE-7RM6 and ILCE-6700 distortion (`docs/sony-ilce7rm6-lens-corrections.md`) and Nikon Z 6 / Z 7 / Z 6II / Z 8 / Z f distortion (`docs/nikon-lens-corrections.md`); Z 6 / Z 7 evidence is limited to two scenes at 52/56 mm, with extreme corners unvalidated; Nikon vignette correction remains unfinished (the provisional eight-power model and its strength are not validated across captures or correction settings); tracked in #329 | Adobe ships 3,635 lens profiles; we never use them | distortion / vignetting correction is a default step for many | 40–80 + calibration shots | [raw-parity](raw-parity.md#lens-profiles) | +| 8 B | **Lens profiles: lensfun only, no picker, no own calibration** (LR-EDIT-OPTICS-PROFILE): the desktop app offers lensfun's database (CC BY-SA 3.0, pinned, never bundled) once on the first launch and downloads it on that click or from Settings, then looks every raw up by its lens ([lens-profiles.md](lens-profiles.md)), but those profiles are not validated against Lightroom, there is no profile picker (in the file / lens database / own calibration) and no calibration wizard; in-file corrections: DNG opcodes, RW2 in-file distortion, Sony ILCE-7RM4A, ILCE-7M3, full-frame ILCE-7CR distortion (Auto only) and ILCE-7RM6 and ILCE-6700 distortion (`docs/sony-ilce7rm6-lens-corrections.md`) and Nikon Z 6 / Z 7 / Z 6II / Z 8 / Z f distortion (`docs/nikon-lens-corrections.md`); Z 6 / Z 7 evidence is limited to two scenes at 52/56 mm, with extreme corners unvalidated; Nikon vignette correction remains unfinished; tracked in #329 | Adobe ships 3,635 lens profiles; we never use them | distortion / vignetting correction is a default step for many | 40–80 + calibration shots | [raw-parity](raw-parity.md#lens-profiles) | | 9 B | **Tests don't run in CI on macOS, run on Windows only for Windows code, and no CI job runs the GPU equivalence tests**: the CI gate (`ci.yml`, #2667) runs `cargo xtask ci`, which includes `cargo test`, on Linux x64 for every push to `main` and every pull request; its Windows leg (`ci-windows.yml`) runs clippy and the tests of the crates with `cfg(windows)` code (wincolor, catalog, engine, ui-egui, lightcraft) on windows-latest when a pull request or a push to `main` changes that code, and on pull requests labelled `full-ci`; FreeBSD runs `cargo test` nightly, on pushes to `release` and on PRs that change its workflow or `packaging/freebsd/`; the macOS and Windows jobs build packages | `.github/workflows/` (ci, ci-windows, freebsd, packaging-lint, release, sonarcloud, windows-arm64); the gate's runner has Mesa software Vulkan drivers installed, but `Gpu::new` refuses software adapters (`crates/gpu/src/ctx.rs`), so the CPU ↔ GPU equivalence tests skip; the linux-riscv64 release job added in 0.6.0 (#844) runs only `lightcraft-cli --version` under QEMU; #1148 (open, not merged; #2667 names it superseded) has the macOS and Windows test legs and a `LIGHTCRAFT_GPU_ALLOW_SOFTWARE` opt-in that runs the GPU tests on lavapipe, Metal and WARP | a regression that only shows on macOS, on Windows in code outside the Windows leg's paths, or only on a GPU, reaches users; the full `cargo xtask ci` runs only on Linux in CI | 6–12 | [target-app-parity](target-app-parity.md#by-dimension) | | 10 B | **Per-model verification thin, plus cheap per-body decode fixes**: 557 of 1,446 Adobe models verified (39%), ~86% of photographers on a verified body; Nikon 5 bodies verified, Canon 34, Leica 14 (the Q3 by a recorded check of 38 private DNGs). Cheap fixes: Z 6II packed 14-bit NEF (#769, PR #671), Sony A100 regression (#702); F828 SRF now discovered and imported as preview-only, sensor decoding still missing, DSLR-A200…A390 / A850 12-bit ARW (#535) | measured: [raw/coverage.tsv](raw/coverage.tsv) | per-body bugs (levels, crops, WB) surface only from users | 25–45 | [raw-parity](raw-parity.md#by-maker-measured) | | 11 | **Enhance: Raw Details, Super Resolution; trained denoise weights and X-Trans** | ENH rows 0%; denoise Bayer only; the built-in denoiser is classical (block-matching collaborative filtering), RawNIND weights GPL and opt-in | Fujifilm users get no AI denoise; very noisy files gain less than from a trained model | 30–60 + model decision | [raw-parity](raw-parity.md#demosaic-levels-crops-and-lens-metadata) | diff --git a/docs/nikon-lens-corrections.md b/docs/nikon-lens-corrections.md index 6a3f95cf6f8..a96967e80e1 100644 --- a/docs/nikon-lens-corrections.md +++ b/docs/nikon-lens-corrections.md @@ -1,241 +1,29 @@ # Nikon embedded distortion corrections -Nikon writes its own distortion correction into NEFs from its mirrorless bodies, in the raw SubIFD tag `0xc7d5` -(NikonNEFInfo). LightCraft reads it for the NIKON Z 6, NIKON Z 7, NIKON Z 6_2 (Z 6II), NIKON Z 8 and NIKON Z f and turns it into an -`OpcodeList3` `WarpRectilinear`, so it goes through the same profile correction control, optics path, orientation -handling and DNG export as the other embedded corrections. Other bodies are left alone for now even if they have the -same tag. Body recognition is limited to files checked against their camera JPEGs. +LightCraft uses the distortion warp that craft-raw reads from supported full-frame Nikon Z 6, Z 7, Z 6II, Z 8 and +Z f NEFs. Modes 1 (On Optional) and 3 (On Required) supply a warp. Modes 0, 2 (Off) and unknown values do not. +The shared decoder documents the file layout, camera support and validation against camera JPEGs. +[Decoder and validation notes](https://github.com/storytold/craft-libs/blob/23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3/crates/raw/docs/nikon-lens-corrections.md) -This is distortion only. The vignetting block (`0x0006`) and what looks like lateral CA (`0x0007`) aren't applied -yet. Like the Sony, Fujifilm and Panasonic corrections it's on by default and can be turned off under Lens -Corrections. +LightCraft enables the embedded profile on import and gives it precedence over a lens-database profile. The profile +switch and distortion amount control the warp in previews and rendered exports. The correction follows the photo's +orientation. DNG export preserves the warp with the sensor data, including when the profile is switched off for +the current edit. Nikon vignetting remains unsupported. -## Where the data comes from +## Existing libraries -The [ExifTool Nikon tag-name documentation](https://exiftool.org/TagNames/Nikon.html) gives tag identities and offsets -for NikonNEFInfo and its DistortionInfo entry (`0x0005`), including DistortionCorrection and -RadialDistortionCoefficient1 to 3. The ExifTool executable also extracts metadata and embedded JPEG data black-box. -The mapping was worked out independently by comparing LightCraft's uncorrected render of each NEF with the -full-size JPEG the camera embeds in it. That JPEG is always distortion-corrected with Z lenses ("On (Required)"), and -with other lenses when Auto distortion control is on. The comparison matched textured patches between the two images -(normalised cross-correlation on the green channel at quarter size). +Reload from Disk refreshes the catalog's lens metadata. It enables a newly discovered profile on an untouched photo +without an import preset. A photo with saved edits keeps its settings, including an explicit off switch. -NikonNEFInfo starts with `"Nikon\0"` and a 4-byte version, followed by a small TIFF stream. The two entries used here: +The camera-look fit uses the recognized geometry even when the profile switch is off. Decoding an existing edit +again can therefore change its tone or colour on any process version. LightCraft advances the camera-look and +render-cache versions so it can refresh these fits and thumbnails. An offline original keeps its old smart preview. +After reconnect, Build Smart Previews reads the original even if the loupe has cached the offline proxy. +[Rendering process versions](process-versions.md) -| Entry | Bytes | What it holds | -|---|---|---| -| `0x0005` DistortionInfo | 0–3 | `"0100"` | -| | 4 | correction mode: 1 "On (Optional)", 3 "On (Required)"; 0 none, 2 "Off" and unknown modes are skipped | -| | 8–15 | normalisation radius in mm, a signed rational. It's 21.6 (the FX half diagonal) in every file I looked at | -| | 16–19 | number of terms, 4 | -| | 20, 28, 36 | the three coefficients, called `k1`, `k2`, `k3` here after ExifTool's names | -| | 64–71 | the zoom `q` the camera uses to fill the frame | -| `0x0008` | 0–3, 4–11, 12–19 | `"0100"`, then the optical center's offset from the center of the image area in pixels (x right, y down) | +## Render evidence -The `0x0008` offset is where the in-body stabilization left the sensor. It's zero with a VR lens, since the lens does -the stabilizing, and up to about 100 px with the Z lenses. The center of the distortion measured in the JPEG follows -it closely, for example (−90.1, +18.6) recorded and (−91.2, +17.5) measured. - -From an output pixel to the raw, around the optical center, the mapping is - -``` -rho = r_out / half diagonal of the image area -r_src = r_out * (1 + k3*rho^2 + k2*rho^4 + k1*rho^6) / (1 + q) -``` - -So the stored order goes from the highest power down. Reading them the other way round (`k1` with `rho^2`) doesn't fit -the JPEG at all. `q` really is the zoom: fitting a separate zoom for every file gives `1 / (1 + q)` to four decimals -(0.9675 fitted and 0.9676 from `q` on one of them), so nothing is fitted per file. The decoder turns this into DNG -terms the same way `docs/sony-lens-corrections.md` describes for Sony, with the center in active-area coordinates and -the coefficients rescaled to the farthest corner of the active area. - -## How well it matches - -I checked it on 83 of my own Z 6II photos with three lenses between 20 and 200 mm, 45 Z 8 photos (below), plus the -CC0 Z f sample in the corpus. The numbers are the radial error against the camera JPEG at full size (6048 px wide), out to 0.95 half -diagonals: - -| Lens | Focal length | Frames | Uncorrected median / p95 | Corrected median / p95 | -|---|---:|---:|---:|---:| -| VR 70-200mm f/2.8G (F-mount, FTZ) | 70 mm | 11 | 10.9 / 15.9 px | 0.19 / 0.57 px | -| VR 70-200mm f/2.8G (F-mount, FTZ) | 105–140 mm | 15 | 34–42 / 38–46 px | 0.13–0.18 / 0.59–0.90 px | -| VR 70-200mm f/2.8G (F-mount, FTZ) | 175–200 mm | 21 | 45–46 / 50–51 px | 0.10–0.18 / 0.48–0.95 px | -| NIKKOR Z 24-70mm f/4 S | 70 mm | 8 | 126.4 / 141.2 px | 0.48 / 4.38 px | -| NIKKOR Z 24-70mm f/4 S | 38–59 mm | 6 | 59–101 / 69–121 px | 0.36–0.76 / 4.6–6.8 px | -| NIKKOR Z 24-70mm f/4 S | 33–34 mm | 4 | 32–44 / 43–53 px | 1.0–1.3 / 8.5–9.6 px | -| NIKKOR Z 24-70mm f/4 S | 24 mm | 7 | 16.0 / 105.6 px | 6.90 / 23.56 px | -| NIKKOR Z 20mm f/1.8 S | 20 mm | 5 | 8.2 / 53.9 px | 1.49 / 5.46 px | -| Tamron 35-150mm (Z f, CC0 corpus) | 150 mm | 1 | 70.4 px median | 0.22 px median | - -On the Z 8 (8256 px wide JPEGs) it looks the same. The 70-200 f/2.8G on the FTZ matches within 0.14 to 0.21 px median -at 70, 135 and 200 mm. The NIKKOR Z 24-120mm f/4 S is within 0.6 to 1.0 px median from 36 to 120 mm and 1.5 px at 24 -to 28 mm, with the same kind of error toward the edges at the wide end as the Z lenses on the Z 6II. A few 14-24mm -f/2.8G frames had Auto distortion control off, so their JPEGs aren't corrected and match about the same either way. - -I also rendered a few with `lightcraft-cli render` at default settings and measured those against the camera JPEG. -The median error was 0.10 px for the 70-200 at 200 mm and 0.12 px for the Z f sample. The 24-70 was 0.32 px at 70 mm, -on a frame with a 92 px sensor shift, and 8.4 px at 24 mm. The 20 mm came out at 1.3 px. On the Z 8 it was 0.14 px for the 70-200 at 200 mm, 0.45 and 0.68 px for the 24-120 -at 68 and 120 mm, 1.8 px for the Z 20 mm and 3.7 px for the 24-120 at 24 mm. That checks the -center, crop and DNG conversion along with the model itself. - -The F-mount lens on the FTZ matches about as well as I can measure. The native Z lenses still have a smooth error -toward the edges that doesn't depend on the sensor shift and is the same in every frame at a given focal length: about -+22 px at 0.7 to 0.9 half diagonals at 24 mm, +8 px at 33 mm and +3.5 px at 70 mm. It seems the camera applies an -extra correction for Z lenses that isn't in the readable coefficients. NikonNEFInfo `0x000e` looks encrypted and I -didn't try to decode it. Even so, the readable correction takes most of the distortion out. At 24 mm the error at 0.7 -half diagonals goes from −82 px to +25 px, and at 70 mm from about −137 px to under 4 px. - -## Z 6 and Z 7 validation - -The six CC0 raw.pixls.us files in `docs/raw/coverage-sweep.tsv` are six exposures -of two repeated scenes, with one NIKKOR Z 24-70mm f/4 S. The Z 6 files (3584, -3581, 3582) are at 52 mm and f/6.7; the Z 7 files (2792, 2789, 2790) are at -56 mm and f/5.6. They do not establish coverage at other focal lengths or lenses. -All six file SHA-256 hashes were checked before decoding. - -`docs/raw/nikon_lens_probe.py` matches log-green patches in a quarter-size sensor -proxy against the full-size embedded JPEG. It requires normalized correlation -at least 0.90 and a peak at least 0.02 above competing matches outside its -7-by-7 neighborhood. The stored coefficients, zoom and optical center are used -without fitting a correction to each photo. Radial errors below are full-size -pixels over reliable matches between 0.15 and 0.95 image half-diagonals. - -| Body | Files | Uncorrected radial median | Corrected radial median | Corrected radial p95 | -|---|---:|---:|---:|---:| -| Z 6 | 3 | 82.84-84.00 px | 0.88-0.96 px | 4.69-4.99 px | -| Z 7 | 3 | 124.21-124.80 px | 1.37-1.46 px | 6.18-6.38 px | - -Reliable patches reach about 0.90-0.91 half-diagonals on the Z 6 and 0.94 on -the Z 7. The extreme corners remain unvalidated geometrically. The remaining -smooth edge error is consistent with the native Z lens residual described -above. These results support extending the existing model to these bodies, -with the same full-frame crop, layout, radius and mapping guards. - -Fresh production exports, including the refitted camera look, were compared -against the same references across all 40 coverage-sweep rows. The measurement -method, base/candidate results and unchanged-image hashes are recorded in -[`raw/nikon-distortion-sweep.tsv`](raw/nikon-distortion-sweep.tsv). The historical file and sensor-hash provenance -in the TSV is retained. Only rows whose rendered pixels change are updated. - -The production comparison uses CPU CLI exports at a 1200 px long edge, the -recorded reference orientation and a center crop to the camera reference aspect, -then Lab L* at 200 px. The outer ring starts at 0.75 image half-diagonals. -A lens database is disabled for both runs. The camera look is refitted by each -binary, and all settings remain at their import defaults. - -| File ID | Base r | Corrected r | Base mean dL | Corrected mean dL | Base outer mean dL | Corrected outer mean dL | -|---|---:|---:|---:|---:|---:|---:| -| 3584 | 0.8769 | 0.9964 | +0.299 | +0.173 | -3.479 | -1.609 | -| 3581 | 0.8772 | 0.9964 | +0.320 | +0.196 | -3.470 | -1.611 | -| 3582 | 0.8775 | 0.9964 | +0.430 | +0.212 | -3.431 | -1.592 | -| 2792 | 0.7497 | 0.9914 | +1.924 | +1.215 | -2.982 | -2.068 | -| 2789 | 0.7483 | 0.9910 | +2.188 | +1.271 | -2.881 | -2.028 | -| 2790 | 0.7480 | 0.9910 | +2.240 | +1.251 | -2.868 | -2.073 | - -Here dL is LightCraft minus camera JPEG. All six improve in correlation, -absolute mean dL and outer-ring mean absolute error. The other 34 production -RGB outputs are byte-identical. Residual tone and corner brightness differences -remain; neither Auto Picture Control nor Nikon shading is reproduced exactly. - -## Vignetting remains unfinished - -No Nikon vignette correction or fitted per-body strength is applied. The -investigation used the six Z 6 / Z 7 files and one public file each from the -Z 6II, Z 8 and Z f. That is nine exposures, five scenes, four lenses and five -focal lengths in total; the repeated scenes are not independent lens evidence. - -The `0100` block at `0x0006` has a 21.600098 mm radius and a term count of eight -in these files. Nine signed rationals start at offset 20. A provisional model -reads them in descending polynomial order: odd terms are zero and the last -term is one. It includes an unnamed rational `a` at offset 20 as well as the -three named coefficients at offsets 36, 52 and 68: - -```text -P(rho) = 1 + c3*rho^2 + c2*rho^4 + c1*rho^6 + a*rho^8 -candidate gain = 1 + strength * (P(rho) - 1) -``` - -Here `rho` is the unwarped source radius over the image-area half diagonal, -about the recorded optical center. The ordering, powers, normalization and -strength are hypotheses derived from the files and camera-JPEG comparisons. -Tag identities and the named coefficient offsets came from ExifTool's tag-name -documentation; its executable also extracts file metadata and embedded JPEG data -black-box. No external decoder implementation was read. - -The unnamed term matters: at `rho = 1`, the named three alone give gains of -0.912 on the Z 6 and 2.790 on the Z 7; the complete polynomial gives 1.705 and -1.673. However, diagnostic renders that retain the old camera-look fit overbrighten -the corners at full strength and worsen the Z 8 and Z f comparison. Those -experiments do not predict production output after a camera-look refit. Treating the rational at offset 96 as the strength -also fails to establish one consistent interpretation across bodies and scenes. - -The diagnostic fitter uses a global log-tone spline and color-ratio terms, -with alternating spatial tiles reserved for validation. It rejects undersampled -splits and radial bins and non-finite statistics. Effective fitted strengths -vary among captures. Scene brightness correlated with radius, Auto Picture -Control on the Z 6, and Auto Active D-Lighting on the Z 6II sample limit the -inference. No contrast response was tuned to close those differences. - -Further investigation needs other lenses, apertures and focal lengths, whole -captures held out, flat or near-flat scenes where available, and different -correction settings. Private pairs must stay in place, with diagnostics outside -the repository and anonymous results. Vignetting requires a later review. -If validated, `FixVignetteRadial` before the warp in `OpcodeList3` would use the -existing profile toggle, amount, orientation and DNG path. A `GainMap` would -be baked into the source and would not provide that lens toggle. - -## Existing libraries and process versions - -These are source corrections under `docs/process-versions.md`; they do not -introduce a rendering process. Qualifying Z 6 / Z 7 NEFs can acquire the warp, -and mode-2 NEFs on previously validated bodies lose the unwanted warp. Modes -1 (On Optional) and 3 (On Required) are accepted; 0, 2 and unknown modes are skipped. - -The camera-look fit uses the recognized geometry even when profile corrections -are switched off, so existing edited photos on any process can change tone or -color when decoded again. `LOOK_VERSION` and `RENDER_CACHE_VERSION` are advanced -together. Old smart previews are rebuilt from online originals and retained -with their stored pixels, tone and lens data while originals are offline. -Build Smart Previews reads the original independently of decoded-source caches, -so a proxy cached by the offline loupe cannot prevent rebuilding after reconnect. - -The 2026-11-05 audit of all 747 open PR patches found a highest assigned -`LOOK_VERSION` of 25 (#1206) and a highest `RENDER_CACHE_VERSION` of -8,589,934,600 (#160, `8 | (2 << 32)`). A 2026-11-11 recheck found -`LOOK_VERSION` 26 in #3943 and 27 in #3429, so this change uses 28 and -8,589,934,601. -Other PRs still assign 14 or 76, and #784 assigns 24 and 81. Whichever look or -render change lands later must renumber above the versions already on main. - -Reload from Disk refreshes catalog lens metadata. It enables a newly found -profile for an untouched photo without an import preset; an edited photo keeps -its settings, including an explicit off switch. Reload is required to update -an older catalog's Optics metadata. A file profile takes precedence over a -lens-database profile, so a Z 6 / Z 7 photo previously using database corrections -can also change when its embedded profile is recognized. The production sweep -above disables the optional database in both runs. Existing DNGs without these -opcodes, other bodies and preview-only raw variants do not acquire this NEF correction. - -## What's left out - -Only `NIKON Z 6`, `NIKON Z 7`, `NIKON Z 6_2`, `NIKON Z 8` and `NIKON Z f` are corrected, matched exactly. A matching tag on another body doesn't tell us its -pixel pitch or image area, so other bodies can be added once someone checks their files. Only the full-frame 3:2 -image area is corrected, because the stored 21.6 mm radius is the FX half diagonal, so DX and other crops are skipped. -The decoder also skips data it doesn't recognise (another layout, radius or term count, or a correction mode other than 1 or 3), -values that are clearly wrong (coefficients past ±1, a zoom past ±0.5, a sensor shift over 5% of the frame) and any -mapping that folds back on itself before the farthest corner. - -The decoder and its unit tests live in craft-raw ([storytold/craft-libs](https://github.com/storytold/craft-libs), -`crates/raw`; the Z 6 / Z 7 change is storytold/craft-libs#1314). The tests in `nef_lens` cover the polynomial and zoom, -the sensor-shift center and refusing other bodies, layouts and crops. `nikon_in_file_distortion_becomes_a_warp` runs -a synthetic Z 6II NEF through the header and full decode and a DNG export. LightCraft's -`nikon_in_file_distortion_is_limited_to_validated_bodies` (`crates/raw/tests/it/corpus.rs`) checks the corpus: the Z f -sample gets the warp and the D5100, D7000, D7500 and Coolpix B700 samples don't. - -None of my photos, crops or reference images are committed, only the numbers above. - -## Revision history - -| Date | Change | Summary | -|---|---|---| -| 2026-11-05 | minor | Z 6 / Z 7 distortion, correction-mode guards, reconnect-safe smart-preview rebuilds, cache-version collision audit and probe geometry guards; vignette model remains unshipped | +The 2026-11-05 CPU export comparison covered 40 pinned inputs. All six Z 6 and Z 7 exports matched their camera +JPEGs more closely in luminance correlation. The other 34 outputs had identical RGB pixels. The six exposures cover +two scenes with one NIKKOR Z 24-70mm f/4 S at 52 and 56 mm. The extreme corners remain unvalidated. The comparison +records the original binaries, input hashes and per-file results. [Render comparison](raw/nikon-distortion-sweep.tsv) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 4c2ecc3c64d..c2f615b104b 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -214,7 +214,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-DETAIL-AISHARPEN | AI sharpen | OOS | 🚫 | | | | LR-EDIT-DETAIL-HOTPIXELS | Hot pixel removal | P1 | ✅ | `check:detail.nrOutliers`, `crates/raw/src/hotpixel.rs`, `crates/engine/src/files/load.rs` (`load_bytes_now`), `cmd:app.hotPixelLimit` | Lightroom has no control for this. Here a box under Noise Reduction (raws only), on for newly imported raws and off for edits saved before it existed (issue #1345): single photosites far above all their same-colour neighbours are replaced in the mosaic before demosaicing; a point lit across neighbouring photosites (a star, a spark) is kept. A raw with more than 0.2 % of its photosites to replace (real light kept doesn't count) is left unchanged; Settings ▸ Performance ▸ Hot pixel limit sets the share (test `the_hot_pixel_limit_renders_afresh_only_the_photos_that_remove_hot_pixels`). Switching it decodes the raw again (tests `hot_pixel_box_is_on_for_new_raws_only`, `hot_pixel_box_decodes_the_raw_again`) | | LR-EDIT-OPTICS-CA | Remove chromatic aberration | P1 | ✅ | `crates/ui-egui/src/panels/edit.rs` (checkbox), `ctl:optics.caRed`, `ctl:optics.caBlue` | | -| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `craft-raw`, `craft-raw`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, ILCE-7M3 (FE 16–35 F4 ZA, FE 28–70, FE 50 F1.8; 26 shots within 0.06–0.44 px median of the camera JPEG at 6000 px, from up to 26 px uncorrected), and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `craft-raw`, `docs/nikon-lens-corrections.md`) for the Z 6, Z 7, Z 6II, Z 8 and Z f, full-frame image area only (modes 1/3 on, mode 2 off and unknown modes skipped); the Z 6 / Z 7 extension is measured on six exposures of two scenes with the 24-70mm f/4 S at 52/56 mm, corrected radial medians 0.88-0.96 / 1.37-1.46 px, with extreme corners unvalidated; Nikon vignetting remains unfinished and no fitted body strength is applied; camera-look and render-cache versions advance together, old smart previews rebuild online and remain usable offline, Reload updates lens metadata while preserving edited settings: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `craft-raw`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-T30 III, X-M5, X-T5 crops; X-S20 supported) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`craft-raw`), but only the ILCE-7RM4A, ILCE-7M3, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; lens database: the desktop app offers lensfun's `data/db` once on the first launch (Download / Not Now with its size; Settings ▸ General ▸ Lens profiles downloads it later; nothing is fetched without that click; CC BY-SA 3.0, pinned by commit, size and SHA-256, never bundled; `cmd:lens.downloadDatabase`, `crates/engine/src/lensfun_download.rs`) and downloads it with an activity row, and when it arrives every library raw whose lens it knows is looked up again in the background (`cmd:library.refreshLensProfiles`, `crates/engine/src/cmd/lens_refresh.rs`), as is a photo whose Enable Lens Corrections is ticked; the Optics panel names the loaded profile and its source, or says "No lens profile found for " (`crates/ui-egui/src/lens_db.rs`); presets, Copy / Paste and Sync carry only the switch and amounts, never a profile (`crates/engine/src/tests/lens_refresh.rs`); no source picker or own calibration yet | +| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `craft-raw`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, ILCE-7M3 (FE 16–35 F4 ZA, FE 28–70, FE 50 F1.8; 26 shots within 0.06–0.44 px median of the camera JPEG at 6000 px, from up to 26 px uncorrected), and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon Z 6, Z 7, Z 6II, Z 8 and Z f NEFs use the distortion warp from `craft-raw` for supported full-frame images in modes 1 and 3. The profile switch and amount control the warp in previews and exports. DNG export preserves it. Nikon vignetting remains unfinished ([Nikon corrections](nikon-lens-corrections.md)); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `craft-raw`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-T30 III, X-M5, X-T5 crops; X-S20 supported) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`craft-raw`), but only the ILCE-7RM4A, ILCE-7M3, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; lens database: the desktop app offers lensfun's `data/db` once on the first launch (Download / Not Now with its size; Settings ▸ General ▸ Lens profiles downloads it later; nothing is fetched without that click; CC BY-SA 3.0, pinned by commit, size and SHA-256, never bundled; `cmd:lens.downloadDatabase`, `crates/engine/src/lensfun_download.rs`) and downloads it with an activity row, and when it arrives every library raw whose lens it knows is looked up again in the background (`cmd:library.refreshLensProfiles`, `crates/engine/src/cmd/lens_refresh.rs`), as is a photo whose Enable Lens Corrections is ticked; the Optics panel names the loaded profile and its source, or says "No lens profile found for " (`crates/ui-egui/src/lens_db.rs`); presets, Copy / Paste and Sync carry only the switch and amounts, never a profile (`crates/engine/src/tests/lens_refresh.rs`); no source picker or own calibration yet | ) | LR-EDIT-OPTICS-DEFRINGE | Defringe | P1 | ✅ | `ctl:optics.defringe*` | no fringe eyedropper | | LR-EDIT-OPTICS-MANUAL | Manual distortion / vignetting | P1 | ✅ | `ctl:optics.distortion`, `ctl:optics.vignetting`, `ctl:optics.vignettingMidpoint` | | diff --git a/docs/raw/coverage_render_sweep.py b/docs/raw/coverage_render_sweep.py deleted file mode 100644 index 896a40e9f3a..00000000000 --- a/docs/raw/coverage_render_sweep.py +++ /dev/null @@ -1,266 +0,0 @@ -#!/usr/bin/env python3 -"""Compare production CLI exports across all 40 pinned coverage-sweep inputs. - -Run from the repository root with Python, numpy, scipy, Pillow and exiftool: - python3 docs/raw/coverage_render_sweep.py --cli BASE_CLI --out corpus/nikon-lens/base - python3 docs/raw/coverage_render_sweep.py --cli CANDIDATE_CLI --out corpus/nikon-lens/candidate \ - --compare corpus/nikon-lens/base/scores.json - -Use a fresh output directory per binary. The second run reuses the first run's -reference images and framing. Existing PNGs allow an interrupted run to resume. -Inputs are only the SHA-256-pinned public corpus rows. Images and binary copies -stay in gitignored corpus; commit the numerical evidence separately. PreviewTIFF -rows use encoded-luminance correlation for structure only, with no sRGB transfer -or colour-error metrics. Older PreviewTIFF baseline scores must be regenerated -with this tool; valid cached PNGs can be reused. -Cache filenames include the input SHA-256. Legacy stem-only caches are ignored. -""" -import argparse, csv, hashlib, io, json, math, os, subprocess, sys -from pathlib import Path -import numpy as np -from PIL import Image, ImageOps -from nikon_lens_probe import score - - -def readable_png(path): - """Only a complete, decodable PNG can stand in for a completed render.""" - try: - with Image.open(path) as image: - if image.format != "PNG": - return False - image.verify() - with Image.open(path) as image: - image.load() - return True - except (OSError, ValueError, SyntaxError, Image.DecompressionBombError): - return False - - -def measure_pair(render, reference, structure_only): - if not structure_only: - return score(render, reference) - # Unknown TIFF encoding: compare spatial luminance without assuming an sRGB transfer function. - if reference.width <= 0 or reference.height <= 0: - raise ValueError("structure reference dimensions must be positive") - height = round(reference.height * 200 / reference.width) - if not 1 <= height <= 2000: - raise ValueError("structure reference aspect ratio exceeds the scoring limit") - size = (200, height) - a, b = [ - np.asarray(ImageOps.grayscale(image).resize(size, Image.Resampling.LANCZOS), dtype=float) - for image in (render, reference) - ] - if np.std(a) < 1e-8 or np.std(b) < 1e-8: - raise ValueError("cannot correlate a constant structure image") - return dict(r=float(np.corrcoef(a.ravel(), b.ravel())[0, 1])) - - -def compare_record(name, record, base): - """Compare scores only after confirming that both runs measured the same inputs.""" - if not isinstance(base, dict): - raise ValueError("baseline record missing or invalid: " + name) - for key in ("file_sha256", "reference_sha256", "reference_size", "reference", "rotation"): - if base.get(key) != record[key]: - raise ValueError("baseline " + key + " differs: " + name) - if base.get("metric_kind", "lab_lstar") != record["metric_kind"]: - raise ValueError("baseline metric_kind differs; regenerate baseline scores: " + name) - keys = ("r", "mean_dl", "outer_mae_dl") if record["metric_kind"] == "lab_lstar" else ("r",) - for key in keys: - value = base.get(key) - if type(value) not in (int, float) or not math.isfinite(value): - raise ValueError("baseline " + key + " is missing or non-finite: " + name) - if not isinstance(base.get("pixel_sha256"), str): - raise ValueError("baseline pixel_sha256 is missing or invalid: " + name) - record["pixels_changed"] = record["pixel_sha256"] != base["pixel_sha256"] - record["delta_r"] = record["r"] - base["r"] - if record["metric_kind"] == "lab_lstar": - record["delta_abs_mean_dl"] = abs(record["mean_dl"]) - abs(base["mean_dl"]) - - -def metrics_regressed(record, base): - if record["r"] < base["r"] - 1e-9: - return True - return record["metric_kind"] == "lab_lstar" and ( - abs(record["mean_dl"]) > abs(base["mean_dl"]) + 1e-9 - or record["outer_mae_dl"] > base["outer_mae_dl"] + 1e-9 - ) - - -def main(): - p = argparse.ArgumentParser() - p.add_argument("--cli", type=Path, required=True) - p.add_argument("--out", type=Path, required=True) - p.add_argument("--compare", type=Path) - a = p.parse_args() - a.out.mkdir(parents=True, exist_ok=True) - rows = list( - csv.DictReader( - [ - l - for l in Path("docs/raw/coverage-sweep.tsv").read_text().splitlines() - if not l.startswith("#") - ], - delimiter="\t", - ) - ) - previous = json.loads(a.compare.read_text())["records"] if a.compare else None - if previous is not None and ( - not isinstance(previous, dict) or set(previous) != {row["file"] for row in rows} - ): - raise ValueError("baseline input files differ from the coverage manifest") - empty = Path("corpus/nikon-lens/empty-lensdb").resolve() - empty.mkdir(parents=True, exist_ok=True) - env = dict( - os.environ, - LIGHTCRAFT_GPU="0", - LIGHTCRAFT_LENSFUN_DIR=str(empty), - RAYON_NUM_THREADS="6", - ) - results = {} - cli_sha = hashlib.sha256(a.cli.read_bytes()).hexdigest() - record_path = a.out / "run.json" - configuration = dict( - cli_sha256=cli_sha, - compare=str(a.compare.resolve()) if a.compare else None, - rayon_threads=6, - gpu=False, - ) - if record_path.exists() and json.loads(record_path.read_text()) != configuration: - raise ValueError( - "output directory belongs to a different binary or comparison; use a fresh directory" - ) - record_path.write_text(json.dumps(configuration, indent=2, allow_nan=False) + "\n") - for row in rows: - raw = Path("corpus/raw") / row["file"] - digest = hashlib.sha256(raw.read_bytes()).hexdigest() - if digest != row["sha256"]: - raise ValueError("SHA-256 mismatch " + row["file"]) - cache_stem = raw.stem + "-" + digest - out = a.out / (cache_stem + ".png") - ref = (a.compare.parent if a.compare else a.out) / (cache_stem + "-reference.png") - if not readable_png(out): - with (a.out / (cache_stem + ".log")).open("w") as log: - subprocess.run( - [str(a.cli), "render", str(raw), "-o", str(out), "--size", "1200"], - env=env, - stdout=log, - stderr=log, - check=True, - ) - if not ref.exists(): - images = [] - for tag in ("JpgFromRaw", "PreviewImage", "PreviewTIFF"): - data = subprocess.check_output( - ["exiftool", "-b", "-" + tag, str(raw)], stderr=subprocess.DEVNULL - ) - if data: - im = Image.open(io.BytesIO(data)) - im.load() - images.append((im.width * im.height, tag, im.convert("RGB"))) - if not images: - tags = json.loads( - subprocess.check_output( - [ - "exiftool", - "-j", - "-n", - "-G1", - "-StripOffsets", - "-StripByteCounts", - "-Compression", - str(raw), - ] - ) - )[0] - for key, compression in tags.items(): - if not key.endswith(":Compression") or compression not in (6, 7): - continue - group = key.rsplit(":", 1)[0] - offset = tags.get(group + ":StripOffsets") - length = tags.get(group + ":StripByteCounts") - if ( - not isinstance(offset, int) - or not isinstance(length, int) - or length <= 0 - or length > 64 * 1024 * 1024 - or offset < 0 - or offset + length > raw.stat().st_size - ): - continue - with raw.open("rb") as stream: - stream.seek(offset) - data = stream.read(length) - im = Image.open(io.BytesIO(data)) - im.load() - images.append( - (im.width * im.height, group + " JPEG strip", im.convert("RGB")) - ) - if not images: - raise ValueError("no camera reference in " + row["file"]) - _, tag, reference = max(images, key=lambda x: x[0]) - reference.save(ref) - else: - reference = Image.open(ref).convert("RGB") - tag = "cached" - rendered = Image.open(out).convert("RGB") - pixel_sha = hashlib.sha256( - f"{rendered.width}x{rendered.height}:RGB:".encode() + rendered.tobytes() - ).hexdigest() - rotation = 180 if "comparison Rotate180/" in row["notes"] else 0 - if rotation: - rendered = rendered.rotate(rotation, expand=True) - # The historical records use crop-render: retain the camera's reference aspect and center-crop the render. - framed = ImageOps.fit( - rendered, - (200, round(reference.height * 200 / reference.width)), - method=Image.Resampling.LANCZOS, - centering=(0.5, 0.5), - ) - structure_only = "PreviewTIFF" in row["reference"] - measured = measure_pair(framed, reference, structure_only) - record = dict( - file_sha256=digest, - pixel_sha256=pixel_sha, - render_size=rendered.size, - reference=row["reference"], - reference_sha256=hashlib.sha256(reference.tobytes()).hexdigest(), - reference_size=list(reference.size), - rotation=rotation, - metric_kind="structure_luma" if structure_only else "lab_lstar", - **measured, - ) - if previous is not None: - compare_record(row["file"], record, previous.get(row["file"])) - results[row["file"]] = record - (a.out / "scores.json").write_text( - json.dumps( - dict( - cli_sha256=cli_sha, - method="CLI PNG 1200px; CPU; 6 Rayon threads; no lens database; largest embedded reference; recorded rotation; center crop-render; Lab L* 200px for display references, encoded-luminance r only for PreviewTIFF; outer rho>=0.75; pixel SHA256 includes WxH:RGB: and row-major RGB bytes", - records=results, - ), - indent=2, - allow_nan=False, - ) - + "\n" - ) - print(row["file"], json.dumps(record, allow_nan=False), flush=True) - - if previous is not None: - regressions = [ - name - for name, record in results.items() - if metrics_regressed(record, previous[name]) - ] - if regressions: - raise ValueError( - "render/reference metrics regressed: " + ", ".join(regressions) - ) - - -if __name__ == "__main__": - try: - main() - except (ValueError, OSError, subprocess.CalledProcessError) as error: - print(f"coverage_render_sweep: {error}", file=sys.stderr) - sys.exit(1) diff --git a/docs/raw/nikon_lens_probe.py b/docs/raw/nikon_lens_probe.py deleted file mode 100644 index 869542b116b..00000000000 --- a/docs/raw/nikon_lens_probe.py +++ /dev/null @@ -1,612 +0,0 @@ -#!/usr/bin/env python3 -"""Measure Nikon optics without changing LightCraft's decoder or saved edits. - -Requires Python with numpy, scipy and Pillow, plus exiftool. Build the companion: - CARGO_TARGET_DIR=target/agent-nikon-lens cargo build --release -p lightcraft-engine \ - --example nikon_lens_probe -Run on SHA-256-verified, local CC0 corpus files: - python3 docs/raw/nikon_lens_probe.py --binary target/agent-nikon-lens/release/examples/nikon_lens_probe \ - --out corpus/nikon-lens corpus/raw/coverage-3584.nef - -Outputs contain camera images and must remain outside version control. Never point -this at private originals when sharing the output folder. TIFF fields are read -here directly. ExifTool's documentation gives tag identities and offsets; the tool -extracts metadata and embedded JPEG data black-box. No external decoder implementation -is read. Models are hypotheses, not production -corrections. The default render uses the existing camera look; replacing optics -after source loading deliberately does not refit that look. -""" -import argparse -import hashlib -import json -import math -from pathlib import Path -import struct -import subprocess -import sys - -import numpy as np -from PIL import Image -from scipy import ndimage, optimize, signal - - -def json_text(value, **kwargs): - """Reject non-finite output instead of writing nonstandard JSON NaN/Infinity.""" - return json.dumps(value, allow_nan=False, **kwargs) - - -def validate_fit_samples(train, radius): - """Require both tile parities and radial coverage before fitting or averaging. - - At least 250 pairs in each split, and 32 in each inner/middle/outer bin - of each split, keep empty or tiny regions from masquerading as evidence. - """ - for name, split in (("training", train), ("validation", ~train)): - if np.count_nonzero(split) < 250: - raise ValueError(f"not enough {name} brightness pairs") - for lo, hi in ((0, 0.35), (0.35, 0.75), (0.75, 0.95)): - if np.count_nonzero(split & (radius >= lo) & (radius < hi)) < 32: - raise ValueError(f"not enough {name} pairs in radial bin {lo} to {hi}") - - -def tiff_entries(data, offset, order): - """Read one bounded classic-TIFF IFD, without following arbitrary pointers.""" - if offset < 0 or offset + 2 > len(data): - raise ValueError("invalid IFD offset") - count = struct.unpack_from(order + "H", data, offset)[0] - if count > 4096 or offset + 2 + count * 12 > len(data): - raise ValueError("invalid IFD length") - sizes = {1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8} - result = {} - for i in range(count): - at = offset + 2 + i * 12 - tag, kind, n, value = struct.unpack_from(order + "HHII", data, at) - if kind not in sizes: - raise ValueError("unsupported TIFF entry type") - length = sizes[kind] * n - start = at + 8 if length <= 4 else value - if length > 16 * 1024 * 1024 or start + length > len(data): - raise ValueError("invalid TIFF entry range") - result[tag] = data[start : start + length] - return result - - -def nef_blocks(path): - """Read NikonNEFInfo through the raw SubIFD, not a decoder's interpretation.""" - data = path.read_bytes() - order = "<" if data[:2] == b"II" else ">" - root = tiff_entries(data, struct.unpack_from(order + "I", data, 4)[0], order) - offsets = root.get(330, b"") - if len(offsets) % 4 or len(offsets) > 128: - raise ValueError("invalid SubIFD offsets") - for at in struct.unpack(order + "I" * (len(offsets) // 4), offsets): - blob = tiff_entries(data, at, order).get(0xC7D5) - if blob is not None: - if not blob.startswith(b"Nikon\0"): - raise ValueError("unrecognized NikonNEFInfo") - inner = blob[10:] - order = "<" if inner[:2] == b"II" else ">" - entries = tiff_entries( - inner, struct.unpack_from(order + "I", inner, 4)[0], order - ) - - def rat(block, at): - n, d = struct.unpack_from(order + "ii", block, at) - if d <= 0: - raise ValueError("invalid signed rational") - return n / d - - distortion, vignette, center = (entries[k] for k in (5, 6, 8)) - for name, block, minimum in ( - ("DistortionInfo", distortion, 72), - ("VignetteInfo", vignette, 104), - ("optical center", center, 20), - ): - if len(block) < minimum: - raise ValueError(f"truncated {name} block: need {minimum} bytes") - return dict( - distortion_version=distortion[:4].decode("ascii"), - distortion_mode=distortion[4], - distortion_radius=rat(distortion, 8), - distortion_k=[rat(distortion, at) for at in (20, 28, 36)], - zoom=rat(distortion, 64), - center=[rat(center, at) for at in (4, 12)], - vignette_version=vignette[:4].decode("ascii"), - vignette_mode=vignette[4], - vignette_radius=rat(vignette, 8), - vignette_terms=struct.unpack_from(order + "I", vignette, 16)[0], - vignette_polynomial=[rat(vignette, at) for at in range(20, 92, 8)], - vignette_tail=rat(vignette, 96), - blocks={str(k): entries[k].hex() for k in (5, 6, 8)}, - ) - raise ValueError("NikonNEFInfo absent") - - -def proxy(folder): - """Read the companion example's little-endian camera RGB float dump.""" - data = (folder / "camera-rgb.f32").read_bytes() - w, h = struct.unpack_from(" 16_000_000 or len(data) != 8 + w * h * 12: - raise ValueError("invalid proxy dimensions or length") - return np.frombuffer(data, " 216 / 24389, 116 * np.cbrt(y) - 16, y * 24389 / 27) - - -def score(render, reference): - """Pearson and signed render-minus-reference dL, all pixels and outer ring.""" - # The old sweep's alignment script is absent from this checkout. Here both frames have - # the camera's aspect ratio, normal orientation, and are resized directly. - size = (200, round(reference.height * 200 / reference.width)) - a = lstar(render.convert("RGB").resize(size, Image.Resampling.LANCZOS)) - b = lstar(reference.convert("RGB").resize(size, Image.Resampling.LANCZOS)) - y, x = np.mgrid[: a.shape[0], : a.shape[1]] - rho = ( - np.hypot((x + 0.5 - a.shape[1] / 2), (y + 0.5 - a.shape[0] / 2)) - / math.hypot(*a.shape) - * 2 - ) - ring = rho >= 0.75 - if np.std(a) < 1e-8 or np.std(b) < 1e-8: - raise ValueError("cannot correlate a constant image") - delta = a - b - return dict( - r=float(np.corrcoef(a.ravel(), b.ravel())[0, 1]), - mean_dl=float(delta.mean()), - outer_mean_dl=float(delta[ring].mean()), - outer_mae_dl=float(np.abs(delta[ring]).mean()), - outer_pixels=int(ring.sum()), - ) - - -def patches(camera, jpeg, raw, meta): - """NCC patch matches with subpixel peaks; no fitted geometry parameters.""" - h, w = camera.shape[:2] - reference = np.asarray(jpeg.resize((w, h), Image.Resampling.LANCZOS), float)[..., 1] - source = np.log(np.maximum(camera[..., 1], 1e-6)) - reference = np.log(np.maximum(reference, 1)) - sx, sy, _ = coordinates(raw, meta, camera.shape) - records = [] - radius, search = 9, 12 - for y in np.linspace(24, h - 25, 19).astype(int): - for x in np.linspace(24, w - 25, 27).astype(int): - px, py = (sx[y, x] + 0.5) / 4 - 0.5, (sy[y, x] + 0.5) / 4 - 0.5 - ix, iy = round(px), round(py) - if ( - ix - search - radius < 0 - or iy - search - radius < 0 - or ix + search + radius >= w - or iy + search + radius >= h - ): - continue - template = reference[ - y - radius : y + radius + 1, x - radius : x + radius + 1 - ] - template = template - template.mean() - if np.std(template) < 0.025: - continue - region = source[ - iy - search - radius : iy + search + radius + 1, - ix - search - radius : ix + search + radius + 1, - ] - n = template.size - ones = np.ones(template.shape) - sums = signal.correlate2d(region, ones, mode="valid") - squares = signal.correlate2d(region**2, ones, mode="valid") - cc = signal.correlate2d(region, template, mode="valid") / np.sqrt( - np.maximum((squares - sums**2 / n) * np.sum(template**2), 1e-20) - ) - by, bx = np.unravel_index(np.argmax(cc), cc.shape) - peak = cc[by, bx] - cc_other = cc.copy() - cc_other[max(0, by - 3) : by + 4, max(0, bx - 3) : bx + 4] = -1 - if ( - peak < 0.9 - or peak - cc_other.max() < 0.02 - or bx in (0, 2 * search) - or by in (0, 2 * search) - ): - continue - - def sub(a, b, c): - denominator = a - 2 * b + c - return ( - float(np.clip(0.5 * (a - c) / denominator, -0.5, 0.5)) - if denominator < -1e-8 - else 0 - ) - - dx = sub(cc[by, bx - 1], peak, cc[by, bx + 1]) - dy = sub(cc[by - 1, bx], peak, cc[by + 1, bx]) - mx, my = ix + bx - search + dx, iy + by - search + dy - records.append([x, y, px, py, mx, my, float(peak)]) - points = np.asarray(records) - if len(points) < 12: - raise ValueError("too few reliable patch matches") - errors = np.hypot(points[:, 4] - points[:, 2], points[:, 5] - points[:, 3]) * 4 - before = np.hypot(points[:, 4] - points[:, 0], points[:, 5] - points[:, 1]) * 4 - return dict( - matches=len(points), - before_median_px=float(np.median(before)), - before_p95_px=float(np.quantile(before, 0.95)), - after_median_px=float(np.median(errors)), - after_p95_px=float(np.quantile(errors, 0.95)), - points=points.tolist(), - **geometry_details(points, raw, meta), - ) - - -def geometry_details(points, raw, meta): - """Radial residuals, reversed-order control, and an independently fitted zoom.""" - points = np.asarray(points, dtype=float) - if points.ndim != 2 or points.shape[1] < 6 or not np.isfinite(points).all(): - raise ValueError("invalid or non-finite geometry patch positions") - cw, ch = raw["crop"]["width"] - 1, raw["crop"]["height"] - 1 - numbers = np.asarray([cw, ch, *meta["center"], *meta["distortion_k"], meta["zoom"]]) - if not np.isfinite(numbers).all(): - raise ValueError("non-finite geometry dimensions or lens coefficients") - if cw <= 0 or ch <= 0: - raise ValueError("geometry needs an image area wider and taller than one pixel") - zoom_denominator = 1 + meta["zoom"] - if zoom_denominator <= 0: - raise ValueError("geometry zoom denominator 1 + zoom must be positive") - cx, cy = cw / 2 + meta["center"][0], ch / 2 + meta["center"][1] - dx = (points[:, 0] + 0.5) * 4 - 0.5 - cx - dy = (points[:, 1] + 0.5) * 4 - 0.5 - cy - mx = (points[:, 4] + 0.5) * 4 - 0.5 - cx - my = (points[:, 5] + 0.5) * 4 - 0.5 - cy - length = np.hypot(dx, dy) - rho = length / (math.hypot(cw, ch) / 2) - measured = (mx * dx + my * dy) / np.maximum(length, 1e-9) - k1, k2, k3 = meta["distortion_k"] - x = rho**2 - unscaled = length * (1 + x * (k3 + x * (k2 + x * k1))) - predicted = unscaled / zoom_denominator - reversed_order = length * (1 + x * (k1 + x * (k2 + x * k3))) / zoom_denominator - if not all(np.isfinite(array).all() for array in (rho, measured, unscaled, predicted, reversed_order)): - raise ValueError("non-finite geometry radii or distortion predictions") - use = (rho > 0.15) & (rho < 0.95) - count = int(np.count_nonzero(use)) - if count < 20: - raise ValueError(f"too few radial geometry matches: {count}; need at least 20 with 0.15 < rho < 0.95") - norm = float(np.dot(unscaled[use], unscaled[use])) - projected = float(np.dot(unscaled[use], measured[use])) - if not math.isfinite(norm) or not math.isfinite(projected) or norm <= 0 or projected <= 0: - raise ValueError("geometry zoom fit has a zero, negative or non-finite denominator; check matched radii") - zoom = norm / projected - 1 - radial = np.abs(measured[use] - predicted[use]) - result = dict( - before_radial_median_px=float(np.median(np.abs(measured[use] - length[use]))), - before_radial_p95_px=float( - np.quantile(np.abs(measured[use] - length[use]), 0.95) - ), - radial_median_px=float(np.median(radial)), - radial_p95_px=float(np.quantile(radial, 0.95)), - reversed_order_radial_median_px=float( - np.median(np.abs(measured[use] - reversed_order[use])) - ), - stored_zoom=meta["zoom"], - fitted_zoom=float(zoom), - radius_min=float(rho.min()), - radius_max=float(rho.max()), - ) - if not all(math.isfinite(value) for value in result.values()): - raise ValueError("non-finite geometry fit statistics") - return result - - -def vignette_fit(camera, jpeg, raw, meta): - """Compare gain hypotheses with a nuisance tone curve and spatial holdout. - - A spline absorbs global Picture Control contrast. Colour ratios absorb the - first-order camera-to-JPEG colour transform. No radial term enters that fit. - Alternate 24-pixel tiles are withheld. The fitted gain strength is diagnostic - only, never a per-file production adjustment. Scene/radius confounding remains - possible, especially on the Auto Picture Control samples. - """ - w = 480 - h = round(jpeg.height * w / jpeg.width) - sx, sy, r2 = coordinates(raw, meta, (h, w)) - sensor = sample(camera, sx, sy) - rgb = np.asarray(jpeg.resize((w, h), Image.Resampling.LANCZOS), float) / 255 - target = np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4) - yy, xx = np.mgrid[:h, :w] - mask = ( - (rgb.min(axis=-1) > 0.04) - & (rgb.max(axis=-1) < 0.95) - & (sensor.min(axis=-1) > 0.0002) - & (sensor.max(axis=-1) < 0.9) - & (r2 < 0.95**2) - ) - # Smooth edges can compare different subjects when geometry is imperfect. - grad = np.hypot( - ndimage.sobel(np.log(np.maximum(target[..., 1], 1e-5)), 0), - ndimage.sobel(np.log(np.maximum(target[..., 1], 1e-5)), 1), - ) - mask &= grad < 1.0 - train = ((xx // 24 + yy // 24) % 2 == 0)[mask] - radius = np.sqrt(r2[mask]) - green = np.log(sensor[..., 1][mask]) - response = np.log(target[..., 1][mask]) - colours = np.log( - np.maximum(sensor[..., [0, 2]][mask], 1e-8) / sensor[..., 1][mask, None] - ) - red, blue = colours.T - poly = meta["vignette_polynomial"] - x = r2[mask] - complete = np.polyval(poly, np.sqrt(x)) - named = 1 + x * (poly[6] + x * (poly[4] + x * poly[2])) - validate_fit_samples(train, radius) - if not all(np.isfinite(a).all() for a in (green, response, colours, complete)): - raise ValueError("non-finite brightness pairs or gain") - if not np.all(complete > 0): - raise ValueError("not enough valid brightness pairs or nonpositive gain") - - def fit(gain): - if not np.isfinite(gain).all() or not np.all(gain > 0): - raise ValueError("non-finite or nonpositive candidate gain") - corrected = green + np.log(gain) - knots = np.linspace(-11, 1, 17) - design = np.stack( - [np.ones_like(green), corrected] - + [np.maximum(corrected - k, 0) for k in knots[1:-1]] - + [red, blue, red * blue, red**2, blue**2], - axis=-1, - ) - coef = np.linalg.lstsq(design[train], response[train], rcond=1e-8)[0] - residual = response - design @ coef - test = ~train - ring = test & (radius >= 0.75) - inner = test & (radius <= 0.35) - statistics = dict( - training_log_rmse=float(np.sqrt(np.mean(residual[train] ** 2))), - heldout_log_rmse=float(np.sqrt(np.mean(residual[test] ** 2))), - outer_log_bias=float(np.mean(residual[ring])), - inner_log_bias=float(np.mean(residual[inner])), - outer_minus_inner=float(np.mean(residual[ring]) - np.mean(residual[inner])), - ) - if not all(math.isfinite(value) for value in statistics.values()): - raise ValueError("non-finite brightness fit statistics") - return statistics - - candidates = { - "none": np.ones_like(x), - "complete": complete, - "named_three": named, - "reciprocal": 1 / complete, - "sqrt": np.sqrt(complete), - "squared": complete**2, - "tail_strength": 1 + meta["vignette_tail"] * (complete - 1), - "stops": 2 ** (complete - 1), - } - result = {name: fit(gain) for name, gain in candidates.items()} - fitted = optimize.minimize_scalar( - lambda a: fit(1 + a * (complete - 1))["training_log_rmse"], - bounds=(0, 2), - method="bounded", - options={"xatol": 0.01}, - ) - if not fitted.success or not math.isfinite(fitted.x): - raise ValueError("brightness strength optimization did not converge") - result["fitted_strength"] = dict( - alpha=float(fitted.x), **fit(1 + fitted.x * (complete - 1)) - ) - result["samples"] = len(green) - result["outer_samples"] = int(np.sum((~train) & (radius >= 0.75))) - result["gains_at_rho"] = { - str(r): float(np.polyval(poly, r)) for r in (0.25, 0.5, 0.75, 1) - } - return result - - -def opcodes(raw, meta, vignette=False, strength=1.0): - """Convert candidate models to the existing active-area OpcodeList3 convention.""" - crop, active = raw["crop"], raw["active_area"] - cw, ch = crop["width"] - 1, crop["height"] - 1 - ax, ay = active["width"] - 1, active["height"] - 1 - cx, cy = ( - crop["x"] + cw / 2 + meta["center"][0], - crop["y"] + ch / 2 + meta["center"][1], - ) - half = math.hypot(cw, ch) / 2 - a = math.hypot(max(cx, ax - cx), max(cy, ay - cy)) / half - k1, k2, k3 = meta["distortion_k"] - s = 1 / (1 + meta["zoom"]) - result = [ - { - "WarpRectilinear": dict( - planes=[[s, k3 * a * a * s, k2 * a**4 * s, k1 * a**6 * s, 0, 0]], - center=[cx / ax, cy / ay], - ) - } - ] - if vignette: - poly = meta["vignette_polynomial"] - result.insert( - 0, - { - "FixVignetteRadial": dict( - k=[ - strength * poly[6] * a * a, - strength * poly[4] * a**4, - strength * poly[2] * a**6, - strength * poly[0] * a**8, - 0, - ], - center=[cx / ax, cy / ay], - ) - }, - ) - return result - - -def prepare(path, folder, binary): - """Write diagnostics beside verified public inputs, without touching originals.""" - folder.mkdir(parents=True, exist_ok=True) - previous = folder / "metadata.json" - digest = hashlib.sha256(path.read_bytes()).hexdigest() - if previous.exists() and json.loads(previous.read_text()).get("sha256") != digest: - raise ValueError("output folder belongs to another input; use a fresh folder") - subprocess.run([str(binary), str(path), str(folder)], check=True) - tags = [ - "Model", - "LensModel", - "FocalLength", - "FNumber", - "DateTimeOriginal", - "ShutterCount", - "VignetteControl", - "PictureControlName", - "ActiveD-Lighting", - "AutoDistortionControl", - "ColorSpace", - ] - exif = json.loads( - subprocess.check_output( - ["exiftool", "-j", "-n"] + ["-" + t for t in tags] + [str(path)] - ) - )[0] - exif.pop("SourceFile", None) - if exif.get("ColorSpace") != 1: - raise ValueError("this probe currently requires an sRGB camera JPEG") - meta = nef_blocks(path) - meta.update(exif=exif, sha256=hashlib.sha256(path.read_bytes()).hexdigest()) - (folder / "metadata.json").write_text(json_text(meta, indent=2) + "\n") - if not (folder / "camera.jpg").exists(): - data = subprocess.check_output(["exiftool", "-b", "-JpgFromRaw", str(path)]) - if not data: - raise ValueError("full-size embedded camera JPEG absent") - (folder / "camera.jpg").write_bytes(data) - raw = json.loads((folder / "raw.json").read_text()) - crop = raw["crop"] - if crop["width"] % 4 or crop["height"] % 4: - raise ValueError("this probe requires crop dimensions divisible by four") - if raw["orientation"] != "Normal": - raise ValueError("this probe currently requires normal EXIF orientation") - with Image.open(folder / "camera.jpg") as jpeg: - if jpeg.size != (crop["width"], crop["height"]): - raise ValueError("camera JPEG does not cover the full default crop") - for name, vig, strength in [ - ("distortion", False, 1), - ("vignette", True, 1), - ("vignette-tail", True, meta["vignette_tail"]), - ]: - ops = folder / (name + ".json") - ops.write_text(json_text(opcodes(raw, meta, vig, strength), indent=2) + "\n") - return raw, meta - - -def main(): - """Prepare data and report baseline and geometry, leaving production untouched.""" - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--binary", type=Path, required=True) - parser.add_argument("--out", type=Path, required=True) - parser.add_argument( - "--render-candidates", - action="store_true", - help="render the stored polynomial hypotheses after source loading", - ) - parser.add_argument("files", type=Path, nargs="+") - args = parser.parse_args() - for path in args.files: - folder = args.out / path.stem - manifest = Path(__file__).with_name("coverage-sweep.tsv") - for line in manifest.read_text().splitlines(): - cols = line.split("\t") - if ( - len(cols) == 14 - and cols[3] == path.name - and hashlib.sha256(path.read_bytes()).hexdigest() != cols[5] - ): - raise ValueError("input differs from pinned coverage-sweep SHA-256") - raw, meta = prepare(path, folder, args.binary) - camera = proxy(folder) - jpeg = Image.open(folder / "camera.jpg").convert("RGB") - result = dict( - sha256=meta["sha256"], - exif=meta["exif"], - baseline=score(Image.open(folder / "baseline.png"), jpeg), - distortion=patches(camera, jpeg, raw, meta), - vignette=vignette_fit(camera, jpeg, raw, meta), - ) - if args.render_candidates: - scores = {} - for name in ("distortion", "vignette", "vignette-tail"): - subprocess.run( - [ - str(args.binary), - str(path), - str(folder), - str(folder / (name + ".json")), - ], - check=True, - ) - (folder / "candidate.png").replace(folder / (name + ".png")) - scores[name] = score(Image.open(folder / (name + ".png")), jpeg) - result["experimental_renders_no_look_refit"] = scores - (folder / "measurements.json").write_text(json_text(result, indent=2) + "\n") - print( - path.name, - json_text( - dict( - baseline=result["baseline"], - fitted_strength=result["vignette"]["fitted_strength"], - ) - ), - flush=True, - ) - print( - "distortion", - json_text({k: v for k, v in result["distortion"].items() if k != "points"}), - flush=True, - ) - - -if __name__ == "__main__": - try: - main() - except ( - ValueError, - OSError, - KeyError, - struct.error, - subprocess.CalledProcessError, - ) as error: - print(f"nikon_lens_probe: {error}", file=sys.stderr) - sys.exit(1) diff --git a/docs/raw/test_coverage_render_sweep.py b/docs/raw/test_coverage_render_sweep.py deleted file mode 100644 index cab68e39b86..00000000000 --- a/docs/raw/test_coverage_render_sweep.py +++ /dev/null @@ -1,242 +0,0 @@ -"""Synthetic sweep-tool checks, with no corpus or external renderer required. - -Run: python3 -m unittest discover -s docs/raw -p 'test_*.py' -""" - -import copy -import csv -import hashlib -import io -import json -import os -from pathlib import Path -import tempfile -import unittest -from unittest import mock - -import numpy as np -from PIL import Image - -import coverage_render_sweep as sweep - - -def gradient(): - values = np.tile(np.arange(20, 220, 4, dtype=np.uint8), (32, 1)) - return Image.fromarray(np.repeat(values[..., None], 3, axis=-1)) - - -class Measurements(unittest.TestCase): - def test_preview_tiff_uses_structure_without_srgb_colour_metrics(self): - image = gradient() - with mock.patch.object(sweep, "score", side_effect=AssertionError("colour scorer must not run")): - measured = sweep.measure_pair(image, image, True) - self.assertEqual(set(measured), {"r"}) - self.assertAlmostEqual(measured["r"], 1) - with self.assertRaisesRegex(ValueError, "constant structure"): - sweep.measure_pair(Image.new("RGB", (32, 32)), image, True) - with self.assertRaisesRegex(ValueError, "aspect ratio"): - sweep.measure_pair(image, Image.new("RGB", (1, 11)), True) - with self.assertRaisesRegex(ValueError, "dimensions"): - sweep.measure_pair(image, Image.new("RGB", (0, 1)), True) - - def test_display_references_keep_the_existing_colour_scorer(self): - image = gradient() - self.assertEqual(sweep.measure_pair(image, image, False), sweep.score(image, image)) - - def test_structure_gate_ignores_colour_errors_but_keeps_correlation(self): - base = dict(r=0.9, mean_dl=0, outer_mae_dl=0) - candidate = dict(metric_kind="structure_luma", r=0.95, mean_dl=100, outer_mae_dl=100) - self.assertFalse(sweep.metrics_regressed(candidate, base)) - self.assertTrue(sweep.metrics_regressed(dict(candidate, r=0.8), base)) - self.assertTrue(sweep.metrics_regressed(dict(candidate, metric_kind="lab_lstar"), base)) - self.assertTrue(sweep.metrics_regressed(dict(candidate, metric_kind="lab_lstar", mean_dl=0), base)) - - def test_baseline_inputs_are_checked_before_any_deltas(self): - current = dict( - file_sha256="a" * 64, - reference_sha256="b" * 64, - reference_size=[50, 32], - reference="embedded JPEG", - rotation=0, - metric_kind="lab_lstar", - pixel_sha256="c" * 64, - r=0.95, - mean_dl=0.1, - outer_mae_dl=0.2, - ) - changes = dict( - file_sha256="d" * 64, - reference_sha256="e" * 64, - reference_size=[32, 50], - reference="exiftool:PreviewTIFF", - rotation=180, - metric_kind="structure_luma", - ) - for key, wrong in changes.items(): - for value in (wrong, None): - with self.subTest(key=key, value=value): - record = copy.deepcopy(current) - base = dict(current, **{key: value}) - with self.assertRaisesRegex(ValueError, "baseline " + key + ".*sample.nef"): - sweep.compare_record("sample.nef", record, base) - self.assertNotIn("delta_r", record) - base = json.loads(json.dumps(current)) - del base["metric_kind"] # Existing display-reference baseline records remain compatible. - sweep.compare_record("sample.nef", current, base) - self.assertEqual(current["delta_r"], 0) - self.assertEqual(current["delta_abs_mean_dl"], 0) - self.assertFalse(current["pixels_changed"]) - - def test_old_tiff_metrics_and_nonfinite_baselines_are_rejected(self): - record = dict( - file_sha256="a", reference_sha256="b", reference_size=[50, 32], - reference="exiftool:PreviewTIFF", rotation=0, metric_kind="structure_luma", - pixel_sha256="c", r=1, - ) - old = dict(record) - del old["metric_kind"] - with self.assertRaisesRegex(ValueError, "regenerate baseline"): - sweep.compare_record("sample.fff", record, old) - for value in (float("nan"), float("inf"), None, "1"): - with self.subTest(value=value), self.assertRaisesRegex(ValueError, "baseline r"): - sweep.compare_record("sample.fff", record, dict(record, r=value)) - with self.assertRaisesRegex(ValueError, "baseline record missing"): - sweep.compare_record("sample.fff", record, None) - - -class Resume(unittest.TestCase): - def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.addCleanup(self.temp.cleanup) - previous = Path.cwd() - self.addCleanup(os.chdir, previous) - os.chdir(self.temp.name) - self.cli = Path("renderer") - self.cli.write_bytes(b"synthetic renderer identity") - self.output = Path("elsewhere/output") - self.fields = ["file", "sha256", "reference", "notes"] - Path("docs/raw").mkdir(parents=True) - - def manifest(self, rows): - with Path("docs/raw/coverage-sweep.tsv").open("w") as stream: - writer = csv.DictWriter(stream, fieldnames=self.fields, delimiter="\t") - writer.writeheader() - writer.writerows(rows) - - def invoke(self, extra=()): - with mock.patch("sys.argv", ["sweep", "--cli", str(self.cli), "--out", str(self.output), *extra]), mock.patch("builtins.print"): - sweep.main() - - def prepare_sample(self): - raw = Path("corpus/raw/sample.nef") - raw.parent.mkdir(parents=True) - raw.write_bytes(b"original synthetic input") - self.manifest([dict(file=raw.name, sha256=hashlib.sha256(raw.read_bytes()).hexdigest(), reference="embedded JPEG", notes="")]) - self.output.mkdir(parents=True) - cache_stem = raw.stem + "-" + hashlib.sha256(raw.read_bytes()).hexdigest() - gradient().save(self.output / (cache_stem + "-reference.png")) - return self.output / (cache_stem + ".png") - - def test_missing_lens_database_parents_are_created_with_an_external_output(self): - self.manifest([]) - self.assertFalse(Path("corpus").exists()) - self.invoke() - self.assertTrue(Path("corpus/nikon-lens/empty-lensdb").is_dir()) - - def test_readable_png_rejects_partial_corrupt_and_non_png_files(self): - path = Path("cached.png") - buffer = io.BytesIO() - gradient().save(buffer, format="PNG") - data = buffer.getvalue() - self.assertFalse(sweep.readable_png(path)) - corrupt = bytearray(data) - corrupt[29] ^= 1 # Corrupt the IHDR CRC while preserving the pixel stream. - for bad in (b"", data[:24], data[:-12], bytes(corrupt)): - with self.subTest(length=len(bad)): - path.write_bytes(bad) - self.assertFalse(sweep.readable_png(path)) - gradient().save(path, format="JPEG") - self.assertFalse(sweep.readable_png(path)) - path.write_bytes(data) - self.assertTrue(sweep.readable_png(path)) - - def test_valid_cached_render_is_reused_and_empty_render_is_rebuilt(self): - output = self.prepare_sample() - gradient().save(output) - with mock.patch.object(sweep.subprocess, "run") as run: - self.invoke() - run.assert_not_called() - output.write_bytes(b"") - def render(args, **kwargs): - gradient().save(args[args.index("-o") + 1]) - with mock.patch.object(sweep.subprocess, "run", side_effect=render) as run: - self.invoke() - run.assert_called_once() - self.assertTrue(sweep.readable_png(output)) - - def test_changed_input_cannot_reuse_same_stem_pixels_or_references(self): - output = self.prepare_sample() - gradient().save(output) - self.invoke() - baseline = self.output / "scores.json" - for name in ("sample.nef", "sample.dng"): - with self.subTest(name=name): - raw = Path("corpus/raw") / name - raw.write_bytes(("replacement input " + name).encode()) - digest = hashlib.sha256(raw.read_bytes()).hexdigest() - self.manifest([dict(file=name, sha256=digest, reference="embedded JPEG", notes="")]) - image = gradient().transpose(Image.Transpose.FLIP_LEFT_RIGHT) - buffer = io.BytesIO() - image.save(buffer, format="PNG") - def render(args, **kwargs): - image.save(args[args.index("-o") + 1]) - def extract(args, **kwargs): - return buffer.getvalue() if "-JpgFromRaw" in args else b"" - with mock.patch.object(sweep.subprocess, "run", side_effect=render) as run, mock.patch.object(sweep.subprocess, "check_output", side_effect=extract) as extract_call: - self.invoke() - run.assert_called_once() - self.assertEqual(extract_call.call_count, 3) - self.assertEqual(Path(run.call_args.args[0][run.call_args.args[0].index("-o") + 1]).name, "sample-" + digest + ".png") - self.assertTrue((self.output / ("sample-" + digest + ".log")).is_file()) - reference = self.output / ("sample-" + digest + "-reference.png") - with Image.open(reference) as cached: - self.assertEqual(cached.tobytes(), image.tobytes()) - record = json.loads(baseline.read_text())["records"][name] - self.assertEqual(record["file_sha256"], digest) - self.assertEqual(record["reference_sha256"], hashlib.sha256(image.tobytes()).hexdigest()) - with mock.patch.object(sweep.subprocess, "run") as run, mock.patch.object(sweep.subprocess, "check_output") as extract_call: - self.invoke() - run.assert_not_called() - extract_call.assert_not_called() - self.output = Path("candidate") - with mock.patch.object(sweep.subprocess, "run", side_effect=render) as run, mock.patch.object(sweep.subprocess, "check_output") as extract_call: - self.invoke(["--compare", str(baseline)]) - run.assert_called_once() - extract_call.assert_not_called() - record = json.loads((self.output / "scores.json").read_text())["records"][name] - self.assertFalse(record["pixels_changed"]) - self.assertEqual(record["delta_r"], 0) - - def test_preview_tiff_run_records_structure_only(self): - output = self.prepare_sample() - gradient().save(output) - raw = Path("corpus/raw/sample.nef") - self.manifest([dict(file=raw.name, sha256=hashlib.sha256(raw.read_bytes()).hexdigest(), reference="exiftool:PreviewTIFF", notes="")]) - with mock.patch.object(sweep, "score", side_effect=AssertionError("colour scorer must not run")): - self.invoke() - record = json.loads((self.output / "scores.json").read_text())["records"][raw.name] - self.assertEqual(record["metric_kind"], "structure_luma") - self.assertAlmostEqual(record["r"], 1) - self.assertNotIn("mean_dl", record) - self.assertNotIn("outer_mae_dl", record) - - def test_a_baseline_with_different_input_files_is_rejected(self): - self.manifest([]) - baseline = Path("baseline.json") - baseline.write_text(json.dumps(dict(records={"another.nef": {}}))) - with self.assertRaisesRegex(ValueError, "baseline input files differ"): - self.invoke(["--compare", str(baseline)]) - - -if __name__ == "__main__": - unittest.main() diff --git a/docs/raw/test_nikon_lens_probe.py b/docs/raw/test_nikon_lens_probe.py deleted file mode 100644 index ef8c93ecd04..00000000000 --- a/docs/raw/test_nikon_lens_probe.py +++ /dev/null @@ -1,199 +0,0 @@ -"""Synthetic checks for the Nikon measurement tool, with no media fixtures. - -Run: python3 -m unittest discover -s docs/raw -p 'test_nikon_lens_probe.py' -""" - -import struct -import unittest -from pathlib import Path -from unittest import mock - -import numpy as np -from PIL import Image - -import nikon_lens_probe as probe - - -class Measurements(unittest.TestCase): - def test_lab_score_sign_and_outer_ring(self): - """An identical ramp has zero error; a darker render has negative dL.""" - ramp = np.tile(np.arange(32, 232, dtype=np.uint8), (133, 1)) - reference = Image.fromarray(np.repeat(ramp[..., None], 3, axis=-1)) - score = probe.score(reference, reference) - self.assertAlmostEqual(score["r"], 1) - self.assertEqual(score["mean_dl"], 0) - self.assertEqual(score["outer_mae_dl"], 0) - self.assertEqual(score["outer_pixels"], 5040) - darker = Image.fromarray(np.repeat((ramp - 10)[..., None], 3, axis=-1)) - self.assertLess(probe.score(darker, reference)["mean_dl"], 0) - with self.assertRaisesRegex(ValueError, "constant image"): - probe.score(Image.new("RGB", (200, 133)), reference) - - def test_ifd_ranges_are_bounded(self): - """A truncated directory or out-of-file entry fails before unpacking it.""" - for data, offset in [(b"", 0), (b"\0\0", -1), (b"\1\0", 0)]: - with self.assertRaises(ValueError): - probe.tiff_entries(data, offset, "<") - directory = struct.pack("