mirror of
https://github.com/storytold/lightcraft.git
synced 2026-12-01 10:56:23 +01:00
LR-PROF-CAMERACOLOR: narrow standalone color geometry scope
Merge current upstream main without rewriting the published branch. Keep non-CR3 geometry and fixed-lens resolution, required pooled/DNG consistency and the loaded-LensDB/Smart-preview producer provenance as an independent proposal. The other feature PR is not a prerequisite or merge parent. Restore current main for general UI/task runtime code, GPU equivalence tests and Cull benchmark whitespace. Preserve geometry and source-identity gates. Two bounded CI fixtures remain: stale V1/V2 golden constants aligned to exact unmodified-main output, and decoded-source isolation before a Find Similar retry. Main independently reproduced both failures. Assertions, signature caches, expected counts, production UI and renderer remain unchanged. Adapt the shared test-directory helper to main's new no-panic lint contract. Final cargo xtask ci passes all nine gates with Rust1.95.0, actual Metal and WebAssembly. Tested, staged and committed trees match. Capability skips are recorded separately. No current real-photo acceptance or product install. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
commit
bd3ee7ea8d
186 files changed
+7910
-581
No files matched your search
@@ -50,10 +50,15 @@ of it.
|
||||
- **Last-resort guard:** a panic hook plus `catch_unwind` around command dispatch and import/export turns an escaped
|
||||
panic into an error dialog and keeps the document. It's a safety net, not a licence; keep `panic = "unwind"` on native.
|
||||
- **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix.
|
||||
- Enforced by clippy: root `clippy.toml` allows unwrap/expect/panic in tests only; indexing is not denied. Every production crate
|
||||
root (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
|
||||
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Not `[workspace.lints]`: those would also hit
|
||||
integration tests, examples and benches. New crates start with the attribute.
|
||||
- Enforced by clippy: root `clippy.toml` keeps unwrap/expect/panic allowances scoped to tests; indexing is not denied. The workspace
|
||||
denies `cognitive_complexity`, `too_many_arguments` and `wildcard_imports`; members inherit them with
|
||||
`[lints] workspace = true`, and `sysmem` repeats those denies in its local lint table. Every production crate root
|
||||
(`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
|
||||
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include
|
||||
`[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include
|
||||
the attribute before modules or other crate items; crate-level `//!` documentation may precede it. `cargo xtask roots`
|
||||
(part of `ci` and `ci --quick`) machine-checks that every root, including binary-only crates and the `cdylib`/`rlib`
|
||||
web build, carries both this and the `#![forbid(unsafe_code)]` above (`crates/sysmem` is the one forbid exception).
|
||||
|
||||
## Non-negotiables
|
||||
- **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…).
|
||||
@@ -62,7 +67,7 @@ of it.
|
||||
- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP all dispatch by id. Every slider is a `develop` control spec.
|
||||
- **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match.
|
||||
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
|
||||
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm).
|
||||
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, roots, wasm).
|
||||
- **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment.
|
||||
|
||||
## Assets: icons, images, fonts (ABSOLUTE RULE — never violate)
|
||||
|
||||
@@ -57,7 +57,9 @@ of it.
|
||||
(`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
|
||||
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include
|
||||
`[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include
|
||||
the attribute before modules or other crate items; crate-level `//!` documentation may precede it.
|
||||
the attribute before modules or other crate items; crate-level `//!` documentation may precede it. `cargo xtask roots`
|
||||
(part of `ci` and `ci --quick`) machine-checks that every root, including binary-only crates and the `cdylib`/`rlib`
|
||||
web build, carries both this and the `#![forbid(unsafe_code)]` above (`crates/sysmem` is the one forbid exception).
|
||||
|
||||
## Non-negotiables
|
||||
- **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…).
|
||||
@@ -71,7 +73,7 @@ of it.
|
||||
- **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match.
|
||||
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
|
||||
- **Quality gates** before every commit: `cargo xtask ci --quick` (fmt, clippy -D warnings, the changed packages'
|
||||
tests, layers, assets, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR
|
||||
tests, layers, assets, roots, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR
|
||||
(`.github/workflows/ci.yml`); run the full one locally before merging branches (below) or when `--quick` can't see
|
||||
the risk. One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`).
|
||||
- **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment.
|
||||
|
||||
@@ -350,7 +350,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det
|
||||
Fujifilm / Nikon / older-Canon raws on one machine; see [docs/raw-parity.md](docs/raw-parity.md) for your camera.
|
||||
- **The biggest gaps:**
|
||||
- **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 and CRW raws have guarded estimates from their camera JPEGs, with built-in Canon EOS D60, ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration covers one model so far (chart-measured matrices for the Canon EOS D60), and other raws or rejected fits retain a neutral matrix;
|
||||
- **compressed Olympus raws and unsupported CR3 variants:** these use embedded JPEG previews when present. Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md);
|
||||
- **unsupported CR3 variants and Nikon High Efficiency NEFs:** these use embedded JPEG previews when present. Olympus compressed ORF now decodes sensor data on 58 more bodies (2 verified) ([docs/orf-compression.md](docs/orf-compression.md)); Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md);
|
||||
- **AI quality and model setup:** Subject and Sky selection are classical heuristics; Object/Describe use an
|
||||
optional SAM 3 model. AI Denoise supports Bayer RAW with separately installed weights, while X-Trans and
|
||||
linear-RGB denoise and Super Resolution remain missing; see [AI masks](docs/ai-masks.md) and [AI Denoise](docs/denoise.md);
|
||||
@@ -370,7 +370,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det
|
||||
| Profiles (Color, Neutral, Vivid, Landscape, Portrait, Monochrome: our own looks), presets, versions, history, copy/paste/sync settings | ✅ |
|
||||
| Camera colour: DNG matrices, guarded camera-JPEG look fits and built-in profiles for selected cameras | 🚧 measured calibration and per-model coverage remain incomplete ([raw parity](docs/raw-parity.md)) |
|
||||
| Native macOS menu bar (generated from the command registry), control channel + every widget addressable, headless UI snapshots | ✅ |
|
||||
| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed ORF / SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) |
|
||||
| RAW: DNG, CR2, CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW), ARW, NEF (uncompressed + lossless/lossy compressed, incl. lossy after split), Fujifilm RAF (uncompressed + lossless/lossy compressed, Bayer + X-Trans), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format, DMC-LX1 to DC-S1RM2), Pentax PEF, Olympus ORF (uncompressed, 12.8 bpp, compressed), Samsung SRW (uncompressed); embedded previews for every format incl. CR3 | 🚧 · other CR3 variants, compressed SRW and Nikon HE NEF decode ⬜ ([raw parity](docs/raw-parity.md)) |
|
||||
| Detail: sharpening, luminance + colour noise reduction | ✅ · AI Denoise 🚧 (Bayer, user-installed weights; [setup](docs/denoise.md)), Super Resolution ⬜ |
|
||||
| Remove / Heal / Clone spots (auto source), non-generative Fill, editable spot pins, Visualize Spots, Red Eye and Pet Eye | ✅ · Fill uses PatchMatch; no generative fill |
|
||||
| Export: JPEG / PNG / TIFF / flat PSD / WebP / AVIF / JPEG XL / raw or rendered DNG / original, sizing, file-size limit, output sharpening, naming templates, batch, metadata policy, text or image watermark | ✅ |
|
||||
|
||||
+9
-8
@@ -14,25 +14,25 @@ from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are
|
||||
|---|---:|---|
|
||||
| **Feature breadth** (checklist) | **81.6%** of 532 rows (P0 98.0%, P1 95.2%, P2 50.0%) | measured: [parity-checklist.md](docs/parity-checklist.md) recount |
|
||||
| **Feature breadth** (weighted by use) | **~77%** | estimated |
|
||||
| **Ready for real work** (full target) | **~61%** (56–66%) | estimated: weighted sum over the dimensions |
|
||||
| **Ready for real work** (full target) | **~62%** (57–67%) | estimated: weighted sum over the dimensions |
|
||||
| **Mainstream practitioner** | **~51%** (46–56%) | estimated |
|
||||
| **Essentials user** | **~65%** (60–70%) | estimated |
|
||||
| Remaining to **beta** | **~340–600 h** (Opus 5.5 agent hours, ~60% parallel) | estimated |
|
||||
| Remaining to **full parity** | **~1,000–1,800 h** (~70% parallel) | estimated |
|
||||
| Remaining to **full parity** | **~980–1,750 h** (~70% parallel) | estimated |
|
||||
|
||||
Each audience with its own hours (Opus 5.5 agent wall-clock hours to ~95%):
|
||||
|
||||
| Audience | Ready | Opus 5.5 agent wall-clock hours to ~95% | Work that dominates |
|
||||
|---|---:|---:|---|
|
||||
| Full target (ready for real work) | **~61%** | **1,000–1,800 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem |
|
||||
| Mainstream practitioner | **~51%** | **450–840 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability |
|
||||
| Full target (ready for real work) | **~62%** | **980–1,750 h** (~70% parallelizes) | raw colour, lens and camera data; AI models; Classic output modules; localization; plug-in ecosystem |
|
||||
| Mainstream practitioner | **~51%** | **440–820 h** (~60% parallelizes) | camera colour and render fidelity; CR3 / ORF / HE NEF; lens database; subject / sky masks; Lightroom XMP exchange; stability |
|
||||
| Essentials user | **~65%** | **160–300 h** (~50% parallelizes) | default raw look for popular cameras; launch stability; basic-slider feel; opening CR3 / HEIC files people send |
|
||||
|
||||
The gap between breadth and readiness is quality and coverage, not missing buttons: camera colour is
|
||||
estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), compressed ORF and HE NEF
|
||||
open as previews, rendering is tuned by eye, AI masks are heuristics, there is no lens database, and
|
||||
estimated rather than measured, CR3 decodes on 26 verified Canon bodies (rarer CRX variants still open as previews), HE NEF opens
|
||||
as preview (compressed ORF now decodes on 58 more bodies (2 verified)), rendering is tuned by eye, AI masks are heuristics, there is no lens database, and
|
||||
tests run in CI on Linux x64 (every pull request and push to `main`) and FreeBSD (nightly), not on macOS or Windows. **Why alpha:** core workflows run end to end, but readiness is below
|
||||
the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have blocking gaps (compressed ORF and HE NEF open as previews; Canon,
|
||||
the ~75% beta bar (it is above the ~40% alpha bar) and Lightroom's main inputs, raw files, still have gaps (Nikon HE NEF opens as preview; Canon,
|
||||
~30% of raw users, decodes CR3 on 26 verified bodies). It passes the alpha gate: all six core workflows
|
||||
(import, cull, develop, save and reopen, batch looks, export) work end to end on macOS
|
||||
([docs/roadmap.md](docs/roadmap.md#alpha-gate)). The three readiness numbers and their weights and discounts are in
|
||||
@@ -107,13 +107,14 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
|
||||
3. Render-fidelity suite against Lightroom, then tuning (30–60 h)
|
||||
4. ~~Full-resolution zoom~~ (done 2026-10-12)
|
||||
5. AI masks: Subject / Sky / People (40–70 h + model decision)
|
||||
6. Compressed ORF and HE NEF (28–55 h)
|
||||
6. ~~Compressed ORF~~ (done 2026-11-04) and HE NEF (20–40 h)
|
||||
7. Lens profile database of our own (40–80 h, #329)
|
||||
8. Tests in CI on macOS and Windows, and the GPU tests in CI (6–12 h)
|
||||
9. Per-model raw verification (20–35 h)
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-04: Olympus / OM System compressed ORF decodes from sensor data: clean-room pure-Rust bitstream decoder (`crates/raw/src/vendor/orfc.rs`) derived strictly from Olympus patents US7333035B2/US7715639B2, maker notes and CC0 samples without third-party decoder code (see `docs/orf-compression.md`), verified on OM-D E-M1 (r=0.995) and E-M10 Mark III (r=0.929) CC0 samples; 58 bodies newly unlocked (78 total across Olympus and OM; OM/Olympus 6% → 81% fully working, overall weighted camera coverage 94% → 97%).
|
||||
- 2026-10-22: Print page setup and PDF output gain the Japanese photo and postcard papers — L判
|
||||
(89 × 127 mm), 2L判 (127 × 178), KG判 (102 × 152), はがき (100 × 148), 往復はがき (148 × 200),
|
||||
六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog
|
||||
|
||||
@@ -600,6 +600,9 @@ impl WebApp {
|
||||
let mut saved = serde_json::from_slice::<serde_json::Value>(&ui_written).unwrap_or_default();
|
||||
if let Some(fields) = saved.as_object_mut() {
|
||||
lightcraft_ui_egui::docking::drop_outdated(fields);
|
||||
// a stored ui.json means an installation that has been run: due What's New, never
|
||||
// the first-run tour (the same migration the desktop settings loader runs)
|
||||
lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields);
|
||||
}
|
||||
if let Ok(ui) = serde_json::from_value::<UiState>(saved) {
|
||||
app.ui = ui;
|
||||
|
||||
@@ -33,6 +33,9 @@ pub struct WireJob {
|
||||
pub origin: Source,
|
||||
/// Decode the source at most this long.
|
||||
pub max_edge: usize,
|
||||
/// Resize an already decoded source exactly as the engine's cached-source path does.
|
||||
#[serde(default)]
|
||||
pub fit_edge: Option<usize>,
|
||||
pub raw: bool,
|
||||
#[serde(default)]
|
||||
pub relative_wb: bool,
|
||||
@@ -67,7 +70,8 @@ impl WireJob {
|
||||
/// `view`: the slot name, for jobs that keep a stage cache.
|
||||
pub fn from_job(job: &RenderJob, thumb_cached: bool, view: &str) -> WireJob {
|
||||
let max_edge = match &job.source {
|
||||
SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } | SourceRef::Fit { max_edge, .. } => *max_edge,
|
||||
SourceRef::Demo { max_edge, .. } | SourceRef::File { max_edge, .. } => *max_edge,
|
||||
SourceRef::Fit { from, .. } => from.image.width.max(from.image.height),
|
||||
SourceRef::Loaded(img) => img.image.width.max(img.image.height),
|
||||
SourceRef::Smart { .. } => 2560,
|
||||
};
|
||||
@@ -77,6 +81,10 @@ impl WireJob {
|
||||
level: job.level,
|
||||
origin: job.origin.clone(),
|
||||
max_edge,
|
||||
fit_edge: match &job.source {
|
||||
SourceRef::Fit { max_edge, .. } => Some(*max_edge),
|
||||
_ => None,
|
||||
},
|
||||
raw: job.info.raw,
|
||||
relative_wb: job.info.relative_wb,
|
||||
legacy_relative_wb: job.info.legacy_relative_wb,
|
||||
@@ -114,6 +122,7 @@ impl WireJob {
|
||||
RenderRequest {
|
||||
max_w: self.max_w,
|
||||
max_h: self.max_h,
|
||||
exact_size: false,
|
||||
quality: if self.draft { Quality::Draft } else { Quality::Full },
|
||||
apply_crop: self.apply_crop,
|
||||
overlay: lightcraft_engine::pipeline::Overlay::from_parts(self.overlay.0, self.overlay.1),
|
||||
@@ -196,6 +205,10 @@ impl WorkerCore {
|
||||
src
|
||||
}
|
||||
};
|
||||
let src = match job.fit_edge {
|
||||
Some(max_edge) => SourceRef::Fit { from: Box::new(src), max_edge }.load_source()?,
|
||||
None => src,
|
||||
};
|
||||
let info = src.info_or(job.info());
|
||||
let mut rendered = match &job.stages {
|
||||
Some(view) => {
|
||||
@@ -472,6 +485,7 @@ mod tests {
|
||||
level: SourceLevel::Thumb,
|
||||
origin,
|
||||
max_edge: 512,
|
||||
fit_edge: None,
|
||||
raw: false,
|
||||
relative_wb: false,
|
||||
legacy_relative_wb: false,
|
||||
|
||||
@@ -67,6 +67,11 @@ fn decode_saved_ui(bytes: &[u8]) -> Result<(UiState, bool), String> {
|
||||
if recovered {
|
||||
fields.remove("docking");
|
||||
}
|
||||
// A settings file from before the startup dialog existed has no `seenVersion` key: the file
|
||||
// is there, so this is an installation that has been run, due What's New — never the
|
||||
// first-run tour. Shared with the browser's loader, which runs the same migration on its
|
||||
// stored `ui.json` (`startup::migrate_legacy_seen_version` carries the full story).
|
||||
lightcraft_ui_egui::startup::migrate_legacy_seen_version(fields);
|
||||
let ui = serde_json::from_value(saved).map_err(|error| error.to_string())?;
|
||||
Ok((ui, recovered))
|
||||
}
|
||||
|
||||
@@ -223,6 +223,42 @@ fn memory_session_leaves_a_damaged_ui_json_alone() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A settings file from before the startup dialog existed (no `seenVersion`) belongs to an
|
||||
/// installation that has been run: its first launch after the update shows What's New, never
|
||||
/// the first-run tour. A file this version saved before the dialog was presented carries an
|
||||
/// explicit `null` and is not migrated; only a missing file stays a first run as well.
|
||||
#[test]
|
||||
fn legacy_ui_json_shows_whats_new_not_the_first_run_tour() {
|
||||
let d = dir("legacy-startup");
|
||||
let path = d.join("ui.json");
|
||||
std::fs::write(&path, br#"{"language":"en","settings":{"startupView":"detail"}}"#).unwrap();
|
||||
let (ui, warning, keep) = load_prefs_at(&path, true);
|
||||
assert!(warning.is_none() && !keep);
|
||||
let ui = ui.unwrap();
|
||||
assert_eq!(ui.seen_version.as_deref(), Some(lightcraft_ui_egui::startup::LEGACY_SEEN_VERSION));
|
||||
assert_eq!(
|
||||
lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")),
|
||||
Some(lightcraft_ui_egui::startup::StartupDialog::WhatsNew)
|
||||
);
|
||||
// a file that already records the running version is migrated nowhere
|
||||
std::fs::write(&path, format!(r#"{{"seenVersion":"{}"}}"#, env!("CARGO_PKG_VERSION"))).unwrap();
|
||||
let (ui, warning, _) = load_prefs_at(&path, true);
|
||||
assert!(warning.is_none());
|
||||
assert_eq!(ui.unwrap().seen_version.as_deref(), Some(env!("CARGO_PKG_VERSION")));
|
||||
// an explicit `null` is this version's "not presented yet" (the launch chooser saves while
|
||||
// the tour still waits): it stays a first run, not a pre-feature file
|
||||
std::fs::write(&path, br#"{"language":"en","seenVersion":null}"#).unwrap();
|
||||
let (ui, warning, _) = load_prefs_at(&path, true);
|
||||
assert!(warning.is_none());
|
||||
let ui = ui.unwrap();
|
||||
assert_eq!(ui.seen_version, None);
|
||||
assert_eq!(
|
||||
lightcraft_ui_egui::startup::startup_dialog(ui.seen_version.as_deref(), env!("CARGO_PKG_VERSION")),
|
||||
Some(lightcraft_ui_egui::startup::StartupDialog::FirstRun)
|
||||
);
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn docking_survives_native_settings_file_reload() {
|
||||
use lightcraft_ui_egui::docking::Panel;
|
||||
|
||||
+132
-28
@@ -25,6 +25,12 @@
|
||||
//! - a bad record **followed by good ones** is real damage: replay stops there, the log is kept
|
||||
//! as `catalog.log.damaged-<seq>`, and a fresh snapshot is written so the library stays usable.
|
||||
//!
|
||||
//! Segmentation grids are shared within a snapshot (issue #2154): each distinct grid is written
|
||||
//! once into `Catalog.grids` and the masks of the photo's develop settings, versions, history
|
||||
//! steps and import look refer to it by index, so an unchanged mask no longer repeats with every
|
||||
//! history step. The table lives only in the snapshot file; log records keep the full grids
|
||||
//! inline.
|
||||
//!
|
||||
//! **Background compaction** ([`Journal::snapshot_in_background`], when the store offers a
|
||||
//! [`Store::background_writer`]): a worker thread writes the snapshot of a copy of the catalog at
|
||||
//! op `N` while appends go on (durably, as always) to the same log. Once the snapshot is durable,
|
||||
@@ -57,6 +63,7 @@
|
||||
//! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` |
|
||||
//! | 10 | masks stay on the photo under lens corrections, Upright and Transform | `Mask.on_photo` (develop settings) |
|
||||
//! | 11 | lens database profiles named in the Optics panel | `EmbeddedLens.source` |
|
||||
//! | 12 | history steps and versions share segmentation grids (#2154) | `Catalog.grids`, `SegMask.grid` |
|
||||
//!
|
||||
//! Rules:
|
||||
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
|
||||
@@ -81,7 +88,7 @@ pub const LOG: &str = "catalog.log";
|
||||
const FORMAT: &str = "lightcraft-catalog";
|
||||
/// The catalog format this build writes (and the newest it reads). See the module docs →
|
||||
/// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added.
|
||||
pub const VERSION: u32 = 11;
|
||||
pub const VERSION: u32 = 12;
|
||||
|
||||
/// When [`Journal::wants_snapshot`] says it's time to compact the log.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -272,12 +279,18 @@ fn newer(what: String) -> CatalogError {
|
||||
CatalogError::Newer(format!("{what}; this version reads catalog format v{VERSION} and older"))
|
||||
}
|
||||
|
||||
/// The most `resync` spends re-validating the suffixes of one line whose whole bytes are not valid
|
||||
/// UTF-8 (a real fragment ends at any byte): one line of a modest malformed log that holds a start
|
||||
/// of a record in every few bytes used to re-validate the whole remaining suffix at every attempt
|
||||
/// (CWE-407). Past the budget the rest of the line stays a torn tail, which the damaged path keeps
|
||||
/// and reports, same state as before, minus the CPU.
|
||||
const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Start markers that `resync` decoded on this thread (test builds only; see the cost test).
|
||||
pub(crate) static RESYNC_CANDIDATES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Total bytes of candidate suffixes `resync` may decode per damaged line: every attempt reads
|
||||
/// the rest of the line, so trying every candidate of a crafted line would make
|
||||
/// [`Journal::open`] quadratic in the line length (CWE-407). The budget is far above any
|
||||
/// fragment-plus-retry a failed append can leave, but caps the stall; past it the line reads as
|
||||
/// damage, which is handled safely.
|
||||
pub(crate) const MAX_SCAN: usize = 64 << 20;
|
||||
|
||||
/// A line that doesn't decode but ends with a whole record: a fragment of a failed append followed
|
||||
/// by the record that retried it (the retry re-encodes the same ops with the same `seq`s). Returns
|
||||
@@ -285,32 +298,70 @@ const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB
|
||||
/// The record's CRC must match, so damage is never mistaken for it.
|
||||
fn resync(line: &[u8], last: u64) -> Option<(usize, (u64, Op))> {
|
||||
const START: &[u8] = b"{\"seq\":";
|
||||
// One record per line, so a line of valid UTF-8 holds a valid suffix at every record start and
|
||||
// one validation covers every candidate; only a line that is not wholly valid re-checks, and
|
||||
// then up to the budget rather than the suffix length times the candidate count.
|
||||
let whole = std::str::from_utf8(line).ok();
|
||||
let mut spent = 0usize;
|
||||
(1..line.len().saturating_sub(START.len() - 1)).filter(|&i| line[i..].starts_with(START)).find_map(|i| {
|
||||
let text = match &whole {
|
||||
Some(t) => &t[i..],
|
||||
None => {
|
||||
if spent >= RESYNC_BUDGET_BYTES {
|
||||
return None;
|
||||
}
|
||||
spent = spent.saturating_add(line.len() - i);
|
||||
std::str::from_utf8(&line[i..]).ok()?
|
||||
}
|
||||
// The retry record starts with the `{"seq":` marker, but that marker can also occur inside
|
||||
// the op body (a smart-album rule value such as `{"seq":1}`); then the last occurrence is
|
||||
// nested, not the record start, and decoding it rejects a valid retry. Scan every marker
|
||||
// once, left to right, then try them from the end. A candidate must match the record header
|
||||
// shape — `{"seq":<digits>,"crc":<digits>,"op":`, what `encode_record` writes — so a marker
|
||||
// nested inside the op body (followed by `}` or `,`) or plain junk never reaches
|
||||
// `decode_record`; only a real record start does. This imposes no fixed limit on how many
|
||||
// nested markers a valid record may contain. Each attempt then decodes the rest of the line,
|
||||
// so the scan budget bounds the total when a hostile line still holds many header-shaped
|
||||
// markers, keeping the work near-linear instead of quadratic. The fragment that precedes the
|
||||
// record stays to its left (`i > 0`).
|
||||
let digits = |b: &[u8]| b.iter().take_while(|x| x.is_ascii_digit()).count();
|
||||
let mut candidates: Vec<usize> = Vec::new();
|
||||
let mut from = 0;
|
||||
while let Some(i) = line[from..].windows(START.len()).position(|w| w == START) {
|
||||
let pos = from + i;
|
||||
let Some(after) = line.get(pos + START.len()..) else { break };
|
||||
let seq_digits = digits(after);
|
||||
let crc_field = after.get(seq_digits..).and_then(|rest| rest.strip_prefix(b",\"crc\":"));
|
||||
let crc_digits = crc_field.map(digits).unwrap_or(0);
|
||||
let op_field = crc_field.and_then(|rest| rest.get(crc_digits..)).and_then(|rest| rest.strip_prefix(b",\"op\":"));
|
||||
if seq_digits > 0 && crc_digits > 0 && op_field.is_some() {
|
||||
candidates.push(pos);
|
||||
}
|
||||
from = pos + START.len();
|
||||
}
|
||||
let mut scanned = 0usize;
|
||||
for &i in candidates.iter().rev() {
|
||||
if i == 0 {
|
||||
break; // the record must follow a fragment
|
||||
}
|
||||
let Some(suffix) = line.get(i..) else { continue };
|
||||
scanned = match scanned.checked_add(suffix.len()) {
|
||||
Some(total) if total <= MAX_SCAN => total,
|
||||
_ => break, // the budget is spent: stop trying further candidates
|
||||
};
|
||||
let rec = decode_record(text.trim_end_matches('\r'))?;
|
||||
(rec.0 <= last.saturating_add(1)).then_some((i, rec))
|
||||
})
|
||||
let Ok(text) = std::str::from_utf8(suffix) else { continue };
|
||||
#[cfg(test)]
|
||||
RESYNC_CANDIDATES.with(|c| c.set(c.get() + 1));
|
||||
if let Some((seq, op)) = decode_record(text.trim_end_matches('\u{0D}'))
|
||||
&& seq <= last.saturating_add(1)
|
||||
{
|
||||
return Some((i, (seq, op)));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Write `catalog.snap` for the state after op `seq`, streaming the JSON into the store (no
|
||||
/// whole-file string). The bytes are exactly
|
||||
/// `{"format":"lightcraft-catalog","version":1,"seq":N,"catalog":<serde_json of the catalog>}\n`,
|
||||
/// as before streaming. Fills in the serialise / write+sync times and the size.
|
||||
/// as before streaming. Each distinct segmentation grid of the photos' settings holders (see
|
||||
/// `Photo::settings_holders`) is written once (`Catalog.grids`), with the masks referring to it
|
||||
/// by index, so an unchanged mask does not repeat with every history step (issue #2154). Fills
|
||||
/// in the serialise / write+sync times and the size.
|
||||
fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io::Result<SnapshotTiming> {
|
||||
write_snapshot_owned(store, seq, catalog.clone())
|
||||
}
|
||||
|
||||
/// The same write, taking the catalog by value: the background path hands over the copy it
|
||||
/// already made, so a snapshot in flight holds one catalog, not two ([`Catalog::clone`] copies
|
||||
/// the photo pointers and the small tables, and the derived indexes start empty — real work on a
|
||||
/// large library).
|
||||
fn write_snapshot_owned(store: &mut dyn Store, seq: u64, mut snapshot: Catalog) -> std::io::Result<SnapshotTiming> {
|
||||
let t0 = web_time::Instant::now();
|
||||
let mut serialize_ms = 0.0;
|
||||
let bytes = store.write_atomic_with(SNAPSHOT, &mut |w| {
|
||||
@@ -320,7 +371,35 @@ fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io
|
||||
// 1 MiB chunks go through the store's `dyn Write`
|
||||
let mut b = std::io::BufWriter::with_capacity(1 << 20, w);
|
||||
write!(b, "{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":{seq},\"catalog\":")?;
|
||||
serde_json::to_writer(&mut b, catalog).map_err(std::io::Error::other)?;
|
||||
// The shared grids, in first-appearance order. The pool is a serialization detail:
|
||||
// `snapshot` itself is never modified (log records, presets and XMP stay inline).
|
||||
let mut pool: Vec<String> = Vec::new();
|
||||
let mut index: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
|
||||
{
|
||||
let mut see = |s: &lightcraft_develop::DevelopSettings| {
|
||||
s.visit_seg_masks(&mut |m| {
|
||||
// borrowed lookup: a grid every history step shares is not cloned just to
|
||||
// find it already indexed (only a new grid is copied, into pool and table)
|
||||
if !m.data.is_empty() && !index.contains_key(m.data.as_str()) {
|
||||
index.insert(m.data.clone(), pool.len() as u32);
|
||||
pool.push(m.data.clone());
|
||||
}
|
||||
});
|
||||
};
|
||||
for p in snapshot.photos.values() {
|
||||
for settings in p.settings_holders() {
|
||||
see(settings);
|
||||
}
|
||||
}
|
||||
}
|
||||
snapshot.grids = pool;
|
||||
match lightcraft_develop::with_grid_interner(index, || serde_json::to_writer(&mut b, &snapshot)) {
|
||||
// no interner can be active here (snapshot writes don't nest), so `None` is a bug:
|
||||
// fail the write rather than store a truncated or reference-less snapshot
|
||||
Some(Ok(())) => {}
|
||||
Some(Err(e)) => return Err(std::io::Error::other(e)),
|
||||
None => return Err(std::io::Error::other("nested grid interner while writing a snapshot")),
|
||||
}
|
||||
b.write_all(b"}\n")?;
|
||||
b.flush()?;
|
||||
serialize_ms = ms_since(t);
|
||||
@@ -607,7 +686,7 @@ impl Journal {
|
||||
let Some(mut writer) = self.store.background_writer() else { return self.snapshot(catalog) };
|
||||
let copy = catalog.clone();
|
||||
let seq = self.seq;
|
||||
let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot(writer.as_mut(), seq, ©));
|
||||
let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot_owned(writer.as_mut(), seq, copy));
|
||||
let worker = match spawned {
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
@@ -792,4 +871,29 @@ mod tests_resync {
|
||||
// matches, so the double `Some` is only reached with `last >= 4`
|
||||
assert_eq!(resync(&line, 100).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
|
||||
}
|
||||
|
||||
/// A retry record whose op body holds more than eight nested `{"seq":` markers (a
|
||||
/// `SetAlbumRules` with nine rule values of `{"seq":1}`) exhausts `resync`'s fixed
|
||||
/// `MAX_DECODES = 8` decode budget on the nested markers, so the outer record's real
|
||||
/// start is never decoded and the valid operation is truncated as damage.
|
||||
#[test]
|
||||
fn resync_recovers_retry_beyond_eight_nested_markers() {
|
||||
let mut c = Catalog::new();
|
||||
let album_id = c.alloc_album_id();
|
||||
let mut rules = Vec::new();
|
||||
for _ in 0..9 {
|
||||
rules.push(crate::Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) });
|
||||
}
|
||||
let retry_op = Op::SetAlbumRules {
|
||||
id: album_id,
|
||||
rules: Box::new(crate::Filter { rule_set: Some(crate::RuleSet { mode: crate::Match::All, rules }), ..Default::default() }),
|
||||
};
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let record = format!("{{\"seq\":5,\"crc\":{crc},\"op\":{body}}}");
|
||||
let mut line = Vec::from(b"torn fragment" as &[u8]);
|
||||
let fragment = line.len();
|
||||
line.extend_from_slice(record.as_bytes());
|
||||
assert_eq!(resync(&line, 4).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
|
||||
}
|
||||
}
|
||||
@@ -289,6 +289,13 @@ pub struct Catalog {
|
||||
/// What the library keeps about its folders (folder identity → record), see [`folders`].
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
folder_records: BTreeMap<String, FolderRecord>,
|
||||
/// Segmentation grids shared by this snapshot's masks: each distinct grid's data once, in
|
||||
/// first-appearance order, referenced by index from the masks ([`lightcraft_develop::\
|
||||
/// SegMask::grid`] is a position here). A serialization detail of snapshots
|
||||
/// ([`journal`]): never held in the live catalog — [`Catalog::repair`] resolves the
|
||||
/// references and clears the table when a snapshot is read.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
grids: Vec<String>,
|
||||
/// Increments on every applied op, and when a batch fails and its rollback cannot undo it whole (the catalog
|
||||
/// changed, so what is keyed by the revision is out of date).
|
||||
#[serde(skip)]
|
||||
@@ -367,6 +374,25 @@ impl std::fmt::Debug for PlansMemo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the shared-grid references of one settings holder (see [`Photo::settings_holders`])
|
||||
/// against a snapshot's grid table: each referenced mask takes its
|
||||
/// grid's data and the reference is cleared. A reference past the table (a damaged snapshot)
|
||||
/// leaves the mask empty — it renders nothing, like any other damaged grid. Data present on the
|
||||
/// mask itself wins over a stray reference. Returns the dangling count added to `dangling`.
|
||||
fn resolve_grids(settings: &mut Arc<DevelopSettings>, grids: &[String], dangling: usize) -> usize {
|
||||
let mut dangling = dangling;
|
||||
Arc::make_mut(settings).visit_seg_masks_mut(&mut |m| {
|
||||
if let Some(i) = m.grid.take() {
|
||||
match (m.data.is_empty(), grids.get(i as usize)) {
|
||||
(true, Some(data)) => m.data = data.clone(),
|
||||
(true, None) => dangling += 1,
|
||||
(false, _) => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
dangling
|
||||
}
|
||||
|
||||
/// A short memory of what the latest ops changed, so that what is derived from the catalog (the grid's list) can
|
||||
/// follow a small edit without being worked out again from every photo.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -1192,6 +1218,23 @@ impl Catalog {
|
||||
/// wrote).
|
||||
pub fn repair(&mut self) -> Vec<String> {
|
||||
let mut changed = Vec::new();
|
||||
// Segmentation grids shared by the snapshot this was read from (issue #2154): each
|
||||
// reference takes its grid's data, and the table is not kept — a live catalog always
|
||||
// stores the data inline, so masks render and serialize without the snapshot's table.
|
||||
// Resolving is the normal way a snapshot in this format reads (not reported); a
|
||||
// reference past the table is damage and is reported — that includes a reference into
|
||||
// an empty table, which is always dangling, so the table being empty does not skip it.
|
||||
let grids = std::mem::take(&mut self.grids);
|
||||
let mut dangling = 0usize;
|
||||
for p in self.photos.values_mut() {
|
||||
let photo = Arc::make_mut(p);
|
||||
for settings in photo.settings_holders_mut() {
|
||||
dangling = resolve_grids(settings, &grids, dangling);
|
||||
}
|
||||
}
|
||||
if dangling > 0 {
|
||||
changed.push(format!("{dangling} segmentation grid reference(s) pointed past the shared table: cleared"));
|
||||
}
|
||||
for (id, p) in self.photos.iter_mut() {
|
||||
if p.id != *id {
|
||||
changed.push(format!("photo {} was filed as {}", p.id.0, id.0));
|
||||
@@ -1488,6 +1531,8 @@ mod tests_folders;
|
||||
#[cfg(test)]
|
||||
mod tests_format_version;
|
||||
#[cfg(test)]
|
||||
mod tests_grids;
|
||||
#[cfg(test)]
|
||||
mod tests_index;
|
||||
#[cfg(test)]
|
||||
mod tests_journal;
|
||||
|
||||
@@ -238,6 +238,7 @@ impl Writer {
|
||||
return Ok(());
|
||||
}
|
||||
self.file = None;
|
||||
crate::store::check_regular_directory_entry(&self.path)?;
|
||||
let f = match std::fs::OpenOptions::new().write(true).open(&self.path) {
|
||||
Ok(f) => f,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
|
||||
@@ -439,6 +439,23 @@ impl Photo {
|
||||
pub fn relative_wb(&self) -> bool {
|
||||
self.develops_raw() && relative_wb_camera(&self.format, &self.meta.camera)
|
||||
}
|
||||
/// Every settings holder of this photo that can carry segmentation grids: the develop
|
||||
/// settings, the versions', the history steps' and the import look. A snapshot's shared grid
|
||||
/// table ([`crate::Catalog`]'s `grids`) covers all of them, so a new holder belongs here.
|
||||
pub(crate) fn settings_holders(&self) -> impl Iterator<Item = &Arc<DevelopSettings>> {
|
||||
std::iter::once(&self.develop)
|
||||
.chain(self.versions.iter().map(|v| &v.settings))
|
||||
.chain(self.history.iter().map(|h| &h.settings))
|
||||
.chain(self.import_look.iter())
|
||||
}
|
||||
/// [`Photo::settings_holders`] with mutable access (resolving a snapshot's grid references).
|
||||
pub(crate) fn settings_holders_mut(&mut self) -> impl Iterator<Item = &mut Arc<DevelopSettings>> {
|
||||
let Photo { develop, versions, history, import_look, .. } = self;
|
||||
std::iter::once(develop)
|
||||
.chain(versions.iter_mut().map(|v| &mut v.settings))
|
||||
.chain(history.iter_mut().map(|h| &mut h.settings))
|
||||
.chain(import_look.as_mut())
|
||||
}
|
||||
/// The develop settings import gave this photo: [`Photo::camera_defaults`], or the user's
|
||||
/// default preset applied on top of them ([`Photo::import_look`]). Like the camera defaults,
|
||||
/// in the photo's own rendering process.
|
||||
|
||||
@@ -238,8 +238,9 @@ fn op_variants_are_versioned() {
|
||||
Op::SetHistoryCursor { .. } => 8,
|
||||
}
|
||||
}
|
||||
/// v11: `EmbeddedLens.source` (v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`).
|
||||
const NEWEST_FIELDS: u32 = 11;
|
||||
/// v12: `Catalog.grids` and `SegMask.grid`, shared by a snapshot's masks (#2154) (v11: `EmbeddedLens.source`; v10: `Mask.on_photo`; v9:
|
||||
/// `Photo.preview_checked` and `Op::SetContent.preview_checked`).
|
||||
const NEWEST_FIELDS: u32 = 12;
|
||||
let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None });
|
||||
assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version");
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
//! Issue #2154: a snapshot keeps each distinct segmentation grid once (`Catalog.grids`) and the
|
||||
//! masks of the develop settings, versions, history steps and import look refer to it by index,
|
||||
//! so an unchanged mask no longer repeats with every history step. In-memory catalogs and log
|
||||
//! records always hold the grids inline; older catalogs (inline everywhere) load and are upgraded.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use lightcraft_develop::{DevelopSettings, Mask, MaskComponent, MaskOp, MaskShape, SegMask};
|
||||
|
||||
use crate::journal::{LOG, SNAPSHOT, VERSION};
|
||||
use crate::*;
|
||||
|
||||
fn snapshot_version(m: &MemStore) -> u64 {
|
||||
let v: serde_json::Value = serde_json::from_slice(&m.get(SNAPSHOT).unwrap()).unwrap();
|
||||
v["version"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn open(m: &MemStore) -> (Journal, Catalog, LoadReport) {
|
||||
Journal::open(Box::new(m.clone())).unwrap()
|
||||
}
|
||||
|
||||
/// Develop settings with one AI mask over an object segmentation.
|
||||
fn settings_with_seg(seg: SegMask, exposure: f64) -> DevelopSettings {
|
||||
let mut s = DevelopSettings::default();
|
||||
s.light.exposure = exposure;
|
||||
s.masks.push(Mask {
|
||||
id: 1,
|
||||
components: vec![MaskComponent {
|
||||
name: None,
|
||||
op: MaskOp::Add,
|
||||
invert: false,
|
||||
shape: MaskShape::Object {
|
||||
hint: vec![lightcraft_geom::Point::new(0.5, 0.5)],
|
||||
exclude: vec![],
|
||||
seg: Some(seg),
|
||||
detail: vec![],
|
||||
edge: 0.0,
|
||||
},
|
||||
}],
|
||||
..Default::default()
|
||||
});
|
||||
s
|
||||
}
|
||||
|
||||
/// One mask (`id`) whose only component is an Object segmentation `seg`.
|
||||
fn object_mask(id: u32, seg: SegMask) -> Mask {
|
||||
Mask {
|
||||
id,
|
||||
components: vec![MaskComponent {
|
||||
name: None,
|
||||
op: MaskOp::Add,
|
||||
invert: false,
|
||||
shape: MaskShape::Object {
|
||||
hint: vec![lightcraft_geom::Point::new(0.5, 0.5)],
|
||||
exclude: vec![],
|
||||
seg: Some(seg),
|
||||
detail: vec![],
|
||||
edge: 0.0,
|
||||
},
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A catalog of one photo whose history is `steps` slider edits over the same mask, plus the
|
||||
/// ops that built it (each step is one `SetDevelop` + one `PushHistory`, as the engine commits
|
||||
/// an edit) and the shared grid's bytes.
|
||||
fn masked_catalog(steps: usize) -> (Catalog, Vec<Op>, PhotoId, String) {
|
||||
let seg = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
|
||||
let blob = seg.data.clone();
|
||||
let mut c = Catalog::new();
|
||||
let id = c.alloc_photo_id();
|
||||
let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::File { path: "/p/1.jpg".into() }, "1.jpg", "JPEG", 60, 40, "2026-01-01")) };
|
||||
c.apply(add.clone()).unwrap();
|
||||
let mut ops = vec![add];
|
||||
for i in 1..=steps {
|
||||
let settings = Arc::new(settings_with_seg(seg.clone(), f64::from(i as u32) * 0.1));
|
||||
let op = Op::Batch {
|
||||
ops: vec![
|
||||
Op::SetDevelop { id, settings: settings.clone(), label: "Exposure".into(), edited: Some(format!("t{i}")) },
|
||||
Op::PushHistory { id, step: HistoryStep { label: "Exposure".into(), settings } },
|
||||
],
|
||||
};
|
||||
c.apply(op.clone()).unwrap();
|
||||
ops.push(op);
|
||||
}
|
||||
(c, ops, id, blob)
|
||||
}
|
||||
|
||||
/// N history steps over one mask store the grid exactly once and load back identical.
|
||||
#[test]
|
||||
fn snapshot_deduplicates_shared_grid() {
|
||||
let (live, ops, id, blob) = masked_catalog(20);
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, report) = open(&m);
|
||||
assert!(report.created);
|
||||
j.append(&ops).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(snapshot_version(&m), u64::from(VERSION));
|
||||
assert_eq!(body.match_indices(&blob).count(), 1, "the grid is stored once for every step that shares it");
|
||||
let v: serde_json::Value = serde_json::from_str(body).unwrap();
|
||||
assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 1);
|
||||
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!((report.replayed, report.upgraded_from, report.repaired.len()), (0, None, 0));
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
let p = loaded.photo(id).unwrap();
|
||||
assert_eq!(p.history.len(), 20);
|
||||
for h in &p.history {
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &h.settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), (blob.as_str(), None), "every step's grid is back inline");
|
||||
}
|
||||
}
|
||||
|
||||
/// A catalog written before the shared table (grids inline everywhere, format v9) loads as it
|
||||
/// was and its upgrade rewrite deduplicates.
|
||||
#[test]
|
||||
fn v9_catalog_with_inline_grids_loads_and_is_upgraded() {
|
||||
let (live, _, _, blob) = masked_catalog(3);
|
||||
let body = live.to_snapshot();
|
||||
assert!(body.contains(&blob), "a live catalog stores its grids inline");
|
||||
let m = MemStore::new();
|
||||
m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":9,\"seq\":2,\"catalog\":{body}}}\n").into_bytes());
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!((report.replayed, report.upgraded_from), (0, Some(9)));
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
// rewritten in this format before anything is appended, with the grid once
|
||||
assert_eq!(snapshot_version(&m), u64::from(VERSION));
|
||||
let rewritten_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let rewritten = std::str::from_utf8(&rewritten_bytes).unwrap();
|
||||
assert_eq!(rewritten.match_indices(&blob).count(), 1);
|
||||
assert!(rewritten.contains("\"grids\":["), "the shared table is in the file");
|
||||
}
|
||||
|
||||
/// The op log is not deduplicated: every record keeps the grids inline (a log never carries the
|
||||
/// shared table), and replaying it rebuilds the same state.
|
||||
#[test]
|
||||
fn log_records_keep_their_grids_inline() {
|
||||
let (live, ops, _, blob) = masked_catalog(2);
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&ops).unwrap();
|
||||
drop(j); // no snapshot: the log holds the whole state
|
||||
let log_bytes = m.get(LOG).unwrap();
|
||||
let log = std::str::from_utf8(&log_bytes).unwrap();
|
||||
assert_eq!(log.match_indices(&blob).count(), 4, "two edits, SetDevelop + PushHistory each, inline");
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!(report.replayed, 3, "the photo and the two edits");
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// A reference that points past the shared table is cleared (the mask renders nothing, like any
|
||||
/// damaged grid); a good reference resolves back to the full grid.
|
||||
#[test]
|
||||
fn shared_grid_references_resolve_or_are_repaired() {
|
||||
let (live, _, id, blob) = masked_catalog(1);
|
||||
let inline = live.to_snapshot();
|
||||
|
||||
// a damaged snapshot: the develop mask refers past the one-entry table
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":7", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!(
|
||||
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"dHdv\"],{} }} }}\n",
|
||||
&body[1..body.len() - 1]
|
||||
)
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, damaged, report) = open(&m);
|
||||
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
|
||||
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
|
||||
let p = damaged.photo(id).unwrap();
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared, never a crash");
|
||||
// the history step's inline grid is untouched
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!(seg.data, blob);
|
||||
|
||||
// a good reference resolves (the normal way a snapshot in this format reads, so it is not
|
||||
// reported as a repair): the mask reads exactly as it was written
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!(
|
||||
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[\"{blob}\"],{} }} }}\n",
|
||||
&body[1..body.len() - 1]
|
||||
)
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, resolved, report) = open(&m);
|
||||
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
|
||||
assert_eq!(resolved.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// The background snapshot path shares the grids too (the interner is per thread).
|
||||
#[test]
|
||||
fn background_snapshot_deduplicates_shared_grid() {
|
||||
let (live, ops, _, blob) = masked_catalog(5);
|
||||
let mut m = MemStore::new();
|
||||
m.background = true;
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&ops).unwrap();
|
||||
j.snapshot_in_background(&live).unwrap();
|
||||
j.wait().unwrap();
|
||||
drop(j);
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(body.match_indices(&blob).count(), 1);
|
||||
let (_, loaded, _) = open(&m);
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// A version (not only history steps) shares the grid: one photo with a snapshot version and a
|
||||
/// history step over the same mask stores the grid once.
|
||||
#[test]
|
||||
fn versions_share_the_grid_too() {
|
||||
let seg = SegMask::from_logits(32, &vec![1.0f32; 32 * 32]);
|
||||
let blob = seg.data.clone();
|
||||
let id = PhotoId(1);
|
||||
let add = Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 0 }, "d.jpg", "JPEG", 60, 40, "2026-01-01")) };
|
||||
let settings = Arc::new(settings_with_seg(seg, 0.5));
|
||||
let versions =
|
||||
Op::SetVersions { id, versions: vec![Version { name: "v".into(), created: "2026-01-01".into(), settings: settings.clone(), auto: false }] };
|
||||
let history = Op::PushHistory { id, step: HistoryStep { label: "e".into(), settings } };
|
||||
let mut live = Catalog::new();
|
||||
for op in [&add, &versions, &history] {
|
||||
live.apply(op.clone()).unwrap();
|
||||
}
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&[add, versions, history]).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(body.match_indices(&blob).count(), 1, "the version and the step share the grid");
|
||||
let (_, loaded, _) = open(&m);
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// The import look (`Photo.import_look`, the settings a default preset gave the photo on import)
|
||||
/// can hold AI masks, and their grids can be grids the develop settings or a history step hold.
|
||||
/// Every settings holder shares the snapshot's table, so the look's masks are referenced and
|
||||
/// resolved on load like the others; a grid only the look holds is in the table too.
|
||||
#[test]
|
||||
fn import_look_masks_share_the_table_and_resolve_on_load() {
|
||||
let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
|
||||
let look_only = SegMask::from_logits(64, &vec![-0.5f32; 64 * 64]);
|
||||
let mut look = DevelopSettings::default();
|
||||
look.masks.push(object_mask(1, shared.clone()));
|
||||
look.masks.push(object_mask(2, look_only.clone()));
|
||||
let mut edit = DevelopSettings::default();
|
||||
edit.light.exposure = 0.7;
|
||||
edit.masks.push(object_mask(1, shared.clone()));
|
||||
let edit = Arc::new(edit);
|
||||
|
||||
let id = PhotoId(1);
|
||||
let mut photo = Photo::new(id, Source::File { path: "/p/2.jpg".into() }, "2.jpg", "JPEG", 60, 40, "2026-01-01");
|
||||
photo.develop = edit.clone();
|
||||
photo.import_look = Some(Arc::new(look));
|
||||
photo.history.push(HistoryStep { label: "Exposure".into(), settings: edit });
|
||||
let add = Op::AddPhoto { photo: Box::new(photo) };
|
||||
let mut live = Catalog::new();
|
||||
live.apply(add.clone()).unwrap();
|
||||
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&[add]).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
let snap_bytes = m.get(SNAPSHOT).unwrap();
|
||||
let body = std::str::from_utf8(&snap_bytes).unwrap();
|
||||
assert_eq!(body.match_indices(&shared.data).count(), 1, "the grid of the look and of the edit is stored once");
|
||||
assert_eq!(body.match_indices(&look_only.data).count(), 1);
|
||||
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
|
||||
let p = loaded.photo(id).unwrap();
|
||||
let look_masks = &p.import_look.as_ref().unwrap().masks;
|
||||
assert_eq!(look_masks.len(), 2);
|
||||
for (mask, want) in look_masks.iter().zip([&shared, &look_only]) {
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &mask.components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), (want.data.as_str(), None), "the look's grid is back inline");
|
||||
}
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
let v: serde_json::Value = serde_json::from_str(body).unwrap();
|
||||
assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 2, "one table entry per distinct grid, the look's included");
|
||||
}
|
||||
|
||||
/// A `grid` that arrives from a document (a command's mask JSON, a preset, a merged partial) is
|
||||
/// not a reference and is never written as one: a snapshot must not resolve it to another mask's
|
||||
/// grid. Here photo two's mask carries `grid: 0` with empty data, while photo one's grid is the
|
||||
/// table's entry 0; before the fix the inline form wrote `"grid":0` and the load filled photo two
|
||||
/// with photo one's grid.
|
||||
#[test]
|
||||
fn stray_grid_from_a_document_is_not_written_as_a_reference() {
|
||||
let shared = SegMask::from_logits(64, &vec![0.5f32; 64 * 64]);
|
||||
let stray: SegMask = serde_json::from_str(r#"{"side":64,"data":"","grid":0}"#).unwrap();
|
||||
assert_eq!(stray.grid, Some(0), "a document can set grid");
|
||||
let mut stray_settings = DevelopSettings::default();
|
||||
stray_settings.masks.push(object_mask(1, stray));
|
||||
|
||||
let (one, two) = (PhotoId(1), PhotoId(2));
|
||||
let photo = |id: PhotoId, name: &str| Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01");
|
||||
let ops = [
|
||||
Op::AddPhoto { photo: Box::new(photo(one, "1.jpg")) },
|
||||
Op::SetDevelop { id: one, settings: Arc::new(settings_with_seg(shared.clone(), 0.2)), label: "Exposure".into(), edited: Some("t1".into()) },
|
||||
Op::AddPhoto { photo: Box::new(photo(two, "2.jpg")) },
|
||||
Op::SetDevelop { id: two, settings: Arc::new(stray_settings), label: "Edit".into(), edited: Some("t2".into()) },
|
||||
];
|
||||
let mut live = Catalog::new();
|
||||
for op in &ops {
|
||||
live.apply(op.clone()).unwrap();
|
||||
}
|
||||
|
||||
let m = MemStore::new();
|
||||
let (mut j, _, _) = open(&m);
|
||||
j.append(&ops).unwrap();
|
||||
j.snapshot(&live).unwrap();
|
||||
drop(j);
|
||||
let (_, loaded, report) = open(&m);
|
||||
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &loaded.photo(two).unwrap().develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the stray reference is not resolved to photo one's grid");
|
||||
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
|
||||
}
|
||||
|
||||
/// A snapshot whose shared grid table is empty (`grids: []`) but whose masks still refer into
|
||||
/// it: the table being empty must not skip the repair. A reference past an empty table is
|
||||
/// dangling, so it is cleared (the mask renders nothing, like any other damaged grid), the
|
||||
/// repair is reported, and a mask that carries its own grid inline is left untouched.
|
||||
#[test]
|
||||
fn empty_shared_grid_table_clears_dangling_references() {
|
||||
let (live, _, id, blob) = masked_catalog(1);
|
||||
let inline = live.to_snapshot();
|
||||
|
||||
// a damaged snapshot: an empty table, but the develop mask still refers to entry 0
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!(
|
||||
"{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"grids\":[],{} }} }}\n",
|
||||
&body[1..body.len() - 1]
|
||||
)
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, damaged, report) = open(&m);
|
||||
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
|
||||
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
|
||||
let p = damaged.photo(id).unwrap();
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with an empty table");
|
||||
|
||||
// the history step carries its grid inline: nothing there to resolve, left as it was
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!(seg.data, blob, "the history step's inline grid is untouched");
|
||||
}
|
||||
|
||||
/// A snapshot that omits the shared grid table entirely (no `grids` key) but whose masks still
|
||||
/// refer into it: an absent table deserializes to an empty Vec, so a reference past it is
|
||||
/// dangling and is cleared and reported, just like the empty-table case.
|
||||
#[test]
|
||||
fn omitted_shared_grid_table_clears_dangling_references() {
|
||||
let (live, _, id, blob) = masked_catalog(1);
|
||||
let inline = live.to_snapshot();
|
||||
|
||||
// a damaged snapshot: no table at all, but the develop mask still refers to entry 0
|
||||
let body = inline.replacen(&format!("\"data\":\"{blob}\""), "\"grid\":0", 1);
|
||||
let m = MemStore::new();
|
||||
m.set(
|
||||
SNAPSHOT,
|
||||
format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{{} }} }}\n", &body[1..body.len() - 1])
|
||||
.into_bytes(),
|
||||
);
|
||||
let (_, damaged, report) = open(&m);
|
||||
assert_eq!(report.repaired.len(), 1, "{:?}", report.repaired);
|
||||
assert!(report.repaired[0].contains("pointed past the shared table"), "{:?}", report.repaired);
|
||||
let p = damaged.photo(id).unwrap();
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.develop.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!((seg.data.as_str(), seg.grid), ("", None), "the dangling reference is cleared even with no table");
|
||||
|
||||
// the history step carries its grid inline: nothing there to resolve, left as it was
|
||||
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
|
||||
assert_eq!(seg.data, blob, "the history step's inline grid is untouched");
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::journal::LOG;
|
||||
use crate::journal::{LOG, RESYNC_CANDIDATES};
|
||||
use crate::*;
|
||||
|
||||
/// A store whose next append writes only a prefix of its data, then fails.
|
||||
@@ -224,3 +224,208 @@ fn fs_store_truncates_a_missing_file_quietly() {
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Issue #2124: `resync` must be linear in the line length, not quadratic. A line that is nothing
|
||||
/// but the start marker repeated 300k times must open fast, and a valid retry record placed after
|
||||
/// it must still be recovered.
|
||||
#[test]
|
||||
fn resync_is_not_quadratic_in_line_length() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
// Build a valid snapshot + an initial record so `j.seq()` is non-zero and the `seq <= last + 1`
|
||||
// gate in resync can be exercised.
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
let first = apply(&mut c, vec![add]);
|
||||
j.append(&first).unwrap();
|
||||
|
||||
let log = probe.get(LOG).unwrap();
|
||||
let base_len = log.len();
|
||||
|
||||
// A hostile 300k-repetition marker line (about 2.3 MB), then one valid retried record that
|
||||
// continues the log (seq == j.seq() + 1, so resync's gate accepts it).
|
||||
let marker = b"{\"seq\":";
|
||||
let mut hostile = Vec::with_capacity(marker.len() * 300_000 + log.len() + 256);
|
||||
hostile.extend_from_slice(&log[..base_len]);
|
||||
for _ in 0..300_000 {
|
||||
hostile.extend_from_slice(marker);
|
||||
}
|
||||
|
||||
// Encode the retry record the same way the journal writes records, so decode_record accepts it.
|
||||
let next_seq = j.seq() + 1;
|
||||
let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 };
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n");
|
||||
hostile.extend_from_slice(retry.as_bytes());
|
||||
|
||||
probe.set(LOG, hostile);
|
||||
|
||||
// Count the start markers resync decodes instead of timing it: a slow worker must not fail this.
|
||||
RESYNC_CANDIDATES.with(|c| c.set(0));
|
||||
let (j2, _c2, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let candidates = RESYNC_CANDIDATES.with(|c| c.get());
|
||||
assert!(candidates <= 1, "resync decoded {candidates} start markers of a hostile 2 MB line; only the last one may be decoded");
|
||||
assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment");
|
||||
assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment");
|
||||
}
|
||||
|
||||
/// A retry record whose op body holds a nested `{"seq":` (a smart-album rule value such as
|
||||
/// `{"seq":1}` on a `title isEmpty` rule) shadows the record's own start marker: `rposition` in
|
||||
/// `resync` picks the nested occurrence, `decode_record` rejects the suffix, and `Journal::open`
|
||||
/// truncates the final line instead of replaying the retry — the valid operation is lost.
|
||||
#[test]
|
||||
fn resync_preserves_retry_record_with_nested_start_marker() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
j.append(&apply(&mut c, vec![add])).unwrap();
|
||||
|
||||
let album_id = c.alloc_album_id();
|
||||
let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } };
|
||||
j.append(&apply(&mut c, vec![add_album])).unwrap();
|
||||
|
||||
let retry_op = Op::SetAlbumRules {
|
||||
id: album_id,
|
||||
rules: Box::new(Filter {
|
||||
rule_set: Some(RuleSet {
|
||||
mode: Match::All,
|
||||
rules: vec![Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }],
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
apply(&mut c, vec![retry_op.clone()]);
|
||||
|
||||
// Encode the retry exactly as the journal writes records, so `decode_record` accepts it once
|
||||
// resync finds its real start: `seq` continues the log and the CRC matches the body.
|
||||
let next_seq = j.seq() + 1;
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n");
|
||||
|
||||
// A torn fragment glued to the retry on the final line. The outer record start sits right
|
||||
// after the fragment, but the last `{"seq":` byte occurrence is the nested rule value.
|
||||
let mut log = probe.get(LOG).unwrap();
|
||||
log.extend_from_slice(b"torn fragment without a newline");
|
||||
log.extend_from_slice(retry.as_bytes());
|
||||
probe.set(LOG, log);
|
||||
|
||||
let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
assert_eq!(j2.seq(), next_seq, "resync should have recovered the retried record after the fragment");
|
||||
assert_eq!(report.torn_fragments, 1, "resync should report exactly one torn fragment");
|
||||
assert_eq!(report.torn_bytes, 0, "the valid retry record must not be truncated as torn");
|
||||
assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the recovered smart-album rule should be preserved");
|
||||
}
|
||||
|
||||
/// The maintainer's regression for issue #2124, with the damaged line as the file's LAST one: a
|
||||
/// torn fragment glued to a CRC-valid `SetAlbumRules` retry whose rules hold several nested
|
||||
/// `{"seq":1}` values. Picking the last raw `{"seq":` occurrence as the record start (as the
|
||||
/// original `rposition` scan did) lands in a nested value, rejects the whole record, and cuts the
|
||||
/// final line away — losing the valid operation. `resync` must recover the retry (its real start
|
||||
/// is followed by the `,"crc":` header no nested rule value has) and leave the log file whole.
|
||||
#[test]
|
||||
fn resync_recovers_rules_retry_with_many_nested_values_on_the_final_line() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
j.append(&apply(&mut c, vec![add])).unwrap();
|
||||
|
||||
let album_id = c.alloc_album_id();
|
||||
let add_album = Op::AddAlbum { album: Album { smart: Some(Box::new(Filter::default())), ..Album::new(album_id, "Smart") } };
|
||||
j.append(&apply(&mut c, vec![add_album])).unwrap();
|
||||
|
||||
let rules =
|
||||
(0..12).map(|_| Rule::Field { field: "title".into(), op: "isEmpty".into(), value: serde_json::json!({ "seq": 1 }) }).collect::<Vec<_>>();
|
||||
let retry_op =
|
||||
Op::SetAlbumRules { id: album_id, rules: Box::new(Filter { rule_set: Some(RuleSet { mode: Match::All, rules }), ..Default::default() }) };
|
||||
apply(&mut c, vec![retry_op.clone()]);
|
||||
|
||||
// Encode the retry exactly as the journal writes records, so `decode_record` accepts it once
|
||||
// resync finds its real start: `seq` continues the log and the CRC matches the body.
|
||||
let next_seq = j.seq() + 1;
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let retry = format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}");
|
||||
|
||||
// The failed append's fragment glued to the retry, and nothing after: the damaged line is the
|
||||
// file's last, without a closing newline.
|
||||
let mut log = probe.get(LOG).unwrap();
|
||||
log.extend_from_slice(b"torn fragment without a newline");
|
||||
log.extend_from_slice(retry.as_bytes());
|
||||
let damaged = log.clone();
|
||||
probe.set(LOG, log);
|
||||
|
||||
let (j2, loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
assert_eq!(report.torn_fragments, 1, "the fragment must be reported and the retry recovered");
|
||||
assert_eq!(report.torn_bytes, 0, "the retry record must not be cut away as a torn tail");
|
||||
assert_eq!(j2.seq(), next_seq, "the retried SetAlbumRules must be recovered");
|
||||
assert_eq!(report.replayed, 3);
|
||||
assert_eq!(loaded.to_snapshot(), c.to_snapshot(), "the smart-album rules must survive the reload");
|
||||
|
||||
// The log file is preserved: its bytes stay (plus only the newline that closes the final
|
||||
// line), instead of the damaged line being truncated away.
|
||||
let after = probe.get(LOG).unwrap();
|
||||
assert_eq!(after.len(), damaged.len() + 1, "the log must keep the fragment and the recovered record");
|
||||
assert_eq!(&after[..damaged.len()], &damaged[..]);
|
||||
}
|
||||
|
||||
/// A crafted final line of many header-shaped markers (`{"seq":1,"crc":2,"op":`) passes the
|
||||
/// record-header filter, so every marker becomes a resync candidate, and each attempt decodes the
|
||||
/// whole rest of the line: trying all of them is quadratic in the line length, a stall of
|
||||
/// `Journal::open` on a hostile log (CWE-407). The per-line scan budget must bound the candidate
|
||||
/// decodes (counted, not timed) and open must still finish safely. A CRC-valid retry placed after
|
||||
/// the junk must stay recoverable: it is the last candidate, so the scan reaches it first.
|
||||
#[test]
|
||||
fn resync_scan_budget_bounds_a_line_of_header_shaped_markers() {
|
||||
let probe = MemStore::new();
|
||||
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let add = add_photo(&mut c);
|
||||
j.append(&apply(&mut c, vec![add])).unwrap();
|
||||
let good = probe.get(LOG).unwrap();
|
||||
|
||||
const MARKERS: usize = 5_000;
|
||||
let marker: &[u8] = b"{\"seq\":1,\"crc\":2,\"op\":";
|
||||
let mut hostile = good.clone();
|
||||
hostile.extend_from_slice(b"torn fragment"); // so no marker sits at line position 0
|
||||
for _ in 0..MARKERS {
|
||||
hostile.extend_from_slice(marker);
|
||||
}
|
||||
let hostile_len = (hostile.len() - good.len()) as u64;
|
||||
probe.set(LOG, hostile);
|
||||
|
||||
RESYNC_CANDIDATES.with(|count| count.set(0));
|
||||
let (j2, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let candidates = RESYNC_CANDIDATES.with(|count| count.get());
|
||||
assert!(
|
||||
candidates < MARKERS,
|
||||
"resync tried all {candidates} candidates of a hostile {hostile_len}-byte line; the scan budget must bound the work"
|
||||
);
|
||||
assert!(report.damaged.is_none(), "{report:?}");
|
||||
assert_eq!(report.torn_fragments, 0);
|
||||
assert_eq!(report.torn_bytes, hostile_len, "the hostile line must be dropped as a torn tail");
|
||||
assert_eq!(j2.seq(), 1, "the records before the hostile line must survive");
|
||||
assert_eq!(probe.get(LOG).unwrap().len(), good.len(), "the log must be cut back to the last good record");
|
||||
|
||||
let retry_op = Op::SetRating { id: c.photos().next().unwrap().id, rating: 5 };
|
||||
let next_seq = j2.seq() + 1;
|
||||
let body = serde_json::to_string(&retry_op).unwrap();
|
||||
let crc = crc32fast::hash(body.as_bytes());
|
||||
let mut log = good.clone();
|
||||
for _ in 0..MARKERS {
|
||||
log.extend_from_slice(marker);
|
||||
}
|
||||
log.extend_from_slice(format!("{{\"seq\":{next_seq},\"crc\":{crc},\"op\":{body}}}\n").as_bytes());
|
||||
probe.set(LOG, log);
|
||||
|
||||
RESYNC_CANDIDATES.with(|count| count.set(0));
|
||||
let (j3, _loaded, report) = Journal::open(Box::new(probe.clone())).unwrap();
|
||||
let candidates = RESYNC_CANDIDATES.with(|count| count.get());
|
||||
assert_eq!(candidates, 1, "the retry is the last candidate and must decode first");
|
||||
assert_eq!(j3.seq(), next_seq, "the retried record after the junk must be recovered");
|
||||
assert_eq!(report.torn_fragments, 1, "the junk before the retry is one skipped fragment");
|
||||
assert_eq!(report.torn_bytes, 0, "the valid retry record must not be cut away");
|
||||
}
|
||||
@@ -13,7 +13,7 @@ pub mod settings;
|
||||
|
||||
pub use controls::{CONTROLS, ControlSpec, Section, Track};
|
||||
pub use presets::{Preset, SettingsGroup, apply_partial, extract_groups};
|
||||
pub use segmask::SegMask;
|
||||
pub use segmask::{SegMask, with_grid_interner};
|
||||
pub use settings::*;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
+310
-16
@@ -1,8 +1,12 @@
|
||||
//! Presets and copy/paste subsets.
|
||||
//!
|
||||
//! A preset is a *partial* settings object (JSON) — only the groups it includes. Applying merges it
|
||||
//! into the photo's settings; `amount` (0..200 %) interpolates numeric values between the current
|
||||
//! settings and the preset's. Copy/paste/sync use the same group selection ([`SettingsGroup`]).
|
||||
//! A preset is a *partial* settings object (JSON) — only the settings it names. Applying it changes
|
||||
//! exactly the settings it names (a leaf: a number, a flag, a name; an array is one leaf): each is
|
||||
//! computed from the photo's *original* state (its import settings, when known) and the preset's
|
||||
//! value, and replaces the photo's value; every other setting keeps the photo's value (issue
|
||||
//! #2159). `amount` (0..200 %) moves each named number between the original and the preset's
|
||||
//! value. Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the
|
||||
//! current settings as before.
|
||||
//!
|
||||
//! The rendering process ([`crate::ProcessVersion`]) is in no group: copy, paste, sync and presets
|
||||
//! made from a photo never carry it, so the photos they change keep their own. A partial that names
|
||||
@@ -191,6 +195,74 @@ pub fn apply_partial(s: &DevelopSettings, partial: &Value, amount: f64) -> Devel
|
||||
s.merged(&patch).unwrap_or_else(|_| s.clone())
|
||||
}
|
||||
|
||||
/// Top-level settings keys that hold per-photo pixel repairs: a preset's named repairs compose on
|
||||
/// the photo's own values instead of the original's (masks are added by [`Preset::apply_on`]), and
|
||||
/// a preset without them leaves the photo's alone.
|
||||
const REPAIR_KEYS: [&str; 3] = ["masks", "spots", "red_eye"];
|
||||
|
||||
/// The settings `settings` (a partial JSON object) names, applied to `current` at `amount`: each
|
||||
/// named setting is computed from `original` (the photo's import state) and the preset's value,
|
||||
/// and replaces the photo's value (issue #2159). Every setting the preset does not name keeps the
|
||||
/// photo's current value, edits included. Pixel repairs compose on the photo's own values, as they
|
||||
/// always have.
|
||||
fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings: &Value, amount: f64) -> DevelopSettings {
|
||||
// At 100 % the preset's own values apply as they are, and `original` is not read. The presets
|
||||
// panel calls this for every visible row on every frame, so the scaling base is built below only.
|
||||
if (amount - 1.0).abs() < 1e-9 {
|
||||
return current.merged(settings).unwrap_or_else(|_| current.clone());
|
||||
}
|
||||
let cur = current.to_json();
|
||||
let mut base = original.to_json();
|
||||
if let (Some(b), Some(c)) = (base.as_object_mut(), cur.as_object()) {
|
||||
for k in REPAIR_KEYS {
|
||||
if let Some(v) = c.get(k) {
|
||||
b.insert(k.to_string(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let composed = match settings.as_object() {
|
||||
Some(patch) => Value::Object(interpolate_object(base.as_object(), patch, amount)),
|
||||
None => Value::Object(Map::new()),
|
||||
};
|
||||
// `merged` deep-merges: the named settings replace, everything else stays as `current` has it
|
||||
current.merged(&composed).unwrap_or_else(|_| current.clone())
|
||||
}
|
||||
|
||||
/// The leaves of `patch` that apply at `t` (below 100 %), each computed from the same place in
|
||||
/// `base`. A leaf the amount does not reach is left out, so the photo keeps its own value there.
|
||||
fn interpolate_object(base: Option<&Map<String, Value>>, patch: &Map<String, Value>, t: f64) -> Map<String, Value> {
|
||||
let mut out = Map::new();
|
||||
for (k, pv) in patch {
|
||||
let bv = base.and_then(|b| b.get(k));
|
||||
let v = match pv {
|
||||
Value::Object(p) => Some(Value::Object(interpolate_object(bv.and_then(Value::as_object), p, t))),
|
||||
_ => interpolate_leaf(bv, pv, t),
|
||||
};
|
||||
if let Some(v) = v {
|
||||
out.insert(k.clone(), v);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One leaf at `t`. Numbers move from `base` towards `patch`. Other values switch to the preset's
|
||||
/// at half amount and up, and below it take the base's value. A null in the base is the baseline
|
||||
/// value the import state recorded (a cleared option, such as a free crop aspect): below half
|
||||
/// amount it applies and clears the photo's value, as the amount contract promises. A null the
|
||||
/// preset writes is a value like any other, so it applies at half amount and up (a preset can
|
||||
/// clear an option field such as a crop aspect).
|
||||
fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option<Value> {
|
||||
match (base, patch) {
|
||||
// integer fields (the grain seed, ids) are discrete like strings: see `scale_patch`
|
||||
(Some(Value::Number(b)), Value::Number(p)) if b.is_f64() || p.is_f64() => {
|
||||
let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0));
|
||||
serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number)
|
||||
}
|
||||
_ if t >= 0.5 => Some(patch.clone()),
|
||||
_ => base.cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Preset {
|
||||
pub id: String,
|
||||
@@ -209,30 +281,49 @@ impl Preset {
|
||||
pub fn from_settings(id: &str, name: &str, group: &str, s: &DevelopSettings, groups: &[SettingsGroup]) -> Preset {
|
||||
Preset { id: id.into(), name: name.into(), group: group.into(), settings: extract_groups(s, groups), favorite: false, builtin: false }
|
||||
}
|
||||
/// Apply at `amount` (1.0 = 100 %). Masks in the preset are added to the photo's own (ones it
|
||||
/// already has are skipped), their effect scaled by the amount.
|
||||
/// Apply at `amount` (1.0 = 100 %), with `s` as both the photo's current and its original
|
||||
/// settings (see [`Preset::apply_on`]): right for the import default preset and for scratch
|
||||
/// bases. Masks in the preset are added to the photo's own (ones it already has are skipped),
|
||||
/// their effect scaled by the amount.
|
||||
pub fn apply(&self, s: &DevelopSettings, amount: f64) -> DevelopSettings {
|
||||
self.apply_on(s, s, amount)
|
||||
}
|
||||
/// Apply at `amount` (1.0 = 100 %), composing on `original` (the photo's import state, or the
|
||||
/// photo's current settings when that is not known): each setting the preset names is computed
|
||||
/// from `original` and the preset's value, `amount` moving it between the two, and replaces the
|
||||
/// photo's value. Every setting the preset does not name keeps `current`'s value, and so do
|
||||
/// the photo's pixel repairs (masks, spots, red eye), which the preset patches; masks in the
|
||||
/// preset are added to the photo's own (ones it already has are skipped), their effect scaled
|
||||
/// by the amount. A second preset therefore restores what the first one changed in the
|
||||
/// settings it names (issue #2159), and nothing it leaves out.
|
||||
pub fn apply_on(&self, current: &DevelopSettings, original: &DevelopSettings, amount: f64) -> DevelopSettings {
|
||||
let Some(masks) = self.settings.get("masks").and_then(Value::as_array).filter(|m| !m.is_empty()) else {
|
||||
return apply_partial(s, &self.settings, amount);
|
||||
return compose_named(current, original, &self.settings, amount);
|
||||
};
|
||||
let mut rest = self.settings.clone();
|
||||
if let Some(o) = rest.as_object_mut() {
|
||||
o.remove("masks");
|
||||
}
|
||||
let mut out = apply_partial(s, &rest, amount);
|
||||
for m in masks {
|
||||
let Ok(mut m) = serde_json::from_value::<crate::Mask>(m.clone()) else { continue };
|
||||
if out.masks.iter().any(|q| q.name == m.name && q.components == m.components) {
|
||||
continue;
|
||||
}
|
||||
m.id = out.next_mask_id();
|
||||
m.adjust.amount = (m.adjust.amount * amount).clamp(0.0, 200.0);
|
||||
out.masks.push(m);
|
||||
}
|
||||
let mut out = compose_named(current, original, &rest, amount);
|
||||
add_masks(&mut out, masks, amount);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The preset's masks, added to the photo's own (ones it already has are skipped), their effect
|
||||
/// scaled by the amount.
|
||||
fn add_masks(out: &mut DevelopSettings, masks: &[Value], amount: f64) {
|
||||
for m in masks {
|
||||
let Ok(mut m) = serde_json::from_value::<crate::Mask>(m.clone()) else { continue };
|
||||
if out.masks.iter().any(|q| q.name == m.name && q.components == m.components) {
|
||||
continue;
|
||||
}
|
||||
m.id = out.next_mask_id();
|
||||
m.adjust.amount = (m.adjust.amount * amount).clamp(0.0, 200.0);
|
||||
out.masks.push(m);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -285,6 +376,209 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset changes only the settings it names: a setting in a group it styles but does not
|
||||
/// name keeps the photo's value, and so does a whole group it leaves out.
|
||||
#[test]
|
||||
fn apply_on_changes_only_the_settings_it_names() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.light.exposure = 2.0;
|
||||
current.light.blacks = -30.0;
|
||||
current.effects.clarity = 30.0;
|
||||
let original = DevelopSettings::default();
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"light": {"contrast": 12.0}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = p.apply_on(¤t, &original, 1.0);
|
||||
assert_eq!(out.light.contrast, 12.0);
|
||||
assert_eq!(out.light.exposure, 2.0, "a setting the preset doesn't name keeps the photo's value");
|
||||
assert_eq!(out.light.blacks, -30.0, "a setting in the same group, not named, keeps the photo's value");
|
||||
assert_eq!(out.effects.clarity, 30.0, "a group the preset doesn't name is untouched");
|
||||
}
|
||||
|
||||
/// A partial preset that names one colour of the mixer leaves the other colours, and the
|
||||
/// unnamed settings of the colour it names, as the photo has them.
|
||||
#[test]
|
||||
fn apply_on_keeps_the_mixer_colours_it_does_not_name() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.mixer.red.sat = 20.0;
|
||||
current.mixer.blue.hue = 15.0;
|
||||
current.mixer.blue.sat = 5.0;
|
||||
let original = DevelopSettings::default();
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"mixer": {"blue": {"sat": 15.0, "lum": -25.0}}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = p.apply_on(¤t, &original, 1.0);
|
||||
assert_eq!(out.mixer.red.sat, 20.0, "a colour the preset doesn't name");
|
||||
assert_eq!(out.mixer.blue.hue, 15.0, "a setting of a named colour that the preset doesn't name");
|
||||
assert_eq!((out.mixer.blue.sat, out.mixer.blue.lum), (15.0, -25.0));
|
||||
}
|
||||
|
||||
/// The white balance is not one setting: a preset that names only the temperature keeps the
|
||||
/// photo's tint.
|
||||
#[test]
|
||||
fn apply_on_keeps_the_white_balance_fields_it_does_not_name() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.wb.temp = 6000.0;
|
||||
current.wb.tint = 12.0;
|
||||
let original = DevelopSettings::default();
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"wb": {"temp": 5000.0}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = p.apply_on(¤t, &original, 1.0);
|
||||
assert_eq!((out.wb.temp, out.wb.tint), (5000.0, 12.0));
|
||||
}
|
||||
|
||||
/// A preset's amount 0 changes nothing when the original is the photo's current settings (no
|
||||
/// import state is recorded for the photo), and any other amount moves the named settings
|
||||
/// from where the photo has them.
|
||||
#[test]
|
||||
fn apply_on_without_an_import_state_scales_from_the_current_settings() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.light.exposure = 2.0;
|
||||
current.light.blacks = -30.0;
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"light": {"exposure": 0.45, "contrast": 12.0}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
assert_eq!(p.apply_on(¤t, ¤t, 0.0), current, "amount 0 applies nothing");
|
||||
let half = p.apply_on(¤t, ¤t, 0.5);
|
||||
assert!((half.light.exposure - 1.225).abs() < 1e-9, "{}", half.light.exposure);
|
||||
assert_eq!(half.light.blacks, -30.0);
|
||||
}
|
||||
|
||||
/// An unresolved `crs:Look` reference (its profile object has no id; the importer leaves
|
||||
/// `look` in it) changes nothing: the photo keeps its own profile.
|
||||
#[test]
|
||||
fn an_unresolved_profile_reference_keeps_the_photos_profile() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.profile.id = "lc.vivid".into();
|
||||
current.profile.amount = 60.0;
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"profile": {"look": {"name": "Not imported", "amount": 100.0}}, "light": {"contrast": 12.0}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
for amount in [1.0, 0.5] {
|
||||
let out = p.apply_on(¤t, ¤t, amount);
|
||||
assert_eq!((out.profile.id.as_str(), out.profile.amount), ("lc.vivid", 60.0), "amount {amount}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The amount interpolates between the original and the preset, not between the visible
|
||||
/// values and the preset: a preset at 50 % looks the same however the photo was edited before.
|
||||
#[test]
|
||||
fn apply_on_scales_against_the_original() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.light.exposure = 2.0;
|
||||
let original = DevelopSettings::default();
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"light": {"exposure": 0.45}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = p.apply_on(¤t, &original, 0.5);
|
||||
assert!((out.light.exposure - 0.225).abs() < 1e-9, "{}", out.light.exposure);
|
||||
}
|
||||
|
||||
/// Pixel repairs are the photo's own: a preset's are patched in, and one without them never
|
||||
/// restores the original's.
|
||||
#[test]
|
||||
fn apply_on_patches_pixel_repairs_into_the_current_ones() {
|
||||
let current = DevelopSettings {
|
||||
spots: serde_json::from_value(json!([{"mode": "heal", "points": [[0.5, 0.5]], "size": 0.05, "feather": 50.0, "opacity": 100.0}]))
|
||||
.unwrap(),
|
||||
..Default::default()
|
||||
};
|
||||
let original = DevelopSettings::default();
|
||||
let none = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"light": {"contrast": 10.0}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = none.apply_on(¤t, &original, 1.0);
|
||||
assert_eq!(out.spots.len(), 1, "the photo's spot survives a preset without spots");
|
||||
let clearing = Preset {
|
||||
id: "q".into(),
|
||||
name: "Q".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"light": {"contrast": 10.0}, "spots": []}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let out = clearing.apply_on(¤t, &original, 1.0);
|
||||
assert_eq!(out.spots.len(), 0, "a preset that names spots replaces them, as before");
|
||||
}
|
||||
|
||||
/// A null a preset writes into an option field (here a crop aspect: null is "free") is the
|
||||
/// preset's value, so it clears the photo's aspect from half amount up, as any value of the
|
||||
/// preset does; below half amount the import baseline applies, which here is null as well.
|
||||
#[test]
|
||||
fn a_preset_null_clears_an_option_field_from_half_amount() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.crop.aspect = Some((3, 2));
|
||||
let original = DevelopSettings::default(); // the import state has no aspect
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"crop": {"aspect": null}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
for amount in [1.0, 0.7, 0.5] {
|
||||
assert_eq!(p.apply_on(¤t, &original, amount).crop.aspect, None, "amount {amount}: the preset's null clears the aspect");
|
||||
}
|
||||
assert_eq!(p.apply_on(¤t, &original, 0.3).crop.aspect, None, "below half amount the import baseline (no aspect) applies");
|
||||
}
|
||||
|
||||
/// The import state has no aspect, and that null is the baseline below half amount (the amount
|
||||
/// contract: a named setting moves between the import state and the preset's value); from half
|
||||
/// amount the preset's aspect applies.
|
||||
#[test]
|
||||
fn a_null_in_the_original_is_the_baseline_below_half_amount() {
|
||||
let mut current = DevelopSettings::default();
|
||||
current.crop.aspect = Some((3, 2));
|
||||
let original = DevelopSettings::default();
|
||||
let p = Preset {
|
||||
id: "p".into(),
|
||||
name: "P".into(),
|
||||
group: "G".into(),
|
||||
settings: json!({"crop": {"aspect": [16, 9]}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
assert_eq!(p.apply_on(¤t, &original, 0.4).crop.aspect, None, "40 %: the import baseline (no aspect) applies");
|
||||
assert_eq!(p.apply_on(¤t, &original, 0.6).crop.aspect, Some((16, 9)), "60 %: the preset's aspect applies");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_merge_objects() {
|
||||
let mut a = json!({"x": {"a": 1, "b": 2}, "y": [1]});
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Model segmentations stored with a mask ([`SegMask`]), so rendering never needs the model.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::{Deserialize, Serialize, Serializer};
|
||||
|
||||
/// Logits are stored in steps of 1/`SCALE`, clamped to ±127/`SCALE` (≈ ±15.9: a sigmoid of
|
||||
/// 1 − 1.2e-7, i.e. fully in or out).
|
||||
@@ -13,15 +16,26 @@ pub const MAX_SIDE: usize = 1024;
|
||||
/// normalized `((x + 0.5) / side, (y + 0.5) / side)`), quantized to `i8`, deflated and base64
|
||||
/// encoded. Coverage at a point is the sigmoid of the bilinearly sampled logit, so edges stay
|
||||
/// smooth at any output size.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
pub struct SegMask {
|
||||
pub side: u32,
|
||||
/// The grid's bytes (quantized, deflated, base64), unless this is a reference into the
|
||||
/// snapshot's shared grid table (`grid` is set and `data` is empty).
|
||||
#[serde(default)]
|
||||
pub data: String,
|
||||
/// The part of the image the grid covers, normalized `[x0, y0, x1, y1]` (`None` = all of
|
||||
/// it). A zoomed-in pass over one object covers just its surroundings, at a higher
|
||||
/// resolution than a pass over the whole photo.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub rect: Option<[f64; 4]>,
|
||||
/// Index into the catalog snapshot's shared grid table (`Catalog::grids`) this mask refers
|
||||
/// to instead of carrying its own `data`. A serialization detail of snapshots only: the
|
||||
/// snapshot writer sets it (through the interner, into its own table), `Catalog::repair`
|
||||
/// resolves it when a snapshot is read, and no other serialization writes it. A `grid` that
|
||||
/// arrives from any other document (a command, a preset, XMP, a log record) is read but
|
||||
/// never written back, so it cannot point a snapshot at another mask's grid.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub grid: Option<u32>,
|
||||
}
|
||||
|
||||
impl SegMask {
|
||||
@@ -29,7 +43,7 @@ impl SegMask {
|
||||
pub fn from_logits(side: usize, logits: &[f32]) -> SegMask {
|
||||
let q: Vec<u8> = logits.iter().take(side * side).map(|l| ((l * SCALE).round().clamp(-127.0, 127.0) as i8) as u8).collect();
|
||||
let z = miniz_oxide::deflate::compress_to_vec(&q, 8);
|
||||
SegMask { side: side as u32, data: base64_encode(&z), rect: None }
|
||||
SegMask { side: side as u32, data: base64_encode(&z), rect: None, grid: None }
|
||||
}
|
||||
|
||||
/// From `side × side` logits over the part `rect` of the image.
|
||||
@@ -55,6 +69,63 @@ impl SegMask {
|
||||
}
|
||||
}
|
||||
|
||||
// The grid table a snapshot serialization refers to: each distinct grid's data → its index.
|
||||
thread_local! {
|
||||
static INTERNER: RefCell<Option<HashMap<String, u32>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Serializes masks as references into a shared grid table (`grid` = index, `data` omitted)
|
||||
/// while `f` runs, one thread at a time (snapshot writes). Nested calls are ignored (`None`):
|
||||
/// the outermost writer owns the table.
|
||||
pub fn with_grid_interner<T>(map: HashMap<String, u32>, f: impl FnOnce() -> T) -> Option<T> {
|
||||
INTERNER.with(|i| {
|
||||
if i.borrow().is_some() {
|
||||
return None;
|
||||
}
|
||||
struct Guard;
|
||||
impl Drop for Guard {
|
||||
fn drop(&mut self) {
|
||||
INTERNER.with(|j| *j.borrow_mut() = None);
|
||||
}
|
||||
}
|
||||
*i.borrow_mut() = Some(map);
|
||||
let _guard = Guard;
|
||||
Some(f())
|
||||
})
|
||||
}
|
||||
|
||||
impl Serialize for SegMask {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
use serde::ser::SerializeMap;
|
||||
// While a snapshot is being written with a shared grid table, a mask whose exact bytes
|
||||
// are in the table refers to it by index instead of repeating the blob (issue #2154).
|
||||
if !self.data.is_empty()
|
||||
&& let Some(id) = INTERNER.with(|i| i.borrow().as_ref().and_then(|m| m.get(&self.data).copied()))
|
||||
{
|
||||
let len = if self.rect.is_some() { 3 } else { 2 };
|
||||
let mut map = serializer.serialize_map(Some(len))?;
|
||||
map.serialize_entry("side", &self.side)?;
|
||||
map.serialize_entry("grid", &id)?;
|
||||
if let Some(rect) = self.rect {
|
||||
map.serialize_entry("rect", &rect)?;
|
||||
}
|
||||
return map.end();
|
||||
}
|
||||
// Without a table hit: exactly the pre-v10 derived form (field order and skips included),
|
||||
// so every serialization that doesn't dedup keeps its bytes (`hash64`, cache keys). `grid`
|
||||
// is never written here: a value read from some document is dropped on save, and only the
|
||||
// interner above can write a reference (into the table of the snapshot being written).
|
||||
let len = 2 + usize::from(self.rect.is_some());
|
||||
let mut map = serializer.serialize_map(Some(len))?;
|
||||
map.serialize_entry("side", &self.side)?;
|
||||
map.serialize_entry("data", &self.data)?;
|
||||
if let Some(rect) = self.rect {
|
||||
map.serialize_entry("rect", &rect)?;
|
||||
}
|
||||
map.end()
|
||||
}
|
||||
}
|
||||
|
||||
/// Most zoomed-in detail patches one AI mask component keeps (the app makes one; each costs a
|
||||
/// decode per render, so a hostile document can't make rendering explode).
|
||||
pub const MAX_DETAIL: usize = 4;
|
||||
@@ -189,7 +260,51 @@ mod tests {
|
||||
assert!(m.logits().is_none(), "size mismatch");
|
||||
m.side = 100_000;
|
||||
assert!(m.logits().is_none(), "absurd size");
|
||||
assert!(SegMask { side: 8, data: "not base64 !".into(), rect: None }.logits().is_none());
|
||||
assert!(SegMask { side: 8, data: "not base64 !".into(), rect: None, grid: None }.logits().is_none());
|
||||
assert!(SegMask { rect: Some([0.5, 0.0, 0.2, 1.0]), ..SegMask::from_logits(2, &[0.0; 4]) }.bounds().is_none());
|
||||
}
|
||||
|
||||
/// A `grid` read from a document is never written outside the snapshot interner, with or
|
||||
/// without data: the bytes stay the pre-v10 form, so `hash64` and cache keys don't depend on
|
||||
/// a stray value (issue #2154).
|
||||
#[test]
|
||||
fn stray_grid_is_never_written_outside_the_interner() {
|
||||
let empty = SegMask { side: 4, data: String::new(), rect: None, grid: None };
|
||||
let stray = SegMask { grid: Some(3), ..empty.clone() };
|
||||
assert_eq!(serde_json::to_string(&stray).unwrap(), "{\"side\":4,\"data\":\"\"}");
|
||||
assert_eq!(serde_json::to_string(&stray).unwrap(), serde_json::to_string(&empty).unwrap());
|
||||
let with_data = SegMask { grid: Some(3), ..SegMask::from_logits(4, &[1.0; 16]) };
|
||||
assert!(!serde_json::to_string(&with_data).unwrap().contains("grid"), "no grid key outside the interner");
|
||||
}
|
||||
|
||||
/// Without the snapshot interner the JSON is exactly the derived form it always was; with
|
||||
/// it, a pooled grid serializes as an index and the data is left to the table (issue #2154).
|
||||
#[test]
|
||||
fn serialization_refs_only_under_the_interner() {
|
||||
let m = SegMask::from_logits(4, &[1.0; 16]);
|
||||
let plain = serde_json::to_string(&m).unwrap();
|
||||
assert_eq!(plain, format!("{{\"side\":4,\"data\":\"{}\"}}", m.data), "no interner: unchanged bytes");
|
||||
let with_rect = SegMask { rect: Some([0.0, 0.0, 0.5, 0.5]), ..m.clone() };
|
||||
assert_eq!(serde_json::to_string(&with_rect).unwrap(), format!("{{\"side\":4,\"data\":\"{}\",\"rect\":[0.0,0.0,0.5,0.5]}}", m.data));
|
||||
|
||||
let mut table = std::collections::HashMap::new();
|
||||
table.insert(m.data.clone(), 3u32);
|
||||
let referenced = with_grid_interner(table, || serde_json::to_string(&m).unwrap()).unwrap();
|
||||
assert_eq!(referenced, "{\"side\":4,\"grid\":3}", "pooled grid: an index, no data");
|
||||
// a grid the table doesn't hold, and an empty-data mask, stay inline
|
||||
let other = SegMask::from_logits(2, &[0.0; 4]);
|
||||
let mixed = with_grid_interner(std::collections::HashMap::new(), || serde_json::to_string(&other).unwrap()).unwrap();
|
||||
assert_eq!(mixed, format!("{{\"side\":2,\"data\":\"{}\"}}", other.data));
|
||||
// the interner is gone afterwards: serialization is inline again
|
||||
assert_eq!(serde_json::to_string(&m).unwrap(), plain);
|
||||
// nested calls are ignored: the outer writer keeps its table
|
||||
let outer_table = std::collections::HashMap::from([(m.data.clone(), 0u32)]);
|
||||
let nested = with_grid_interner(outer_table, || {
|
||||
let inner_table = std::collections::HashMap::from([(other.data.clone(), 1u32)]);
|
||||
(with_grid_interner(inner_table, || serde_json::to_string(&other).unwrap()), serde_json::to_string(&m).unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(nested.0, None, "the nested writer is refused");
|
||||
assert_eq!(nested.1, "{\"side\":4,\"grid\":0}");
|
||||
}
|
||||
}
|
||||
@@ -90,12 +90,15 @@ pub enum Process {
|
||||
/// camera curve keeps V2 Whites and fitted pointwise operators follow it
|
||||
/// (`lightcraft_pipeline::light_v3`, `docs/light-v3.md`).
|
||||
V4,
|
||||
/// V4, with a raw's tone curve rolling off into white in stops past its last fitted knot, so
|
||||
/// highlights the sensor recorded keep their detail when Exposure lifts them (issue #1632).
|
||||
V5,
|
||||
}
|
||||
|
||||
impl Process {
|
||||
/// Every process, oldest first.
|
||||
pub const ALL: [Process; 4] = [Process::V1, Process::V2, Process::V3, Process::V4];
|
||||
pub const LATEST: Process = Process::V4;
|
||||
pub const ALL: [Process; 5] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5];
|
||||
pub const LATEST: Process = Process::V5;
|
||||
|
||||
pub const fn version(self) -> ProcessVersion {
|
||||
match self {
|
||||
@@ -103,6 +106,7 @@ impl Process {
|
||||
Process::V2 => ProcessVersion(2),
|
||||
Process::V3 => ProcessVersion(3),
|
||||
Process::V4 => ProcessVersion(4),
|
||||
Process::V5 => ProcessVersion(5),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1123,6 +1127,72 @@ impl Default for Mask {
|
||||
}
|
||||
}
|
||||
|
||||
impl DevelopSettings {
|
||||
/// Calls `f` for every segmentation grid stored in these settings (the `seg` and `detail`
|
||||
/// of Object and Prompt mask shapes).
|
||||
pub fn visit_seg_masks(&self, f: &mut impl FnMut(&crate::SegMask)) {
|
||||
for mask in &self.masks {
|
||||
for component in &mask.components {
|
||||
visit_shape(&component.shape, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`DevelopSettings::visit_seg_masks`] with mutable access (resolving references into a
|
||||
/// snapshot's grid table).
|
||||
pub fn visit_seg_masks_mut(&mut self, f: &mut impl FnMut(&mut crate::SegMask)) {
|
||||
for mask in &mut self.masks {
|
||||
for component in &mut mask.components {
|
||||
visit_shape_mut(&mut component.shape, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_shape(shape: &MaskShape, f: &mut impl FnMut(&crate::SegMask)) {
|
||||
match shape {
|
||||
MaskShape::Object { seg, detail, .. } => {
|
||||
if let Some(seg) = seg {
|
||||
f(seg);
|
||||
}
|
||||
for d in detail {
|
||||
f(d);
|
||||
}
|
||||
}
|
||||
MaskShape::Prompt { seg, detail, .. } => {
|
||||
if let Some(seg) = seg {
|
||||
f(seg);
|
||||
}
|
||||
for d in detail {
|
||||
f(d);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_shape_mut(shape: &mut MaskShape, f: &mut impl FnMut(&mut crate::SegMask)) {
|
||||
match shape {
|
||||
MaskShape::Object { seg, detail, .. } => {
|
||||
if let Some(seg) = seg.as_mut() {
|
||||
f(seg);
|
||||
}
|
||||
for d in detail {
|
||||
f(d);
|
||||
}
|
||||
}
|
||||
MaskShape::Prompt { seg, detail, .. } => {
|
||||
if let Some(seg) = seg.as_mut() {
|
||||
f(seg);
|
||||
}
|
||||
for d in detail {
|
||||
f(d);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Heal / remove / red eye
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ mod tone;
|
||||
pub(crate) use colour::{PROFILE_PROXY, dng_colour, dng_tone_eligible};
|
||||
#[cfg(test)]
|
||||
use colour::{PROXY, starting_colour_with};
|
||||
pub(crate) use colour::{file_local_look, starting_colour, starting_colour_tags, with_starting_colour};
|
||||
pub(crate) use colour::{correspondence_correction, file_local_look, starting_colour, starting_colour_tags, with_starting_colour};
|
||||
pub(crate) use hue_sat::HueSat;
|
||||
#[cfg(test)]
|
||||
use hue_sat::{MIN_LUMINANCE_KEPT, NO_LUMINANCE_KEPT, fit_hue_sat, hue_saturation, restore_weight};
|
||||
|
||||
@@ -125,6 +125,14 @@ pub(super) fn starting_colour_with(
|
||||
(xy, t, look.or_else(|| dark(raw, &t)))
|
||||
}
|
||||
|
||||
/// Additional profile resolution for this proposal's pooled/DNG routes; CR3 keeps Main's route.
|
||||
pub(crate) fn correspondence_correction(raw: &RawImage, bytes: &[u8]) -> Option<lightcraft_develop::EmbeddedLens> {
|
||||
if raw.format == RawFormat::Cr3 {
|
||||
return None;
|
||||
}
|
||||
crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(bytes))
|
||||
}
|
||||
|
||||
/// The colour a raw starts from ([`starting_colour`]) as DNG colour tags, for a DNG of the raw's camera RGB (Photo
|
||||
/// Merge, issue #965): without them a merge of CR2s, whose colour comes from a look fitted to their JPEG, rendered
|
||||
/// green and dark. `None` when the file has colour matrices of its own (a DNG keeps them).
|
||||
@@ -132,7 +140,7 @@ pub(crate) fn starting_colour_tags(raw: &mut RawImage, bytes: &[u8]) -> Option<C
|
||||
if lightcraft_raw::color::has_matrix(&raw.color) {
|
||||
return None;
|
||||
}
|
||||
let correction = crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(bytes));
|
||||
let correction = correspondence_correction(raw, bytes);
|
||||
starting_colour_tags_with_correction(raw, bytes, correction.as_ref())
|
||||
}
|
||||
|
||||
@@ -141,6 +149,7 @@ pub(super) fn starting_colour_tags_with_correction(
|
||||
bytes: &[u8],
|
||||
correction: Option<&lightcraft_develop::EmbeddedLens>,
|
||||
) -> Option<ColorData> {
|
||||
let correction = correction.filter(|_| raw.format != RawFormat::Cr3);
|
||||
// the white the source shows, decided before `starting_colour` may fill in measured matrices
|
||||
let scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata);
|
||||
let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(raw));
|
||||
|
||||
@@ -169,7 +169,12 @@ pub(super) fn dro_off(own_tone: &CameraTone) -> CameraTone {
|
||||
// Past its last knot a curve goes on as a shoulder whose rate comes from its last two knots
|
||||
// (`CameraTone::apply`): lowering the second-last knot more than the last steepens it, and the
|
||||
// extended highlights would end up above the fitted curve. Raise the second-last knot (never
|
||||
// above the fitted curve) until the rate is at most the fitted curve's.
|
||||
// above the fitted curve) until the rate is at most the fitted curve's. Process V5's shoulder
|
||||
// (`CameraTone::apply_rolloff`) is not part of this bound or of `at_most`: V1 to V4 read the
|
||||
// same curve, and a V5 bound here would change their renders. It stays below the fitted
|
||||
// curve's too when the last segment's slope over the squared gap to white is at most the fitted
|
||||
// curve's; a lowered curve with a nearly flat last segment can end up above it far past the last
|
||||
// knot under V5 (issue #1632).
|
||||
let ([a, b], last) = ([own[30], own[31]], knots[31]);
|
||||
let rate = ((b[1] - a[1]) / (b[0] - a[0])).clamp(0.1, 16.0) / (1.0 - b[1]).max(0.01);
|
||||
let floor = last[1] - rate * (1.0 - last[1]).max(0.01) * (b[0] - a[0]);
|
||||
|
||||
@@ -1290,6 +1290,16 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop()
|
||||
let mut file = TiffWriter::default().write(&[ifd]).unwrap();
|
||||
assert_eq!(file.len(), offset);
|
||||
file.extend(jpeg);
|
||||
// Standalone non-CR3 scope: a coherent profile must not alter Main's CR3 framing route.
|
||||
let mut cr3 = raw.clone();
|
||||
cr3.format = RawFormat::Cr3;
|
||||
let baseline = proxies(&cr3, &file, &transform, PROXY, 0.0, None, None).unwrap();
|
||||
let proposed = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap();
|
||||
let bits = |image: &Rgb32f| image.data.iter().flatten().map(|v| v.to_bits()).collect::<Vec<_>>();
|
||||
assert_eq!(bits(&baseline.0), bits(&proposed.0), "CR3 sensor keeps Main framing");
|
||||
assert_eq!(bits(&baseline.1), bits(&proposed.1), "CR3 reference is unchanged");
|
||||
assert_eq!(baseline.2, proposed.2, "CR3 clipping is unchanged");
|
||||
assert_eq!(profile_pairs(&cr3, &file, None, None), profile_pairs(&cr3, &file, None, Some(&lens)), "CR3 pooled pairs keep Main");
|
||||
let (plain, reference, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, None).unwrap();
|
||||
let (mut aligned, _, _) = proxies(&raw, &file, &transform, PROXY, 0.0, None, Some(&lens)).unwrap();
|
||||
let mut plain_render = plain;
|
||||
@@ -1337,6 +1347,32 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop()
|
||||
with_starting_colour(&mut raw, &file);
|
||||
assert_eq!(raw.color, expected, "standalone DNG colour agrees with opening the RAW");
|
||||
assert_eq!(raw.opcodes.list3, ops, "DNG retains its file corrections");
|
||||
|
||||
// A real configured profile with nonzero vignetting must still be available to Main's
|
||||
// per-file CR3 path, while this proposal's new Pool/DNG lookup stays excluded.
|
||||
let vignetted_db =
|
||||
DB.replace("</calibration>", r#"<vignetting model="pa" focal="18" aperture="3.5" distance="1000" k1="-0.4" k2="0" k3="0" /></calibration>"#);
|
||||
let path = std::path::PathBuf::from(std::env::var_os(crate::lens_profiles::ENV).unwrap()).join("synthetic.xml");
|
||||
std::fs::write(path, vignetted_db).unwrap();
|
||||
crate::lens_profiles::reload();
|
||||
let resolved = crate::lens_profiles::for_raw(&cr3.info(), || lightcraft_meta::extract(&file)).unwrap();
|
||||
assert!(resolved.warp.is_some() && resolved.vignette.is_some(), "fixture resolves both corrections");
|
||||
let mut main_lens = resolved;
|
||||
main_lens.warp = None;
|
||||
let main_proxy = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&main_lens)).unwrap();
|
||||
let actual_proxy = proxies(&cr3, &file, &transform, PROXY, 0.0, None, Some(&resolved)).unwrap();
|
||||
assert_eq!(bits(&main_proxy.0), bits(&actual_proxy.0), "CR3 keeps Main's vignetting and framing, ignoring the new radial proposal");
|
||||
assert_ne!(bits(&baseline.0), bits(&actual_proxy.0), "nonzero vignetting remains active for CR3");
|
||||
assert_eq!(main_proxy.2, actual_proxy.2, "CR3 masks keep Main semantics");
|
||||
assert_eq!(profile_pairs(&cr3, &file, None, Some(&main_lens)), profile_pairs(&cr3, &file, None, Some(&resolved)));
|
||||
assert!(correspondence_correction(&cr3, &file).is_none(), "the actual shared Pool/DNG lookup excludes CR3");
|
||||
let expected = super::colour::starting_colour_tags_with_correction(&mut cr3.clone(), &file, None);
|
||||
assert_eq!(starting_colour_tags(&mut cr3.clone(), &file), expected, "public DNG lookup keeps Main's CR3 route");
|
||||
assert_eq!(
|
||||
super::colour::starting_colour_tags_with_correction(&mut cr3, &file, Some(&resolved)),
|
||||
expected,
|
||||
"injected CR3 correction cannot bypass DNG scope"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1664,6 +1700,30 @@ fn assert_lowered(fitted: &CameraLook, fixed: &CameraLook, what: &str) {
|
||||
let x = 0.001 * 1.005f32.powi(i);
|
||||
assert!(fixed.tone.apply(x) <= fitted.tone.apply(x) + 1e-5, "{what} at {x}: {} > {}", fixed.tone.apply(x), fitted.tone.apply(x));
|
||||
}
|
||||
// V5's shoulder stays below too whenever the lowered last segment's slope over its squared gap to
|
||||
// white is at most the fitted one's (`dro_off` doesn't enforce it, so V1 to V4 keep their curve;
|
||||
// issue #1632)
|
||||
if v5_bounded(&fixed.tone, &fitted.tone) {
|
||||
assert!(v5_below(&fixed.tone, &fitted.tone), "{what}: brighter than the fitted curve under V5");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the last segment of `a`, over its squared gap to white, is at most `b`'s: then `a`'s V5
|
||||
/// shoulder ([`CameraTone::apply_rolloff`]) is nowhere above `b`'s (issue #1632).
|
||||
fn v5_bounded(a: &CameraTone, b: &CameraTone) -> bool {
|
||||
let rate = |t: &CameraTone| {
|
||||
let k = t.knots();
|
||||
((k[31][1] - k[30][1]) / (k[31][0] - k[30][0])).max(0.0) / (1.0 - k[31][1]).powi(2)
|
||||
};
|
||||
rate(a) <= rate(b)
|
||||
}
|
||||
|
||||
/// Whether `a`'s V5 curve is nowhere brighter than `b`'s, from deep shadows to far past the last knot.
|
||||
fn v5_below(a: &CameraTone, b: &CameraTone) -> bool {
|
||||
(0..=2400).all(|i| {
|
||||
let x = 0.001 * 1.005f32.powi(i);
|
||||
a.apply_rolloff(x) <= b.apply_rolloff(x) + 1e-5
|
||||
})
|
||||
}
|
||||
|
||||
/// Issue #244: Sony's Dynamic Range Optimizer lifts the camera JPEG's shadows, not the raw's. A
|
||||
@@ -1802,6 +1862,8 @@ fn corpus_arw_with_dro_is_lowered_to_the_dro_off_tone() {
|
||||
let fitted = fit_look(&sensor, &reference, &clipped, colour).unwrap();
|
||||
if dro {
|
||||
assert_lowered(&fitted, &look, name);
|
||||
// the Sony DRO samples' lowered curves stay below their fitted ones under V5 as well
|
||||
assert!(v5_below(&look.tone, &fitted.tone), "{name}: brighter than the fitted curve under V5");
|
||||
for x in lowered {
|
||||
assert!(look.tone.apply(x) < 0.95 * fitted.tone.apply(x), "{name} at {x}: {} vs {}", look.tone.apply(x), fitted.tone.apply(x));
|
||||
}
|
||||
|
||||
@@ -220,7 +220,7 @@ impl Pool {
|
||||
let mut raw = lightcraft_raw::decode(bytes).map_err(|e| e.to_string())?;
|
||||
// colour only: geometric lens corrections would stop the sensor proxy from binning (the pairs still follow
|
||||
// the warp the camera applied to its JPEG)
|
||||
let correction = crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(bytes));
|
||||
let correction = crate::camera_preview::correspondence_correction(&raw, bytes);
|
||||
let lens = crate::camera_preview::lens_geometry(&raw.opcodes.list3);
|
||||
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
|
||||
let Some(model) = raw.metadata.model.as_deref().map(str::trim).filter(|m| !m.is_empty()) else { return Ok(None) };
|
||||
|
||||
@@ -271,6 +271,66 @@ pub(crate) fn bool_or(p: &Value, key: &str, d: bool) -> bool {
|
||||
pub(crate) fn ok() -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// A batch-edit recipe from a command's params: `[{id, value}, …]`, each `id` a develop control a
|
||||
/// recipe may name ([`check_recipe`]). Empty when absent or null. A malformed item, a control a
|
||||
/// recipe may not name, or more entries than there are controls is an error, so a typo is refused
|
||||
/// rather than silently ignored. An id named twice counts once, the last value winning; the list
|
||||
/// comes back in id order.
|
||||
pub(crate) fn recipe_param(p: &Value, cmd: &str) -> Result<Vec<(String, f64)>> {
|
||||
let Some(v) = p.get("recipe").filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
|
||||
let Some(items) = v.as_array() else {
|
||||
return Err(bad(cmd, "`recipe` must be a list of {id, value}"));
|
||||
};
|
||||
let most = lightcraft_develop::controls::CONTROLS.len();
|
||||
if items.len() > most {
|
||||
return Err(bad(cmd, format!("a recipe has one entry per control, at most {most} (it has {})", items.len())));
|
||||
}
|
||||
let mut by_id = std::collections::BTreeMap::new();
|
||||
for it in items {
|
||||
let id = it.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad(cmd, "each recipe item needs an `id`"))?;
|
||||
let value = it.get("value").and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("recipe `{id}` needs a numeric `value`")))?;
|
||||
by_id.insert(id.to_string(), value);
|
||||
}
|
||||
let recipe: Vec<(String, f64)> = by_id.into_iter().collect();
|
||||
check_recipe(&recipe).map_err(|e| bad(cmd, e))?;
|
||||
Ok(recipe)
|
||||
}
|
||||
|
||||
/// Whether every control of `recipe` is one a batch-edit recipe may name, else why not. The rule is
|
||||
/// on the control's spec: a plain control of the shared list, writable on any photo's settings
|
||||
/// (`set` takes it), outside the Geometry section and not white balance.
|
||||
///
|
||||
/// - Per-photo instances (`pointColor.0.hueShift`, `redEye.0.pupilSize`) are not in the list; on a
|
||||
/// photo without that instance a write is dropped.
|
||||
/// - Geometry controls (`crop.angle`, `geometry.*`) need the photo's own size: the slider refits the
|
||||
/// crop around a new angle, which a batch write cannot do.
|
||||
/// - White balance means something else on each kind of file (Kelvin on a raw with matrices,
|
||||
/// relative to the as-shot white on a rendered photo or a raw without them), so one temperature
|
||||
/// cannot name the same look for every photo of a batch.
|
||||
pub(crate) fn check_recipe(recipe: &[(String, f64)]) -> std::result::Result<(), String> {
|
||||
use lightcraft_develop::{Section, controls};
|
||||
let mut scratch = lightcraft_develop::DevelopSettings::default();
|
||||
for (id, value) in recipe {
|
||||
let Some(spec) = controls::CONTROLS.iter().find(|c| c.id == id.as_str()) else {
|
||||
return Err(format!(
|
||||
"unknown recipe control `{id}` (see develop.controls; a control that belongs to one photo, such as pointColor.0.hueShift, is not one)"
|
||||
));
|
||||
};
|
||||
if spec.section == Section::Geometry {
|
||||
return Err(format!("`{id}` is a geometry control: a recipe does not crop, straighten or transform photos"));
|
||||
}
|
||||
if id.starts_with("wb.") {
|
||||
return Err(format!(
|
||||
"`{id}` is white balance: a recipe does not set it, because a temperature means something else on a raw than on a rendered photo"
|
||||
));
|
||||
}
|
||||
if !controls::set(&mut scratch, id, *value) {
|
||||
return Err(format!("recipe control `{id}` cannot be set"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn point(p: &Value, key: &str) -> Option<lightcraft_geom::Point> {
|
||||
let a = p.get(key)?.as_array()?;
|
||||
Some(lightcraft_geom::Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?))
|
||||
|
||||
@@ -33,6 +33,58 @@ fn groups_param(p: &Value, c: &str) -> Result<Option<Vec<SettingsGroup>>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The leaves of `a` that differ from `b` (same shape), as a partial JSON object: `None` when they
|
||||
/// are equal. Used to store only what a batch-edit recipe names, so applying the saved preset
|
||||
/// later never overrides the settings the recipe doesn't name.
|
||||
fn partial_diff(a: &Value, b: &Value) -> Option<Value> {
|
||||
match (a, b) {
|
||||
(Value::Object(x), Value::Object(y)) => {
|
||||
let mut out = serde_json::Map::new();
|
||||
for (k, v) in x {
|
||||
if let Some(d) = partial_diff(v, y.get(k).unwrap_or(&Value::Null)) {
|
||||
out.insert(k.clone(), d);
|
||||
}
|
||||
}
|
||||
(!out.is_empty()).then_some(Value::Object(out))
|
||||
}
|
||||
(x, y) => (x != y).then(|| x.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings as JSON with the HDR subtree always present: [`Hdr`] is left out while it is the default
|
||||
/// (its JSON stays as it was), so a reset to a default HDR value would have nothing to compare with and
|
||||
/// would be dropped from a saved preset.
|
||||
fn full_json(s: &DevelopSettings) -> Value {
|
||||
let mut v = s.to_json();
|
||||
if let Some(obj) = v.as_object_mut() {
|
||||
obj.entry("hdr").or_insert_with(|| serde_json::to_value(s.hdr).unwrap_or(Value::Null));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The partial settings a batch-edit recipe names, with the values the import would give (clamped
|
||||
/// by the control specs). Each named control is compared with the same control at a value it is not
|
||||
/// set to, so a control the recipe sets to its default (a reset) is stored too, and nothing else is.
|
||||
/// `None` when the recipe names nothing that is stored, or a control that cannot be written.
|
||||
fn recipe_partial(recipe: &[(String, f64)]) -> Option<Value> {
|
||||
let (mut named, mut other) = (DevelopSettings::default(), DevelopSettings::default());
|
||||
for (id, v) in recipe {
|
||||
if !controls::set(&mut named, id, *v) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
for (id, _) in recipe {
|
||||
let (spec, now) = (controls::find(id)?, controls::get(&named, id)?);
|
||||
if !controls::set(&mut other, id, if now > spec.min { spec.min } else { spec.max }) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
partial_diff(&full_json(&named), &full_json(&other))
|
||||
}
|
||||
|
||||
/// The longest name or group a saved recipe preset may have (characters).
|
||||
const MAX_PRESET_TEXT: usize = 100;
|
||||
|
||||
fn crop_dims(s: &Session, id: PhotoId) -> (f64, f64) {
|
||||
let p = s.catalog.photo(id);
|
||||
let (w, h) = p.map(|p| (p.width.max(1) as f64, p.height.max(1) as f64)).unwrap_or((3.0, 2.0));
|
||||
@@ -460,24 +512,51 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Ok(json!({"mix": m}))
|
||||
}
|
||||
),
|
||||
cmd!("develop.auto", "Auto Settings", ["Photo"], Some("Shift+A"), "{}", has_active, |s, _| {
|
||||
let id = active(s, "develop.auto")?;
|
||||
let src = s.source_now(id, SourceLevel::Thumb).map_err(|e| bad("develop.auto", e))?;
|
||||
let info = s.source_info(id);
|
||||
let d = s.develop_of(id).unwrap_or_default();
|
||||
let a = lightcraft_pipeline::auto::auto_tone(&src, &info, &d);
|
||||
edit(s, "develop.auto", "Auto", |d| {
|
||||
d.light.exposure = a.exposure;
|
||||
d.light.contrast = a.contrast;
|
||||
d.light.highlights = a.highlights;
|
||||
d.light.shadows = a.shadows;
|
||||
d.light.whites = a.whites;
|
||||
d.light.blacks = a.blacks;
|
||||
d.color.vibrance = a.vibrance;
|
||||
d.color.saturation = a.saturation;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(serde_json::to_value(a).unwrap_or_default())
|
||||
cmd!("develop.auto", "Auto Settings", ["Photo"], Some("Shift+A"), "{}", has_selection, |s, p| {
|
||||
const C: &str = "develop.auto";
|
||||
let ids = s.targets(p)?;
|
||||
// a wrong id is a bad request, unlike a photo that can't be read just now
|
||||
if let Some(id) = ids.iter().find(|id| s.catalog.photo(**id).is_none()) {
|
||||
return Err(bad(C, format!("no such photo: {}", id.0)));
|
||||
}
|
||||
let mut first: Option<Value> = None;
|
||||
let mut ops: Vec<Op> = Vec::new();
|
||||
let mut failed = None;
|
||||
for id in ids {
|
||||
// a photo that can't be read (offline, no decoder) is left out, not the whole selection
|
||||
let src = match s.source_now(id, SourceLevel::Thumb) {
|
||||
Ok(src) => src,
|
||||
Err(e) => {
|
||||
failed.get_or_insert(e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let info = s.source_info(id);
|
||||
let d = s.develop_of(id).unwrap_or_default();
|
||||
let a = lightcraft_pipeline::auto::auto_tone(&src, &info, &d);
|
||||
if first.is_none() {
|
||||
first = Some(serde_json::to_value(a).unwrap_or_default());
|
||||
}
|
||||
let mut nd = (*d).clone();
|
||||
nd.light.exposure = a.exposure;
|
||||
nd.light.contrast = a.contrast;
|
||||
nd.light.highlights = a.highlights;
|
||||
nd.light.shadows = a.shadows;
|
||||
nd.light.whites = a.whites;
|
||||
nd.light.blacks = a.blacks;
|
||||
nd.color.vibrance = a.vibrance;
|
||||
nd.color.saturation = a.saturation;
|
||||
if let Some(op) = s.develop_op(id, nd, "Auto") {
|
||||
ops.push(op);
|
||||
}
|
||||
}
|
||||
if let (None, Some(e)) = (&first, failed) {
|
||||
return Err(bad(C, e));
|
||||
}
|
||||
if !ops.is_empty() {
|
||||
s.commit("Auto", Op::Batch { ops })?;
|
||||
}
|
||||
Ok(first.unwrap_or_default())
|
||||
}),
|
||||
cmd!(
|
||||
"develop.wb",
|
||||
@@ -1108,7 +1187,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let prepared = prepare_photo_for_wb_partial(&d, &preset.settings, &info);
|
||||
let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb;
|
||||
let base: &DevelopSettings = prepared.as_ref().unwrap_or(&d);
|
||||
let mut next = preset.apply(base, amount);
|
||||
// Amount is measured from the import look only when the photo has one.
|
||||
// Otherwise the current settings (on the partial's WB scale) are its baseline.
|
||||
let imported = s.catalog.photo(id).filter(|p| p.import_look.is_some() && amount != 1.0).map(|p| p.import_defaults());
|
||||
let prepared_import =
|
||||
imported.as_ref().map(|d| prepare_photo_for_wb_partial(d, &preset.settings, &info).unwrap_or_else(|| d.clone()));
|
||||
let original = prepared_import.as_ref().unwrap_or(base);
|
||||
let mut next = preset.apply_on(base, original, amount);
|
||||
if on_kelvin_scale {
|
||||
lightcraft_pipeline::local::normalize_wb(&mut next, &info);
|
||||
}
|
||||
@@ -1129,6 +1214,41 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
s.presets.push(Preset::from_settings(&pid, name, group, &d, &groups));
|
||||
Ok(json!({"id": pid}))
|
||||
}),
|
||||
cmd!(
|
||||
"preset.saveRecipe",
|
||||
"Save Import Recipe as Preset",
|
||||
[],
|
||||
None,
|
||||
"{name (up to 100 characters), group?: default Import Recipes, recipe: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}]} → {id, name} — save a batch-edit recipe (as library.import takes it) as a user preset, so it can be reused from the Preset list; only the settings the recipe names are stored, so applying it later never overrides the rest. The preset gets an id no other preset has; saving the same recipe under the same name and group again returns the preset that already is",
|
||||
always,
|
||||
|s, p| {
|
||||
const C: &str = "preset.saveRecipe";
|
||||
let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(C, "missing name"))?.to_string();
|
||||
let group = str_param(p, "group").map(str::trim).filter(|g| !g.is_empty()).unwrap_or("Import Recipes").to_string();
|
||||
if name.chars().count() > MAX_PRESET_TEXT || group.chars().count() > MAX_PRESET_TEXT {
|
||||
return Err(bad(C, format!("a name or group is at most {MAX_PRESET_TEXT} characters")));
|
||||
}
|
||||
let recipe = super::recipe_param(p, C)?;
|
||||
if recipe.is_empty() {
|
||||
return Err(bad(C, "the recipe is empty"));
|
||||
}
|
||||
let settings = recipe_partial(&recipe).ok_or_else(|| bad(C, "the recipe sets nothing a preset can store"))?;
|
||||
// presets get their ids as imported ones do (`user.<group>-<name>`, then -2, -3…): an id from the list's
|
||||
// length repeats once a preset is deleted, and the first preset with an id is the one that gets applied
|
||||
let preset = Preset { id: String::new(), name, group, settings, favorite: false, builtin: false };
|
||||
let id = match s.add_presets(vec![preset.clone()]).into_iter().next() {
|
||||
Some(id) => id,
|
||||
// the same recipe under the same name and group is already a preset
|
||||
None => s
|
||||
.presets
|
||||
.iter()
|
||||
.find(|q| !q.builtin && q.name == preset.name && q.group == preset.group && q.settings == preset.settings)
|
||||
.map(|q| q.id.clone())
|
||||
.ok_or_else(|| bad(C, "the preset could not be saved"))?,
|
||||
};
|
||||
Ok(json!({"id": id, "name": preset.name}))
|
||||
}
|
||||
),
|
||||
cmd!("preset.delete", "Delete Preset", [], None, "{id}", always, |s, p| {
|
||||
let pid = str_param(p, "id").ok_or_else(|| bad("preset.delete", "missing id"))?;
|
||||
let i = s.presets.iter().position(|x| x.id == pid).ok_or_else(|| bad("preset.delete", "unknown preset"))?;
|
||||
@@ -1303,3 +1423,46 @@ fn has_history_after(s: &Session) -> std::result::Result<(), String> {
|
||||
Err("at the latest History step".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod recipe_tests {
|
||||
use super::*;
|
||||
|
||||
/// Equal settings differ nowhere, so there is nothing to store; a difference comes back with
|
||||
/// its path only.
|
||||
#[test]
|
||||
fn partial_diff_is_the_changed_leaves_only() {
|
||||
let a = json!({"light": {"exposure": 1.0, "contrast": 0.0}, "color": {"vibrance": 5.0}});
|
||||
assert_eq!(partial_diff(&a, &a), None);
|
||||
let b = json!({"light": {"exposure": 0.0, "contrast": 0.0}, "color": {"vibrance": 5.0}});
|
||||
assert_eq!(partial_diff(&a, &b), Some(json!({"light": {"exposure": 1.0}})));
|
||||
assert_eq!(partial_diff(&a, &json!({})), Some(a.clone()), "a leaf the other side lacks is a difference");
|
||||
}
|
||||
|
||||
fn recipe(items: &[(&str, f64)]) -> Vec<(String, f64)> {
|
||||
items.iter().map(|(id, v)| (id.to_string(), *v)).collect()
|
||||
}
|
||||
|
||||
/// A recipe that names nothing, or a control `set` would drop (a per-photo instance on fresh
|
||||
/// settings), stores nothing: the command answers with an error, not an empty preset.
|
||||
#[test]
|
||||
fn a_recipe_that_stores_nothing_is_none() {
|
||||
assert_eq!(recipe_partial(&[]), None);
|
||||
assert_eq!(recipe_partial(&recipe(&[("pointColor.0.hueShift", 5.0)])), None, "set returns false for it");
|
||||
assert_eq!(recipe_partial(&recipe(&[("nope.nope", 5.0)])), None);
|
||||
assert_eq!(recipe_partial(&recipe(&[("light.exposure", 0.5)])), Some(json!({"light": {"exposure": 0.5}})));
|
||||
// a reset to the control's default is stored
|
||||
assert_eq!(recipe_partial(&recipe(&[("light.exposure", 0.0)])), Some(json!({"light": {"exposure": 0.0}})));
|
||||
}
|
||||
|
||||
/// The HDR subtree is left out of the JSON while it is the default, so a reset of a headroom to its
|
||||
/// default is stored in the preset by itself and next to another adjustment.
|
||||
#[test]
|
||||
fn an_hdr_reset_is_stored_alone_and_next_to_another_adjustment() {
|
||||
let reset = recipe_partial(&recipe(&[("hdr.maxEv", 3.0)])).expect("a reset is stored");
|
||||
assert_eq!(reset.pointer("/hdr/max_ev"), Some(&json!(3.0)), "{reset}");
|
||||
let both = recipe_partial(&recipe(&[("hdr.maxEv", 3.0), ("light.exposure", 0.5)])).expect("both are stored");
|
||||
assert_eq!(both.pointer("/hdr/max_ev"), Some(&json!(3.0)), "{both}");
|
||||
assert_eq!(both.pointer("/light/exposure"), Some(&json!(0.5)), "{both}");
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,31 @@ impl Session {
|
||||
builtin_presets().into_iter().map(|p| (p, true)).chain(self.export_presets.iter().cloned().map(|p| (p, false))).collect()
|
||||
}
|
||||
|
||||
/// The user's export presets, renamed where they shadow a built-in: the built-ins are looked up
|
||||
/// first, so a preset whose name matches one of them (in any case) could never be selected or
|
||||
/// exported, and the save path refuses a built-in's name. Such a preset gets a free name of its
|
||||
/// own (`<name> (mine)`, then a number when that is taken too), keeping its settings.
|
||||
pub(crate) fn rename_shadowing_export_presets(&mut self) {
|
||||
let builtins: Vec<String> = builtin_presets().into_iter().map(|p| p.name).collect();
|
||||
// the names that may not be taken: the built-ins', and every user preset's own
|
||||
let mut taken: Vec<String> = builtins.clone();
|
||||
taken.extend(self.export_presets.iter().map(|p| p.name.clone()));
|
||||
for preset in self.export_presets.iter_mut() {
|
||||
if !builtins.iter().any(|b| b.eq_ignore_ascii_case(&preset.name)) {
|
||||
continue;
|
||||
}
|
||||
let base = format!("{} (mine)", preset.name);
|
||||
let mut name = base.clone();
|
||||
let mut n = 2;
|
||||
while taken.iter().any(|t| t.eq_ignore_ascii_case(&name)) {
|
||||
name = format!("{base} {n}");
|
||||
n += 1;
|
||||
}
|
||||
taken.push(name.clone());
|
||||
preset.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
/// `app.export` params with a named `preset` expanded: the preset's params, overridden by the
|
||||
/// call's own (`preset` itself removed). Unknown preset names are an error.
|
||||
pub fn export_params(&self, p: &Value) -> std::result::Result<Value, String> {
|
||||
|
||||
@@ -82,6 +82,7 @@ pub fn import_params(s: &Session, p: &Value) -> Result<ImportRequest> {
|
||||
metadata_preset,
|
||||
convert_dng: bool_or(p, "dng", false),
|
||||
local: bool_or(p, "local", false),
|
||||
recipe: crate::cmd::recipe_param(p, "library.import")?,
|
||||
};
|
||||
let album_name = str_param(p, "albumName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
|
||||
Ok(ImportRequest { paths, opts, album, album_name })
|
||||
|
||||
@@ -1325,16 +1325,22 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Review Import",
|
||||
[],
|
||||
None,
|
||||
"{paths: [file or folder (recursive)]} → {candidates: [{path, name, format, kind, width, height, fileSize, captured, duplicate?: path|content, existing?, error?, previewOnly?: why a raw can only be shown from its embedded preview}], duplicates, scanned} — nothing is added",
|
||||
"{paths: [file or folder (recursive)]} → {candidates: [{path, name, format, kind, width, height, fileSize, captured, duplicate?: path|content, existing?, error?, previewOnly?: why a raw can only be shown from its embedded preview}], duplicates, scanned, scanLimited: bool (the folder walk stopped at its scan limit: there may be more photos), skipped: {unreadable (folders that could not be listed), unsupported (files in the folders that are not a supported photo type, XMP sidecars not counted; a file named in paths is always tried)}} — nothing is added",
|
||||
always,
|
||||
|s, p| {
|
||||
let paths = strs(p, "paths");
|
||||
if paths.is_empty() {
|
||||
return Err(bad("library.importPreview", "no paths"));
|
||||
}
|
||||
let c = crate::import::scan(s, &paths);
|
||||
let dups = c.iter().filter(|c| c.duplicate.is_some()).count();
|
||||
Ok(json!({"scanned": c.len(), "duplicates": dups, "candidates": c}))
|
||||
let out = crate::import::scan_report(s, &paths);
|
||||
let dups = out.candidates.iter().filter(|c| c.duplicate.is_some()).count();
|
||||
Ok(json!({
|
||||
"scanned": out.candidates.len(),
|
||||
"duplicates": dups,
|
||||
"candidates": out.candidates,
|
||||
"scanLimited": out.truncated,
|
||||
"skipped": {"unreadable": out.unreadable, "unsupported": out.unsupported},
|
||||
}))
|
||||
}
|
||||
),
|
||||
cmd!(
|
||||
@@ -1342,7 +1348,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import Photos",
|
||||
["File"],
|
||||
Some("Cmd+Shift+I"),
|
||||
"{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}",
|
||||
"{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, recipe?: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}] (a batch-edit recipe: each control is set to its value, clamped to the control's range, on every photo this import adds, after its sidecar, camera default and preset, as one extra History step named Import adjustments; a photo the library already has — a duplicate, one restored from Recently Deleted, one joined from a browsed folder — is not changed; a control a recipe may not name is refused before anything is imported; preset.saveRecipe keeps a recipe for reuse), keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), album?}",
|
||||
always,
|
||||
|s, p| {
|
||||
let req = import_params(s, p)?;
|
||||
|
||||
@@ -1095,16 +1095,16 @@ mod smart_provenance_tests {
|
||||
use lightcraft_catalog::{MediaKind, Photo, PhotoId, Source};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn temp(tag: &str) -> std::path::PathBuf {
|
||||
fn temp(tag: &str) -> std::io::Result<std::path::PathBuf> {
|
||||
let dir = std::env::temp_dir().join(format!("lc-smart-provenance-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_shard_never_relabels_cached_legacy_fallback_and_repairs_from_online_original() {
|
||||
let dir = temp("legacy-fallback");
|
||||
let dir = temp("legacy-fallback").unwrap();
|
||||
let mut photo = Photo::new(
|
||||
PhotoId(1),
|
||||
Source::File { path: dir.join("offline.arw").to_string_lossy().into_owned() },
|
||||
@@ -1160,7 +1160,7 @@ mod smart_provenance_tests {
|
||||
|
||||
#[test]
|
||||
fn missing_target_never_encodes_proxy_sources_but_keeps_valid_offline_proxies() {
|
||||
let dir = temp("missing-target");
|
||||
let dir = temp("missing-target").unwrap();
|
||||
let legacy = dir.join("legacy.lcsp");
|
||||
let image = lightcraft_raster::Rgb32f::new(48, 32);
|
||||
let bytes = crate::smart::encode(&image, Some(&Default::default())).unwrap();
|
||||
@@ -1190,7 +1190,7 @@ mod smart_provenance_tests {
|
||||
|
||||
#[test]
|
||||
fn smart_command_reads_original_instead_of_cached_pixels() {
|
||||
let dir = temp("fresh-original");
|
||||
let dir = temp("fresh-original").unwrap();
|
||||
let photo = Photo::new(
|
||||
PhotoId(1),
|
||||
Source::File { path: dir.join("original.arw").to_string_lossy().into_owned() },
|
||||
@@ -1233,7 +1233,7 @@ mod smart_provenance_tests {
|
||||
#[test]
|
||||
fn fresh_smart_build_and_refresh_keep_the_photos_hot_pixel_decode() {
|
||||
for outliers in [false, true] {
|
||||
let dir = temp(if outliers { "fresh-hot-on" } else { "fresh-hot-off" });
|
||||
let dir = temp(if outliers { "fresh-hot-on" } else { "fresh-hot-off" }).unwrap();
|
||||
let mut photo = Photo::new(
|
||||
PhotoId(1),
|
||||
Source::File { path: dir.join("original.arw").to_string_lossy().into_owned() },
|
||||
@@ -1311,7 +1311,7 @@ mod smart_provenance_tests {
|
||||
<cropfactor>1.5</cropfactor><calibration><distortion model="poly3" focal="18" k1="-0.03" />
|
||||
</calibration></lens></lensdatabase>"#;
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
let dir = temp("runtime-reload-child");
|
||||
let dir = temp("runtime-reload-child").unwrap();
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
|
||||
@@ -64,5 +64,8 @@ pub(crate) use settings::{Settings, forget_gpu_set_ups, installed_models, read_c
|
||||
pub(crate) use state::State;
|
||||
pub use state::{Pace, PhotoState};
|
||||
|
||||
#[cfg(all(test, feature = "denoise"))]
|
||||
// Two stacked cfgs (not `all(test, feature = …)`): clippy only recognises a plain `cfg(test)`
|
||||
// module as test code, so the `allow-*-in-tests` settings in clippy.toml apply to its helpers.
|
||||
#[cfg(test)]
|
||||
#[cfg(feature = "denoise")]
|
||||
mod gpu_tests;
|
||||
@@ -2,6 +2,7 @@ use super::*;
|
||||
use crate::denoise::forget_gpu_set_ups;
|
||||
|
||||
/// A folder of the test's own: the card's set-up leaves its marker in it.
|
||||
#[allow(clippy::unwrap_used)]
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("lc-engine-builtin-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
@@ -198,6 +198,11 @@ pub struct ExportPreset {
|
||||
}
|
||||
|
||||
/// The built-in export presets (File → Export with Preset).
|
||||
///
|
||||
/// A preset sets output options (format, quality, size, colour space, sharpening, metadata), never a
|
||||
/// crop. "Instagram Story / Reel" therefore applies no crop to 9:16: it sets a 1920 px long edge only, so
|
||||
/// a 3:2 photo exports at 1920 × 1280. The export options have no crop-to-aspect setting; a photo's own
|
||||
/// crop is the only way to change its shape before export.
|
||||
pub fn builtin_presets() -> Vec<ExportPreset> {
|
||||
let p = |name: &str, params: serde_json::Value| ExportPreset { name: name.into(), params };
|
||||
vec![
|
||||
@@ -205,6 +210,13 @@ pub fn builtin_presets() -> Vec<ExportPreset> {
|
||||
p("JPEG (Large)", serde_json::json!({"format": "jpeg", "quality": 92, "longEdge": 0, "colorSpace": "srgb"})),
|
||||
p("Original + Settings", serde_json::json!({"format": "original"})),
|
||||
p("DNG", serde_json::json!({"format": "dng"})),
|
||||
p("Instagram Feed", serde_json::json!({"format": "jpeg", "quality": 85, "longEdge": 1080, "colorSpace": "srgb", "sharpen": "screen"})),
|
||||
p(
|
||||
"Instagram Story / Reel",
|
||||
serde_json::json!({"format": "jpeg", "quality": 85, "longEdge": 1920, "colorSpace": "srgb", "sharpen": "screen"}),
|
||||
),
|
||||
p("Web / Portfolio", serde_json::json!({"format": "jpeg", "quality": 85, "longEdge": 2048, "colorSpace": "srgb", "metadata": "copyright"})),
|
||||
p("Full Resolution Master", serde_json::json!({"format": "jpeg", "quality": 95, "longEdge": 0, "colorSpace": "displayP3"})),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -123,12 +123,21 @@ fn prepare_guarded(
|
||||
let label = p.file_name.clone();
|
||||
let meta = export_metadata(p, &session.catalog, o);
|
||||
let gain_map = o.hdr_output() && o.format == ExportFormat::Jpeg;
|
||||
let job = session.export_job(id, w, h, o.effective_space(), o.effective_depth())?;
|
||||
let mut job = session.export_job(id, w, h, o.effective_space(), o.effective_depth())?;
|
||||
job.request.exact_size = true;
|
||||
job.key ^= 0x86e2_fadc_0917_b435;
|
||||
let weight = render_weight(full_px, long, job.level, w.saturating_mul(h));
|
||||
if let Some(why) = too_big_for_memory((w, h), native_px, weight, crate::memory::total_ram()) {
|
||||
return Err(format!("{label}: {why}"));
|
||||
}
|
||||
let hdr_job = if gain_map { Some(session.export_job(id, w, h, o.effective_space(), OutputDepth::F32Hdr)?) } else { None };
|
||||
let hdr_job = if gain_map {
|
||||
let mut hdr = session.export_job(id, w, h, o.effective_space(), OutputDepth::F32Hdr)?;
|
||||
hdr.request.exact_size = true;
|
||||
hdr.key ^= 0x86e2_fadc_0917_b435;
|
||||
Some(hdr)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(Work::Render(Box::new(RenderWork { job, hdr_job, meta, opts: o.clone() })), weight)
|
||||
} else {
|
||||
let lightcraft_catalog::Source::File { path } = &p.source else {
|
||||
|
||||
@@ -225,7 +225,7 @@ fn sharpened_pixels_are_pinned() {
|
||||
let samples = src.data.iter().flat_map(|p| [p[0], p[1], p[2]].map(|v| u16::from(v) * 257)).collect();
|
||||
let mut deep = DeepImage { width: src.width, height: src.height, samples: DeepSamples::U16(samples), space: OutputSpace::Srgb };
|
||||
output_sharpen_deep(&mut deep, target, SharpenAmount::Standard);
|
||||
let DeepSamples::U16(v) = &deep.samples else { unreachable!() };
|
||||
let DeepSamples::U16(v) = &deep.samples else { panic!("expected U16 samples") };
|
||||
got.push(fnv(&v.iter().flat_map(|s| s.to_le_bytes()).collect::<Vec<u8>>()));
|
||||
}
|
||||
assert_eq!(got, SHARPENED, "{got:#x?}");
|
||||
|
||||
@@ -246,7 +246,10 @@ fn run(spec: &Download, mirror: &str, staging: &Path, shared: &Shared) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
// Two stacked cfgs (not `all(test, …)`): clippy only recognises a plain `cfg(test)`
|
||||
// module as test code, so the `allow-*-in-tests` settings in clippy.toml apply to its helpers.
|
||||
#[cfg(test)]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_faces::hash::sha256_hex;
|
||||
|
||||
@@ -1844,3 +1844,35 @@ fn existing_photo_settings_are_not_rewritten() {
|
||||
drop(s);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Issue #1632: a DNG's `ProfileToneCurve` is the finish stage's camera curve, so process V5 extends
|
||||
/// it past its last point (the sensor's white, scene 1.0) with the stop roll-off as well. A curve
|
||||
/// that reaches white there renders as under V4 up to it and white past it; one that ends below
|
||||
/// white (here 0.9) keeps what Exposure lifts past the sensor's white apart instead of reaching
|
||||
/// 8-bit 255 within a stop.
|
||||
#[test]
|
||||
fn v5_extends_a_dng_tone_curve_past_white_in_stops() {
|
||||
use lightcraft_color::transfer::linear_to_srgb;
|
||||
use lightcraft_develop::{DevelopSettings, Process};
|
||||
use lightcraft_pipeline::SourceInfo;
|
||||
let code = |curve: &[f64], process: Process, y: f32| {
|
||||
let tone = lightcraft_raw::profile::ToneCurve::from_tag(curve).and_then(|c| super::dng_tone_curve(&c));
|
||||
let info = SourceInfo { raw: true, camera_tone: Some(tone.expect("a valid curve")), ..SourceInfo::default() };
|
||||
let s = DevelopSettings { process: process.version(), ..DevelopSettings::default() };
|
||||
let o = lightcraft_pipeline::finish::base_tone(&s, &info, 1.0).apply(y);
|
||||
(linear_to_srgb(o.clamp(0.0, 1.0)) * 255.0).round()
|
||||
};
|
||||
let to_white = [0.0, 0.0, 0.03, 0.09, 0.18, 0.4, 0.5, 0.78, 1.0, 1.0];
|
||||
for y in [0.01, 0.05, 0.18, 0.5, 0.9] {
|
||||
assert_eq!(code(&to_white, Process::V5, y), code(&to_white, Process::V4, y), "{y}");
|
||||
}
|
||||
for y in [1.0, 2.0, 4.0] {
|
||||
assert_eq!((code(&to_white, Process::V4, y), code(&to_white, Process::V5, y)), (255.0, 255.0), "{y}");
|
||||
}
|
||||
let below_white = [0.0, 0.0, 0.03, 0.09, 0.18, 0.4, 0.5, 0.72, 1.0, 0.9];
|
||||
let at = |process, ev: f32| code(&below_white, process, ev.exp2());
|
||||
assert_eq!(at(Process::V5, 0.0), at(Process::V4, 0.0));
|
||||
assert_eq!(at(Process::V4, 1.0), 255.0, "V4 is frozen");
|
||||
let (white, beyond) = (at(Process::V5, 0.0), at(Process::V5, 1.0));
|
||||
assert!(beyond < 254.0 && beyond - white >= 3.0, "{white} then {beyond} a stop past the sensor's white");
|
||||
}
|
||||
@@ -15,7 +15,8 @@
|
||||
//! 6. Apply each photo's XMP sidecar (or a raw/DNG file's embedded XMP): the sidecar wins for
|
||||
//! metadata and develop settings are restored (see [`crate::sidecar`]). Its capture time fills
|
||||
//! in when the file has none (read before step 5, so it also files and names the copy).
|
||||
//! 7. Optionally apply a preset and add keywords (the import dialog's options).
|
||||
//! 7. Optionally apply a preset, then a batch-edit recipe (one more History step), and add
|
||||
//! keywords (the import dialog's options).
|
||||
//! 8. Commit all new photos as one undoable op. (Undoing a move removes the catalog records;
|
||||
//! the files stay at the destination — undo never moves files back over a card.)
|
||||
//! 9. Copy and Move rename sequences use checked platform-sized numbers: the last number is usable once, and any
|
||||
@@ -46,7 +47,8 @@ pub(crate) use commit::workers;
|
||||
pub use commit::{batch_size, civil, commit_prepared, system_clock};
|
||||
pub use defaults::{CameraDefault, ImportDefaults, apply_import_defaults, has_import_look, import_defaults};
|
||||
pub use files::{
|
||||
EXTENSIONS, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_within, is_supported, launch_deadline, launch_path, launch_path_until,
|
||||
EXTENSIONS, Expansion, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_report, expand_within, is_supported, launch_deadline,
|
||||
launch_path, launch_path_until,
|
||||
};
|
||||
pub(crate) use files::{expand_noting, probe_all, probe_paths, probe_with};
|
||||
#[cfg(test)]
|
||||
@@ -54,7 +56,8 @@ use job::PreparedItem;
|
||||
pub use job::{ImportJob, Prepared, candidate_thumb_key, import, import_with};
|
||||
pub(crate) use scan::scan_files;
|
||||
pub use scan::{
|
||||
ScanInput, ScanOutput, ScanProgress, browse_files, browse_order, browse_path, browse_queue, browse_queue_until, browse_spelling, scan, scan_with,
|
||||
ScanInput, ScanOutput, ScanProgress, browse_files, browse_order, browse_path, browse_queue, browse_queue_until, browse_spelling, scan,
|
||||
scan_report, scan_with,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use scan::{library_files, library_hashes};
|
||||
|
||||
@@ -291,6 +291,19 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
|
||||
p.edited = Some(now.clone());
|
||||
p.history.push(lightcraft_catalog::HistoryStep { label, settings: d });
|
||||
}
|
||||
// the batch-edit recipe goes on top of everything above (sidecar, camera default,
|
||||
// preset): only the controls it names change, through the same specs the sliders use
|
||||
if !opts.recipe.is_empty() {
|
||||
let mut d = (*p.develop).clone();
|
||||
for (id, v) in &opts.recipe {
|
||||
// (`ImportJob::new` refused any id `set` would not write, and `set` clamps to the range)
|
||||
lightcraft_develop::controls::set(&mut d, id, *v);
|
||||
}
|
||||
let d = std::sync::Arc::new(d);
|
||||
p.develop = d.clone();
|
||||
p.edited = Some(now.clone());
|
||||
p.history.push(lightcraft_catalog::HistoryStep { label: "Import adjustments".into(), settings: d });
|
||||
}
|
||||
report.imported.push(id.0);
|
||||
p.local = opts.local;
|
||||
if opts.local {
|
||||
|
||||
@@ -24,6 +24,11 @@ pub fn is_supported(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| EXTENSIONS.contains(&e.to_string_lossy().to_lowercase().as_str()))
|
||||
}
|
||||
|
||||
/// An XMP sidecar (`.xmp`, any letter case): read with its photo on import, never a photo itself.
|
||||
fn is_xmp_sidecar(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp"))
|
||||
}
|
||||
|
||||
/// The web file picker's accept list, derived from [`EXTENSIONS`]. Each extension
|
||||
/// is listed in both cases: browsers' `accept` matching is case-insensitive per
|
||||
/// spec, but some implementations (e.g. Windows/Edge) match case-sensitively and
|
||||
@@ -78,19 +83,57 @@ pub(crate) fn expand_noting(
|
||||
paths: &[String],
|
||||
skip: Option<&Path>,
|
||||
limits: crate::walk::Limits,
|
||||
mut note: Option<crate::walk::NoteFolder>,
|
||||
note: Option<crate::walk::NoteFolder>,
|
||||
) -> (Vec<String>, bool) {
|
||||
let mut out = Vec::new();
|
||||
let mut truncated = false;
|
||||
let e = expand_report_noting(paths, skip, limits, note);
|
||||
(e.files, e.truncated)
|
||||
}
|
||||
|
||||
/// What expanding import sources found, and what the walks left out ([`expand_report`]), so a
|
||||
/// review can say that it did not see everything.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Expansion {
|
||||
/// Supported files, folders walked recursively and deduplicated by path, in walk order.
|
||||
pub files: Vec<String>,
|
||||
/// A walk stopped at a depth or entry bound: there may be more files.
|
||||
pub truncated: bool,
|
||||
/// Folders whose contents couldn't be listed (permissions, a folder that vanished or went offline).
|
||||
pub unreadable: usize,
|
||||
/// Files found inside the folders walked that are not a supported type (see [`is_supported`]),
|
||||
/// not counting XMP sidecars, which the import reads with their photos. A file named directly
|
||||
/// is attempted whatever its extension and is never counted here. Both counts add up over the
|
||||
/// sources, so a folder named twice (or inside another source) counts twice.
|
||||
pub unsupported: usize,
|
||||
}
|
||||
|
||||
/// [`expand_within`] keeping the walks' diagnostics. A walk that stops at a bound is logged here
|
||||
/// (once per folder), as it always was.
|
||||
pub fn expand_report(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits) -> Expansion {
|
||||
expand_report_noting(paths, skip, limits, None)
|
||||
}
|
||||
|
||||
/// ([`expand_report`], handing the listing of every folder that is walked to `note`, as
|
||||
/// [`expand_noting`] does.)
|
||||
fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits, mut note: Option<crate::walk::NoteFolder>) -> Expansion {
|
||||
let mut out = Expansion::default();
|
||||
for p in paths {
|
||||
let p = Path::new(p);
|
||||
if skip.is_some_and(|s| p == s) {
|
||||
continue;
|
||||
}
|
||||
if p.is_dir() {
|
||||
// XMP sidecars are read with their photos, not skipped: they are left out of the count
|
||||
let mut sidecars = 0usize;
|
||||
let keep = |f: &Path| {
|
||||
let keep = is_supported(f);
|
||||
if !keep && is_xmp_sidecar(f) {
|
||||
sidecars = sidecars.saturating_add(1);
|
||||
}
|
||||
keep
|
||||
};
|
||||
let w = match note.as_mut() {
|
||||
Some(note) => crate::walk::files_in_noting(p, skip, limits, is_supported, &mut **note),
|
||||
None => crate::walk::files_in(p, skip, limits, is_supported),
|
||||
Some(note) => crate::walk::files_in_noting(p, skip, limits, keep, &mut **note),
|
||||
None => crate::walk::files_in(p, skip, limits, keep),
|
||||
};
|
||||
if w.truncated {
|
||||
log::warn!(
|
||||
@@ -101,16 +144,18 @@ pub(crate) fn expand_noting(
|
||||
limits.max_depth
|
||||
);
|
||||
}
|
||||
truncated |= w.truncated;
|
||||
out.extend(w.files.into_iter().map(|f| f.to_string_lossy().to_string()));
|
||||
out.truncated |= w.truncated;
|
||||
out.unreadable = out.unreadable.saturating_add(w.unreadable);
|
||||
out.unsupported = out.unsupported.saturating_add(w.skipped.saturating_sub(sidecars));
|
||||
out.files.extend(w.files.into_iter().map(|f| f.to_string_lossy().to_string()));
|
||||
} else {
|
||||
// explicitly named files are attempted even with an unknown extension (sniffed)
|
||||
out.push(p.to_string_lossy().to_string());
|
||||
out.files.push(p.to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
out.retain(|p| seen.insert(p.clone()));
|
||||
(out, truncated)
|
||||
out.files.retain(|p| seen.insert(p.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
/// What a path given on the command line at launch becomes ([`launch_path`]).
|
||||
|
||||
@@ -163,6 +163,8 @@ impl ImportJob {
|
||||
/// Snapshot what an import with `opts` needs from the session (no file-system calls). Takes
|
||||
/// the probes a preceding scan left ([`Session::import_probes`]).
|
||||
pub fn new(s: &mut Session, opts: ImportOptions) -> crate::Result<Self> {
|
||||
// a recipe is checked before any file is read or placed, not when the photos are committed
|
||||
crate::cmd::check_recipe(&opts.recipe).map_err(|e| crate::cmd::bad("library.import", e))?;
|
||||
let mode = opts.mode;
|
||||
// Only a library on disk has an `Originals/` folder. The browser build keeps the bytes of
|
||||
// every added file in its own storage already, so "copy" there means "add".
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::files::{Seen, expand, is_supported, probe_all, reusable_probes};
|
||||
use super::files::{Seen, expand, expand_report, is_supported, probe_all, reusable_probes};
|
||||
use super::types::ImportCandidate;
|
||||
use super::{HashMap, Path, PathBuf, PhotoId, ProbeInfo, Session, Source};
|
||||
|
||||
@@ -77,6 +77,12 @@ pub struct ScanProgress {
|
||||
pub struct ScanOutput {
|
||||
pub candidates: Vec<ImportCandidate>,
|
||||
pub probes: HashMap<String, ProbeInfo>,
|
||||
/// A folder walk stopped at a depth or entry bound: there may be more photos ([`Expansion`]).
|
||||
pub truncated: bool,
|
||||
/// Folders whose contents couldn't be listed.
|
||||
pub unreadable: usize,
|
||||
/// Files inside the folders that are not a supported photo type (XMP sidecars not counted).
|
||||
pub unsupported: usize,
|
||||
}
|
||||
|
||||
impl ScanInput {
|
||||
@@ -283,20 +289,32 @@ fn browse_order_until(files: &mut [String], sort: &lightcraft_catalog::Sort, can
|
||||
/// against the library and earlier candidates). Nothing is added; the probes are kept for the
|
||||
/// import that follows.
|
||||
pub fn scan(s: &mut Session, paths: &[String]) -> Vec<ImportCandidate> {
|
||||
scan_report(s, paths).candidates
|
||||
}
|
||||
|
||||
/// [`scan`] keeping what the walks left out. The probes are already kept in the session for the
|
||||
/// import that follows, so `probes` of the output is empty.
|
||||
pub fn scan_report(s: &mut Session, paths: &[String]) -> ScanOutput {
|
||||
let (input, paths) = ScanInput::new(s, paths);
|
||||
let out = scan_with(input, &paths, &ScanProgress::default());
|
||||
s.import_probes = out.probes;
|
||||
out.candidates
|
||||
let mut out = scan_with(input, &paths, &ScanProgress::default());
|
||||
s.import_probes = std::mem::take(&mut out.probes);
|
||||
out
|
||||
}
|
||||
|
||||
/// [`scan`] without the session, so it can run on a worker thread. Stops early (returning what it
|
||||
/// has) when `progress.cancel` is set.
|
||||
pub fn scan_with(input: ScanInput, paths: &[String], progress: &ScanProgress) -> ScanOutput {
|
||||
let files = expand(paths, input.skip.as_deref());
|
||||
scan_files(input, files, progress)
|
||||
let expansion = expand_report(paths, input.skip.as_deref(), crate::walk::Limits::default());
|
||||
let mut out = scan_files(input, expansion.files, progress);
|
||||
out.truncated = expansion.truncated;
|
||||
out.unreadable = expansion.unreadable;
|
||||
out.unsupported = expansion.unsupported;
|
||||
out
|
||||
}
|
||||
|
||||
/// [`scan_with`] for files that were found already (`paths` expanded, [`expand`]).
|
||||
/// [`scan_with`] for files that were found already (`paths` expanded, [`expand`]). The walks'
|
||||
/// diagnostics ([`ScanOutput::truncated`] and friends) are left empty: who expanded the paths has
|
||||
/// them ([`expand_report`]).
|
||||
pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &ScanProgress) -> ScanOutput {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let by_path = library_files(&input.library, &files);
|
||||
@@ -357,5 +375,6 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &Sc
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
ScanOutput { candidates: out, probes: kept }
|
||||
// (the walks' diagnostics are [`scan_with`]'s: these files were found already)
|
||||
ScanOutput { candidates: out, probes: kept, truncated: false, unreadable: 0, unsupported: 0 }
|
||||
}
|
||||
@@ -67,6 +67,16 @@ pub struct ImportOptions {
|
||||
pub metadata_preset: Option<String>,
|
||||
/// Copy: raws are copied as DNG (Copy as DNG).
|
||||
pub convert_dng: bool,
|
||||
/// A batch-edit recipe: develop control id / value pairs (e.g. `light.exposure` → 0.5),
|
||||
/// applied to every imported photo *after* its XMP sidecar, camera default and import preset,
|
||||
/// as one more History step (`Import adjustments`). Only the named controls change; the recipe
|
||||
/// is a snapshot taken when the import starts, so editing a preset afterwards cannot change it.
|
||||
/// It names plain adjustments only (no white balance, geometry or crop: `cmd::check_recipe`),
|
||||
/// and [`ImportJob::new`] refuses anything else.
|
||||
/// Empty (the default) = no recipe. A photo the library already has keeps its own settings:
|
||||
/// one skipped as a duplicate, restored from Recently Deleted, or joined from a browsed
|
||||
/// folder (Local) is never touched, as the preset and keywords never are.
|
||||
pub recipe: Vec<(String, f64)>,
|
||||
}
|
||||
|
||||
/// How copies are filed in the destination. The date is the capture time, else the time of the
|
||||
|
||||
@@ -113,6 +113,12 @@ fn load(dir: &Path, downloaded: bool) -> Option<Arc<LensDb>> {
|
||||
}
|
||||
match LensDb::load_dir(dir) {
|
||||
Ok((db, errors)) => {
|
||||
let n_files = std::fs::read_dir(dir)
|
||||
.map(|rd| {
|
||||
rd.filter_map(|e| e.ok()).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("xml"))).count()
|
||||
})
|
||||
.unwrap_or(0);
|
||||
log::info!("lens database: {files} files, {profiles} profiles", files = n_files, profiles = db.lenses.len());
|
||||
for (file, e) in errors {
|
||||
log::warn!("lens database: skipped {file}: {e}");
|
||||
}
|
||||
@@ -540,6 +546,44 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The database that was found is reported: how many files it holds and how many profiles they carry, so a
|
||||
/// directory that was pointed at but holds nothing (or holds profiles that never match a photo) is visible in
|
||||
/// the log instead of passing unnoticed. The database is read from the environment and kept for the process,
|
||||
/// so the check runs in a child process of this test binary.
|
||||
#[test]
|
||||
fn lens_database_summary_reports_files_and_profiles() {
|
||||
let dir = std::env::temp_dir().join(format!("lc-lens-summary-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("one.xml"), DB).unwrap();
|
||||
std::fs::write(dir.join("two.xml"), DB.replace("Testcam 18-55mm f/3.5-5.6", "Testcam 24-70mm f/2.8")).unwrap();
|
||||
let exe = std::env::current_exe().unwrap();
|
||||
let out = std::process::Command::new(exe)
|
||||
.args(["--exact", "lens_profiles::tests::lens_database_summary_child", "--ignored", "--test-threads=1", "--nocapture"])
|
||||
.env(ENV, &dir)
|
||||
.env("LIGHTCRAFT_LOG", "trace")
|
||||
.output()
|
||||
.unwrap();
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).to_lowercase();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert!(out.status.success(), "the child process failed: {stderr}");
|
||||
let logged: Vec<&str> = stderr.lines().filter(|l| l.starts_with("lightcraft: ")).collect();
|
||||
assert!(!logged.is_empty(), "the database was read without a word in the log: {stderr}");
|
||||
let summary = logged.iter().find(|l| l.contains("lens database:")).expect("the lens database summary line was not logged");
|
||||
let mut counts = summary.split_whitespace().filter_map(|t| t.trim_end_matches(',').parse::<usize>().ok());
|
||||
assert_eq!(counts.next(), Some(2), "expected 2 files in the lens database summary: {summary}");
|
||||
assert_eq!(counts.next(), Some(2), "expected 2 profiles in the lens database summary: {summary}");
|
||||
}
|
||||
|
||||
/// Run by [`lens_database_summary_reports_files_and_profiles`] in a child process: read the database the
|
||||
/// environment points at, so its summary reaches the log the parent reads.
|
||||
#[test]
|
||||
#[ignore = "helper process for lens_database_summary_reports_files_and_profiles"]
|
||||
fn lens_database_summary_child() {
|
||||
crate::logging::install("lightcraft");
|
||||
let _ = database();
|
||||
}
|
||||
|
||||
/// A synthetic grid recorded through the profile's barrel distortion comes out of the pipeline's geometry
|
||||
/// stage with straight lines.
|
||||
#[test]
|
||||
|
||||
@@ -608,6 +608,7 @@ mod tests {
|
||||
let _ = std::fs::remove_file(beside(&dir, LOCK));
|
||||
}
|
||||
|
||||
#[allow(clippy::unwrap_used)]
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("lc-lensfun-{name}-{}", std::process::id()));
|
||||
for leftover in [d.clone(), beside(&d, STAGING), beside(&d, PREVIOUS)] {
|
||||
@@ -618,6 +619,7 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A local server answering `GET /db/<name>` with that file's body (404 otherwise).
|
||||
#[allow(clippy::unwrap_used)]
|
||||
fn serve(files: Vec<(&'static str, Vec<u8>)>) -> String {
|
||||
let l = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let base = format!("http://{}/db", l.local_addr().unwrap());
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
//! of decoded source proxies. Rendering is done by [`RenderJob`]s that are `Send` so frontends can
|
||||
//! run them off the UI thread.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
// Model/cache types remain available without linking the optional inference crate.
|
||||
#[cfg(not(feature = "denoise"))]
|
||||
|
||||
@@ -581,6 +581,9 @@ impl Session {
|
||||
self.last_export = prefs.last_export;
|
||||
self.last_merge = prefs.last_merge;
|
||||
self.export_presets = prefs.export_presets;
|
||||
// a user preset whose name shadows a built-in one could never be selected or exported
|
||||
// (the built-ins are looked up first); it gets a name of its own instead
|
||||
self.rename_shadowing_export_presets();
|
||||
self.print_templates = prefs.print_templates;
|
||||
self.metadata_presets = prefs.metadata_presets;
|
||||
self.filter_presets = prefs.filter_presets;
|
||||
|
||||
@@ -937,6 +937,35 @@ pub(crate) struct ApplyPrepared<'a> {
|
||||
pub(crate) undo0: usize,
|
||||
}
|
||||
|
||||
/// The catalog's collections with each id once, in catalog order. A row repeated as it is drops quietly; a different
|
||||
/// collection with an id an earlier one has is left out with a warning naming both, since two albums can't have one id
|
||||
/// (#1588: one bad Lightroom record costs that record, not the import). The photos listed under the id go to the first.
|
||||
fn first_of_each_collection<'a>(data: &'a CatalogImport, warnings: &mut Vec<String>) -> Vec<&'a Row> {
|
||||
let mut first: HashMap<i64, &Row> = HashMap::new();
|
||||
let mut rows = Vec::new();
|
||||
for collection in &data.collections {
|
||||
let id = number(collection, "id_local");
|
||||
let Some(kept) = first.get(&id) else {
|
||||
first.insert(id, collection);
|
||||
rows.push(collection);
|
||||
continue;
|
||||
};
|
||||
if *kept != collection {
|
||||
let photos = if data.members.iter().any(|m| number(m, "collection") == id) {
|
||||
format!("; the photos listed under that id go to “{}”", text(kept, "name"))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
warnings.push(format!(
|
||||
"collection “{}”: not imported, it has the id of collection “{}”{photos}",
|
||||
text(collection, "name"),
|
||||
text(kept, "name")
|
||||
));
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn stage_collections(
|
||||
s: &mut crate::Session,
|
||||
data: &CatalogImport,
|
||||
@@ -944,24 +973,42 @@ fn stage_collections(
|
||||
ids: &HashMap<i64, PhotoId>,
|
||||
ops: &mut Vec<Op>,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> usize {
|
||||
) -> crate::Result<usize> {
|
||||
let rows = first_of_each_collection(data, warnings);
|
||||
let mut albums = HashMap::new();
|
||||
for collection in &data.collections {
|
||||
// Two collections never share an album. An index that names one album for two gives the second a new one; the
|
||||
// counter saturates, so a damaged one hands out an id that's taken, and that stops the import instead.
|
||||
let mut assigned = HashSet::new();
|
||||
for &collection in &rows {
|
||||
if number(collection, "systemOnly") != 0 {
|
||||
continue;
|
||||
}
|
||||
let collection_key = format!("{}:{}", key(&data.source), number(collection, "id_local"));
|
||||
let id = index
|
||||
let indexed = index
|
||||
.collections
|
||||
.get(&collection_key)
|
||||
.copied()
|
||||
.map(lightcraft_catalog::AlbumId)
|
||||
.filter(|id| s.catalog.album(*id).is_some())
|
||||
.unwrap_or_else(|| s.catalog.alloc_album_id());
|
||||
.filter(|id| s.catalog.album(*id).is_some() && !assigned.contains(id));
|
||||
let id = match indexed {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
let id = s.catalog.alloc_album_id();
|
||||
if s.catalog.album(id).is_some() || assigned.contains(&id) {
|
||||
return Err(error(format!(
|
||||
"collection “{}”: the library has no unused album id left for it (its album numbering is exhausted or damaged)",
|
||||
text(collection, "name")
|
||||
)));
|
||||
}
|
||||
id
|
||||
}
|
||||
};
|
||||
assigned.insert(id);
|
||||
index.collections.insert(collection_key, id.0);
|
||||
albums.insert(number(collection, "id_local"), id);
|
||||
}
|
||||
let parents: HashMap<_, _> = data.collections.iter().map(|r| (number(r, "id_local"), number(r, "parent"))).collect();
|
||||
let parents: HashMap<_, _> = rows.iter().map(|r| (number(r, "id_local"), number(r, "parent"))).collect();
|
||||
let collections: HashMap<_, _> = rows.iter().map(|r| (number(r, "id_local"), *r)).collect();
|
||||
let mut grouped_members: HashMap<i64, Vec<&Row>> = HashMap::new();
|
||||
for member in &data.members {
|
||||
grouped_members.entry(number(member, "collection")).or_default().push(member);
|
||||
@@ -969,7 +1016,7 @@ fn stage_collections(
|
||||
for members in grouped_members.values_mut() {
|
||||
members.sort_by(|a, b| text(a, "positionInCollection").cmp(text(b, "positionInCollection")));
|
||||
}
|
||||
let mut ordered: Vec<_> = data.collections.iter().collect();
|
||||
let mut ordered = rows.clone();
|
||||
ordered.sort_by_key(|r| {
|
||||
let mut depth = 0;
|
||||
let mut at = number(r, "parent");
|
||||
@@ -979,10 +1026,19 @@ fn stage_collections(
|
||||
}
|
||||
depth
|
||||
});
|
||||
// Collections whose albums are folders: a collection set, or an earlier import's album when it is a folder.
|
||||
let sets: HashSet<i64> = albums
|
||||
.iter()
|
||||
.filter(|(lr, id)| match s.catalog.album(**id) {
|
||||
Some(album) => album.folder,
|
||||
None => collections.get(*lr).is_some_and(|r| text(r, "creationId").contains("group")),
|
||||
})
|
||||
.map(|(lr, _)| *lr)
|
||||
.collect();
|
||||
let mut added_folders = HashSet::new();
|
||||
for collection in ordered {
|
||||
let Some(id) = albums.get(&number(collection, "id_local")).copied() else { continue };
|
||||
let mut album = Album::new(id, text(collection, "name"));
|
||||
album.parent = albums.get(&number(collection, "parent")).copied();
|
||||
album.folder = text(collection, "creationId").contains("group");
|
||||
if text(collection, "creationId").contains("smart") {
|
||||
warnings.push(format!("{}: smart rules preserved in archive; imported current membership", album.name));
|
||||
@@ -1008,10 +1064,49 @@ fn stage_collections(
|
||||
ops.push(Op::SetAlbumPhotos { id, photos });
|
||||
}
|
||||
} else {
|
||||
let (set, moved) = collection_parent(collection, &collections, &sets);
|
||||
album.parent = set.and_then(|set| albums.get(&set).copied());
|
||||
// `AddAlbum` rejects a parent that isn't a folder yet, and that would roll back the whole batch: every
|
||||
// album and every catalog-only photo. `collection_parent` already prevents it; this keeps a bug there
|
||||
// (or a cycle `validate` missed) from doing so.
|
||||
if let Some(parent) = album.parent
|
||||
&& !added_folders.contains(&parent)
|
||||
&& !s.catalog.album(parent).is_some_and(|a| a.folder)
|
||||
{
|
||||
album.parent = None;
|
||||
warnings.push(format!(
|
||||
"{}: its collection set could not be created first; imported at the top level (Lightroom collection {})",
|
||||
album.name,
|
||||
number(collection, "id_local")
|
||||
));
|
||||
} else if moved {
|
||||
let lr_parent = number(collection, "parent");
|
||||
let why = match collections.get(&lr_parent) {
|
||||
None => "its parent collection isn't in the catalog".to_string(),
|
||||
Some(r) => match albums.get(&lr_parent).and_then(|id| s.catalog.album(*id)) {
|
||||
// a set imported earlier whose album is no longer a folder
|
||||
Some(a) if text(r, "creationId").contains("group") => {
|
||||
format!("its collection set “{}” is the album “{}” in this library, which isn't a folder", text(r, "name"), a.name)
|
||||
}
|
||||
_ => format!("Lightroom keeps it inside “{}”, which isn't a collection set", text(r, "name")),
|
||||
},
|
||||
};
|
||||
// the set's name in this library: the user may have renamed it since an earlier import
|
||||
let to = match (album.parent.and_then(|id| s.catalog.album(id)), set.and_then(|set| collections.get(&set))) {
|
||||
(Some(a), _) => format!("into “{}”", a.name),
|
||||
(None, Some(r)) => format!("into “{}”", text(r, "name")),
|
||||
(None, None) => "at the top level".to_string(),
|
||||
};
|
||||
// the Lightroom id tells apart collections that share a name (#2165)
|
||||
warnings.push(format!("{}: {why}; imported {to} (Lightroom collection {})", album.name, number(collection, "id_local")));
|
||||
}
|
||||
if album.folder {
|
||||
added_folders.insert(id);
|
||||
}
|
||||
ops.push(Op::AddAlbum { album });
|
||||
}
|
||||
}
|
||||
albums.len()
|
||||
Ok(albums.len())
|
||||
}
|
||||
|
||||
/// Turn the read catalog into library records in one undo step and return the import report
|
||||
@@ -1240,7 +1335,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
|
||||
}
|
||||
by_path.entry(key(&src.path)).or_insert(photo_id);
|
||||
}
|
||||
let album_count = stage_collections(s, &data, index, &ids, &mut ops, &mut warnings);
|
||||
let album_count = stage_collections(s, &data, index, &ids, &mut ops, &mut warnings)?;
|
||||
if !ops.is_empty() {
|
||||
s.commit("Import Lightroom Catalog", Op::Batch { ops })?;
|
||||
}
|
||||
@@ -1251,5 +1346,22 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co
|
||||
})
|
||||
}
|
||||
|
||||
/// The collection set a Lightroom collection's album goes into (`None`: the top level), and whether that isn't its
|
||||
/// Lightroom parent. A LightCraft album nests only in a folder, but Lightroom also keeps a print, book, slideshow or
|
||||
/// web gallery (or, in an odd catalog, a collection) inside a plain or smart collection, and a parent can be
|
||||
/// system-only (not imported) or gone from the catalog. Such an album joins the nearest collection set above it.
|
||||
fn collection_parent(collection: &Row, collections: &HashMap<i64, &Row>, sets: &HashSet<i64>) -> (Option<i64>, bool) {
|
||||
let mut at = number(collection, "parent");
|
||||
let mut seen = HashSet::from([number(collection, "id_local")]);
|
||||
while at != 0 && !sets.contains(&at) {
|
||||
// `validate` rejects cycles and deep chains; stop at the top level if one got here anyway.
|
||||
if seen.len() > 64 || !seen.insert(at) {
|
||||
return (None, true);
|
||||
}
|
||||
at = collections.get(&at).map_or(0, |r| number(r, "parent"));
|
||||
}
|
||||
((at != 0).then_some(at), at != number(collection, "parent"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -405,6 +405,255 @@ fn a_reimport_counts_each_trashed_match_once() {
|
||||
assert_eq!(r["imported"], 0, "{r}");
|
||||
assert!(ids.iter().all(|id| s.catalog.photo(*id).unwrap().deleted));
|
||||
}
|
||||
/// The import report's warnings about `album`.
|
||||
fn warnings_naming(r: &Value, album: &str) -> Vec<String> {
|
||||
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).filter(|w| w.starts_with(&format!("{album}:"))).map(String::from).collect()
|
||||
}
|
||||
fn album_named<'a>(s: &'a crate::Session, name: &str) -> &'a lightcraft_catalog::Album {
|
||||
s.catalog.albums().find(|a| a.name == name).unwrap_or_else(|| panic!("no album {name}"))
|
||||
}
|
||||
/// A LightCraft album nests only in a folder. A collection Lightroom keeps inside a plain collection used to fail the
|
||||
/// whole batch with "parent must be an existing folder", taking every album with it (#2165, #2532).
|
||||
#[test]
|
||||
fn a_collection_inside_a_plain_collection_joins_the_set_above_it() {
|
||||
let mut s = crate::Session::new();
|
||||
let mut data = sample();
|
||||
data.collections.push(row(json!({"id_local":11,"parent":10,"name":"Picks","creationId":"com.adobe.ag.library.collection"})));
|
||||
data.members.push(row(json!({"collection":11,"image":1,"positionInCollection":"a"})));
|
||||
let r = apply(&mut s, data, false).unwrap();
|
||||
assert_eq!(r["collections"], 3);
|
||||
assert_eq!(s.catalog.photos().count(), 2);
|
||||
let travel = album_named(&s, "Travel").id;
|
||||
assert_eq!(album_named(&s, "Keepers").parent, Some(travel));
|
||||
assert_eq!(album_named(&s, "Keepers").photos.len(), 2);
|
||||
assert_eq!(album_named(&s, "Picks").parent, Some(travel));
|
||||
assert_eq!(album_named(&s, "Picks").photos.len(), 1);
|
||||
let w = warnings_naming(&r, "Picks");
|
||||
assert_eq!(w.len(), 1, "{w:?}");
|
||||
assert!(w[0].contains("Keepers") && w[0].contains("into “Travel”"), "{w:?}");
|
||||
assert!(warnings_naming(&r, "Keepers").is_empty());
|
||||
}
|
||||
/// Lightroom Classic saves a print, book, slideshow or web gallery inside a collection; with no set above it, the
|
||||
/// creation lands at the top level.
|
||||
#[test]
|
||||
fn a_creation_saved_inside_a_top_level_collection_lands_at_the_top_level() {
|
||||
let mut s = crate::Session::new();
|
||||
let mut data = sample();
|
||||
data.collections.push(row(json!({"id_local":12,"name":"Loose","creationId":"com.adobe.ag.library.collection"})));
|
||||
data.collections.push(row(json!({"id_local":13,"parent":12,"name":"Poster","creationId":"com.adobe.ag.print"})));
|
||||
data.collections.push(row(json!({"id_local":14,"parent":10,"name":"Album Book","creationId":"com.adobe.ag.layout.book"})));
|
||||
data.members.push(row(json!({"collection":13,"image":1,"positionInCollection":"a"})));
|
||||
let r = apply(&mut s, data, false).unwrap();
|
||||
assert_eq!(r["collections"], 5);
|
||||
let poster = album_named(&s, "Poster");
|
||||
assert_eq!((poster.parent, poster.folder, poster.photos.len()), (None, false, 1));
|
||||
assert_eq!(album_named(&s, "Album Book").parent, Some(album_named(&s, "Travel").id));
|
||||
let w = warnings_naming(&r, "Poster");
|
||||
assert!(w.len() == 1 && w[0].contains("Loose") && w[0].contains("at the top level"), "{w:?}");
|
||||
assert_eq!(warnings_naming(&r, "Album Book").len(), 1);
|
||||
assert_eq!(album_named(&s, "Keepers").photos.len(), 2);
|
||||
}
|
||||
/// A parent that's gone from the catalog or system-only (Quick Collection, an unsaved print…) isn't imported; the
|
||||
/// album lands at the top level, and the report says why it isn't where Lightroom had it.
|
||||
#[test]
|
||||
fn a_collection_whose_parent_is_missing_or_system_only_lands_at_the_top_level_with_a_warning() {
|
||||
let mut s = crate::Session::new();
|
||||
let mut data = sample();
|
||||
data.collections.push(row(json!({"id_local":11,"parent":99,"name":"Orphan","creationId":"com.adobe.ag.library.collection"})));
|
||||
data.collections.push(row(json!({"id_local":5,"name":"quick collection","creationId":"com.adobe.ag.library.collection","systemOnly":1})));
|
||||
data.collections.push(row(json!({"id_local":12,"parent":5,"name":"Stray","creationId":"com.adobe.ag.print"})));
|
||||
let r = apply(&mut s, data, false).unwrap();
|
||||
assert_eq!(r["collections"], 4);
|
||||
assert_eq!(album_named(&s, "Orphan").parent, None);
|
||||
assert_eq!(album_named(&s, "Stray").parent, None);
|
||||
assert!(s.catalog.albums().all(|a| a.name != "quick collection"));
|
||||
let w = warnings_naming(&r, "Orphan");
|
||||
assert!(w.len() == 1 && w[0].contains("isn't in the catalog"), "{w:?}");
|
||||
let w = warnings_naming(&r, "Stray");
|
||||
assert!(w.len() == 1 && w[0].contains("quick collection") && w[0].contains("at the top level"), "{w:?}");
|
||||
assert_eq!(album_named(&s, "Keepers").parent, Some(album_named(&s, "Travel").id));
|
||||
}
|
||||
/// Imports `data` keeping `index` between imports, as a library on disk does.
|
||||
fn import_indexed(s: &mut crate::Session, data: CatalogImport, index: &mut ImportIndex) -> crate::Result<Value> {
|
||||
let undo0 = s.undo.len();
|
||||
let missing_sources = HashSet::new();
|
||||
let context =
|
||||
ApplyPrepared { update_existing: false, files: Default::default(), index, archive_path: None, missing_sources: &missing_sources, undo0 };
|
||||
apply_prepared(s, data, context).map(|applied| applied.report)
|
||||
}
|
||||
/// The sample with “Picks”, a collection Lightroom keeps inside the plain collection “Keepers”.
|
||||
fn with_picks() -> CatalogImport {
|
||||
let mut data = sample();
|
||||
data.collections.push(row(json!({"id_local":11,"parent":10,"name":"Picks","creationId":"com.adobe.ag.library.collection"})));
|
||||
data.members.push(row(json!({"collection":11,"image":1,"positionInCollection":"a"})));
|
||||
data
|
||||
}
|
||||
/// Importing the catalog again finds the moved album where the first import put it, adds nothing twice and doesn't
|
||||
/// warn again: the album is already in the library.
|
||||
#[test]
|
||||
fn a_relocated_collection_keeps_its_place_on_reimport_without_duplicates_or_a_second_warning() {
|
||||
let mut s = crate::Session::new();
|
||||
let mut index = ImportIndex::default();
|
||||
let first = import_indexed(&mut s, with_picks(), &mut index).unwrap();
|
||||
assert_eq!(warnings_naming(&first, "Picks").len(), 1);
|
||||
let second = import_indexed(&mut s, with_picks(), &mut index).unwrap();
|
||||
assert_eq!(second["collections"], 3);
|
||||
assert_eq!(s.catalog.albums().count(), 3);
|
||||
assert_eq!(album_named(&s, "Picks").parent, Some(album_named(&s, "Travel").id));
|
||||
assert_eq!(album_named(&s, "Picks").photos.len(), 1);
|
||||
assert_eq!(album_named(&s, "Keepers").photos.len(), 2);
|
||||
assert!(warnings_naming(&second, "Picks").is_empty(), "{second}");
|
||||
}
|
||||
/// Albums the user moved after an import stay where the user put them when the catalog is imported again.
|
||||
#[test]
|
||||
fn an_album_the_user_moved_keeps_its_place_on_reimport() {
|
||||
let mut s = crate::Session::new();
|
||||
let mut index = ImportIndex::default();
|
||||
import_indexed(&mut s, with_picks(), &mut index).unwrap();
|
||||
for name in ["Picks", "Keepers"] {
|
||||
let id = album_named(&s, name).id;
|
||||
s.commit("Move Album", Op::MoveAlbum { id, parent: None }).unwrap();
|
||||
}
|
||||
let r = import_indexed(&mut s, with_picks(), &mut index).unwrap();
|
||||
assert_eq!(s.catalog.albums().count(), 3);
|
||||
assert_eq!(album_named(&s, "Picks").parent, None);
|
||||
assert_eq!(album_named(&s, "Keepers").parent, None);
|
||||
assert!(warnings_naming(&r, "Picks").is_empty() && warnings_naming(&r, "Keepers").is_empty(), "{r}");
|
||||
}
|
||||
/// A collection new since the last import goes into the set's album, and the warning names that album as the
|
||||
/// library calls it now, not by its Lightroom name.
|
||||
#[test]
|
||||
fn a_relocation_warning_names_the_set_as_the_user_renamed_it() {
|
||||
let mut s = crate::Session::new();
|
||||
let mut index = ImportIndex::default();
|
||||
import_indexed(&mut s, sample(), &mut index).unwrap();
|
||||
let travel = album_named(&s, "Travel").id;
|
||||
s.commit("Rename Album", Op::RenameAlbum { id: travel, name: "Trips".into() }).unwrap();
|
||||
let r = import_indexed(&mut s, with_picks(), &mut index).unwrap();
|
||||
assert_eq!(album_named(&s, "Picks").parent, Some(travel));
|
||||
let w = warnings_naming(&r, "Picks");
|
||||
assert!(w.len() == 1 && w[0].contains("inside “Keepers”") && w[0].ends_with("imported into “Trips” (Lightroom collection 11)"), "{w:?}");
|
||||
}
|
||||
/// The album an earlier import made for a Lightroom set may no longer be a folder (here: an index that names a plain
|
||||
/// album). A collection in that set lands at the top level, and the warning says why without calling the set
|
||||
/// something it isn't.
|
||||
#[test]
|
||||
fn a_set_whose_album_is_not_a_folder_puts_its_collections_at_the_top_level() {
|
||||
let mut s = crate::Session::new();
|
||||
let plain = s.catalog.alloc_album_id();
|
||||
s.commit("New Album", Op::AddAlbum { album: Album::new(plain, "Travel picks") }).unwrap();
|
||||
let mut index = ImportIndex::default();
|
||||
index.collections.insert(format!("{}:9", key("test.lrcat")), plain.0);
|
||||
let r = import_indexed(&mut s, sample(), &mut index).unwrap();
|
||||
assert_eq!(s.catalog.albums().count(), 2);
|
||||
assert!(!s.catalog.album(plain).unwrap().folder);
|
||||
let keepers = album_named(&s, "Keepers");
|
||||
assert_eq!((keepers.parent, keepers.photos.len()), (None, 2));
|
||||
let w = warnings_naming(&r, "Keepers");
|
||||
assert_eq!(w.len(), 1, "{w:?}");
|
||||
assert!(w[0].contains("“Travel” is the album “Travel picks”") && w[0].contains("isn't a folder"), "{w:?}");
|
||||
assert!(!w[0].contains("isn't a collection set") && w[0].ends_with("at the top level (Lightroom collection 10)"), "{w:?}");
|
||||
}
|
||||
/// Only the outermost set inside a plain collection moves; the sets and creations inside it keep their places.
|
||||
#[test]
|
||||
fn sets_nested_under_a_plain_collection_keep_their_own_nesting() {
|
||||
let mut s = crate::Session::new();
|
||||
let mut data = sample();
|
||||
data.collections.push(row(json!({"id_local":12,"name":"Loose","creationId":"com.adobe.ag.library.collection"})));
|
||||
data.collections.push(row(json!({"id_local":13,"parent":12,"name":"Outer","creationId":"com.adobe.ag.library.group"})));
|
||||
data.collections.push(row(json!({"id_local":14,"parent":13,"name":"Inner","creationId":"com.adobe.ag.library.group"})));
|
||||
data.collections.push(row(json!({"id_local":15,"parent":14,"name":"Poster","creationId":"com.adobe.ag.print"})));
|
||||
data.members.push(row(json!({"collection":15,"image":1,"positionInCollection":"a"})));
|
||||
let r = apply(&mut s, data, false).unwrap();
|
||||
assert_eq!(r["collections"], 6);
|
||||
let outer = album_named(&s, "Outer");
|
||||
assert_eq!((outer.parent, outer.folder), (None, true));
|
||||
let inner = album_named(&s, "Inner");
|
||||
assert_eq!((inner.parent, inner.folder), (Some(outer.id), true));
|
||||
assert_eq!(album_named(&s, "Poster").parent, Some(inner.id));
|
||||
assert_eq!(album_named(&s, "Poster").photos.len(), 1);
|
||||
let w = warnings_naming(&r, "Outer");
|
||||
assert!(w.len() == 1 && w[0].contains("inside “Loose”") && w[0].ends_with("at the top level (Lightroom collection 13)"), "{w:?}");
|
||||
assert!(warnings_naming(&r, "Inner").is_empty() && warnings_naming(&r, "Poster").is_empty(), "{r}");
|
||||
}
|
||||
/// The album counter saturates: one at its end hands every collection the same id. The second collection used to be
|
||||
/// dropped without a word while the report counted it; the import now stops and names it.
|
||||
#[test]
|
||||
fn an_exhausted_album_counter_stops_the_import_naming_the_collection() {
|
||||
let mut s = crate::Session::new();
|
||||
s.commit("New Album", Op::AddAlbum { album: Album::new(lightcraft_catalog::AlbumId(u64::MAX - 1), "Last") }).unwrap();
|
||||
let err = apply(&mut s, sample(), false).unwrap_err().to_string();
|
||||
assert!(err.contains("“Keepers”") && err.contains("no unused album id"), "{err}");
|
||||
assert_eq!(s.catalog.albums().count(), 1);
|
||||
assert!(s.catalog.is_empty());
|
||||
}
|
||||
/// A collection listed twice imports once. A different collection under the same Lightroom id used to stop the import;
|
||||
/// like any bad record it now costs only itself (#1588): it is left out with a warning naming both, and its photos go
|
||||
/// to the first.
|
||||
#[test]
|
||||
fn a_collection_listed_twice_imports_once_and_a_conflicting_one_is_skipped_with_a_warning() {
|
||||
let mut s = crate::Session::new();
|
||||
let mut data = sample();
|
||||
data.collections.push(data.collections[1].clone());
|
||||
let r = apply(&mut s, data, false).unwrap();
|
||||
assert_eq!(r["collections"], 2);
|
||||
assert_eq!(s.catalog.albums().filter(|a| a.name == "Keepers").count(), 1);
|
||||
assert_eq!(album_named(&s, "Keepers").photos.len(), 2);
|
||||
assert_eq!(r["warnings"], json!([]), "an exact repeat drops quietly");
|
||||
|
||||
let mut s = crate::Session::new();
|
||||
let mut data = sample();
|
||||
// shallower than the first, so a depth-ordered pass would meet it first
|
||||
data.collections.push(row(json!({"id_local":10,"parent":0,"name":"Rejects","creationId":"collection"})));
|
||||
let r = apply(&mut s, data, false).unwrap();
|
||||
assert_eq!(r["photos"], 2, "{r}");
|
||||
assert_eq!(r["collections"], 2, "{r}");
|
||||
assert!(s.catalog.albums().all(|a| a.name != "Rejects"));
|
||||
let keepers = album_named(&s, "Keepers");
|
||||
assert_eq!(keepers.photos.len(), 2);
|
||||
assert!(keepers.parent.is_some(), "the first row's place is kept");
|
||||
assert_eq!(
|
||||
r["warnings"],
|
||||
json!(["collection “Rejects”: not imported, it has the id of collection “Keepers”; the photos listed under that id go to “Keepers”"])
|
||||
);
|
||||
assert_eq!(s.undo.len(), 1);
|
||||
}
|
||||
/// The search for the nearest set ends on a parent loop that got past `validate` (A in B in A, a collection in
|
||||
/// itself) and on a chain of plain collections deeper than 64: the album goes to the top level, flagged as moved.
|
||||
#[test]
|
||||
fn the_nearest_set_search_ends_on_a_parent_loop_or_a_deep_chain() {
|
||||
let plain = |id: i64, parent: i64| row(json!({"id_local":id,"parent":parent,"name":format!("C{id}"),"creationId":"collection"}));
|
||||
let (a, b, own) = (plain(1, 2), plain(2, 1), plain(3, 3));
|
||||
let child = plain(4, 1);
|
||||
let collections: HashMap<i64, &Row> = [(1, &a), (2, &b), (3, &own), (4, &child)].into_iter().collect();
|
||||
let no_sets = HashSet::new();
|
||||
for c in [&a, &b, &own, &child] {
|
||||
assert_eq!(collection_parent(c, &collections, &no_sets), (None, true), "{c:?}");
|
||||
}
|
||||
// a set in the loop is still found
|
||||
assert_eq!(collection_parent(&child, &collections, &HashSet::from([2])), (Some(2), true));
|
||||
let chain: Vec<Row> = (100..200).map(|id| plain(id, if id == 100 { 0 } else { id - 1 })).collect();
|
||||
let collections: HashMap<i64, &Row> = chain.iter().map(|r| (number(r, "id_local"), r)).collect();
|
||||
assert_eq!(collection_parent(&chain[99], &collections, &no_sets), (None, true));
|
||||
}
|
||||
/// A damaged index that names one existing album for two collections gives the second an album of its own rather
|
||||
/// than merging its photos into the first's.
|
||||
#[test]
|
||||
fn an_index_naming_one_album_for_two_collections_gives_the_second_its_own() {
|
||||
let mut s = crate::Session::new();
|
||||
let old = s.catalog.alloc_album_id();
|
||||
s.commit("New Album", Op::AddAlbum { album: Album::new(old, "Old") }).unwrap();
|
||||
let mut index = ImportIndex::default();
|
||||
for lr in [10, 11] {
|
||||
index.collections.insert(format!("{}:{lr}", key("test.lrcat")), old.0);
|
||||
}
|
||||
let r = import_indexed(&mut s, with_picks(), &mut index).unwrap();
|
||||
assert_eq!(r["collections"], 3);
|
||||
assert_eq!(s.catalog.album(old).unwrap().photos.len(), 2, "Keepers merges into the album the index names");
|
||||
let picks = album_named(&s, "Picks");
|
||||
assert_ne!(picks.id, old);
|
||||
assert_eq!(picks.photos.len(), 1);
|
||||
}
|
||||
#[test]
|
||||
fn preserves_existing_edits_and_rejects_invalid_structure_before_mutation() {
|
||||
let mut s = crate::Session::new();
|
||||
@@ -873,7 +1122,7 @@ fn record(values: &[SqlValue]) -> Vec<u8> {
|
||||
body.extend(s.as_bytes());
|
||||
13 + 2 * s.len() as u64
|
||||
}
|
||||
_ => unreachable!(),
|
||||
_ => panic!("unexpected SqlValue in a test record: {value:?}"),
|
||||
};
|
||||
header.extend(varint(serial));
|
||||
}
|
||||
|
||||
@@ -344,13 +344,17 @@ impl MediaCache {
|
||||
{
|
||||
return SourceRef::Loaded(Box::new(a));
|
||||
}
|
||||
// a thumbnail of a photo whose preview is decoded (the one in the loupe) is cut from it; not
|
||||
// a thumbnail of a photo whose preview or full source is decoded (the one in the loupe) is cut from it; not
|
||||
// with a denoised picture, which the thumbnail would lose, nor from one decoded with another camera profile
|
||||
if cached
|
||||
&& level == SourceLevel::Thumb
|
||||
&& self.denoise.spec(p.id).is_none()
|
||||
&& let Some(big) = self.get_source(p.id, SourceLevel::Preview).filter(|b| b.fits_outliers(outliers))
|
||||
&& (big.camera_profile == wanted.as_ref().map(|(tag, _)| tag.clone()) || (big.from_proxy && self.original_offline(p)))
|
||||
&& let Some(big) = [SourceLevel::Preview, SourceLevel::Full].into_iter().find_map(|level| {
|
||||
self.get_source(p.id, level).filter(|b| {
|
||||
b.fits_outliers(outliers)
|
||||
&& (b.camera_profile.as_deref() == wanted.as_ref().map(|(tag, _)| tag.as_str()) || (b.from_proxy && self.original_offline(p)))
|
||||
})
|
||||
})
|
||||
{
|
||||
return SourceRef::Fit { from: Box::new(big), max_edge: level.max_edge() };
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
|
||||
|
||||
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
|
||||
pub const RENDER_CACHE_VERSION: u64 = 76;
|
||||
pub const RENDER_CACHE_VERSION: u64 = 77;
|
||||
|
||||
/// 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];
|
||||
|
||||
@@ -644,3 +644,19 @@ fn an_export_develops_from_a_source_twice_its_size() {
|
||||
}
|
||||
assert_eq!(s.render_job(id, 1600, 1600, false, true).unwrap().level, SourceLevel::Preview, "a view keeps the preview");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thumbnail_is_cut_from_the_decoded_full_source() {
|
||||
let mut s = crate::Session::new();
|
||||
let p = Photo::new(PhotoId(1), Source::File { path: "/nowhere/a.ARW".into() }, "a.ARW", "ARW", 2400, 1600, "");
|
||||
s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(p.clone()) }).unwrap();
|
||||
s.media.insert(p.id, SourceLevel::Full, Arc::new(Rgb32f::from_fn(2400, 1600, |x, _| [x as f32 / 2400.0, 0.5, 0.25])));
|
||||
let job = s.thumb_job(p.id, 512).unwrap();
|
||||
assert!(matches!(job.source, SourceRef::Fit { .. }));
|
||||
let r = job.run();
|
||||
let thumb = r.rendered.as_ref().unwrap();
|
||||
assert_eq!((thumb.image.width, thumb.image.height), (512, 341));
|
||||
s.accept(&r);
|
||||
let cached = s.media.get(p.id, SourceLevel::Thumb).unwrap();
|
||||
assert_eq!((cached.width, cached.height), (512, 341), "a thumbnail-sized source is kept, not the full source");
|
||||
}
|
||||
@@ -226,7 +226,10 @@ fn run(spec: &Download, mirror: &str, staging: &Path, shared: &Shared) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
// Two stacked cfgs (not `all(test, …)`): clippy only recognises a plain `cfg(test)`
|
||||
// module as test code, so the `allow-*-in-tests` settings in clippy.toml apply to its helpers.
|
||||
#[cfg(test)]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_denoise::hash::sha256_hex;
|
||||
|
||||
+198
-38
@@ -4,7 +4,8 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lightcraft_develop::Preset;
|
||||
use lightcraft_catalog::PhotoId;
|
||||
use lightcraft_develop::{DevelopSettings, Preset};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -171,6 +172,29 @@ pub fn expand_preset_paths(paths: &[String]) -> Vec<String> {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The settings after applying `preset` to photo `id` at `amount`. The settings the preset
|
||||
/// names are computed on the photo's import state ([`lightcraft_catalog::Photo::import_defaults`])
|
||||
/// when a default preset recorded one (`import_look`); a photo without one (its settings came
|
||||
/// from an XMP sidecar or a catalog import, which record none) composes them on its current
|
||||
/// settings instead, since the camera defaults are not its import state. Either way, the
|
||||
/// settings the preset does not name keep the photo's values (issue #2159). The `preset.apply`
|
||||
/// command and the UI's hover previews share this, so hovering shows exactly what a click commits.
|
||||
pub fn preset_applied(&self, id: PhotoId, preset: &Preset, amount: f64) -> Option<DevelopSettings> {
|
||||
let current = self.develop_of(id)?;
|
||||
let photo = self.catalog.photo(id)?;
|
||||
// The original is read only below 100 %: the panel asks for every visible row at 100 % on
|
||||
// every frame, and then neither the import state nor a copy of the photo's settings is built.
|
||||
let look;
|
||||
let original: &DevelopSettings = match &photo.import_look {
|
||||
Some(_) if (amount - 1.0).abs() >= 1e-9 => {
|
||||
look = photo.import_defaults();
|
||||
&look
|
||||
}
|
||||
_ => ¤t,
|
||||
};
|
||||
Some(preset.apply_on(¤t, original, amount))
|
||||
}
|
||||
|
||||
/// Add imported presets. Identical presets (same name, group and settings) already present are
|
||||
/// skipped; id clashes get a fresh id. Returns the ids added.
|
||||
pub fn add_presets(&mut self, presets: Vec<Preset>) -> Vec<String> {
|
||||
@@ -218,49 +242,49 @@ pub fn builtin() -> Vec<Preset> {
|
||||
"Color",
|
||||
"warm-glow",
|
||||
"Warm Glow",
|
||||
json!({"wb": {"mode": "custom", "temp": 7200.0, "tint": 8.0}, "light": {"contrast": 8.0, "shadows": 12.0}, "color": {"vibrance": 18.0}}),
|
||||
json!({"treatment": "color", "wb": {"mode": "custom", "temp": 7200.0, "tint": 8.0}, "light": {"contrast": 8.0, "shadows": 12.0}, "color": {"vibrance": 18.0}}),
|
||||
),
|
||||
p(
|
||||
"Color",
|
||||
"cool-morning",
|
||||
"Cool Morning",
|
||||
json!({"wb": {"mode": "custom", "temp": 5600.0, "tint": -4.0}, "light": {"highlights": -20.0}, "color": {"vibrance": 10.0}, "grading": {"shadows": {"hue": 215.0, "sat": 12.0, "lum": 0.0}}}),
|
||||
json!({"treatment": "color", "wb": {"mode": "custom", "temp": 5600.0, "tint": -4.0}, "light": {"highlights": -20.0}, "color": {"vibrance": 10.0}, "grading": {"shadows": {"hue": 215.0, "sat": 12.0, "lum": 0.0}}}),
|
||||
),
|
||||
p(
|
||||
"Color",
|
||||
"teal-orange",
|
||||
"Teal & Orange",
|
||||
json!({"grading": {"shadows": {"hue": 195.0, "sat": 28.0, "lum": 0.0}, "highlights": {"hue": 35.0, "sat": 22.0, "lum": 0.0}, "balance": 10.0}, "color": {"vibrance": 12.0}, "light": {"contrast": 14.0}}),
|
||||
json!({"treatment": "color", "grading": {"shadows": {"hue": 195.0, "sat": 28.0, "lum": 0.0}, "highlights": {"hue": 35.0, "sat": 22.0, "lum": 0.0}, "balance": 10.0}, "color": {"vibrance": 12.0}, "light": {"contrast": 14.0}}),
|
||||
),
|
||||
p(
|
||||
"Color",
|
||||
"vivid-pop",
|
||||
"Vivid Pop",
|
||||
json!({"color": {"vibrance": 40.0, "saturation": 8.0}, "light": {"contrast": 18.0, "whites": 10.0, "blacks": -10.0}, "effects": {"clarity": 12.0}}),
|
||||
json!({"treatment": "color", "color": {"vibrance": 40.0, "saturation": 8.0}, "light": {"contrast": 18.0, "whites": 10.0, "blacks": -10.0}, "effects": {"clarity": 12.0}}),
|
||||
),
|
||||
p(
|
||||
"Color",
|
||||
"soft-pastel",
|
||||
"Soft Pastel",
|
||||
json!({"light": {"contrast": -25.0, "highlights": -30.0, "shadows": 35.0, "blacks": 20.0}, "color": {"saturation": -18.0, "vibrance": 10.0}, "curve": {"shadows": 25.0}}),
|
||||
json!({"treatment": "color", "light": {"contrast": -25.0, "highlights": -30.0, "shadows": 35.0, "blacks": 20.0}, "color": {"saturation": -18.0, "vibrance": 10.0}, "curve": {"shadows": 25.0}}),
|
||||
),
|
||||
p(
|
||||
"Film",
|
||||
"faded-matte",
|
||||
"Faded Matte",
|
||||
json!({"curve": {"shadows": 40.0, "highlights": -15.0}, "light": {"contrast": -10.0}, "color": {"saturation": -12.0}, "grain": {"amount": 18.0, "size": 25.0, "roughness": 50.0}}),
|
||||
json!({"treatment": "color", "curve": {"shadows": 40.0, "highlights": -15.0}, "light": {"contrast": -10.0}, "color": {"saturation": -12.0}, "grain": {"amount": 18.0, "size": 25.0, "roughness": 50.0}}),
|
||||
),
|
||||
p(
|
||||
"Film",
|
||||
"warm-film",
|
||||
"Warm Film",
|
||||
json!({"wb": {"mode": "custom", "temp": 6900.0, "tint": 5.0}, "curve": {"shadows": 22.0}, "grading": {"highlights": {"hue": 45.0, "sat": 15.0, "lum": 0.0}}, "grain": {"amount": 22.0, "size": 30.0, "roughness": 55.0}, "vignette": {"amount": -12.0}}),
|
||||
json!({"treatment": "color", "wb": {"mode": "custom", "temp": 6900.0, "tint": 5.0}, "curve": {"shadows": 22.0}, "grading": {"highlights": {"hue": 45.0, "sat": 15.0, "lum": 0.0}}, "grain": {"amount": 22.0, "size": 30.0, "roughness": 55.0}, "vignette": {"amount": -12.0}}),
|
||||
),
|
||||
p(
|
||||
"Film",
|
||||
"muted-film",
|
||||
"Muted Film",
|
||||
json!({"color": {"saturation": -25.0, "vibrance": 5.0}, "light": {"contrast": 10.0}, "curve": {"shadows": 18.0}, "grain": {"amount": 15.0}}),
|
||||
json!({"treatment": "color", "color": {"saturation": -25.0, "vibrance": 5.0}, "light": {"contrast": 10.0}, "curve": {"shadows": 18.0}, "grain": {"amount": 15.0}}),
|
||||
),
|
||||
p(
|
||||
"B&W",
|
||||
@@ -279,181 +303,181 @@ pub fn builtin() -> Vec<Preset> {
|
||||
"Landscape",
|
||||
"crisp-landscape",
|
||||
"Crisp Landscape",
|
||||
json!({"light": {"highlights": -45.0, "shadows": 30.0, "contrast": 12.0}, "effects": {"clarity": 22.0, "dehaze": 12.0, "texture": 15.0}, "color": {"vibrance": 25.0}}),
|
||||
json!({"treatment": "color", "light": {"highlights": -45.0, "shadows": 30.0, "contrast": 12.0}, "effects": {"clarity": 22.0, "dehaze": 12.0, "texture": 15.0}, "color": {"vibrance": 25.0}}),
|
||||
),
|
||||
p(
|
||||
"Landscape",
|
||||
"golden-hour",
|
||||
"Golden Hour",
|
||||
json!({"wb": {"mode": "custom", "temp": 7600.0, "tint": 12.0}, "light": {"highlights": -35.0, "shadows": 20.0}, "grading": {"highlights": {"hue": 38.0, "sat": 25.0, "lum": 5.0}}, "vignette": {"amount": -15.0}}),
|
||||
json!({"treatment": "color", "wb": {"mode": "custom", "temp": 7600.0, "tint": 12.0}, "light": {"highlights": -35.0, "shadows": 20.0}, "grading": {"highlights": {"hue": 38.0, "sat": 25.0, "lum": 5.0}}, "vignette": {"amount": -15.0}}),
|
||||
),
|
||||
p(
|
||||
"Landscape",
|
||||
"blue-hour",
|
||||
"Blue Hour Boost",
|
||||
json!({"wb": {"mode": "custom", "temp": 5200.0, "tint": 6.0}, "light": {"shadows": 25.0, "exposure": 0.2}, "mixer": {"blue": {"hue": 0.0, "sat": 25.0, "lum": 0.0}, "purple": {"hue": 0.0, "sat": 15.0, "lum": 0.0}}}),
|
||||
json!({"treatment": "color", "wb": {"mode": "custom", "temp": 5200.0, "tint": 6.0}, "light": {"shadows": 25.0, "exposure": 0.2}, "mixer": {"blue": {"hue": 0.0, "sat": 25.0, "lum": 0.0}, "purple": {"hue": 0.0, "sat": 15.0, "lum": 0.0}}}),
|
||||
),
|
||||
p(
|
||||
"Portrait",
|
||||
"soft-skin",
|
||||
"Soft Skin",
|
||||
json!({"effects": {"texture": -25.0, "clarity": -10.0}, "light": {"contrast": -5.0, "shadows": 15.0}, "mixer": {"orange": {"hue": 0.0, "sat": -8.0, "lum": 10.0}}}),
|
||||
json!({"treatment": "color", "effects": {"texture": -25.0, "clarity": -10.0}, "light": {"contrast": -5.0, "shadows": 15.0}, "mixer": {"orange": {"hue": 0.0, "sat": -8.0, "lum": 10.0}}}),
|
||||
),
|
||||
p(
|
||||
"Portrait",
|
||||
"bright-airy",
|
||||
"Bright & Airy",
|
||||
json!({"light": {"exposure": 0.45, "contrast": -15.0, "highlights": -40.0, "shadows": 40.0, "whites": 15.0}, "color": {"vibrance": 8.0, "saturation": -8.0}}),
|
||||
json!({"treatment": "color", "light": {"exposure": 0.45, "contrast": -15.0, "highlights": -40.0, "shadows": 40.0, "whites": 15.0}, "color": {"vibrance": 8.0, "saturation": -8.0}}),
|
||||
),
|
||||
p(
|
||||
"Style",
|
||||
"moody",
|
||||
"Moody",
|
||||
json!({"light": {"exposure": -0.3, "contrast": 20.0, "highlights": -30.0, "blacks": -15.0}, "color": {"saturation": -20.0}, "grading": {"shadows": {"hue": 200.0, "sat": 15.0, "lum": -5.0}}, "vignette": {"amount": -30.0}}),
|
||||
json!({"treatment": "color", "light": {"exposure": -0.3, "contrast": 20.0, "highlights": -30.0, "blacks": -15.0}, "color": {"saturation": -20.0}, "grading": {"shadows": {"hue": 200.0, "sat": 15.0, "lum": -5.0}}, "vignette": {"amount": -30.0}}),
|
||||
),
|
||||
p(
|
||||
"Style",
|
||||
"cinematic",
|
||||
"Cinematic",
|
||||
json!({"curve": {"shadows": 20.0, "highlights": -10.0}, "grading": {"shadows": {"hue": 190.0, "sat": 25.0, "lum": 0.0}, "highlights": {"hue": 30.0, "sat": 18.0, "lum": 0.0}}, "light": {"contrast": 15.0}, "vignette": {"amount": -20.0}}),
|
||||
json!({"treatment": "color", "curve": {"shadows": 20.0, "highlights": -10.0}, "grading": {"shadows": {"hue": 190.0, "sat": 25.0, "lum": 0.0}, "highlights": {"hue": 30.0, "sat": 18.0, "lum": 0.0}}, "light": {"contrast": 15.0}, "vignette": {"amount": -20.0}}),
|
||||
),
|
||||
// ---- Portrait
|
||||
p(
|
||||
"Portrait",
|
||||
"moody-portrait",
|
||||
"Moody Portrait",
|
||||
json!({"light": {"exposure": -0.25, "contrast": 20.0, "highlights": -30.0, "blacks": -12.0}, "color": {"saturation": -15.0}, "vignette": {"amount": -25.0, "midpoint": 40.0}, "mixer": {"orange": {"sat": 6.0}}}),
|
||||
json!({"treatment": "color", "light": {"exposure": -0.25, "contrast": 20.0, "highlights": -30.0, "blacks": -12.0}, "color": {"saturation": -15.0}, "vignette": {"amount": -25.0, "midpoint": 40.0}, "mixer": {"orange": {"sat": 6.0}}}),
|
||||
),
|
||||
p(
|
||||
"Portrait",
|
||||
"golden-glow",
|
||||
"Golden Glow",
|
||||
json!({"grading": {"highlights": {"hue": 40.0, "sat": 18.0, "lum": 0.0}, "midtones": {"hue": 35.0, "sat": 8.0, "lum": 0.0}}, "light": {"shadows": 15.0}, "effects": {"clarity": -8.0}}),
|
||||
json!({"treatment": "color", "grading": {"highlights": {"hue": 40.0, "sat": 18.0, "lum": 0.0}, "midtones": {"hue": 35.0, "sat": 8.0, "lum": 0.0}}, "light": {"shadows": 15.0}, "effects": {"clarity": -8.0}}),
|
||||
),
|
||||
p(
|
||||
"Portrait",
|
||||
"clean-studio",
|
||||
"Clean Studio",
|
||||
json!({"light": {"contrast": 10.0, "whites": 15.0, "blacks": -8.0}, "effects": {"texture": -10.0}, "color": {"vibrance": 5.0}}),
|
||||
json!({"treatment": "color", "light": {"contrast": 10.0, "whites": 15.0, "blacks": -8.0}, "effects": {"texture": -10.0}, "color": {"vibrance": 5.0}}),
|
||||
),
|
||||
// ---- Landscape
|
||||
p(
|
||||
"Landscape",
|
||||
"crisp-vista",
|
||||
"Crisp Vista",
|
||||
json!({"effects": {"dehaze": 15.0, "clarity": 18.0, "texture": 12.0}, "light": {"contrast": 12.0, "highlights": -25.0, "shadows": 18.0}, "color": {"vibrance": 20.0}}),
|
||||
json!({"treatment": "color", "effects": {"dehaze": 15.0, "clarity": 18.0, "texture": 12.0}, "light": {"contrast": 12.0, "highlights": -25.0, "shadows": 18.0}, "color": {"vibrance": 20.0}}),
|
||||
),
|
||||
p(
|
||||
"Landscape",
|
||||
"deep-sky",
|
||||
"Deep Sky",
|
||||
json!({"mixer": {"blue": {"lum": -25.0, "sat": 15.0}, "aqua": {"lum": -10.0}}, "light": {"highlights": -30.0}, "effects": {"dehaze": 10.0}}),
|
||||
json!({"treatment": "color", "mixer": {"blue": {"lum": -25.0, "sat": 15.0}, "aqua": {"lum": -10.0}}, "light": {"highlights": -30.0}, "effects": {"dehaze": 10.0}}),
|
||||
),
|
||||
p(
|
||||
"Landscape",
|
||||
"lush-greens",
|
||||
"Lush Greens",
|
||||
json!({"mixer": {"green": {"hue": 12.0, "sat": 18.0, "lum": 8.0}, "yellow": {"hue": 10.0, "sat": 10.0}}, "color": {"vibrance": 12.0}, "effects": {"clarity": 8.0}}),
|
||||
json!({"treatment": "color", "mixer": {"green": {"hue": 12.0, "sat": 18.0, "lum": 8.0}, "yellow": {"hue": 10.0, "sat": 10.0}}, "color": {"vibrance": 12.0}, "effects": {"clarity": 8.0}}),
|
||||
),
|
||||
p(
|
||||
"Landscape",
|
||||
"desert-warmth",
|
||||
"Desert Warmth",
|
||||
json!({"mixer": {"orange": {"sat": 15.0, "lum": 5.0}, "yellow": {"hue": -8.0, "sat": 10.0}, "blue": {"sat": -10.0}}, "grading": {"highlights": {"hue": 38.0, "sat": 12.0, "lum": 0.0}}, "light": {"contrast": 10.0}}),
|
||||
json!({"treatment": "color", "mixer": {"orange": {"sat": 15.0, "lum": 5.0}, "yellow": {"hue": -8.0, "sat": 10.0}, "blue": {"sat": -10.0}}, "grading": {"highlights": {"hue": 38.0, "sat": 12.0, "lum": 0.0}}, "light": {"contrast": 10.0}}),
|
||||
),
|
||||
p(
|
||||
"Landscape",
|
||||
"misty-morning",
|
||||
"Misty Morning",
|
||||
json!({"effects": {"dehaze": -18.0, "clarity": -12.0}, "light": {"contrast": -18.0, "highlights": -10.0}, "grading": {"shadows": {"hue": 210.0, "sat": 10.0, "lum": 0.0}}, "color": {"saturation": -10.0}}),
|
||||
json!({"treatment": "color", "effects": {"dehaze": -18.0, "clarity": -12.0}, "light": {"contrast": -18.0, "highlights": -10.0}, "grading": {"shadows": {"hue": 210.0, "sat": 10.0, "lum": 0.0}}, "color": {"saturation": -10.0}}),
|
||||
),
|
||||
// ---- Urban
|
||||
p(
|
||||
"Urban",
|
||||
"gritty-street",
|
||||
"Gritty Street",
|
||||
json!({"effects": {"clarity": 35.0, "texture": 20.0}, "light": {"contrast": 25.0, "blacks": -15.0}, "color": {"saturation": -30.0}, "vignette": {"amount": -18.0}}),
|
||||
json!({"treatment": "color", "effects": {"clarity": 35.0, "texture": 20.0}, "light": {"contrast": 25.0, "blacks": -15.0}, "color": {"saturation": -30.0}, "vignette": {"amount": -18.0}}),
|
||||
),
|
||||
p(
|
||||
"Urban",
|
||||
"neon-night",
|
||||
"Neon Night",
|
||||
json!({"mixer": {"magenta": {"sat": 20.0}, "purple": {"sat": 18.0}, "blue": {"sat": 12.0}, "aqua": {"sat": 15.0}}, "light": {"contrast": 18.0, "blacks": -12.0}, "color": {"vibrance": 15.0}, "grading": {"shadows": {"hue": 250.0, "sat": 15.0, "lum": 0.0}}}),
|
||||
json!({"treatment": "color", "mixer": {"magenta": {"sat": 20.0}, "purple": {"sat": 18.0}, "blue": {"sat": 12.0}, "aqua": {"sat": 15.0}}, "light": {"contrast": 18.0, "blacks": -12.0}, "color": {"vibrance": 15.0}, "grading": {"shadows": {"hue": 250.0, "sat": 15.0, "lum": 0.0}}}),
|
||||
),
|
||||
p(
|
||||
"Urban",
|
||||
"concrete-cool",
|
||||
"Concrete Cool",
|
||||
json!({"grading": {"shadows": {"hue": 205.0, "sat": 14.0, "lum": 0.0}, "highlights": {"hue": 200.0, "sat": 6.0, "lum": 0.0}}, "color": {"saturation": -20.0}, "light": {"contrast": 12.0}, "effects": {"clarity": 15.0}}),
|
||||
json!({"treatment": "color", "grading": {"shadows": {"hue": 205.0, "sat": 14.0, "lum": 0.0}, "highlights": {"hue": 200.0, "sat": 6.0, "lum": 0.0}}, "color": {"saturation": -20.0}, "light": {"contrast": 12.0}, "effects": {"clarity": 15.0}}),
|
||||
),
|
||||
p(
|
||||
"Urban",
|
||||
"faded-urban",
|
||||
"Faded Urban",
|
||||
json!({"curve": {"shadows": 30.0}, "color": {"saturation": -22.0}, "light": {"contrast": -8.0}, "grain": {"amount": 12.0, "size": 25.0, "roughness": 45.0}}),
|
||||
json!({"treatment": "color", "curve": {"shadows": 30.0}, "color": {"saturation": -22.0}, "light": {"contrast": -8.0}, "grain": {"amount": 12.0, "size": 25.0, "roughness": 45.0}}),
|
||||
),
|
||||
// ---- Food
|
||||
p(
|
||||
"Food",
|
||||
"fresh-bright",
|
||||
"Fresh & Bright",
|
||||
json!({"light": {"exposure": 0.25, "shadows": 20.0, "whites": 10.0}, "color": {"vibrance": 22.0}, "effects": {"texture": 15.0}}),
|
||||
json!({"treatment": "color", "light": {"exposure": 0.25, "shadows": 20.0, "whites": 10.0}, "color": {"vibrance": 22.0}, "effects": {"texture": 15.0}}),
|
||||
),
|
||||
p(
|
||||
"Food",
|
||||
"warm-table",
|
||||
"Warm Table",
|
||||
json!({"grading": {"midtones": {"hue": 32.0, "sat": 10.0, "lum": 0.0}}, "mixer": {"orange": {"sat": 10.0}, "red": {"sat": 8.0}}, "light": {"contrast": 8.0}}),
|
||||
json!({"treatment": "color", "grading": {"midtones": {"hue": 32.0, "sat": 10.0, "lum": 0.0}}, "mixer": {"orange": {"sat": 10.0}, "red": {"sat": 8.0}}, "light": {"contrast": 8.0}}),
|
||||
),
|
||||
p(
|
||||
"Food",
|
||||
"dark-moody-food",
|
||||
"Dark & Moody",
|
||||
json!({"light": {"exposure": -0.3, "contrast": 22.0, "highlights": -20.0, "blacks": -15.0}, "effects": {"texture": 18.0}, "vignette": {"amount": -22.0}}),
|
||||
json!({"treatment": "color", "light": {"exposure": -0.3, "contrast": 22.0, "highlights": -20.0, "blacks": -15.0}, "effects": {"texture": 18.0}, "vignette": {"amount": -22.0}}),
|
||||
),
|
||||
// ---- Seasons
|
||||
p(
|
||||
"Seasons",
|
||||
"autumn-gold",
|
||||
"Autumn Gold",
|
||||
json!({"mixer": {"green": {"hue": -30.0, "sat": -10.0}, "yellow": {"hue": -15.0, "sat": 15.0}, "orange": {"sat": 18.0}}, "grading": {"highlights": {"hue": 40.0, "sat": 10.0, "lum": 0.0}}}),
|
||||
json!({"treatment": "color", "mixer": {"green": {"hue": -30.0, "sat": -10.0}, "yellow": {"hue": -15.0, "sat": 15.0}, "orange": {"sat": 18.0}}, "grading": {"highlights": {"hue": 40.0, "sat": 10.0, "lum": 0.0}}}),
|
||||
),
|
||||
p(
|
||||
"Seasons",
|
||||
"winter-blue",
|
||||
"Winter Blue",
|
||||
json!({"grading": {"shadows": {"hue": 215.0, "sat": 18.0, "lum": 0.0}, "highlights": {"hue": 205.0, "sat": 8.0, "lum": 0.0}}, "color": {"saturation": -12.0}, "light": {"whites": 12.0}}),
|
||||
json!({"treatment": "color", "grading": {"shadows": {"hue": 215.0, "sat": 18.0, "lum": 0.0}, "highlights": {"hue": 205.0, "sat": 8.0, "lum": 0.0}}, "color": {"saturation": -12.0}, "light": {"whites": 12.0}}),
|
||||
),
|
||||
p(
|
||||
"Seasons",
|
||||
"spring-fresh",
|
||||
"Spring Fresh",
|
||||
json!({"mixer": {"green": {"hue": 10.0, "sat": 12.0, "lum": 10.0}, "magenta": {"sat": 10.0}}, "light": {"shadows": 15.0}, "color": {"vibrance": 15.0}}),
|
||||
json!({"treatment": "color", "mixer": {"green": {"hue": 10.0, "sat": 12.0, "lum": 10.0}, "magenta": {"sat": 10.0}}, "light": {"shadows": 15.0}, "color": {"vibrance": 15.0}}),
|
||||
),
|
||||
p(
|
||||
"Seasons",
|
||||
"summer-haze",
|
||||
"Summer Haze",
|
||||
json!({"effects": {"dehaze": -12.0}, "curve": {"shadows": 18.0}, "grading": {"highlights": {"hue": 45.0, "sat": 14.0, "lum": 0.0}}, "light": {"contrast": -10.0}}),
|
||||
json!({"treatment": "color", "effects": {"dehaze": -12.0}, "curve": {"shadows": 18.0}, "grading": {"highlights": {"hue": 45.0, "sat": 14.0, "lum": 0.0}}, "light": {"contrast": -10.0}}),
|
||||
),
|
||||
// ---- Vintage
|
||||
p(
|
||||
"Vintage",
|
||||
"instant-70s",
|
||||
"Instant ’70s",
|
||||
json!({"curve": {"shadows": 28.0, "highlights": -18.0}, "grading": {"shadows": {"hue": 170.0, "sat": 14.0, "lum": 0.0}, "highlights": {"hue": 45.0, "sat": 18.0, "lum": 0.0}}, "color": {"saturation": -10.0}, "vignette": {"amount": -15.0}, "grain": {"amount": 20.0, "size": 30.0, "roughness": 55.0}}),
|
||||
json!({"treatment": "color", "curve": {"shadows": 28.0, "highlights": -18.0}, "grading": {"shadows": {"hue": 170.0, "sat": 14.0, "lum": 0.0}, "highlights": {"hue": 45.0, "sat": 18.0, "lum": 0.0}}, "color": {"saturation": -10.0}, "vignette": {"amount": -15.0}, "grain": {"amount": 20.0, "size": 30.0, "roughness": 55.0}}),
|
||||
),
|
||||
p(
|
||||
"Vintage",
|
||||
"cross-process",
|
||||
"Cross Process",
|
||||
json!({"grading": {"shadows": {"hue": 230.0, "sat": 25.0, "lum": 0.0}, "highlights": {"hue": 60.0, "sat": 25.0, "lum": 0.0}}, "light": {"contrast": 22.0}, "color": {"saturation": 10.0}}),
|
||||
json!({"treatment": "color", "grading": {"shadows": {"hue": 230.0, "sat": 25.0, "lum": 0.0}, "highlights": {"hue": 60.0, "sat": 25.0, "lum": 0.0}}, "light": {"contrast": 22.0}, "color": {"saturation": 10.0}}),
|
||||
),
|
||||
p(
|
||||
"Vintage",
|
||||
"bleach-bypass",
|
||||
"Bleach Bypass",
|
||||
json!({"color": {"saturation": -40.0}, "light": {"contrast": 35.0, "highlights": -15.0}, "effects": {"clarity": 15.0}}),
|
||||
json!({"treatment": "color", "color": {"saturation": -40.0}, "light": {"contrast": 35.0, "highlights": -15.0}, "effects": {"clarity": 15.0}}),
|
||||
),
|
||||
// ---- B&W toners
|
||||
p(
|
||||
@@ -721,4 +745,140 @@ mod tests {
|
||||
assert_eq!((dv.light.exposure, dv.light.shadows, dv.grain.amount), (0.3, 20.0, 12.0));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// Issue #2159: a color preset after a B&W one brings the colors back. The treatment and the
|
||||
/// settings the color preset names take its values; a setting it does not name keeps the
|
||||
/// value the B&W preset gave it.
|
||||
#[test]
|
||||
fn a_color_preset_after_a_bw_one_returns_the_colors() {
|
||||
let mut s = Session::with_demo();
|
||||
s.execute("preset.apply", &json!({"id": "lc.bw-high-contrast"})).unwrap();
|
||||
let dv = s.develop_of(s.active().unwrap()).unwrap();
|
||||
assert_eq!(dv.treatment, lightcraft_develop::Treatment::Bw);
|
||||
s.execute("preset.apply", &json!({"id": "lc.warm-glow"})).unwrap();
|
||||
let dv = s.develop_of(s.active().unwrap()).unwrap();
|
||||
assert_eq!(dv.treatment, lightcraft_develop::Treatment::Color, "the color preset restores the treatment");
|
||||
assert_eq!(dv.light.contrast, 8.0, "the color preset's values, not the B&W preset's");
|
||||
assert_eq!(dv.light.whites, 20.0, "a setting the color preset doesn't name keeps the B&W preset's value");
|
||||
}
|
||||
|
||||
/// A manual edit to a setting a preset does not name survives it, though the preset styles
|
||||
/// the same group (Bright & Airy names exposure, contrast, highlights, shadows and whites).
|
||||
#[test]
|
||||
fn a_preset_keeps_a_setting_it_does_not_name_in_the_group_it_styles() {
|
||||
let mut s = Session::with_demo();
|
||||
s.execute("develop.set", &json!({"control": "light.blacks", "value": -30.0})).unwrap();
|
||||
s.execute("preset.apply", &json!({"id": "lc.bright-airy"})).unwrap();
|
||||
let dv = s.develop_of(s.active().unwrap()).unwrap();
|
||||
assert_eq!(dv.light.blacks, -30.0, "blacks is not named by the preset");
|
||||
assert_eq!(dv.light.exposure, 0.45, "exposure is named by the preset and takes its value");
|
||||
}
|
||||
|
||||
/// Colours a partial preset does not name keep the photo's values. Deep Sky names only the
|
||||
/// blue and aqua mixer colours, and only their luminance and saturation.
|
||||
#[test]
|
||||
fn a_preset_keeps_the_mixer_colours_it_does_not_name() {
|
||||
let mut s = Session::with_demo();
|
||||
s.execute("develop.set", &json!({"control": "mixer.red.sat", "value": 20.0})).unwrap();
|
||||
s.execute("develop.set", &json!({"control": "mixer.blue.hue", "value": 15.0})).unwrap();
|
||||
s.execute("preset.apply", &json!({"id": "lc.deep-sky"})).unwrap();
|
||||
let dv = s.develop_of(s.active().unwrap()).unwrap();
|
||||
assert_eq!(dv.mixer.red.sat, 20.0, "a colour the preset doesn't name");
|
||||
assert_eq!(dv.mixer.blue.hue, 15.0, "a setting of a named colour that the preset doesn't name");
|
||||
assert_eq!(dv.mixer.blue.lum, -25.0, "a setting the preset names takes its value");
|
||||
}
|
||||
|
||||
/// Settings that came from an XMP sidecar or a catalog import record no import look, so the
|
||||
/// camera defaults are not their original: a preset that names only some of their group keeps
|
||||
/// the rest.
|
||||
#[test]
|
||||
fn xmp_imported_exposure_whites_and_blacks_survive_crisp_landscape() {
|
||||
let mut s = Session::with_demo();
|
||||
s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.7})).unwrap();
|
||||
s.execute("develop.set", &json!({"control": "light.whites", "value": 10.0})).unwrap();
|
||||
s.execute("develop.set", &json!({"control": "light.blacks", "value": -20.0})).unwrap();
|
||||
let id = s.active().unwrap();
|
||||
assert!(s.catalog.photo(id).unwrap().import_look.is_none());
|
||||
s.execute("preset.apply", &json!({"id": "lc.crisp-landscape"})).unwrap();
|
||||
let dv = s.develop_of(id).unwrap();
|
||||
assert_eq!((dv.light.exposure, dv.light.whites, dv.light.blacks), (0.7, 10.0, -20.0));
|
||||
assert_eq!(dv.light.contrast, 12.0, "a setting the preset names takes its value");
|
||||
}
|
||||
|
||||
/// Amount 0 applies nothing to a photo with no import look: the photo keeps every value, also
|
||||
/// the exposure that Bright & Airy names (a camera-default original would reset it to 0).
|
||||
#[test]
|
||||
fn amount_zero_applies_nothing_to_a_photo_without_an_import_look() {
|
||||
let mut s = Session::with_demo();
|
||||
s.execute("develop.set", &json!({"control": "light.exposure", "value": 2.0})).unwrap();
|
||||
let id = s.active().unwrap();
|
||||
let before = s.develop_of(id).unwrap();
|
||||
s.execute("preset.apply", &json!({"id": "lc.bright-airy", "amount": 0})).unwrap();
|
||||
assert_eq!(s.develop_of(id).unwrap(), before);
|
||||
}
|
||||
|
||||
/// With no import look, a preset's amount moves the named settings from the photo's current
|
||||
/// values: 50 % of Bright & Airy's exposure (0.45) from 2.0 is 1.225.
|
||||
#[test]
|
||||
fn a_preset_amount_without_an_import_look_is_measured_from_the_current_settings() {
|
||||
let mut s = Session::with_demo();
|
||||
s.execute("develop.set", &json!({"control": "light.exposure", "value": 2.0})).unwrap();
|
||||
s.execute("preset.apply", &json!({"id": "lc.bright-airy", "amount": 50})).unwrap();
|
||||
let dv = s.develop_of(s.active().unwrap()).unwrap();
|
||||
assert!((dv.light.exposure - 1.225).abs() < 1e-9, "{}", dv.light.exposure);
|
||||
}
|
||||
|
||||
/// A photo whose default preset recorded an import look measures a preset's amount from that
|
||||
/// look: 50 % is halfway from the look to the preset whatever the photo was edited to, and
|
||||
/// 0 % gives the look's value for the settings the preset names.
|
||||
#[test]
|
||||
fn a_preset_amount_is_measured_from_the_import_look_when_there_is_one() {
|
||||
let mut s = Session::with_demo();
|
||||
let id = s.active().unwrap();
|
||||
let mut p = (**s.catalog.photo(id).unwrap()).clone();
|
||||
let mut look = p.camera_defaults();
|
||||
look.light.exposure = 0.5;
|
||||
look.light.blacks = -10.0;
|
||||
p.import_look = Some(std::sync::Arc::new(look.clone()));
|
||||
p.develop = std::sync::Arc::new(look);
|
||||
s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id: p.id }).unwrap();
|
||||
s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
s.execute("develop.set", &json!({"control": "light.exposure", "value": 2.0})).unwrap();
|
||||
s.execute("develop.set", &json!({"control": "light.blacks", "value": -30.0})).unwrap();
|
||||
s.execute("preset.apply", &json!({"id": "lc.bright-airy", "amount": 50})).unwrap();
|
||||
let dv = s.develop_of(id).unwrap();
|
||||
assert!((dv.light.exposure - 0.475).abs() < 1e-9, "{}", dv.light.exposure);
|
||||
assert_eq!(dv.light.blacks, -30.0, "a setting the preset doesn't name keeps the photo's edit");
|
||||
s.execute("preset.apply", &json!({"id": "lc.bright-airy", "amount": 0})).unwrap();
|
||||
let dv = s.develop_of(id).unwrap();
|
||||
assert_eq!(dv.light.exposure, 0.5, "amount 0 gives the import look's value for a setting the preset names");
|
||||
}
|
||||
|
||||
/// A photo whose import look records a free crop aspect (null) but whose edits locked one
|
||||
/// gets the import value back at 0 % from a preset that names the aspect: the lock is not
|
||||
/// kept (the baseline of the amount contract), the cleared option is restored.
|
||||
#[test]
|
||||
fn amount_zero_restores_a_null_import_aspect() {
|
||||
let mut s = Session::with_demo();
|
||||
let id = s.active().unwrap();
|
||||
let mut p = (**s.catalog.photo(id).unwrap()).clone();
|
||||
let look = p.camera_defaults();
|
||||
p.import_look = Some(std::sync::Arc::new(look.clone()));
|
||||
p.develop = std::sync::Arc::new(look);
|
||||
s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id: p.id }).unwrap();
|
||||
s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
s.execute("crop.aspect", &json!({"aspect": [3, 2]})).unwrap();
|
||||
assert!(s.develop_of(id).unwrap().crop.aspect.is_some(), "the aspect is locked for this test");
|
||||
let added = s.add_presets(vec![lightcraft_develop::Preset {
|
||||
id: "user.free-aspect".into(),
|
||||
name: "Free aspect".into(),
|
||||
group: "Test".into(),
|
||||
settings: json!({"crop": {"aspect": null}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
}]);
|
||||
s.execute("preset.apply", &json!({"id": added[0], "amount": 0})).unwrap();
|
||||
let dv = s.develop_of(id).unwrap();
|
||||
assert_eq!(dv.crop.aspect, None, "amount 0 gives the import look's free aspect back");
|
||||
}
|
||||
}
|
||||
@@ -775,7 +775,7 @@ mod tests {
|
||||
fn no_region_for_nothing_or_most_of_the_photo() {
|
||||
assert!(detail_region(&seg_box(50, 0, 0, 0, 0), 1.0).is_none());
|
||||
assert!(detail_region(&seg_box(50, 2, 2, 48, 48), 1.0).is_none());
|
||||
let damaged = SegMask { side: 50, data: "?".into(), rect: None };
|
||||
let damaged = SegMask { side: 50, data: "?".into(), rect: None, grid: None };
|
||||
assert!(detail_region(&damaged, 1.0).is_none());
|
||||
}
|
||||
}
|
||||
@@ -499,6 +499,39 @@ fn masks_crop_and_render() {
|
||||
s.execute("develop.wbPick", &json!({"x": 0.5, "y": 0.5})).unwrap();
|
||||
}
|
||||
|
||||
/// Auto applies to every selected photo, not only the highlighted one (#2184).
|
||||
#[test]
|
||||
fn auto_applies_to_every_selected_photo() {
|
||||
use lightcraft_catalog::PhotoId;
|
||||
let mut s = demo();
|
||||
let ids: Vec<u64> = s.catalog.photos().take(3).map(|p| p.id.0).collect();
|
||||
assert_eq!(ids.len(), 3, "the demo library has enough photos to select");
|
||||
s.execute("library.select", &json!({"ids": ids.clone(), "active": ids[1]})).unwrap();
|
||||
s.execute("develop.auto", &json!({})).unwrap();
|
||||
for id in ids {
|
||||
let d = (*s.develop_of(PhotoId(id)).unwrap()).clone();
|
||||
assert_eq!(d.light.contrast, 68.0, "photo {id} got Auto's contrast");
|
||||
assert_eq!(d.color.vibrance, 30.0, "photo {id} got Auto's vibrance");
|
||||
}
|
||||
}
|
||||
|
||||
/// A photo that can't be read is left out: the rest of the selection still gets Auto.
|
||||
#[test]
|
||||
fn auto_skips_a_selected_photo_it_cannot_read() {
|
||||
use lightcraft_catalog::{Op, Photo, PhotoId, Source};
|
||||
let mut s = demo();
|
||||
let good = s.catalog.photos().next().unwrap().id;
|
||||
let missing = s.catalog.alloc_photo_id();
|
||||
let photo = Photo::new(missing, Source::File { path: "/lightcraft-test/missing.jpg".into() }, "missing.jpg", "JPEG", 100, 100, "");
|
||||
s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap();
|
||||
s.execute("library.select", &json!({"ids": [missing.0, good.0], "active": good.0})).unwrap();
|
||||
s.execute("develop.auto", &json!({})).unwrap();
|
||||
assert_eq!(s.develop_of(PhotoId(good.0)).unwrap().color.vibrance, 30.0, "the readable photo got Auto");
|
||||
s.execute("library.select", &json!({"ids": [missing.0], "active": missing.0})).unwrap();
|
||||
assert!(s.execute("develop.auto", &json!({})).is_err(), "with nothing readable the error is reported");
|
||||
assert!(s.execute("develop.auto", &json!({"ids": [good.0, 999_999]})).is_err(), "a wrong id is refused, not skipped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versions_history_and_reset() {
|
||||
let mut s = demo();
|
||||
|
||||
@@ -189,6 +189,63 @@ fn presets_conflicts_and_subfolders() {
|
||||
assert_eq!(written, ["out/Sub/LC01347.png"]);
|
||||
}
|
||||
|
||||
/// Each of the four named delivery-target built-ins: listed as built-in, expanded to the settings the
|
||||
/// issue asks for, valid as `app.export` params, round-tripped through a user preset, and rendered at
|
||||
/// its size. A long edge is all a preset sets, so none of them crops the photo.
|
||||
#[test]
|
||||
fn named_builtin_presets_expand_round_trip_and_apply() {
|
||||
use crate::export::output_size;
|
||||
let mut s = Session::with_demo();
|
||||
// the issue's four named built-ins are listed, marked builtin
|
||||
let builtin: Vec<String> = s
|
||||
.execute("export.presets", &json!({}))
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|p| p["builtin"].as_bool().unwrap())
|
||||
.map(|p| p["name"].as_str().unwrap().to_string())
|
||||
.collect();
|
||||
// 0 = no resize: the photo's own (cropped) full size
|
||||
let issue = [
|
||||
("Instagram Feed", json!({"format": "jpeg", "quality": 85, "longEdge": 1080, "colorSpace": "srgb", "sharpen": "screen"})),
|
||||
("Instagram Story / Reel", json!({"format": "jpeg", "quality": 85, "longEdge": 1920, "colorSpace": "srgb", "sharpen": "screen"})),
|
||||
("Web / Portfolio", json!({"format": "jpeg", "quality": 85, "longEdge": 2048, "colorSpace": "srgb", "metadata": "copyright"})),
|
||||
("Full Resolution Master", json!({"format": "jpeg", "quality": 95, "longEdge": 0, "colorSpace": "displayP3"})),
|
||||
];
|
||||
for (name, settings) in &issue {
|
||||
assert!(builtin.contains(&name.to_string()), "{name}: {builtin:?}");
|
||||
// expanding one yields exactly the issue's settings, and they validate as app.export params
|
||||
let params = s.export_params(&json!({"preset": name})).unwrap();
|
||||
assert_eq!(¶ms, settings, "{name}");
|
||||
ExportOptions::validate("app.export", ¶ms).unwrap_or_else(|e| panic!("{name}: {e:?}"));
|
||||
// round trip: save as a user preset → expand again → identical ExportOptions
|
||||
let mine = format!("My {name}");
|
||||
s.execute("export.savePreset", &json!({"name": mine, "params": params})).unwrap();
|
||||
let again = s.export_params(&json!({"preset": mine})).unwrap();
|
||||
assert_eq!(ExportOptions::from_json(¶ms), ExportOptions::from_json(&again), "{name}");
|
||||
}
|
||||
// built-in names (the new ones too) are reserved
|
||||
assert!(s.execute("export.savePreset", &json!({"name": "web / portfolio", "params": {}})).is_err());
|
||||
// applying each one really renders at its size, and the photo keeps its own shape. The fixture
|
||||
// is a demo scene at 2048×1365 instead of the demo library's 6000×4000: a preset only sets a
|
||||
// long edge, so its behaviour is the same at this size, and every preset edge (1080, 1920,
|
||||
// 2048) still lands — the largest one exactly at the fixture's own size, unresized.
|
||||
use lightcraft_catalog::{Op, Photo, Source};
|
||||
let id = s.catalog.alloc_photo_id();
|
||||
let photo = Photo::new(id, Source::Demo { scene: 1 }, "LC01200.JPG", "JPEG", 2048, 1365, "2026-09-28T09:30:00");
|
||||
s.catalog.apply(Op::AddPhoto { photo: Box::new(photo.clone()) }).unwrap();
|
||||
for (name, settings) in &issue {
|
||||
let o = ExportOptions::from_json(settings);
|
||||
let e = export_photo(&mut s, id, &o, 1).unwrap();
|
||||
assert_eq!((e.width, e.height), output_size(&photo, &o), "{name}");
|
||||
match settings["longEdge"].as_u64().unwrap_or(0) {
|
||||
0 => assert!(o.resize.is_none(), "{name}: full size means no resize"),
|
||||
edge => assert_eq!(e.width.max(e.height) as u64, edge, "{name}: {}×{}", e.width, e.height),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Issue #2571: a subfolder with `..`, a root or a drive wrote outside the chosen folder. It is
|
||||
/// cleaned where the folder is used, so a preset or the Export dialog's field (which set it
|
||||
/// without `from_json`) are covered as well as command parameters.
|
||||
@@ -1463,3 +1520,33 @@ fn huge_export_size_is_an_error() {
|
||||
assert!(s.render_now(id, huge, huge).is_err());
|
||||
assert!(s.render_now(id, 10, 70_000).is_err());
|
||||
}
|
||||
|
||||
/// A user export preset whose name collides with a built-in one (in any case) is shadowed by it:
|
||||
/// the built-ins are looked up first, so the user's preset can never be selected or exported, and
|
||||
/// the save path refuses to recreate it under a free name. Loading the preferences renames it to a
|
||||
/// name of its own instead, keeping its settings.
|
||||
#[test]
|
||||
fn a_user_preset_naming_a_built_in_is_renamed_when_the_library_opens() {
|
||||
let lib = temp_dir("export-preset-rename");
|
||||
{
|
||||
let mut s = Session::new().with_fs();
|
||||
s.open_library(&lib, false).unwrap();
|
||||
s.close_library().unwrap();
|
||||
}
|
||||
std::fs::write(lib.join("prefs.json"), r#"{"exportPresets": [{"name": "web / portfolio", "params": {"format": "png", "width": 64}}]}"#).unwrap();
|
||||
let mut s = Session::new().with_fs();
|
||||
s.open_library(&lib, false).unwrap();
|
||||
|
||||
let builtins: Vec<String> = crate::export::builtin_presets().into_iter().map(|p| p.name).collect();
|
||||
assert_eq!(s.export_presets.len(), 1, "the user's preset is kept");
|
||||
let name = s.export_presets[0].name.clone();
|
||||
assert!(!builtins.iter().any(|b| b.eq_ignore_ascii_case(&name)), "{name} still shadows a built-in");
|
||||
assert_eq!(s.export_presets[0].params, json!({"format": "png", "width": 64}), "its settings are kept");
|
||||
// it is reachable under its own name: the export takes the user's settings
|
||||
let p = s.export_params(&json!({"preset": name})).unwrap();
|
||||
assert_eq!((p["format"].as_str(), p["width"].as_u64()), (Some("png"), Some(64)), "{p}");
|
||||
// and the built-in of that name is still the built-in
|
||||
let b = s.export_params(&json!({"preset": "Web / Portfolio"})).unwrap();
|
||||
assert_eq!((b["format"].as_str(), b["longEdge"].as_u64()), (Some("jpeg"), Some(2048)), "{b}");
|
||||
let _ = std::fs::remove_dir_all(&lib);
|
||||
}
|
||||
@@ -853,7 +853,7 @@ fn import_rename_sequence_keeps_flushed_copy_and_move_results() {
|
||||
assert!(paths[3].is_file(), "the failed source remains in place");
|
||||
assert_eq!(r["moved"].as_array().map(Vec::len), Some(3), "{r}");
|
||||
}
|
||||
_ => unreachable!(),
|
||||
other => panic!("no such mode: {other}"),
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -2172,6 +2172,216 @@ fn expand_stops_at_the_walk_limits() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// `levels` folders named `d` nested below `root` (created); the innermost one's path.
|
||||
fn nested(root: &Path, levels: usize) -> std::path::PathBuf {
|
||||
let mut dir = root.to_path_buf();
|
||||
for _ in 0..levels {
|
||||
dir = dir.join("d");
|
||||
}
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// Expanding folders reports what the walks left out — files of an unsupported type, a walk that
|
||||
/// stopped at a bound — and returns the same files as `expand_within`; a file named on its own is
|
||||
/// attempted whatever its extension and is not counted as unsupported.
|
||||
#[test]
|
||||
fn expand_report_counts_what_the_walks_left_out() {
|
||||
use crate::import::{expand_report, expand_within};
|
||||
let d = temp_dir("expand-report");
|
||||
write_png(&d.join("a.png"), 1);
|
||||
write_png(&d.join("sub/b.png"), 2);
|
||||
std::fs::write(d.join("notes.txt"), "x").unwrap();
|
||||
std::fs::write(d.join("sub/readme.md"), "x").unwrap();
|
||||
std::fs::write(d.join("sub/.hidden.txt"), "x").unwrap();
|
||||
let named = temp_dir("expand-report-named");
|
||||
std::fs::write(named.join("odd.dat"), "x").unwrap();
|
||||
let paths = [d.to_string_lossy().to_string(), named.join("odd.dat").to_string_lossy().to_string()];
|
||||
let limits = crate::walk::Limits::default();
|
||||
|
||||
let e = expand_report(&paths, None, limits);
|
||||
assert_eq!(e.files.len(), 3, "both photos and the named file: {:?}", e.files);
|
||||
assert_eq!((e.unsupported, e.unreadable, e.truncated), (2, 0, false), "notes.txt and readme.md; the hidden file is not counted: {e:?}");
|
||||
assert_eq!(expand_within(&paths, None, limits), (e.files.clone(), false), "expand_within is the same walk");
|
||||
|
||||
// stopping one level down: the second folder is never listed, so its files are not counted
|
||||
let e = expand_report(&paths[..1], None, crate::walk::Limits { max_depth: 1, max_entries: 1000 });
|
||||
assert_eq!((e.files.len(), e.unsupported, e.truncated), (1, 1, true), "{e:?}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
let _ = std::fs::remove_dir_all(&named);
|
||||
}
|
||||
|
||||
/// A scan says that its folder walk stopped at the depth limit (there may be more photos), and
|
||||
/// does not when the tree ends within it.
|
||||
#[test]
|
||||
fn scan_with_reports_a_walk_that_stopped_at_a_bound() {
|
||||
use crate::import::{ScanInput, ScanProgress, scan_with};
|
||||
let scan = |dir: &Path| {
|
||||
let mut s = Session::new().with_fs();
|
||||
let (input, paths) = ScanInput::new(&mut s, &[dir.to_string_lossy().to_string()]);
|
||||
scan_with(input, &paths, &ScanProgress::default())
|
||||
};
|
||||
// the deepest folder a walk lists is one level above the limit; one more folder is never entered
|
||||
let cut = temp_dir("scan-cut");
|
||||
write_png(&cut.join("top.png"), 1);
|
||||
write_png(&nested(&cut, crate::walk::MAX_DEPTH - 1).join("last.png"), 2);
|
||||
nested(&cut, crate::walk::MAX_DEPTH);
|
||||
let out = scan(&cut);
|
||||
assert_eq!(out.candidates.len(), 2, "what was reached is still returned");
|
||||
assert_eq!((out.truncated, out.unreadable, out.unsupported), (true, 0, 0));
|
||||
|
||||
let whole = temp_dir("scan-whole");
|
||||
write_png(&whole.join("top.png"), 1);
|
||||
write_png(&nested(&whole, crate::walk::MAX_DEPTH - 1).join("last.png"), 2);
|
||||
let out = scan(&whole);
|
||||
assert_eq!(out.candidates.len(), 2);
|
||||
assert_eq!((out.truncated, out.unreadable, out.unsupported), (false, 0, 0));
|
||||
let _ = std::fs::remove_dir_all(&cut);
|
||||
let _ = std::fs::remove_dir_all(&whole);
|
||||
}
|
||||
|
||||
/// A folder this process is not allowed to list, until it is dropped (Unix: no permissions;
|
||||
/// Windows: a deny entry for Everyone on listing it).
|
||||
struct Unlistable(std::path::PathBuf);
|
||||
|
||||
impl Unlistable {
|
||||
/// `None` when the folder can still be listed (the super-user ignores permissions) or the
|
||||
/// means to deny it is missing: the test then has nothing to check.
|
||||
fn new(dir: &Path) -> Option<Unlistable> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o000)).ok()?;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let denied = std::process::Command::new("icacls").arg(dir).args(["/deny", "*S-1-1-0:(RD)"]).output();
|
||||
if !denied.is_ok_and(|o| o.status.success()) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// from here the folder is restored on drop, whatever the test does
|
||||
let guard = Unlistable(dir.to_path_buf());
|
||||
std::fs::read_dir(dir).is_err().then_some(guard)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Unlistable {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = std::process::Command::new("icacls").arg(&self.0).args(["/remove:d", "*S-1-1-0"]).output();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder the scan can't list is counted — by the scan and by `library.importPreview` — and the
|
||||
/// photos around it are still found.
|
||||
#[test]
|
||||
fn an_unlistable_folder_is_reported_by_the_scan() {
|
||||
use crate::import::{ScanInput, ScanProgress, scan_with};
|
||||
let src = temp_dir("unlistable");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
write_png(&src.join("locked").join("b.png"), 2);
|
||||
let Some(locked) = Unlistable::new(&src.join("locked")) else {
|
||||
eprintln!("skipped: this process can still list a folder it was denied");
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
return;
|
||||
};
|
||||
let mut s = Session::new().with_fs();
|
||||
let (input, paths) = ScanInput::new(&mut s, &[src.to_string_lossy().to_string()]);
|
||||
let out = scan_with(input, &paths, &ScanProgress::default());
|
||||
assert_eq!(out.candidates.len(), 1, "only the photo outside the folder");
|
||||
assert_eq!((out.unreadable, out.unsupported, out.truncated), (1, 0, false));
|
||||
let r = s.execute("library.importPreview", &json!({"paths": [src.to_string_lossy()]})).unwrap();
|
||||
assert_eq!((r["scanned"].clone(), r["skipped"].clone()), (json!(1), json!({"unreadable": 1, "unsupported": 0})), "{r}");
|
||||
drop(locked);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// `library.importPreview` reports the walk's diagnostics next to the keys it always returned, and
|
||||
/// still leaves its probes for the import that follows.
|
||||
#[test]
|
||||
fn import_preview_reports_what_the_scan_skipped() {
|
||||
let src = temp_dir("preview-diag");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
write_png(&src.join("sub/b.png"), 2);
|
||||
std::fs::write(src.join("notes.txt"), b"not a photo").unwrap();
|
||||
std::fs::write(src.join("sub/readme.md"), b"x").unwrap();
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.importPreview", &json!({"paths": [src.to_string_lossy()]})).unwrap();
|
||||
assert_eq!((r["scanned"].clone(), r["duplicates"].clone()), (json!(2), json!(0)), "{r}");
|
||||
assert_eq!(ids(&r, "candidates"), 2, "{r}");
|
||||
assert_eq!(r["scanLimited"], false, "{r}");
|
||||
assert_eq!(r["skipped"], json!({"unreadable": 0, "unsupported": 2}), "notes.txt and readme.md are reported: {r}");
|
||||
for f in [src.join("a.png"), src.join("sub").join("b.png")] {
|
||||
let key = f.to_string_lossy().to_string();
|
||||
assert!(s.import_probes.contains_key(&key), "the probe of {key} is kept for the import: {:?}", s.import_probes.keys());
|
||||
}
|
||||
// a second preview reuses them: a file that has not changed is not read again
|
||||
let reads = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let (counted, probe) = (reads.clone(), s.media.file_probe.clone().unwrap());
|
||||
s.media.file_probe = Some(std::sync::Arc::new(move |path: &str| {
|
||||
counted.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
probe(path)
|
||||
}));
|
||||
let again = s.execute("library.importPreview", &json!({"paths": [src.to_string_lossy()]})).unwrap();
|
||||
assert_eq!(again["scanned"], 2, "{again}");
|
||||
assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 0, "the first preview's probes are reused");
|
||||
|
||||
// a file named on its own is tried, not reported as skipped
|
||||
let r = s.execute("library.importPreview", &json!({"paths": [src.join("notes.txt").to_string_lossy()]})).unwrap();
|
||||
assert_eq!((r["scanned"].clone(), r["skipped"]["unsupported"].clone()), (json!(1), json!(0)), "{r}");
|
||||
|
||||
// a walk that stopped at the depth limit says so
|
||||
let deep = temp_dir("preview-deep");
|
||||
write_png(&deep.join("top.png"), 3);
|
||||
nested(&deep, crate::walk::MAX_DEPTH);
|
||||
let r = s.execute("library.importPreview", &json!({"paths": [deep.to_string_lossy()]})).unwrap();
|
||||
assert_eq!((r["scanned"].clone(), r["scanLimited"].clone()), (json!(1), json!(true)), "{r}");
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
let _ = std::fs::remove_dir_all(&deep);
|
||||
}
|
||||
|
||||
/// XMP sidecars are read with their photos, so they are not "skipped": the expansion, the scan and
|
||||
/// `library.importPreview` count them (in any letter case, in subfolders too) as nothing, and still
|
||||
/// count every other file that is not a photo.
|
||||
#[test]
|
||||
fn xmp_sidecars_are_not_counted_as_unsupported() {
|
||||
use crate::import::{ScanInput, ScanProgress, expand_report, scan_with};
|
||||
let mut s = Session::new().with_fs();
|
||||
// sidecars beside a photo, a sidecar without one, in any case, one deeper; plus a text file
|
||||
let mixed = temp_dir("sidecars-mixed");
|
||||
write_png(&mixed.join("a.png"), 1);
|
||||
std::fs::write(mixed.join("a.xmp"), b"x").unwrap();
|
||||
std::fs::write(mixed.join("b.XMP"), b"x").unwrap();
|
||||
std::fs::create_dir_all(mixed.join("sub")).unwrap();
|
||||
std::fs::write(mixed.join("sub").join("c.Xmp"), b"x").unwrap();
|
||||
std::fs::write(mixed.join("c.txt"), b"x").unwrap();
|
||||
// only photos and sidecars
|
||||
let tidy = temp_dir("sidecars-only");
|
||||
write_png(&tidy.join("a.png"), 2);
|
||||
std::fs::write(tidy.join("a.xmp"), b"x").unwrap();
|
||||
std::fs::write(tidy.join("b.XMP"), b"x").unwrap();
|
||||
for (dir, unsupported) in [(&mixed, 1usize), (&tidy, 0)] {
|
||||
let path = dir.to_string_lossy().to_string();
|
||||
let e = expand_report(std::slice::from_ref(&path), None, crate::walk::Limits::default());
|
||||
assert_eq!((e.files.len(), e.unsupported), (1, unsupported), "expand_report {e:?}");
|
||||
let (input, paths) = ScanInput::new(&mut s, std::slice::from_ref(&path));
|
||||
let out = scan_with(input, &paths, &ScanProgress::default());
|
||||
assert_eq!((out.candidates.len(), out.unsupported), (1, unsupported), "scan_with");
|
||||
let r = s.execute("library.importPreview", &json!({"paths": [path]})).unwrap();
|
||||
assert_eq!((r["scanned"].clone(), r["skipped"]["unsupported"].clone()), (json!(1), json!(unsupported)), "{r}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&mixed);
|
||||
let _ = std::fs::remove_dir_all(&tidy);
|
||||
}
|
||||
|
||||
/// Raw containers LightCraft cannot decode but shows by their embedded JPEG are picked up from a folder
|
||||
/// (the extensions are in `import::EXTENSIONS`; the files differ so none is a duplicate) and import as preview only.
|
||||
#[test]
|
||||
@@ -2938,6 +3148,319 @@ fn a_file_arriving_beside_its_raws_stem_reads_its_own_sidecar() {
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// A batch-edit recipe changes the imported photos' actual develop settings (not just an option
|
||||
/// label), renders, is one undo step, and can be saved as a preset that stores only what it names.
|
||||
#[test]
|
||||
fn a_batch_edit_recipe_changes_imported_photos() {
|
||||
let src = temp_dir("recipe");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
write_png(&src.join("b.png"), 2);
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s
|
||||
.execute(
|
||||
"library.import",
|
||||
&json!({
|
||||
"paths": [src.to_string_lossy()],
|
||||
"recipe": [{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}],
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 2, "{r}");
|
||||
for p in s.catalog.photos() {
|
||||
assert_eq!(p.develop.light.exposure, 0.5, "{}", p.file_name);
|
||||
assert_eq!(p.develop.color.vibrance, 20.0, "{}", p.file_name);
|
||||
assert!(p.history.iter().any(|h| h.label == "Import adjustments"), "{}", p.file_name);
|
||||
}
|
||||
// the edit really renders (the recipe is applied to the settings, not only recorded)
|
||||
let id = s.catalog.photos().next().unwrap().id;
|
||||
assert!(s.render_now(id, 32, 32).is_ok());
|
||||
// saving the recipe as a preset keeps only the settings it names
|
||||
let p = s.execute("preset.saveRecipe", &json!({"name": "Warm Trip", "recipe": [{"id": "light.exposure", "value": 0.5}]})).unwrap();
|
||||
let saved = s.presets.iter().find(|x| x.id == p["id"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(saved.settings.pointer("/light/exposure"), Some(&json!(0.5)), "{}", saved.settings);
|
||||
assert!(saved.settings.get("color").is_none(), "an unnamed group is not stored: {}", saved.settings);
|
||||
// one undo step for the whole import
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.catalog.len(), 0);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// A malformed recipe, or one naming a control a recipe may not name, is refused before anything
|
||||
/// is imported, and by the command that saves one: unknown ids, controls that belong to one photo,
|
||||
/// geometry and crop controls (the slider refits the crop around them), white balance (a
|
||||
/// temperature means something else on each kind of file), and lists longer than the control list.
|
||||
#[test]
|
||||
fn a_bad_recipe_is_refused() {
|
||||
let mut s = Session::new().with_fs();
|
||||
let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": [{"id": "nope.nope", "value": 1}]})).unwrap_err();
|
||||
assert!(format!("{err}").contains("unknown recipe control"), "{err}");
|
||||
let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": "x"})).unwrap_err();
|
||||
assert!(format!("{err}").contains("recipe"), "{err}");
|
||||
assert_eq!(s.catalog.len(), 0);
|
||||
let too_many: Vec<Value> = (0..lightcraft_develop::controls::CONTROLS.len() + 1).map(|_| json!({"id": "light.exposure", "value": 1})).collect();
|
||||
for (bad, why) in [
|
||||
(json!([{"value": 1}]), "needs an `id`"),
|
||||
(json!([{"id": "light.exposure"}]), "numeric"),
|
||||
(json!([{"id": "light.exposure", "value": "high"}]), "numeric"),
|
||||
(json!([7]), "needs an `id`"),
|
||||
(json!([{"id": "pointColor.0.hueShift", "value": 5}]), "unknown recipe control"),
|
||||
(json!([{"id": "redEye.0.pupilSize", "value": 5}]), "unknown recipe control"),
|
||||
(json!([{"id": "crop.angle", "value": 5}]), "geometry"),
|
||||
(json!([{"id": "geometry.rotate", "value": 5}]), "geometry"),
|
||||
(json!([{"id": "wb.temp", "value": 5200}]), "white balance"),
|
||||
(json!([{"id": "wb.tint", "value": 5}]), "white balance"),
|
||||
(json!([{"id": "light.exposure", "value": 1}, {"id": "crop.angle", "value": 5}]), "geometry"),
|
||||
(json!(too_many), "at most"),
|
||||
] {
|
||||
let err = s.execute("library.import", &json!({"paths": ["/nonexistent-lc"], "recipe": bad})).unwrap_err().to_string();
|
||||
assert!(err.contains(why), "{why}: {err}");
|
||||
let before = s.presets.len();
|
||||
let err = s.execute("preset.saveRecipe", &json!({"name": "Bad", "recipe": bad})).unwrap_err().to_string();
|
||||
assert!(err.contains(why), "{why}: {err}");
|
||||
assert_eq!(s.presets.len(), before, "nothing saved for {why}");
|
||||
}
|
||||
// the job itself refuses what the command would (a recipe built in code, not from JSON)
|
||||
let opts = crate::import::ImportOptions { recipe: vec![("crop.angle".into(), 5.0)], ..Default::default() };
|
||||
assert!(crate::import::ImportJob::new(&mut s, opts).is_err());
|
||||
// no name, a name that is too long, or nothing in the recipe: no preset
|
||||
let one = json!([{"id": "light.exposure", "value": 1}]);
|
||||
for params in [json!({"recipe": one}), json!({"name": " ", "recipe": one}), json!({"name": "x".repeat(101), "recipe": one})] {
|
||||
assert!(s.execute("preset.saveRecipe", ¶ms).is_err(), "{params}");
|
||||
}
|
||||
assert!(s.execute("preset.saveRecipe", &json!({"name": "x".repeat(100), "recipe": one})).is_ok(), "a name of 100 characters is fine");
|
||||
assert!(s.execute("preset.saveRecipe", &json!({"name": "Empty", "recipe": []})).is_err());
|
||||
assert!(s.execute("preset.saveRecipe", &json!({"name": "Empty"})).is_err());
|
||||
assert!(!s.presets.iter().any(|p| p.name == "Empty"));
|
||||
}
|
||||
|
||||
/// The recipe's values go through the control specs like a slider's: past the range they stop at
|
||||
/// it, for the photo and for the preset. A control named twice counts once, the last value wins.
|
||||
#[test]
|
||||
fn recipe_values_are_clamped_like_a_slider() {
|
||||
let src = temp_dir("recipe-clamp");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
let mut s = Session::new().with_fs();
|
||||
let recipe = json!([{"id": "light.exposure", "value": 1}, {"id": "light.exposure", "value": 99}, {"id": "light.contrast", "value": -1000}]);
|
||||
s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": recipe})).unwrap();
|
||||
let p = s.catalog.photos().next().unwrap();
|
||||
assert_eq!((p.develop.light.exposure, p.develop.light.contrast), (5.0, -100.0));
|
||||
let saved = s.execute("preset.saveRecipe", &json!({"name": "Clamped", "recipe": recipe})).unwrap();
|
||||
let saved = s.presets.iter().find(|x| x.id == saved["id"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(saved.settings.pointer("/light/exposure"), Some(&json!(5.0)), "{}", saved.settings);
|
||||
assert_eq!(saved.settings.pointer("/light/contrast"), Some(&json!(-100.0)), "{}", saved.settings);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// A session whose files probe as DNG raws shot at 4800 K, tint +12 (the pixels stay the PNG's;
|
||||
/// nothing here renders them), to see what an import does to a raw's as-shot white balance.
|
||||
fn session_with_raw_probe() -> Session {
|
||||
let mut s = Session::new().with_fs();
|
||||
let real = s.media.file_probe.clone().unwrap();
|
||||
s.media.file_probe = Some(std::sync::Arc::new(move |path: &str| {
|
||||
let mut info = real(path)?;
|
||||
info.kind = lightcraft_catalog::MediaKind::Raw;
|
||||
info.format = "DNG".into();
|
||||
info.as_shot_wb = Some((4800.0, 12.0));
|
||||
Ok(info)
|
||||
}));
|
||||
s
|
||||
}
|
||||
|
||||
fn import_one(s: &mut Session, path: &Path, recipe: Value) -> lightcraft_catalog::PhotoId {
|
||||
let r = s.execute("library.import", &json!({"paths": [path.to_string_lossy()], "recipe": recipe})).unwrap();
|
||||
lightcraft_catalog::PhotoId(r["imported"][0].as_u64().unwrap_or_else(|| panic!("{path:?} not imported: {r}")))
|
||||
}
|
||||
|
||||
fn white_balance(s: &Session, id: lightcraft_catalog::PhotoId) -> lightcraft_develop::WhiteBalance {
|
||||
s.catalog.photo(id).unwrap().develop.wb
|
||||
}
|
||||
|
||||
/// A recipe never touches white balance: a raw keeps the as-shot temperature, tint and scale it was
|
||||
/// imported with, whatever else the recipe sets, and a recipe cannot name a temperature or tint.
|
||||
#[test]
|
||||
fn a_recipe_leaves_a_raws_as_shot_white_balance_alone() {
|
||||
use lightcraft_develop::{WbMode, WbScale};
|
||||
let src = temp_dir("recipe-wb");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
write_png(&src.join("b.png"), 2);
|
||||
let mut s = session_with_raw_probe();
|
||||
let plain = import_one(&mut s, &src.join("a.png"), json!([]));
|
||||
let w = white_balance(&s, plain);
|
||||
assert_eq!((w.mode, w.temp, w.tint, w.scale), (WbMode::AsShot, 4800.0, 12.0, WbScale::Kelvin), "{w:?}");
|
||||
let with = import_one(&mut s, &src.join("b.png"), json!([{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 30}]));
|
||||
assert_eq!(white_balance(&s, with), w, "the as-shot white balance is as the import left it");
|
||||
assert_eq!(s.catalog.photo(with).unwrap().develop.light.exposure, 0.5);
|
||||
for id in ["wb.temp", "wb.tint"] {
|
||||
let err = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": [{"id": id, "value": 5200}]})).unwrap_err();
|
||||
assert!(err.to_string().contains("white balance"), "{err}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// Saved as a preset and applied to a photo as it was imported, a recipe gives the settings
|
||||
/// importing with it gives (for a raw too), and the preset holds a control the recipe sets to its
|
||||
/// default: that is a reset, not "nothing named".
|
||||
#[test]
|
||||
fn a_recipe_saved_as_a_preset_gives_what_the_recipe_gives() {
|
||||
let src = temp_dir("recipe-preset");
|
||||
let recipes = [
|
||||
json!([{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}]),
|
||||
json!([{"id": "light.exposure", "value": 99}]),
|
||||
json!([{"id": "detail.sharpenAmount", "value": 0}, {"id": "grain.amount", "value": 30}]),
|
||||
json!([{"id": "vignette.amount", "value": -25}, {"id": "effects.clarity", "value": 15}, {"id": "mixer.red.hue", "value": 10}]),
|
||||
];
|
||||
let mut s = session_with_raw_probe();
|
||||
for (i, recipe) in recipes.iter().enumerate() {
|
||||
write_png(&src.join(format!("with{i}.png")), 2 * i as u8);
|
||||
write_png(&src.join(format!("plain{i}.png")), 2 * i as u8 + 1);
|
||||
let with = import_one(&mut s, &src.join(format!("with{i}.png")), recipe.clone());
|
||||
let plain = import_one(&mut s, &src.join(format!("plain{i}.png")), json!([]));
|
||||
let saved = s.execute("preset.saveRecipe", &json!({"name": format!("Recipe {i}"), "recipe": recipe})).unwrap();
|
||||
s.selection = crate::Selection::single(plain);
|
||||
s.execute("preset.apply", &json!({"id": saved["id"], "ids": [plain.0]})).unwrap();
|
||||
let (with, plain) = (s.catalog.photo(with).unwrap(), s.catalog.photo(plain).unwrap());
|
||||
assert_eq!(with.develop, plain.develop, "recipe {recipe}");
|
||||
}
|
||||
// the sharpening reset (a raw's default is 40) is in the preset although 0 is the control's default
|
||||
let reset = s.presets.iter().find(|p| p.name == "Recipe 2").unwrap();
|
||||
assert_eq!(reset.settings.pointer("/detail/sharpen_amount"), Some(&json!(0.0)), "{}", reset.settings);
|
||||
assert_eq!(s.catalog.photos().find(|p| p.file_name == "with2.png").unwrap().develop.detail.sharpen_amount, 0.0);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// The recipe applies to the photos an import adds. A file the library has (by path or by
|
||||
/// content), a trashed one that comes back, and a browsed one that joins keep their own
|
||||
/// settings; a trashed one imported afresh is a new photo and gets the recipe.
|
||||
#[test]
|
||||
fn a_recipe_only_touches_the_photos_an_import_adds() {
|
||||
let src = temp_dir("recipe-skipped");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
write_png(&src.join("b.png"), 2);
|
||||
write_png(&src.join("c.png"), 3);
|
||||
std::fs::copy(src.join("a.png"), src.join("a-copy.png")).unwrap(); // same bytes as a
|
||||
let recipe = json!([{"id": "color.vibrance", "value": 20}]);
|
||||
let adjusted = |s: &Session, name: &str| {
|
||||
let p = s.catalog.photos().find(|p| p.file_name == name && !p.deleted).unwrap_or_else(|| panic!("no {name}"));
|
||||
(p.develop.color.vibrance, p.history.iter().any(|h| h.label == "Import adjustments"))
|
||||
};
|
||||
|
||||
let mut s = Session::new().with_fs();
|
||||
let first = import_one(&mut s, &src.join("a.png"), json!([]));
|
||||
s.selection = crate::Selection::single(first);
|
||||
s.execute("develop.set", &json!({"control": "light.exposure", "value": 1.5})).unwrap();
|
||||
let a_before = s.catalog.photo(first).unwrap().develop.clone();
|
||||
|
||||
let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()], "recipe": recipe})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 2, "{r}"); // b and c
|
||||
assert_eq!(ids(&r, "duplicates"), 2, "{r}"); // a (same path) and a-copy (same content)
|
||||
assert_eq!(adjusted(&s, "b.png"), (20.0, true));
|
||||
assert_eq!(adjusted(&s, "c.png"), (20.0, true));
|
||||
assert_eq!(adjusted(&s, "a.png"), (0.0, false), "a duplicate is not edited");
|
||||
assert_eq!(s.catalog.photo(first).unwrap().develop, a_before, "nor is the photo it duplicates");
|
||||
assert_eq!(s.catalog.len(), 3);
|
||||
|
||||
// in Recently Deleted: restored with its own settings, no recipe
|
||||
s.execute("photo.delete", &json!({"ids": [first.0]})).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()], "recipe": recipe})).unwrap();
|
||||
assert_eq!((ids(&r, "imported"), ids(&r, "restored")), (0, 1), "{r}");
|
||||
assert_eq!(s.catalog.photo(first).unwrap().develop, a_before, "a restored photo keeps its edits");
|
||||
assert!(!s.catalog.photo(first).unwrap().history.iter().any(|h| h.label == "Import adjustments"));
|
||||
|
||||
// …imported afresh, it is a new photo and gets the recipe
|
||||
s.execute("photo.delete", &json!({"ids": [first.0]})).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()], "recipe": recipe, "onDeleted": "fresh"})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 1, "{r}");
|
||||
assert_eq!(adjusted(&s, "a.png"), (20.0, true));
|
||||
|
||||
// browsed first (Local), then imported: the record joins the library as it is, as it does for
|
||||
// a preset or keywords
|
||||
let other = temp_dir("recipe-browsed");
|
||||
write_png(&other.join("d.png"), 4);
|
||||
s.execute("library.browse", &json!({"path": other.to_string_lossy()})).unwrap();
|
||||
let r = s.execute("library.import", &json!({"paths": [other.join("d.png").to_string_lossy()], "recipe": recipe})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 1, "{r}");
|
||||
assert_eq!(adjusted(&s, "d.png"), (0.0, false), "a browsed photo that joins keeps its own settings");
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
let _ = std::fs::remove_dir_all(&other);
|
||||
}
|
||||
|
||||
/// A saved recipe never takes another preset's id: with presets A and B, A deleted, a recipe saved
|
||||
/// as "B" is its own preset and applying it applies the recipe, not the older B. Saving the same
|
||||
/// recipe under the same name again is that preset, and the presets are in presets.json.
|
||||
#[test]
|
||||
fn saved_recipe_presets_get_distinct_ids_and_survive_reopening() {
|
||||
let lib = temp_dir("recipe-presets-lib");
|
||||
let src = temp_dir("recipe-presets-src");
|
||||
write_png(&src.join("a.png"), 1);
|
||||
let mut s = Session::new().with_fs();
|
||||
s.open_library(&lib, false).unwrap();
|
||||
let photo = import_one(&mut s, &src.join("a.png"), json!([]));
|
||||
s.selection = crate::Selection::single(photo);
|
||||
let create = |s: &mut Session, name: &str| s.execute("preset.create", &json!({"name": name})).unwrap()["id"].as_str().unwrap().to_string();
|
||||
let (a, old_b) = (create(&mut s, "A"), create(&mut s, "B"));
|
||||
s.execute("preset.delete", &json!({"id": a})).unwrap();
|
||||
let recipe = json!([{"id": "light.exposure", "value": 0.7}]);
|
||||
let saved = s.execute("preset.saveRecipe", &json!({"name": "B", "group": "User Presets", "recipe": recipe})).unwrap();
|
||||
let new_b = saved["id"].as_str().unwrap().to_string();
|
||||
assert_ne!(new_b, old_b);
|
||||
let mut all: Vec<&str> = s.presets.iter().map(|p| p.id.as_str()).collect();
|
||||
let n = all.len();
|
||||
all.sort();
|
||||
all.dedup();
|
||||
assert_eq!(all.len(), n, "every preset has its own id");
|
||||
s.execute("preset.apply", &json!({"id": new_b})).unwrap();
|
||||
assert_eq!(s.catalog.photo(photo).unwrap().develop.light.exposure, 0.7, "the saved recipe is what gets applied");
|
||||
// the same recipe, name and group: the preset it already is
|
||||
let again = s.execute("preset.saveRecipe", &json!({"name": "B", "group": "User Presets", "recipe": recipe})).unwrap();
|
||||
assert_eq!(again["id"], saved["id"]);
|
||||
assert_eq!(s.presets.iter().filter(|p| p.name == "B").count(), 2);
|
||||
drop(s);
|
||||
|
||||
let mut t = Session::new().with_fs();
|
||||
t.open_library(&lib, false).unwrap();
|
||||
let mut bs: Vec<&str> = t.presets.iter().filter(|p| p.name == "B").map(|p| p.id.as_str()).collect();
|
||||
bs.sort();
|
||||
let mut expected = [old_b.as_str(), new_b.as_str()];
|
||||
expected.sort();
|
||||
assert_eq!(bs, expected, "both are still there after reopening");
|
||||
assert!(!t.presets.iter().any(|p| p.name == "A"), "the deleted one stays deleted");
|
||||
drop(t);
|
||||
let _ = std::fs::remove_dir_all(&lib);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// Both commands are in the command list with their parameters documented, which is where the
|
||||
/// control channel, the CLI and MCP's `list_commands` read them.
|
||||
#[test]
|
||||
fn the_recipe_commands_are_listed_with_their_parameters() {
|
||||
let s = Session::new();
|
||||
let commands = s.commands();
|
||||
let import = commands.iter().find(|c| c.id == "library.import").unwrap();
|
||||
assert!(import.params.contains("recipe?: [{id:") && import.params.contains("Import adjustments"), "{}", import.params);
|
||||
assert!(import.params.contains("no white balance, geometry or crop") && import.params.contains("is not changed"), "{}", import.params);
|
||||
let save = commands.iter().find(|c| c.id == "preset.saveRecipe").expect("preset.saveRecipe is a command");
|
||||
assert!(save.enabled && save.params.contains("recipe: [{id:") && save.params.contains("name"), "{}", save.params);
|
||||
}
|
||||
|
||||
/// A saved recipe that resets an HDR control to its default is applied as the recipe would apply it:
|
||||
/// alone, and next to another adjustment, on a photo whose HDR settings are not the default.
|
||||
#[test]
|
||||
fn a_saved_hdr_reset_applies_to_existing_hdr_settings() {
|
||||
let mut s = Session::new();
|
||||
for recipe in [json!([{"id": "hdr.maxEv", "value": 3}]), json!([{"id": "hdr.maxEv", "value": 3}, {"id": "light.exposure", "value": 0.5}])] {
|
||||
let p = s.execute("preset.saveRecipe", &json!({"name": format!("Reset {recipe}"), "recipe": recipe})).unwrap();
|
||||
let saved = s.presets.iter().find(|x| x.id == p["id"].as_str().unwrap()).unwrap().settings.clone();
|
||||
let mut base = lightcraft_develop::DevelopSettings::default();
|
||||
base.hdr.enabled = true;
|
||||
base.hdr.max_ev = 1.5;
|
||||
let out = lightcraft_develop::apply_partial(&base, &saved, 1.0);
|
||||
assert_eq!(out.hdr.max_ev, 3.0, "{saved}");
|
||||
assert!(out.hdr.enabled, "the reset leaves the other HDR settings alone: {saved}");
|
||||
let want_exposure = if recipe.as_array().unwrap().len() > 1 { 0.5 } else { base.light.exposure };
|
||||
assert_eq!(out.light.exposure, want_exposure, "{saved}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder's one spelling: `.` is the current folder, `.` and `..` are taken out, never above the
|
||||
/// root (CodeRabbit on #3055 / #3080).
|
||||
#[test]
|
||||
|
||||
@@ -41,6 +41,13 @@ pub struct Walked {
|
||||
pub truncated: bool,
|
||||
/// Directory entries looked at.
|
||||
pub entries: usize,
|
||||
/// Folders whose contents couldn't be listed (permissions, a folder that vanished or went
|
||||
/// offline): the walk skipped them and carried on. Only a refused listing counts, not an
|
||||
/// entry inside a listed folder that couldn't be examined.
|
||||
pub unreadable: usize,
|
||||
/// Files the walk reached that `keep` refused. Hidden entries and the skipped folder are left
|
||||
/// out silently and not counted.
|
||||
pub skipped: usize,
|
||||
}
|
||||
|
||||
/// Whether the entry has a dot-prefixed name or a Windows or macOS hidden attribute.
|
||||
@@ -93,7 +100,8 @@ pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, Entr
|
||||
|
||||
/// The files below folder `root` that `keep` accepts. Hidden entries (names starting with `.`)
|
||||
/// are left out, the folder `skip` (e.g. the library's own) is never entered, and the walk stops
|
||||
/// at `limits` (see [`Walked::truncated`]). Unreadable folders are skipped.
|
||||
/// at `limits` (see [`Walked::truncated`]). Unreadable folders are skipped and counted
|
||||
/// ([`Walked::unreadable`]), as are the files `keep` refuses ([`Walked::skipped`]).
|
||||
pub fn files_in(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool) -> Walked {
|
||||
walk(root, skip, limits, keep, |_| true, None)
|
||||
}
|
||||
@@ -140,6 +148,8 @@ fn walk(
|
||||
if !is_dir {
|
||||
if keep(&path) {
|
||||
out.files.push(path);
|
||||
} else {
|
||||
out.skipped = out.skipped.saturating_add(1);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -150,7 +160,10 @@ fn walk(
|
||||
out.truncated = true;
|
||||
continue;
|
||||
}
|
||||
let Ok(rd) = std::fs::read_dir(&path) else { continue };
|
||||
let Ok(rd) = std::fs::read_dir(&path) else {
|
||||
out.unreadable = out.unreadable.saturating_add(1);
|
||||
continue;
|
||||
};
|
||||
let mut children: Vec<(PathBuf, bool)> = Vec::new();
|
||||
// (the folder's listing, for who asked for it; all of it unless something below says otherwise)
|
||||
let mut listed = note.is_some().then(Vec::new);
|
||||
@@ -348,6 +361,50 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// Files the caller's `keep` refuses are counted (an import reports most of them as
|
||||
/// unsupported), and so are only those: hidden files and the skipped folder are left out without a count, and
|
||||
/// the files returned are the same ones in the same order.
|
||||
#[test]
|
||||
fn unkept_files_are_counted_as_skipped() {
|
||||
let d = tmp("skipped");
|
||||
for f in ["a.jpg", "b.txt", "c.png", "sub/d.jpg", "sub/e.md", ".hidden.txt", "lib/l.txt"] {
|
||||
let p = d.join(f);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, b"x").unwrap();
|
||||
}
|
||||
let lib = d.join("lib");
|
||||
let w = files_in(&d, Some(&lib), Limits::default(), |p| p.extension().is_some_and(|e| e == "jpg"));
|
||||
let rel: Vec<String> = w.files.iter().map(|p| p.strip_prefix(&d).unwrap().to_string_lossy().replace('\\', "/")).collect();
|
||||
assert_eq!(rel, ["a.jpg", "sub/d.jpg"]);
|
||||
assert_eq!((w.skipped, w.unreadable, w.truncated), (3, 0, false), "{w:?}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A folder that is gone by the time the walk reaches it (here removed while an earlier file is
|
||||
/// looked at, as an unplugged disk or a deleted folder would be) is counted as unreadable;
|
||||
/// the walk carries on and still returns the other files.
|
||||
#[test]
|
||||
fn a_folder_that_vanishes_is_counted_as_unreadable() {
|
||||
let d = tmp("vanished");
|
||||
for f in ["a.jpg", "b/b.jpg", "c.jpg"] {
|
||||
let p = d.join(f);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, b"x").unwrap();
|
||||
}
|
||||
let gone = d.join("b");
|
||||
// `a.jpg` is looked at before the folder `b` is entered
|
||||
let w = files_in(&d, None, Limits::default(), |p| {
|
||||
if p.ends_with("a.jpg") {
|
||||
let _ = std::fs::remove_dir_all(&gone);
|
||||
}
|
||||
true
|
||||
});
|
||||
let rel: Vec<String> = w.files.iter().map(|p| p.strip_prefix(&d).unwrap().to_string_lossy().replace('\\', "/")).collect();
|
||||
assert_eq!(rel, ["a.jpg", "c.jpg"]);
|
||||
assert_eq!((w.unreadable, w.skipped, w.truncated), (1, 0, false), "{w:?}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// Folder imports must not revisit the user's own library through symlinks
|
||||
/// or through an alias to the library's parent.
|
||||
#[cfg(unix)]
|
||||
|
||||
+45
-10
@@ -476,8 +476,10 @@ pub fn forced_window_renderer(app: Option<&str>, wgpu: Option<&str>) -> Option<W
|
||||
|
||||
/// The order in which the window's renderers are tried on `os`: the forced one (environment)
|
||||
/// first, then the one remembered from the last good start, then the platform chain — on Windows
|
||||
/// DX12, Vulkan, GL, then glow. DX12 stays first: with Vulkan loaded, a broken Vulkan driver can
|
||||
/// crash the process uncatchably (issue #136), so Vulkan is touched only after DX12 failed.
|
||||
/// DX12, GL, then glow. On Windows Vulkan is used only when the environment asks for it: with
|
||||
/// Vulkan loaded, a broken Vulkan driver can crash the process uncatchably (issue #136), so it is
|
||||
/// never in the automatic chain, and the renderer remembered from the last run cannot put it
|
||||
/// first either.
|
||||
/// `failed` (the renderer the last start died in) goes last, as a last resort only. Backends not
|
||||
/// in `compiled`, and glow without `glow`, are left out; the list is never empty.
|
||||
pub fn window_renderer_order(
|
||||
@@ -489,7 +491,8 @@ pub fn window_renderer_order(
|
||||
glow: bool,
|
||||
) -> Vec<WindowRenderer> {
|
||||
let platform = match os {
|
||||
"windows" => vec![Backends::DX12, Backends::VULKAN, Backends::GL],
|
||||
// no Vulkan on Windows: its driver can crash the process uncatchably (issue #136)
|
||||
"windows" => vec![Backends::DX12, Backends::GL],
|
||||
"macos" | "ios" => vec![Backends::METAL],
|
||||
_ => vec![Backends::VULKAN, Backends::GL],
|
||||
};
|
||||
@@ -499,7 +502,15 @@ pub fn window_renderer_order(
|
||||
WindowRenderer::Wgpu(b) => !b.is_empty() && compiled.contains(*b),
|
||||
};
|
||||
let not_failed = |r: &WindowRenderer| Some(*r) != failed;
|
||||
let candidates = forced.into_iter().chain(remembered.filter(not_failed)).chain(chain.filter(not_failed)).chain(failed);
|
||||
// On Windows the Vulkan driver is loaded only when the environment asks for it (the forced
|
||||
// renderer): a broken one crashes the process uncatchably (issue #136). So neither the
|
||||
// renderer remembered from the last run nor the one the last start died in can bring it back.
|
||||
let no_vulkan = |r: &WindowRenderer| os != "windows" || !matches!(r, WindowRenderer::Wgpu(b) if b.contains(Backends::VULKAN));
|
||||
let candidates = forced
|
||||
.into_iter()
|
||||
.chain(remembered.filter(|r| not_failed(r) && no_vulkan(r)))
|
||||
.chain(chain.filter(not_failed))
|
||||
.chain(failed.filter(no_vulkan));
|
||||
let mut out: Vec<WindowRenderer> = Vec::new();
|
||||
for r in candidates {
|
||||
if usable(&r) && !out.contains(&r) {
|
||||
@@ -722,27 +733,51 @@ mod tests {
|
||||
}
|
||||
|
||||
/// The window's renderer fallback: forced, remembered, the platform chain, the failed one last.
|
||||
/// On Windows Vulkan is not in the chain (issue #136) — see
|
||||
/// `windows_never_uses_vulkan_unless_it_is_asked_for`.
|
||||
#[test]
|
||||
fn window_renderer_fallback_order() {
|
||||
use WindowRenderer::{Glow, Wgpu};
|
||||
let all = Backends::DX12 | Backends::VULKAN | Backends::GL | Backends::METAL;
|
||||
let (dx, vk, gl) = (Wgpu(Backends::DX12), Wgpu(Backends::VULKAN), Wgpu(Backends::GL));
|
||||
assert_eq!(window_renderer_order(None, None, None, "windows", all, true), [dx, vk, gl, Glow]);
|
||||
assert_eq!(window_renderer_order(None, None, None, "windows", all, false), [dx, vk, gl]);
|
||||
assert_eq!(window_renderer_order(None, None, None, "windows", all, true), [dx, gl, Glow]);
|
||||
assert_eq!(window_renderer_order(None, None, None, "windows", all, false), [dx, gl]);
|
||||
// a build without GL
|
||||
assert_eq!(window_renderer_order(None, None, None, "windows", Backends::DX12 | Backends::VULKAN, true), [dx, vk, Glow]);
|
||||
assert_eq!(window_renderer_order(None, None, None, "windows", Backends::DX12 | Backends::VULKAN, true), [dx, Glow]);
|
||||
// remembered from the last good start goes first
|
||||
assert_eq!(window_renderer_order(None, Some(vk), None, "windows", all, true), [vk, dx, gl, Glow]);
|
||||
assert_eq!(window_renderer_order(None, Some(gl), None, "windows", all, true), [gl, dx, Glow]);
|
||||
// the environment wins over the remembered one
|
||||
assert_eq!(window_renderer_order(Some(gl), Some(vk), None, "windows", all, true), [gl, vk, dx, Glow]);
|
||||
assert_eq!(window_renderer_order(Some(gl), Some(dx), None, "windows", all, true), [gl, dx, Glow]);
|
||||
assert_eq!(window_renderer_order(Some(Glow), None, None, "windows", all, true)[0], Glow);
|
||||
// the last start died in DX12: tried last only (also when it was remembered)
|
||||
assert_eq!(window_renderer_order(None, Some(dx), Some(dx), "windows", all, true), [vk, gl, Glow, dx]);
|
||||
assert_eq!(window_renderer_order(None, Some(dx), Some(dx), "windows", all, true), [gl, Glow, dx]);
|
||||
// a forced backend that is not in the build is skipped
|
||||
assert_eq!(window_renderer_order(Some(Wgpu(Backends::METAL)), None, None, "windows", Backends::DX12, false), [dx]);
|
||||
// never empty
|
||||
assert!(!window_renderer_order(None, None, None, "windows", Backends::empty(), false).is_empty());
|
||||
assert_eq!(window_renderer_order(None, None, None, "macos", all, true), [Wgpu(Backends::METAL), Glow]);
|
||||
// Vulkan is asked for on Windows: it is used
|
||||
assert_eq!(window_renderer_order(Some(vk), None, None, "windows", all, true), [vk, dx, gl, Glow]);
|
||||
}
|
||||
|
||||
/// Issue #136: on Windows the Vulkan driver is never loaded unless it is asked for — a
|
||||
/// broken one crashes the process uncatchably. The renderer remembered from the last run
|
||||
/// must not put Vulkan before DX12 either.
|
||||
#[test]
|
||||
fn windows_never_uses_vulkan_unless_it_is_asked_for() {
|
||||
let all = Backends::DX12 | Backends::VULKAN | Backends::GL | Backends::METAL;
|
||||
let dx = WindowRenderer::Wgpu(Backends::DX12);
|
||||
let vk = WindowRenderer::Wgpu(Backends::VULKAN);
|
||||
// the automatic chain: DX12 first, no Vulkan in it
|
||||
let automatic = window_renderer_order(None, None, None, "windows", all, true);
|
||||
assert!(!automatic.contains(&vk), "the automatic Windows chain must not contain Vulkan: {automatic:?}");
|
||||
assert_eq!(automatic.first(), Some(&dx));
|
||||
// the renderer remembered from the last run does not put Vulkan first either
|
||||
let remembered = window_renderer_order(None, Some(vk), None, "windows", all, true);
|
||||
assert!(!remembered.contains(&vk), "a remembered Vulkan must not be tried: {remembered:?}");
|
||||
assert_eq!(remembered.first(), Some(&dx));
|
||||
// asked for explicitly (the environment), Vulkan is used
|
||||
assert_eq!(window_renderer_order(Some(vk), None, None, "windows", all, true).first(), Some(&vk));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+52
-6
@@ -556,8 +556,12 @@ impl Gpu {
|
||||
}
|
||||
|
||||
/// Submit command buffers, then make the buffers this thread dropped before reusable.
|
||||
/// Nothing is submitted once this render has failed: the render is discarded and recomputed
|
||||
/// on the CPU, and the failure contract says no further GPU work runs after a fatal failure.
|
||||
pub fn submit(&self, cmds: impl IntoIterator<Item = wgpu::CommandBuffer>) {
|
||||
self.queue.submit(cmds);
|
||||
if !failed() {
|
||||
self.queue.submit(cmds);
|
||||
}
|
||||
let retired = take_retired();
|
||||
self.pool(retired);
|
||||
}
|
||||
@@ -610,6 +614,12 @@ impl Gpu {
|
||||
pub fn upload<T: bytemuck::Pod>(&self, data: &[T]) -> Buf {
|
||||
let bytes: &[u8] = bytemuck::cast_slice(data);
|
||||
let len = bytes.len() / 4;
|
||||
// A failed render runs no further GPU work (`Gpu::submit` skips the submission and the
|
||||
// render is redone on the CPU): staging the bytes would still queue a copy for the next
|
||||
// submission, so the caller gets the placeholder with the requested length instead.
|
||||
if failed() {
|
||||
return Buf { buf: Some(Tracked::new(self.placeholder())), len };
|
||||
}
|
||||
if bytes.is_empty() {
|
||||
return self.buffer(1);
|
||||
}
|
||||
@@ -715,7 +725,12 @@ impl Gpu {
|
||||
fail(FailKind::Fatal, format!("unknown kernel {name}"));
|
||||
return;
|
||||
};
|
||||
assert_eq!(bufs.len(), k.nbuf, "{name}: binding count");
|
||||
if bufs.len() != k.nbuf {
|
||||
// a caller/kernel mismatch would bind the wrong buffers: fail this render over to the
|
||||
// CPU instead of crashing
|
||||
fail(FailKind::Fatal, format!("{name}: binding count {} != {}", bufs.len(), k.nbuf));
|
||||
return;
|
||||
}
|
||||
let params = self.init_buffer(bytemuck::cast_slice(if p.is_empty() { &[0u32] } else { p }), wgpu::BufferUsages::STORAGE);
|
||||
let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: params.as_entire_binding() }];
|
||||
for (i, b) in bufs.iter().enumerate() {
|
||||
@@ -731,15 +746,27 @@ impl Gpu {
|
||||
|
||||
/// Submit `enc`, then read back the first `len` 32-bit values of `src`.
|
||||
///
|
||||
/// A failed readback (device lost, map error, timeout) fails the render ([`FailKind::Fatal`])
|
||||
/// and returns zeros, which the caller discards; after an earlier failure in the same render
|
||||
/// nothing more is submitted.
|
||||
/// A failed readback (device lost, map error, timeout) or a `len` past the buffer's end fails
|
||||
/// the render ([`FailKind::Fatal`]) and returns zeros, which the caller discards; after an
|
||||
/// earlier failure in the same render nothing more is submitted. `T` is always a 32-bit type
|
||||
/// at the call sites (the copy and the readback tail are defined in 32-bit words).
|
||||
pub fn finish_and_read<T: bytemuck::Pod>(&self, mut enc: wgpu::CommandEncoder, src: &Buf, len: usize) -> Vec<T> {
|
||||
assert!(len <= src.len, "readback of {len} values from a buffer of {}", src.len);
|
||||
let zeros = || vec![<T as bytemuck::Zeroable>::zeroed(); len];
|
||||
if failed() {
|
||||
return zeros();
|
||||
}
|
||||
// a zero-length readback would issue a `copy_buffer_to_buffer` of size 0, which wgpu
|
||||
// rejects as an invalid copy: submit the (possibly staged) work untouched and return
|
||||
// zeros instead
|
||||
if len == 0 {
|
||||
self.submit([enc.finish()]);
|
||||
return zeros();
|
||||
}
|
||||
if len > src.len {
|
||||
// a caller bug would read past the buffer: fail this render over to the CPU
|
||||
fail(FailKind::Fatal, format!("readback of {len} values from a buffer of {}", src.len));
|
||||
return zeros();
|
||||
}
|
||||
let size = (len * 4) as u64;
|
||||
let staging = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("readback"),
|
||||
@@ -1193,6 +1220,25 @@ mod tests {
|
||||
let back: Vec<[u32; 3]> = g.finish_and_read(g.encoder(), &b, data.len());
|
||||
assert!(back.len() == 1 << 20 && back.as_flattened() == data.as_slice());
|
||||
}
|
||||
/// An upload after this render has failed keeps the failure contract (`Gpu::submit` skips the
|
||||
/// submission, so nothing further runs on the GPU): the caller gets the placeholder with the
|
||||
/// requested length instead of a staging buffer holding a copy of the data for a submission
|
||||
/// that will never happen.
|
||||
#[test]
|
||||
fn an_upload_after_a_failure_returns_the_placeholder() {
|
||||
let Some(g) = crate::device() else {
|
||||
lightcraft_testkit::skip!(Gpu, "no GPU device");
|
||||
return;
|
||||
};
|
||||
super::fail(super::FailKind::Fatal, "simulated failure before an upload".into());
|
||||
assert!(super::failed());
|
||||
let b = g.upload(&[7u32; 1024]);
|
||||
assert_eq!(b.buf.as_ref().map(|t| t.0.size()), Some(16), "the placeholder, not a staged 4 KiB buffer");
|
||||
assert_eq!(b.len, 1024, "the requested length is preserved");
|
||||
// leave this thread's failure for nobody: later tests on the thread start unfailed
|
||||
assert_eq!(super::take_failure().map(|f| f.kind), Some(super::FailKind::Fatal));
|
||||
}
|
||||
|
||||
/// Issue #1858: once a Vulkan or DX12 device is lost, wgpu 30 panics in `Device::poll` instead of
|
||||
/// returning an error. A render's readback panicked; while it unwound, a buffer's way back to
|
||||
/// the pool polls again from a destructor, and that second panic aborted the app.
|
||||
|
||||
@@ -5,6 +5,8 @@ use lightcraft_develop::VignetteStyle;
|
||||
use lightcraft_pipeline::colorops::POINT_WORDS;
|
||||
use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, srgb_lut};
|
||||
|
||||
use crate::ctx::{FailKind, fail};
|
||||
|
||||
/// Entries per tone-curve table (`lightcraft_pipeline::finish` builds them at this size).
|
||||
pub const CURVE_N: u32 = 1024;
|
||||
|
||||
@@ -168,6 +170,9 @@ pub struct Present {
|
||||
|
||||
/// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs |
|
||||
/// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms).
|
||||
///
|
||||
/// A curve whose length is not [`CURVE_N`] fails the render ([`FailKind::Fatal`]) and returns an
|
||||
/// empty parameter block with a truncated aux table, which the caller discards (CPU fallback).
|
||||
pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec<u32>, Vec<f32>) {
|
||||
let mut aux: Vec<f32> = fp.tone.lut().to_vec();
|
||||
aux.extend_from_slice(fp.tone.chroma_lut());
|
||||
@@ -176,7 +181,17 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
|
||||
let curve_off = aux.len();
|
||||
if let Some(c) = &fp.curves {
|
||||
for l in c {
|
||||
assert_eq!(l.v.len(), CURVE_N as usize);
|
||||
if l.v.len() != CURVE_N as usize {
|
||||
// a wrong-length curve would shift every later aux offset (CURVE_OFF, MASK_OFF and
|
||||
// the mask terms that follow) and make the kernel read the wrong data. `fail()`
|
||||
// records the failure on this thread so the render falls back to the CPU; the
|
||||
// partial `(p, aux)` returned here is never bound to a pipeline.
|
||||
fail(FailKind::Fatal, format!("curve table has {} entries, expected {}", l.v.len(), CURVE_N));
|
||||
// `p` is only assembled below the curve loop, so an empty block is as good as any:
|
||||
// the caller (render.rs) gates on `failed()` right after this returns and bails to
|
||||
// the CPU fallback before indexing `p` or uploading `aux`.
|
||||
return (Vec::new(), aux);
|
||||
}
|
||||
aux.extend_from_slice(&l.v);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -764,6 +764,9 @@ pub fn render(
|
||||
(None, None) => None,
|
||||
};
|
||||
let (p, aux) = finish_block(&fp, &terms, &present);
|
||||
if crate::ctx::failed() {
|
||||
return None; // a malformed parameter block failed the render: the CPU fallback redoes it
|
||||
}
|
||||
let aux = gpu.upload(&aux);
|
||||
// cleared, so that work which never ran cannot pass for an image (see the check below)
|
||||
let out = cx.zeroed(n);
|
||||
|
||||
@@ -52,21 +52,11 @@ fn check_v3_luminance_cutoff(chroma: f32, pixel: [f32; 3], expected: [u8; 4]) {
|
||||
let req = RenderRequest::fit(64, 64);
|
||||
let cpu = render(&src, &info, &s, &req).image;
|
||||
let gpu = lightcraft_gpu::try_render(&src, &info, &s, &req, None).expect("GPU render without CPU fallback").image;
|
||||
for (name, image) in [("CPU", &cpu), ("GPU", &gpu)] {
|
||||
// Ordered output dithering varies a uniform source by one 8-bit level.
|
||||
// Every pixel must still stay at the calibrated cutoff colour.
|
||||
let spans: [u8; 3] = std::array::from_fn(|c| {
|
||||
let min = image.data.iter().map(|p| p[c]).min().unwrap();
|
||||
let max = image.data.iter().map(|p| p[c]).max().unwrap();
|
||||
max - min
|
||||
});
|
||||
eprintln!("chroma {chroma} {name}: first {:?}, channel spans {spans:?}", image.data[0]);
|
||||
assert!(spans.into_iter().all(|span| span <= 1), "chroma {chroma} {name}: {spans:?}");
|
||||
for pixel in &image.data {
|
||||
assert_eq!(pixel[3], 255, "opaque output");
|
||||
for (actual, expected) in pixel.iter().copied().zip(expected) {
|
||||
assert!(actual.abs_diff(expected) <= 1, "chroma {chroma}: {pixel:?}, expected {expected}");
|
||||
}
|
||||
for image in [&cpu, &gpu] {
|
||||
// (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);
|
||||
@@ -102,6 +92,12 @@ fn camera_tone_and_relative_wb() {
|
||||
s.wb.mode = WbMode::Custom;
|
||||
s.wb.temp = 8000.0;
|
||||
check("camera tone edited", &src, &info, &s, &RenderRequest::fit(320, 240));
|
||||
// each process's shoulder past the last knot, with highlights lifted into it (issue #1632)
|
||||
for p in Process::ALL {
|
||||
let mut lifted = DevelopSettings { process: p.version(), ..DevelopSettings::default() };
|
||||
lifted.light.exposure = 2.0;
|
||||
check(&format!("camera tone {p:?} exposure +2"), &src, &info, &lifted, &RenderRequest::fit(320, 240));
|
||||
}
|
||||
// a camera chroma curve: richer shadows, highlights bleached toward white
|
||||
let curve = curve.with_chroma([1.4, 1.3, 1.1, 1.0, 0.7, 0.4, 0.25, 0.2]).unwrap();
|
||||
let info = SourceInfo { camera_tone: Some(curve), ..info };
|
||||
@@ -719,8 +715,7 @@ fn light_v3_operators_match() {
|
||||
let req = RenderRequest::fit(720, 720);
|
||||
for id in ["light.contrast", "light.whites", "light.blacks"] {
|
||||
for v in [-100.0, -50.0, 50.0, 100.0] {
|
||||
let mut s = DevelopSettings::default();
|
||||
assert_eq!(s.process.process(), Process::V4);
|
||||
let mut s = DevelopSettings { process: Process::V4.version(), ..Default::default() };
|
||||
lightcraft_develop::controls::set(&mut s, id, v);
|
||||
check(&format!("V4 {id} {v}"), &src, &info, &s, &req);
|
||||
if id == "light.whites" {
|
||||
@@ -733,7 +728,7 @@ fn light_v3_operators_match() {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut s = DevelopSettings::default();
|
||||
let mut s = DevelopSettings { process: Process::V4.version(), ..Default::default() };
|
||||
typical(&mut s);
|
||||
s.light.contrast = 35.0;
|
||||
s.light.whites = 40.0;
|
||||
|
||||
@@ -412,3 +412,48 @@ fn export_without_token_finishes_after_eof() {
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// A batch-edit recipe is reachable over MCP without a tool of its own: `run_command` takes
|
||||
/// `library.import` with a `recipe`, the generated `cmd_preset_saveRecipe` tool saves one as a
|
||||
/// preset, `list_commands` documents both, and a recipe naming white balance is a tool error that
|
||||
/// imports nothing.
|
||||
#[test]
|
||||
fn a_batch_edit_recipe_is_reachable_over_mcp() {
|
||||
let dir = std::env::temp_dir().join(format!("lightcraft-mcp-recipe-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let img = lightcraft_raster::Rgba8::from_fn(96, 64, |x, y| [(x * 2) as u8, (y * 3) as u8, 128, 255]);
|
||||
lightcraft_mcp::write_image(&dir.join("gradient.png"), &img, 90).unwrap();
|
||||
let paths = json!([dir.to_string_lossy()]);
|
||||
let mut server = Server::new(Box::new(Headless::default()));
|
||||
let replies = session(
|
||||
&mut server,
|
||||
&[
|
||||
call(1, "list_commands", json!({"filter": "recipe"})),
|
||||
call(2, "run_command", json!({"command": "library.import", "params": {"paths": paths, "recipe": [{"id": "wb.temp", "value": 5000}]}})),
|
||||
call(3, "query_photos", json!({"limit": 5})),
|
||||
call(
|
||||
4,
|
||||
"run_command",
|
||||
json!({"command": "library.import", "params": {"paths": paths, "recipe": [{"id": "light.exposure", "value": 0.5}, {"id": "color.vibrance", "value": 20}]}}),
|
||||
),
|
||||
call(5, "get_develop", json!({})),
|
||||
call(6, "cmd_preset_saveRecipe", json!({"name": "Warm", "recipe": [{"id": "light.exposure", "value": 0.5}]})),
|
||||
call(7, "list_commands", json!({"filter": "library.import"})),
|
||||
],
|
||||
);
|
||||
let listed = |r: &Value| -> Vec<Value> { serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap() };
|
||||
let save = listed(&replies[0]).into_iter().find(|c| c["id"] == "preset.saveRecipe").expect("preset.saveRecipe is listed");
|
||||
assert!(save["params"].as_str().unwrap().contains("recipe: [{id:"), "{save}");
|
||||
assert_eq!(replies[1]["result"]["isError"], true, "{}", replies[1]);
|
||||
assert!(replies[1]["result"]["content"][0]["text"].as_str().unwrap().contains("white balance"), "{}", replies[1]);
|
||||
assert!(replies[2]["result"]["structuredContent"]["photos"].as_array().unwrap().is_empty(), "the refused import added nothing");
|
||||
assert_eq!(replies[3]["result"]["isError"], false, "{}", replies[3]);
|
||||
assert_eq!(replies[3]["result"]["structuredContent"]["imported"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(replies[4]["result"]["structuredContent"]["light"]["exposure"], 0.5, "{}", replies[4]);
|
||||
assert_eq!(replies[4]["result"]["structuredContent"]["color"]["vibrance"], 20.0, "{}", replies[4]);
|
||||
assert_eq!(replies[5]["result"]["isError"], false, "{}", replies[5]);
|
||||
assert_eq!(replies[5]["result"]["structuredContent"]["name"], "Warm");
|
||||
let import = listed(&replies[6]).into_iter().find(|c| c["id"] == "library.import").expect("library.import is listed");
|
||||
assert!(import["params"].as_str().unwrap().contains("recipe?: [{id:"), "{import}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -211,7 +211,7 @@ pub fn register(frames: &[Frame], progress: &Progress) -> Result<(Vec<Option<Cam
|
||||
}
|
||||
}
|
||||
let long = sizes[ids[0]].0.max(sizes[ids[0]].1) as f64;
|
||||
let exif_f = frames[ids[0]].metadata.focal_length_35mm.filter(|v| *v > 1.0).map(|f35| f35 / 36.0 * long);
|
||||
let exif_f = exif_focal(&frames[ids[0]]);
|
||||
let hom_f = (!fs.is_empty()).then(|| median(fs.clone())).filter(|f| *f > 0.1 * long && *f < 20.0 * long);
|
||||
let f0 = exif_f.or(hom_f).unwrap_or(long * 1.07);
|
||||
let cams = camera::initial_cameras(&ids, &sizes, &pairs, f0);
|
||||
@@ -223,6 +223,12 @@ pub fn register(frames: &[Frame], progress: &Progress) -> Result<(Vec<Option<Cam
|
||||
Ok((cams, adj.rms_before, adj.rms))
|
||||
}
|
||||
|
||||
/// A frame's focal length in pixels, from EXIF's 35 mm equivalent.
|
||||
fn exif_focal(frame: &Frame) -> Option<f64> {
|
||||
let long = frame.width().max(frame.height()) as f64;
|
||||
frame.metadata.focal_length_35mm.filter(|v| *v > 1.0).map(|f35| f35 / 36.0 * long)
|
||||
}
|
||||
|
||||
/// Stitch `frames` (oriented, linear) into a panorama.
|
||||
pub fn stitch(mut frames: Vec<Frame>, opts: &PanoOptions, progress: &Progress) -> Result<PanoResult> {
|
||||
let n = frames.len();
|
||||
@@ -250,7 +256,14 @@ pub fn stitch(mut frames: Vec<Frame>, opts: &PanoOptions, progress: &Progress) -
|
||||
}
|
||||
// output scale: native resolution, limited to max_megapixels and the longest edge
|
||||
let max_px = if opts.max_megapixels.is_nan() { MAX_MEGAPIXELS } else { opts.max_megapixels.clamp(0.1, MAX_MEGAPIXELS) } * 1e6;
|
||||
let s = (max_px / ((bx1 - bx0) * (by1 - by0))).sqrt().min(MAX_EDGE / (bx1 - bx0).max(by1 - by0)).min(1.0);
|
||||
let surface = (bx1 - bx0) * (by1 - by0);
|
||||
// Bundle adjustment fits the focal length freely, and a few wide frames can settle it below the
|
||||
// lens's: the canvas, sized from it, then holds fewer pixels than the photos do. The lens's own
|
||||
// focal length, where EXIF gives it, sets the native scale instead: a canvas pixel at the centre
|
||||
// of a frame is then one pixel of the photo, and nothing is upsampled past that.
|
||||
let lens = used.iter().filter_map(|&i| exif_focal(&frames[i])).fold(0.0, f64::max);
|
||||
let native = if fmed > 0.0 { (lens / fmed).max(1.0) } else { 1.0 };
|
||||
let s = (max_px / surface).sqrt().min(MAX_EDGE / (bx1 - bx0).max(by1 - by0)).min(native);
|
||||
let f_out = fmed * s;
|
||||
let (ox, oy) = (bx0 * s, by0 * s);
|
||||
let (cw, ch) = (((bx1 - bx0) * s).ceil() as usize + 1, ((by1 - by0) * s).ceil() as usize + 1);
|
||||
@@ -400,7 +413,7 @@ pub fn stitch(mut frames: Vec<Frame>, opts: &PanoOptions, progress: &Progress) -
|
||||
rms_before,
|
||||
rms,
|
||||
fov,
|
||||
native_megapixels: (bx1 - bx0) * (by1 - by0) / 1e6,
|
||||
native_megapixels: surface * native * native / 1e6,
|
||||
focal: f_out,
|
||||
origin: (ox, oy),
|
||||
color,
|
||||
|
||||
@@ -280,3 +280,27 @@ fn panoramas_keep_the_photos_resolution_unless_asked() {
|
||||
let nan = run(&shots, 800.0, &opts(f64::NAN)).0;
|
||||
assert_eq!((nan.image.width, nan.image.height), (full.image.width, full.image.height));
|
||||
}
|
||||
|
||||
/// Issue #2320: a few wide frames can settle the fitted focal length below the lens's, and a canvas
|
||||
/// sized from it holds fewer pixels than the photos. EXIF's focal length sets the native scale.
|
||||
#[test]
|
||||
fn the_lens_focal_length_sets_the_native_scale() {
|
||||
let e = env();
|
||||
let f = 2000.0; // what the frames were shot with: the fit settles near it
|
||||
let lens = 2400.0; // what EXIF says, on a 4000-pixel long edge
|
||||
let shots = [
|
||||
Shot { yaw: -20.0, pitch: 0.0, roll: 0.0, gain: 1.0 },
|
||||
Shot { yaw: 0.0, pitch: 0.0, roll: 0.0, gain: 1.0 },
|
||||
Shot { yaw: 20.0, pitch: 0.0, roll: 0.0, gain: 1.0 },
|
||||
];
|
||||
let rs: Vec<M3> = shots.iter().map(|s| rot(s.yaw, s.pitch, s.roll)).collect();
|
||||
let mut frames: Vec<Frame> = shots.iter().zip(&rs).map(|(s, r)| shoot(&e, r, f, 4000, 3000, s.gain)).collect();
|
||||
for frame in &mut frames {
|
||||
frame.metadata.focal_length_35mm = Some(lens / 4000.0 * 36.0);
|
||||
}
|
||||
let res = stitch(frames, &PanoOptions { projection: Projection::Spherical, ..Default::default() }, &no_progress).unwrap();
|
||||
assert_eq!(res.used.len(), 3, "all three frames must connect: {:?}", res.used);
|
||||
assert!((res.focal / lens - 1.0).abs() < 0.01, "output focal {} for a {lens} px lens", res.focal);
|
||||
let mp = (res.image.width * res.image.height) as f64 / 1e6;
|
||||
assert!((mp / res.native_megapixels - 1.0).abs() < 0.02, "canvas {mp} MP for {} MP native", res.native_megapixels);
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
//! - [`cr3`] — the Canon CR3 container (metadata blocks, XMP, the JPEG and raw tracks).
|
||||
//! - [`heif`] — the HEIF/HEIC/AVIF container's Exif and XMP items (no HEVC decoder needed).
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod container;
|
||||
pub mod cr3;
|
||||
|
||||
@@ -305,7 +305,7 @@ fn parse_tree(s: &str) -> Result<Node, XmpError> {
|
||||
}
|
||||
}
|
||||
Event::End(_) if stack.len() > 1 => {
|
||||
let n = stack.pop().expect("len > 1");
|
||||
let Some(n) = stack.pop() else { return Err(XmpError::Xml("end tag without an open element".into())) };
|
||||
scopes.pop();
|
||||
if let Some(parent) = stack.last_mut() {
|
||||
parent.children.push(n);
|
||||
@@ -340,10 +340,11 @@ fn parse_tree(s: &str) -> Result<Node, XmpError> {
|
||||
}
|
||||
// close unterminated elements leniently
|
||||
while stack.len() > 1 {
|
||||
let n = stack.pop().expect("len > 1");
|
||||
stack.last_mut().expect("root").children.push(n);
|
||||
let Some(n) = stack.pop() else { return Err(XmpError::Xml("unterminated element without a node".into())) };
|
||||
let Some(parent) = stack.last_mut() else { return Err(XmpError::Xml("unterminated element without a parent".into())) };
|
||||
parent.children.push(n);
|
||||
}
|
||||
Ok(stack.pop().expect("root"))
|
||||
stack.pop().ok_or_else(|| XmpError::Xml("xmp packet without a root element".into()))
|
||||
}
|
||||
|
||||
fn is_rdf_meta_attr(k: &str) -> bool {
|
||||
|
||||
@@ -347,6 +347,13 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap {
|
||||
None if info.raw => ToneMap::hdr(l.contrast, l.whites, l.blacks, peak),
|
||||
None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak),
|
||||
},
|
||||
// V4, with a raw's tone curve rolling off into white in stops: a camera curve past its last
|
||||
// knot, the generic curve from half a stop below its white point instead of clipping (issue #1632)
|
||||
Process::V5 => match info.camera_tone.as_ref().filter(|_| info.raw) {
|
||||
Some(curve) => ToneMap::camera_rolloff_hdr(curve, 0.0, l.whites, 0.0, peak),
|
||||
None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak),
|
||||
None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -210,7 +210,7 @@ impl Frame {
|
||||
let a = self.aspect();
|
||||
let (mw, mh) = (max_w.max(1) as f64, max_h.max(1) as f64);
|
||||
// a box that is already this aspect up to rounding (an export size) is the size: fitting
|
||||
// into it again rounds twice and can lose a pixel of the edge that was asked for
|
||||
// into it again rounds twice and can lose a pixel of the edge that was asked for.
|
||||
if (mw - 0.5) / a <= mh + 0.5 && (mw + 0.5) / a >= mh - 0.5 {
|
||||
return (max_w.max(1), max_h.max(1));
|
||||
}
|
||||
|
||||
@@ -138,6 +138,9 @@ pub struct RenderRequest {
|
||||
/// Output must fit in `max_w × max_h` (aspect preserved).
|
||||
pub max_w: usize,
|
||||
pub max_h: usize,
|
||||
/// The box is the final export size, already fitted against the full-resolution photo.
|
||||
/// Reduced decode proxies must not fit it a second time.
|
||||
pub exact_size: bool,
|
||||
pub quality: Quality,
|
||||
/// Show the crop frame's content only (true) or the whole uncropped image (crop tool active).
|
||||
pub apply_crop: bool,
|
||||
@@ -199,6 +202,7 @@ impl RenderRequest {
|
||||
Self {
|
||||
max_w,
|
||||
max_h,
|
||||
exact_size: false,
|
||||
quality: Quality::Full,
|
||||
apply_crop: true,
|
||||
overlay: Overlay::None,
|
||||
@@ -209,6 +213,20 @@ impl RenderRequest {
|
||||
display: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Render to a final size calculated from the original photo, even from a rounded proxy.
|
||||
pub fn exact(width: usize, height: usize) -> Self {
|
||||
Self { exact_size: true, ..Self::fit(width, height) }
|
||||
}
|
||||
|
||||
/// The output size for `frame`. An exact box stands against a proxy that only rounds the photo's
|
||||
/// shape differently; a source of another shape (a raw's embedded preview) is fitted, not stretched.
|
||||
fn size(&self, frame: &geometry::Frame) -> (usize, usize) {
|
||||
let fitted = frame.fit(self.max_w, self.max_h);
|
||||
let exact = (self.max_w.max(1), self.max_h.max(1));
|
||||
let near = |a: usize, b: usize| a.abs_diff(b) <= b / 64 + 1;
|
||||
if self.exact_size && near(fitted.0, exact.0) && near(fitted.1, exact.1) { exact } else { fitted }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Rendered {
|
||||
@@ -245,7 +263,7 @@ pub(crate) struct Prepared {
|
||||
|
||||
/// Output size for a source of `src_w × src_h` under `s`, fitting `max_w × max_h`.
|
||||
pub fn output_size(src_w: usize, src_h: usize, s: &DevelopSettings, req: &RenderRequest) -> (usize, usize) {
|
||||
geometry::Frame::new(src_w, src_h, s, req.apply_crop).fit(req.max_w, req.max_h)
|
||||
req.size(&geometry::Frame::new(src_w, src_h, s, req.apply_crop))
|
||||
}
|
||||
|
||||
/// Size of the cropped output of a `src_w × src_h` source under `s` at the source's own resolution
|
||||
@@ -440,7 +458,7 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
|
||||
}
|
||||
let s = &*settings;
|
||||
let frame = frame_for(src, info, s, req.apply_crop);
|
||||
let (full_w, full_h) = frame.fit(req.max_w, req.max_h);
|
||||
let (full_w, full_h) = req.size(&frame);
|
||||
// sizes and scale are those of the whole output; a window only narrows what is drawn
|
||||
let px_per_long = frame.px_per_long(full_w);
|
||||
let mut fixed_air = None;
|
||||
@@ -775,6 +793,28 @@ pub(crate) fn for_rows<T: Send>(data: &mut [T], w: usize, f: impl Fn(usize, &mut
|
||||
par_rows(data, w, f)
|
||||
}
|
||||
|
||||
/// `plan` must keep the output box the caller (export) already decided instead of
|
||||
/// re-fitting it: `Frame::fit` passes a box through unchanged only when it matches
|
||||
/// the *decoded* frame's aspect within rounding slack (geometry.rs:189-191), so a
|
||||
/// reduced source whose aspect rounds differently (a 149 x 100 proxy of a 240 x 160
|
||||
/// photo) makes `plan` return a size a pixel off from the box (issue #1042).
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn plan_preserves_matching_box_size() {
|
||||
let src = Rgb32f::from_fn(149, 100, |_, _| [0.5; 3]);
|
||||
let info = SourceInfo { native_long: Some(240), ..SourceInfo::default() };
|
||||
let s = DevelopSettings::default();
|
||||
let fitted = plan(&src, &info, &s, &RenderRequest::fit(240, 160));
|
||||
assert_eq!((fitted.w, fitted.h), (238, 160));
|
||||
let req = RenderRequest::exact(240, 160);
|
||||
let p = plan(&src, &info, &s, &req);
|
||||
assert_eq!((p.w, p.h), (240, 160));
|
||||
// an embedded preview of another shape keeps its shape: an exact box must not stretch it
|
||||
let preview = Rgb32f::from_fn(120, 100, |_, _| [0.5; 3]);
|
||||
let p = plan(&preview, &info, &s, &req);
|
||||
assert_eq!((p.w, p.h), (192, 160));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -278,13 +278,13 @@ pub struct LightOps {
|
||||
/// The fits of Contrast and Blacks, in the order they apply.
|
||||
pub const FITS: [&Fit; 2] = [&fitted::CONTRAST, &fitted::BLACKS];
|
||||
|
||||
/// Whether `s` renders `info` with the V4 operators: process V4 and a raw with its camera's tone
|
||||
/// Whether `s` renders `info` with the V4 operators: process V4 or later and a raw with its camera's tone
|
||||
/// curve (other sources keep the tone map's own Contrast and Blacks).
|
||||
pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool {
|
||||
let camera_look = info.raw && info.camera_tone.is_some();
|
||||
match s.process.process() {
|
||||
Process::V1 | Process::V2 | Process::V3 => false,
|
||||
Process::V4 => camera_look,
|
||||
Process::V4 | Process::V5 => camera_look,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -375,7 +375,7 @@ pub fn base_detail_radius(px_per_long: f64) -> usize {
|
||||
pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize {
|
||||
match s.process.process() {
|
||||
Process::V1 => 0,
|
||||
Process::V2 | Process::V3 | Process::V4 => base_detail_radius(px_per_long),
|
||||
Process::V2 | Process::V3 | Process::V4 | Process::V5 => base_detail_radius(px_per_long),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -356,8 +356,8 @@ mod tests {
|
||||
m.components.push(comp(MaskShape::Object {
|
||||
hint: vec![Point::new(1e300, -1e300)],
|
||||
exclude: Vec::new(),
|
||||
seg: Some(SegMask { side: 1024, data: "not base64".into(), rect: Some([f64::NAN, 0.0, 2.0, -1.0]) }),
|
||||
detail: vec![SegMask { side: 0, data: String::new(), rect: None }],
|
||||
seg: Some(SegMask { side: 1024, data: "not base64".into(), rect: Some([f64::NAN, 0.0, 2.0, -1.0]), grid: None }),
|
||||
detail: vec![SegMask { side: 0, data: String::new(), rect: None, grid: None }],
|
||||
edge: 0.0,
|
||||
}));
|
||||
m.on_photo = false;
|
||||
|
||||
@@ -205,7 +205,12 @@ fn ai_shapes_without_a_segmentation_select_nothing() {
|
||||
for shape in [
|
||||
MaskShape::Object { hint: vec![], exclude: vec![], seg: None, detail: vec![], edge: 0.0 },
|
||||
MaskShape::Prompt { text: "sky".into(), seg: None, detail: vec![], edge: 0.0 },
|
||||
MaskShape::Prompt { text: "sky".into(), seg: Some(SegMask { side: 4, data: "damaged!".into(), rect: None }), detail: vec![], edge: 0.0 },
|
||||
MaskShape::Prompt {
|
||||
text: "sky".into(),
|
||||
seg: Some(SegMask { side: 4, data: "damaged!".into(), rect: None, grid: None }),
|
||||
detail: vec![],
|
||||
edge: 0.0,
|
||||
},
|
||||
] {
|
||||
assert!(shape_alpha(&shape, &f, 30, 30, &img, &l, 0.0, None).data.iter().all(|v| *v == 0.0));
|
||||
}
|
||||
|
||||
@@ -38,19 +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;
|
||||
// A uniform source varies by one output level with ordered Bayer dithering.
|
||||
let spans: [u8; 3] = std::array::from_fn(|c| {
|
||||
let min = image.data.iter().map(|p| p[c]).min().unwrap();
|
||||
let max = image.data.iter().map(|p| p[c]).max().unwrap();
|
||||
max - min
|
||||
});
|
||||
eprintln!("chroma {chroma}: first {:?}, channel spans {spans:?}", image.data[0]);
|
||||
assert!(spans.into_iter().all(|span| span <= 1), "chroma {chroma}: {spans:?}");
|
||||
for pixel in &image.data {
|
||||
assert_eq!(pixel[3], 255, "opaque output");
|
||||
for (actual, expected) in pixel.iter().copied().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]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,13 +129,11 @@ fn golden(process: ProcessVersion) -> u64 {
|
||||
h
|
||||
}
|
||||
|
||||
/// V1 and V2 match upstream main 89725652, including ordered display dithering from 56d1cc28.
|
||||
/// The exact fixture was run on that unmodified main on macOS aarch64. Restoring only
|
||||
/// its old round-to-nearest 8-bit quantizer reproduced the historical e2d18b5fb hashes
|
||||
/// (V1 0x5bf0a7c8579f3f34, V2 0x87a3598c15979e4d); the new hashes include the intended dither.
|
||||
/// The renders call platform powf / exp2 / log2, whose last bits can differ elsewhere,
|
||||
/// so only macOS aarch64 checks the hashes. Before updating them during a merge,
|
||||
/// run this exact fixture independently on main. The colour proposal must not change V1/V2.
|
||||
/// 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.
|
||||
#[test]
|
||||
fn v1_and_v2_render_as_before_v3() {
|
||||
let got = [golden(ProcessVersion(1)), golden(ProcessVersion(2))];
|
||||
@@ -154,6 +143,8 @@ fn v1_and_v2_render_as_before_v3() {
|
||||
}
|
||||
}
|
||||
|
||||
// Rechecked on unmodified main 472560b3 (macOS aarch64): ordered output dithering
|
||||
// changed these fixture bytes; the assertions and render paths remain unchanged.
|
||||
const GOLDEN: [u64; 2] = [0x4830_59a3_ad92_326c, 0x9653_aed0_ea32_aff3];
|
||||
|
||||
fn on(process: Process, s: &DevelopSettings) -> DevelopSettings {
|
||||
@@ -307,7 +298,7 @@ fn v3_sliders_move_a_grey_ramp_their_way() {
|
||||
let ramp = Rgb32f::from_fn(256, 8, |x, _| [0.0005 * 1.035f32.powi(x as i32); 3]);
|
||||
let shot = |id: &str, v: f64| {
|
||||
let mut s = DevelopSettings::default();
|
||||
assert_eq!(s.process.process(), Process::V4);
|
||||
assert!(s.process.process() >= Process::V4, "the default process has the V4 sliders");
|
||||
controls::set(&mut s, id, v);
|
||||
let r = render(&ramp, &camera_look(), &s, &RenderRequest::fit(256, 8)).image;
|
||||
(0..256).map(|x| r.get(x, 4)).collect::<Vec<[u8; 4]>>()
|
||||
@@ -323,14 +314,8 @@ fn v3_sliders_move_a_grey_ramp_their_way() {
|
||||
("light.blacks", -60.0),
|
||||
] {
|
||||
let r = shot(id, v);
|
||||
// Spatial dither may fall one output level below the running maximum.
|
||||
// Tracking the whole prefix still rejects a gradual cumulative decline.
|
||||
let mut highest = luma(r[0]);
|
||||
for pixel in &r {
|
||||
let value = luma(*pixel);
|
||||
assert!(value + 1 >= highest, "{id} {v}: the ramp falls by more than one dither level");
|
||||
highest = highest.max(value);
|
||||
}
|
||||
// (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::<i32>();
|
||||
let (dark, light) = (diff(40, 90), diff(170, 220));
|
||||
|
||||
@@ -264,3 +264,67 @@ fn the_base_plane_is_cached_per_process() {
|
||||
assert_ne!(local::base_key(&s1, sg, 0), local::base_key(&s2, sg, 0), "the process is part of the key");
|
||||
assert_ne!(local::base_key(&s2, sg, 0), local::base_key(&s2, sg, sig.base_detail));
|
||||
}
|
||||
|
||||
/// Issue #1632: past its last fitted knot (here 1.0 stop below the sensor's white, scene 1.0, at
|
||||
/// 8-bit 233, as on the CC0 ILCE-7CR file) a raw's camera tone curve closed on white exponentially
|
||||
/// in linear light, so Exposure +1 rendered the sensor's white at 255 and Exposure +2 left the top
|
||||
/// stop it recorded (scene 0.5..1.0) under one 8-bit code. The latest process rolls off in stops
|
||||
/// and keeps both apart; V1 to V4 keep their look.
|
||||
#[test]
|
||||
fn exposure_keeps_the_highlights_a_camera_curve_recorded() {
|
||||
use lightcraft_color::transfer::linear_to_srgb;
|
||||
let knots = std::array::from_fn(|i| {
|
||||
let x = 0.003 * 1.18f32.powi(i as i32);
|
||||
[x, 1.0 - (-3.3 * x).exp()]
|
||||
});
|
||||
let info = SourceInfo { raw: true, camera_tone: crate::tone::CameraTone::new(knots), ..SourceInfo::default() };
|
||||
let at = |process: Process, ev: f32, y: f32| {
|
||||
let o = crate::finish::base_tone(&on(process), &info, 1.0).apply(y * ev.exp2());
|
||||
(linear_to_srgb(o.clamp(0.0, 1.0)) * 255.0).round()
|
||||
};
|
||||
for ev in [0.0, 1.0, 2.0] {
|
||||
let (white, half) = (at(Process::LATEST, ev, 1.0), at(Process::LATEST, ev, 0.5));
|
||||
assert!(white <= 254.0, "Exposure {ev:+}: the sensor's white renders at {white}");
|
||||
assert!(white - half >= 1.5, "Exposure {ev:+}: the top stop spans {half}..{white}");
|
||||
}
|
||||
// the earlier processes are frozen: the sensor's white at 255 from Exposure +1
|
||||
for p in [Process::V1, Process::V2, Process::V3, Process::V4] {
|
||||
assert_eq!(at(p, 1.0, 1.0), 255.0, "{p:?}");
|
||||
}
|
||||
// up to the last knot every process renders the camera's curve
|
||||
for y in [0.003, 0.02, 0.18, 0.4, 0.5] {
|
||||
let (v2, v3) = (crate::finish::base_tone(&on(Process::V2), &info, 1.0), crate::finish::base_tone(&on(Process::LATEST), &info, 1.0));
|
||||
assert!((v2.apply(y) - v3.apply(y)).abs() < 1e-6, "{y}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Issue #1632: a raw without a camera curve takes the generic curve, which reached white about ¼
|
||||
/// stop past the sensor's white (scene 1.0) and clipped there, so Exposure +1 rendered the top stop
|
||||
/// the sensor recorded (scene 0.5..1.0) at 8-bit 255 from its upper half. The latest process rolls
|
||||
/// off in stops from half a stop below the white point; V1 to V4 keep their look.
|
||||
#[test]
|
||||
fn exposure_keeps_the_highlights_the_generic_curve_recorded() {
|
||||
use lightcraft_color::transfer::linear_to_srgb;
|
||||
let info = SourceInfo { raw: true, ..SourceInfo::default() };
|
||||
let at = |process: Process, ev: f32, y: f32| {
|
||||
let o = crate::finish::base_tone(&on(process), &info, 1.0).apply(y * ev.exp2());
|
||||
(linear_to_srgb(o.clamp(0.0, 1.0)) * 255.0).round()
|
||||
};
|
||||
for ev in [0.0, 1.0, 2.0] {
|
||||
let (white, half) = (at(Process::LATEST, ev, 1.0), at(Process::LATEST, ev, 0.5));
|
||||
assert!(white <= 253.0, "Exposure {ev:+}: the sensor's white renders at {white}");
|
||||
assert!(white - half >= 3.0, "Exposure {ev:+}: the top stop spans {half}..{white}");
|
||||
}
|
||||
// the curve still reaches white, 5 stops past the sensor's
|
||||
assert_eq!(at(Process::LATEST, 5.0, 1.0), 255.0);
|
||||
// the earlier processes are frozen: the sensor's white at 255 from Exposure +1
|
||||
for p in [Process::V1, Process::V2, Process::V3, Process::V4] {
|
||||
assert_eq!(at(p, 1.0, 1.0), 255.0, "{p:?}");
|
||||
}
|
||||
assert_eq!(at(Process::V2, 0.0, 1.0), at(Process::V1, 0.0, 1.0));
|
||||
// below the knee every process renders the same curve
|
||||
let (v2, v3) = (crate::finish::base_tone(&on(Process::V2), &info, 1.0), crate::finish::base_tone(&on(Process::LATEST), &info, 1.0));
|
||||
for y in [0.003, 0.02, 0.18, 0.4, 0.6] {
|
||||
assert_eq!(v2.apply(y), v3.apply(y), "{y}");
|
||||
}
|
||||
}
|
||||
+233
-4
@@ -90,8 +90,88 @@ impl CameraTone {
|
||||
let slope = ((b[1] - a[1]) / (b[0] - a[0])).clamp(0.1, 16.0);
|
||||
1.0 - (1.0 - b[1]) * (-(y - b[0]) * slope / (1.0 - b[1]).max(0.01)).exp()
|
||||
}
|
||||
|
||||
/// [`CameraTone::apply`] as process V5 extends it past the last knot (issue #1632). The curve is
|
||||
/// fitted only to camera JPEG tones below 0.85, so its last knot lies 1 to 3 stops below the
|
||||
/// sensor's white on most photos and everything above it is extrapolated. [`CameraTone::apply`]
|
||||
/// closes the gap to white exponentially in linear light: it reaches 8-bit 255 within about a
|
||||
/// stop past the sensor's white, and Exposure +1 turns the top stop the sensor recorded white.
|
||||
/// Here the gap shrinks in stops instead, `gap / (1 + c·(2^(k·t) − 1))` at `t` stops past the
|
||||
/// knot, with `c` matching the curve's slope there (so the join is smooth) and the gap halving
|
||||
/// every [`ROLLOFF_STOPS`] stops in the end. Same value as [`CameraTone::apply`] up to the last
|
||||
/// knot, monotone, finite and at most 1. In real numbers it only approaches white; in `f32` the
|
||||
/// gap can round to 0 far up, and within a stop or two for a last knot a few ulps below white.
|
||||
pub fn apply_rolloff(&self, y: f32) -> f32 {
|
||||
let (a, b) = (self.knots[30], self.knots[31]);
|
||||
if !y.is_finite() || y <= b[0] {
|
||||
return self.apply(y);
|
||||
}
|
||||
// the last segment's own slope, so the join is smooth even when it is flat (`new` keeps the
|
||||
// knots non-decreasing, so it is at least 0)
|
||||
let slope = ((b[1] - a[1]) / (b[0] - a[0])).max(0.0);
|
||||
// `CameraTone::new` keeps the last knot below 1, so the gap is positive (no floor: one
|
||||
// would step the curve down past a knot within it of white)
|
||||
rolloff_past(y, b, slope, CAMERA_MIN_SLOPE)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pace [`CameraTone::apply_rolloff`] closes on white at least at, as display per unit of scene
|
||||
/// luminance at the last knot (the floor [`CameraTone::apply`] puts on its slope there). A last
|
||||
/// segment flatter than this still joins with its own slope; [`rolloff_past`] then adds a term that
|
||||
/// has no slope at the knot and reaches this pace further up, so a flat curve does not stay below
|
||||
/// white.
|
||||
const CAMERA_MIN_SLOPE: f32 = 0.1;
|
||||
|
||||
/// Stops in which the gap between a V5 curve and white halves, far past where its shoulder starts
|
||||
/// ([`CameraTone::apply_rolloff`], [`ToneMap::rolloff_hdr`]). With 1, the sensor's white renders at
|
||||
/// 8-bit 239–250 on the CC0 corpus files with a camera curve (Sony, Nikon, Fujifilm) at Exposure 0
|
||||
/// and below 254 up to Exposure +2, where the extension of [`CameraTone::apply`] reaches 254–255 by
|
||||
/// Exposure +1 (issue #1632).
|
||||
pub const ROLLOFF_STOPS: f32 = 1.0;
|
||||
|
||||
/// Process V5's shoulder past a knee at scene luminance `x` and display `o` (below 1), where the
|
||||
/// curve rises at `slope` (display per unit of scene luminance): the gap to white is
|
||||
/// `gap / (1 + c·(2^(k·t) − 1))` at `t = log2(y / x)` stops past the knee, `k = 1 / ROLLOFF_STOPS`,
|
||||
/// so it halves every [`ROLLOFF_STOPS`] stops in the end. `c` gives it the curve's slope at the
|
||||
/// knee: d(display)/d(stop) there is `slope · x · ln 2` on the curve and `gap · c · k · ln 2` on the
|
||||
/// shoulder. When `slope` is below `min_slope`, `d · (u − ln(1 + u))` (with `u = 2^(k·t) − 1`)
|
||||
/// joins the denominator: it adds no slope at the knee, so the join keeps the curve's own slope, and
|
||||
/// far up it grows like `d · u`, so the shoulder closes on white at `min_slope`'s pace (the gap still
|
||||
/// halves every [`ROLLOFF_STOPS`] stops in the end). A term growing faster than `u` would close a
|
||||
/// flat curve on white faster than a steeper one far up, and a darker curve would end up above it.
|
||||
/// Monotone for `y ≥ x`, finite and at most 1; in real numbers it only approaches white, while in
|
||||
/// `f32` the gap rounds to 0 eventually.
|
||||
fn rolloff_past(y: f32, [x, o]: [f32; 2], slope: f32, min_slope: f32) -> f32 {
|
||||
let gap = 1.0 - o;
|
||||
let k = 1.0 / ROLLOFF_STOPS;
|
||||
// bounded, so `c · 0` right past the knee stays 0 for a gap of a few ulps
|
||||
let per = |s: f32| (s * x / (gap * k)).min(1e30);
|
||||
let c = per(slope);
|
||||
let d = (per(min_slope) - c).max(0.0);
|
||||
let u = (k * (y / x).log2()).exp2() - 1.0;
|
||||
// each term only when its coefficient is positive: `0 · ∞` is NaN far up
|
||||
let linear = if c > 0.0 { c * u } else { 0.0 };
|
||||
let floor = if d > 0.0 { d * past_join(u) } else { 0.0 };
|
||||
1.0 - gap / (1.0 + linear + floor)
|
||||
}
|
||||
|
||||
/// `u − ln(1 + u)` for `u ≥ 0`: 0 with no slope at 0, then rising like `u` (infinite for infinite
|
||||
/// `u`). In `f64`, where the difference keeps its digits down to tiny `u`.
|
||||
fn past_join(u: f32) -> f32 {
|
||||
if u.is_infinite() {
|
||||
return u;
|
||||
}
|
||||
let u = f64::from(u);
|
||||
(u - u.ln_1p()).max(0.0) as f32
|
||||
}
|
||||
|
||||
/// Stops below its white point where process V5's generic raw curve ([`ToneMap::rolloff_hdr`])
|
||||
/// leaves the extended Reinhard curve for the [`ROLLOFF_STOPS`] shoulder, instead of clipping at
|
||||
/// the white point. With ½, the sensor's white of a raw without a camera curve (scene 1.0, about
|
||||
/// ¼ stop below that white point at default settings) renders at about 8-bit 235, 248 and 252 at
|
||||
/// Exposure 0, +1 and +2 where V1 to V4 render 239, 255 and 255 (issue #1632).
|
||||
pub const GENERIC_KNEE_STOPS: f32 = 0.5;
|
||||
|
||||
/// Scene EV over grey where [`ToneMap::hdr`] starts lifting highlights above the SDR curve.
|
||||
const HDR_FROM_EV: f32 = 1.5;
|
||||
|
||||
@@ -111,6 +191,16 @@ impl ToneMap {
|
||||
/// gain map only lifts highlights), then the highlights gain up to `peak − 1` more as in
|
||||
/// [`ToneMap::hdr`].
|
||||
pub fn camera_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::camera_with(|y| curve.apply(y), curve.chroma, contrast, whites, blacks, peak)
|
||||
}
|
||||
|
||||
/// [`ToneMap::camera_hdr`] of process V5: past its last knot the camera curve rolls off in stops
|
||||
/// ([`CameraTone::apply_rolloff`]) instead of closing on white within a stop of the sensor's.
|
||||
pub fn camera_rolloff_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::camera_with(|y| curve.apply_rolloff(y), curve.chroma, contrast, whites, blacks, peak)
|
||||
}
|
||||
|
||||
fn camera_with(curve: impl Fn(f32) -> f32, chroma: [f32; CHROMA_N], contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 };
|
||||
let adjustment = Self::display(contrast, whites, blacks);
|
||||
let neutral = contrast == 0.0 && whites == 0.0 && blacks == 0.0;
|
||||
@@ -118,12 +208,12 @@ impl ToneMap {
|
||||
let lut = (0..LUT_N)
|
||||
.map(|i| {
|
||||
let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32;
|
||||
let y = curve.apply(GREY * 2f32.powf(ev));
|
||||
let y = curve(GREY * 2f32.powf(ev));
|
||||
let o = if neutral { y } else { adjustment.apply(y) };
|
||||
if peak > 1.0 { (o + (peak - 1.0) * smooth(HDR_FROM_EV, top, ev)).clamp(0.0, peak) } else { o }
|
||||
})
|
||||
.collect();
|
||||
ToneMap { lut, chroma: curve.chroma }
|
||||
ToneMap { lut, chroma }
|
||||
}
|
||||
/// `contrast`, `whites`, `blacks` in −100..100 (Lightroom slider units).
|
||||
pub fn new(contrast: f64, whites: f64, blacks: f64) -> ToneMap {
|
||||
@@ -136,6 +226,19 @@ impl ToneMap {
|
||||
/// white point moved up by the headroom, so the result stays monotone, never exceeds `peak`,
|
||||
/// and reaches it there (within the table's range).
|
||||
pub fn hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::generic(contrast, whites, blacks, peak, false)
|
||||
}
|
||||
|
||||
/// [`ToneMap::hdr`] of process V5 (issue #1632): from [`GENERIC_KNEE_STOPS`] below the white
|
||||
/// point the curve rolls off into white in stops, with the same value and slope at the join,
|
||||
/// instead of reaching white about ¼ stop past the sensor's white and clipping there. The SDR
|
||||
/// curve stays below 1 (SDR white) and is the same as [`ToneMap::hdr`]'s below the join; for
|
||||
/// `peak` above 1 the HDR lift then takes highlights up to `peak`, as in [`ToneMap::hdr`].
|
||||
pub fn rolloff_hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::generic(contrast, whites, blacks, peak, true)
|
||||
}
|
||||
|
||||
fn generic(contrast: f64, whites: f64, blacks: f64, peak: f32, rolloff: bool) -> ToneMap {
|
||||
let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 };
|
||||
let c = (contrast / 100.0) as f32;
|
||||
let slope = if c >= 0.0 { 1.0 + 0.55 * c } else { 1.0 + 0.4 * c };
|
||||
@@ -144,12 +247,17 @@ impl ToneMap {
|
||||
let wl = GREY * 2f32.powf(white_ev);
|
||||
let pre = 1.0 + GREY / wl; // keep grey near grey
|
||||
let b = (blacks / 100.0) as f32;
|
||||
// extended Reinhard with white point wl: y(1 + y/wl²)/(1 + y), reaching 1 at wl
|
||||
let reinhard = |y: f32| y * (1.0 + y / (wl * wl)) / (1.0 + y);
|
||||
// V5's knee, below the white point, and the curve's slope there: (1 + y(2 + y)/wl²)/(1 + y)²
|
||||
let knee = wl * (-GENERIC_KNEE_STOPS).exp2();
|
||||
let knee_slope = (1.0 + knee * (2.0 + knee) / (wl * wl)) / ((1.0 + knee) * (1.0 + knee));
|
||||
let knee = [knee, reinhard(knee)];
|
||||
let lut = (0..LUT_N)
|
||||
.map(|i| {
|
||||
let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32;
|
||||
let y = GREY * 2f32.powf(ev * slope) * pre;
|
||||
// extended Reinhard with white point wl: y(1 + y/wl²)/(1 + y)
|
||||
let mut o = y * (1.0 + y / (wl * wl)) / (1.0 + y);
|
||||
let mut o = if rolloff && y > knee[0] && knee[1] < 1.0 { rolloff_past(y, knee, knee_slope, 0.0) } else { reinhard(y) };
|
||||
o = o.min(1.0);
|
||||
// Toe: blacks < 0 crushes, > 0 lifts.
|
||||
if b < 0.0 {
|
||||
@@ -324,6 +432,127 @@ mod tests {
|
||||
assert!(serde_json::from_value::<CameraTone>(serde_json::json!({"knots": invalid})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rolloff_joins_the_curve_smoothly_and_never_reaches_white() {
|
||||
let curve = CameraTone::new(knots()).unwrap();
|
||||
let last = curve.knots()[31];
|
||||
// the camera's curve up to the last knot
|
||||
for i in 0..200 {
|
||||
let y = last[0] * i as f32 / 199.0;
|
||||
assert_eq!(curve.apply_rolloff(y), curve.apply(y), "{y}");
|
||||
}
|
||||
// continuous, with the slope of the last segment, at the knot
|
||||
let a = curve.knots()[30];
|
||||
let slope = (last[1] - a[1]) / (last[0] - a[0]);
|
||||
let h = last[0] * 1e-3;
|
||||
let after = (curve.apply_rolloff(last[0] + h) - curve.apply_rolloff(last[0])) / h;
|
||||
assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}");
|
||||
// monotone, below white, and slower to close on it than the V1/V2 extension
|
||||
let mut previous = last[1];
|
||||
for i in 1..3000 {
|
||||
let y = last[0] * 1.005f32.powi(i);
|
||||
let o = curve.apply_rolloff(y);
|
||||
assert!(o >= previous && o < 1.0, "{y}: {o}");
|
||||
assert!(o <= curve.apply(y) + 1e-6, "{y}");
|
||||
previous = o;
|
||||
}
|
||||
assert!(1.0 - curve.apply_rolloff(last[0] * 8.0) > 4.0 * (1.0 - curve.apply(last[0] * 8.0)));
|
||||
// a steep last segment joins with its own slope, and a last knot next to white without a step
|
||||
for top in [0.9, 0.99995, 1.0 - f32::EPSILON] {
|
||||
let mut k = knots();
|
||||
k[31] = [k[30][0] * 1.01, top];
|
||||
let c = CameraTone::new(k).unwrap();
|
||||
let slope = (k[31][1] - k[30][1]) / (k[31][0] - k[30][0]);
|
||||
assert!(slope > 16.0 || top < 0.99, "{slope}");
|
||||
let mut prev = c.apply_rolloff(k[31][0]);
|
||||
assert_eq!(prev, top);
|
||||
for i in 1..2000 {
|
||||
let o = c.apply_rolloff(k[31][0] * 1.0001f32.powi(i));
|
||||
assert!(o.is_finite() && o >= prev && o <= 1.0, "{top} {i}: {o} < {prev}");
|
||||
prev = o;
|
||||
}
|
||||
if top == 0.9 {
|
||||
let h = k[31][0] * 1e-5;
|
||||
let after = (c.apply_rolloff(k[31][0] + h) - top) / h;
|
||||
assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}");
|
||||
}
|
||||
}
|
||||
// a flat or shallow last segment joins with its own slope (not the 0.1 floor of the V1/V2
|
||||
// extension) and still closes on white further up
|
||||
for s in [0.0f32, 0.05] {
|
||||
let mut k = knots();
|
||||
k[31][1] = k[30][1] + s * (k[31][0] - k[30][0]);
|
||||
let c = CameraTone::new(k).unwrap();
|
||||
let (x, top) = (k[31][0], k[31][1]);
|
||||
let h = x * 1e-4;
|
||||
let after = (c.apply_rolloff(x + h) - top) / h;
|
||||
assert!((after - s).abs() < 0.01, "{s}: right slope {after}");
|
||||
let mut prev = top;
|
||||
for i in 1..3000 {
|
||||
let o = c.apply_rolloff(x * 1.005f32.powi(i));
|
||||
assert!(o.is_finite() && o >= prev && o <= 1.0, "{s} {i}: {o} < {prev}");
|
||||
prev = o;
|
||||
}
|
||||
assert!(1.0 - c.apply_rolloff(x * 64.0) < (1.0 - top) / 4.0, "{s}");
|
||||
for y in [f32::MAX, f32::INFINITY] {
|
||||
assert!((0.0..=1.0).contains(&c.apply_rolloff(y)), "{s} {y}");
|
||||
}
|
||||
}
|
||||
// hostile input
|
||||
for y in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX] {
|
||||
let o = curve.apply_rolloff(y);
|
||||
assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}");
|
||||
}
|
||||
// the tone map built from it is monotone and bounded, SDR and HDR
|
||||
for peak in [1.0f32, 4.0] {
|
||||
let t = ToneMap::camera_rolloff_hdr(&curve, 0.0, 0.0, 0.0, peak);
|
||||
let mut prev = -1.0;
|
||||
for i in 0..2400 {
|
||||
let o = t.apply(1e-5 * 1.01f32.powi(i));
|
||||
assert!((0.0..=peak).contains(&o) && o >= prev - 1e-6, "{peak} {i}: {o}");
|
||||
prev = o;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_rolloff_joins_the_curve_smoothly_and_never_reaches_white() {
|
||||
for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0), (0.0, -100.0, 0.0)] {
|
||||
for peak in [1.0f32, 4.0] {
|
||||
let (clip, roll) = (ToneMap::hdr(c, w, b, peak), ToneMap::rolloff_hdr(c, w, b, peak));
|
||||
let (clip, roll) = (clip.lut(), roll.lut());
|
||||
// the generic curve up to the knee, never brighter past it
|
||||
let join = roll.iter().zip(clip).position(|(r, c)| r != c).expect("the shoulder starts inside the table");
|
||||
assert!(join > 2 && roll[join] < clip[join], "{c} {w} {b} {peak}: {join}");
|
||||
for (i, (r, c)) in roll.iter().zip(clip).enumerate() {
|
||||
assert!(*r <= c + 1e-6, "{c} {w} {b} {peak} {i}: {r} > {c}");
|
||||
}
|
||||
// same value and slope at the join: the step across it is the step before it
|
||||
let (before, across) = (roll[join - 1] - roll[join - 2], roll[join] - roll[join - 1]);
|
||||
assert!((across / before - 1.0).abs() < 0.02, "{c} {w} {b} {peak}: {before} then {across}");
|
||||
// monotone, and below white where the V1/V2 curve clips (SDR) or lifts to `peak` (HDR)
|
||||
assert!(roll.windows(2).all(|p| p[1] >= p[0] - 1e-6), "{c} {w} {b} {peak}");
|
||||
if peak == 1.0 {
|
||||
assert_eq!(clip[LUT_N - 1], 1.0);
|
||||
// close to it at the top of the table at default settings (10 EV over grey);
|
||||
// Whites −100 moves the white point, and so the shoulder, up 1.6 stops
|
||||
let top = roll[LUT_N - 1];
|
||||
assert!(top < 1.0 && (top > 0.999 || w < 0.0), "{c} {w} {b}: {top}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// no kink where V1/V2 clip: there the clipped curve stops rising at once
|
||||
let (clip, roll) = (ToneMap::new(0.0, 0.0, 0.0), ToneMap::rolloff_hdr(0.0, 0.0, 0.0, 1.0));
|
||||
let kink = |lut: &[f32]| lut.windows(3).filter(|p| p[1] - p[0] > 1e-5).map(|p| 1.0 - (p[2] - p[1]) / (p[1] - p[0])).fold(0.0f32, f32::max);
|
||||
assert!(kink(clip.lut()) > 0.9);
|
||||
assert!(kink(roll.lut()) < 0.05, "{}", kink(roll.lut()));
|
||||
// hostile input (NaN passes through `ToneMap::apply` as on every curve)
|
||||
for y in [f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX, f32::MIN_POSITIVE] {
|
||||
let o = roll.apply(y);
|
||||
assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monotone_and_bounded() {
|
||||
for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0)] {
|
||||
|
||||
@@ -57,8 +57,16 @@ pub enum Overlay {
|
||||
SharpenDetail,
|
||||
/// The sharpening mask, white where sharpening applies (Alt-drag on Sharpening Masking).
|
||||
SharpenMask,
|
||||
/// Clipping warnings (J): the photo with every pixel that has a channel at 255 painted
|
||||
/// [`CLIP_HIGH`] and every other pixel with a channel at 0 painted [`CLIP_LOW`].
|
||||
ClipWarnings,
|
||||
}
|
||||
|
||||
/// [`Overlay::ClipWarnings`] colour of clipped highlights.
|
||||
pub const CLIP_HIGH: [u8; 3] = [255, 0, 0];
|
||||
/// [`Overlay::ClipWarnings`] colour of clipped shadows.
|
||||
pub const CLIP_LOW: [u8; 3] = [0, 0, 255];
|
||||
|
||||
/// [`Overlay::HdrRange`] colours (sRGB) for 0–1, 1–2, 2–3 and ≥ 3 stops above SDR white.
|
||||
pub const HDR_BANDS: [[u8; 3]; 4] = [[255, 214, 92], [255, 150, 40], [235, 64, 52], [214, 60, 210]];
|
||||
|
||||
@@ -148,6 +156,7 @@ impl Overlay {
|
||||
Overlay::Grayscale => (8, 0.0),
|
||||
Overlay::SharpenDetail => (9, 0.0),
|
||||
Overlay::SharpenMask => (10, 0.0),
|
||||
Overlay::ClipWarnings => (11, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,6 +180,7 @@ impl Overlay {
|
||||
8 => Overlay::Grayscale,
|
||||
9 => Overlay::SharpenDetail,
|
||||
10 => Overlay::SharpenMask,
|
||||
11 => Overlay::ClipWarnings,
|
||||
_ => Overlay::None,
|
||||
}
|
||||
}
|
||||
@@ -189,6 +199,7 @@ impl Overlay {
|
||||
Overlay::Grayscale => 0x5002,
|
||||
Overlay::SharpenDetail => 0x5003,
|
||||
Overlay::SharpenMask => 0x5004,
|
||||
Overlay::ClipWarnings => 0x5005,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,7 +219,7 @@ impl Overlay {
|
||||
/// The clipping previews, which test the sRGB values the histogram counts (a render for a
|
||||
/// display profile draws them in sRGB, then converts).
|
||||
pub fn is_clipping(self) -> bool {
|
||||
matches!(self, Overlay::ClipShadows | Overlay::ClipHighlights)
|
||||
matches!(self, Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::ClipWarnings)
|
||||
}
|
||||
|
||||
/// Whether the overlay draws from the render's detail planes ([`sharpen_plane`]).
|
||||
@@ -219,7 +230,10 @@ impl Overlay {
|
||||
/// Whether the overlay works pixel by pixel on the finished image, so a window render shows
|
||||
/// the same as the whole frame would.
|
||||
pub fn per_pixel(self) -> bool {
|
||||
matches!(self, Overlay::None | Overlay::Mask { .. } | Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::Grayscale)
|
||||
matches!(
|
||||
self,
|
||||
Overlay::None | Overlay::Mask { .. } | Overlay::ClipShadows | Overlay::ClipHighlights | Overlay::ClipWarnings | Overlay::Grayscale
|
||||
)
|
||||
}
|
||||
|
||||
/// The mask an [`Overlay::Mask`] shows (if it exists in `s` and has components).
|
||||
@@ -310,6 +324,7 @@ pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, plane: Option<&Plane>
|
||||
}
|
||||
Overlay::ClipShadows => clipping(img, false),
|
||||
Overlay::ClipHighlights => clipping(img, true),
|
||||
Overlay::ClipWarnings => clip_warnings(img),
|
||||
Overlay::Grayscale => grayscale(img),
|
||||
Overlay::SharpenDetail | Overlay::SharpenMask => {
|
||||
if let Some(p) = plane.filter(|a| (a.width, a.height) == (img.width, img.height)) {
|
||||
@@ -362,6 +377,25 @@ pub fn clipping(img: &mut Rgba8, high: bool) {
|
||||
});
|
||||
}
|
||||
|
||||
/// [`Overlay::ClipWarnings`]: pixels with a channel at 255 in [`CLIP_HIGH`], the rest with a
|
||||
/// channel at 0 in [`CLIP_LOW`], everything else unchanged.
|
||||
pub fn clip_warnings(img: &mut Rgba8) {
|
||||
let w = img.width;
|
||||
for_rows(&mut img.data, w, |_, row| {
|
||||
for px in row.iter_mut() {
|
||||
let c = &px[..3];
|
||||
let paint = if c.contains(&255) {
|
||||
CLIP_HIGH
|
||||
} else if c.contains(&0) {
|
||||
CLIP_LOW
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
*px = [paint[0], paint[1], paint[2], 255];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn grayscale(img: &mut Rgba8) {
|
||||
let w = img.width;
|
||||
for_rows(&mut img.data, w, |_, row| {
|
||||
@@ -713,7 +747,8 @@ mod tests {
|
||||
assert!(Overlay::for_control(c).is_some(), "{c}");
|
||||
}
|
||||
assert!(Overlay::ClipShadows.is_clipping() && Overlay::ClipHighlights.is_clipping() && !Overlay::Grayscale.is_clipping());
|
||||
let all = [Overlay::ClipShadows, Overlay::ClipHighlights, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask];
|
||||
let all =
|
||||
[Overlay::ClipShadows, Overlay::ClipHighlights, Overlay::Grayscale, Overlay::SharpenDetail, Overlay::SharpenMask, Overlay::ClipWarnings];
|
||||
for o in all {
|
||||
let (k, v) = o.to_parts();
|
||||
assert_eq!(Overlay::from_parts(k, v), o);
|
||||
@@ -721,6 +756,16 @@ mod tests {
|
||||
assert_ne!(o.key(), Overlay::HdrRange.key());
|
||||
}
|
||||
assert!(Overlay::ClipShadows.per_pixel() && !Overlay::SharpenDetail.per_pixel());
|
||||
assert!(Overlay::ClipWarnings.is_clipping() && Overlay::ClipWarnings.per_pixel());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clip_warnings_paint_clipped_pixels_only() {
|
||||
let data = vec![[255, 255, 255, 255], [0, 0, 0, 255], [128, 128, 128, 255], [255, 40, 0, 255], [10, 0, 30, 255]];
|
||||
let mut img = Rgba8 { width: 5, height: 1, data };
|
||||
super::clip_warnings(&mut img);
|
||||
let rgb: Vec<[u8; 3]> = img.data.iter().map(|p| [p[0], p[1], p[2]]).collect();
|
||||
assert_eq!(rgb, [super::CLIP_HIGH, super::CLIP_LOW, [128, 128, 128], super::CLIP_HIGH, super::CLIP_LOW]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
//! Canon CR2 / CR3 (lossless CRX Bayer and version 0x100/0x200 C-RAW) / CRW (the CIFF bodies of 2000–2004; clean-room-derived
|
||||
//! compression, `vendor::crw`; the PowerShot G5's anomalous coding is refused), Nikon NEF/NRW (uncompressed, Huffman lossless / lossy compressed), Sony ARW (uncompressed, ARW2, lossless), Fujifilm RAF (uncompressed Bayer
|
||||
//! and X-Trans, lossless and lossy compressed), Panasonic RW2 / Leica RWL / Panasonic RAW (every raw format: compressed 4 and 6, the prefix-coded strips of 8,
|
||||
//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, 12-bit 16-byte blocks of the E-300/E-330/E-500).
|
||||
//! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (compressed ORF, CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources
|
||||
//! packed 2/5/7, the 16-bit words of the oldest bodies), Pentax PEF (uncompressed, Huffman), Olympus ORF (uncompressed: 16-bit words, 12-bit XZ-2 words, 12-bit 16-byte blocks of the E-300/E-330/E-500; compressed: 12-bit entropy-coded sensor differences across interchangeable-lens and modern compact bodies).
|
||||
//! [`embedded_preview`] covers these containers' JPEG previews. Variants we can't decode yet (CR3 unverified marker families / C-RAW configurations) return [`RawError::Unsupported`]; each vendor module documents its sources
|
||||
//! (public specifications, tag-name documentation, black-box analysis of CC0 samples) and gaps. Non-DNG files carry no
|
||||
//! colour matrix: [`spectral`] has matrices fitted to measured spectral sensitivities for 52 models, and
|
||||
//! otherwise [`color`] falls back to a documented neutral model. The decoders never panic on malformed input.
|
||||
@@ -665,6 +665,8 @@ pub struct ColorData {
|
||||
pub as_shot_neutral: Option<[f64; 3]>,
|
||||
pub as_shot_white_xy: Option<Xy>,
|
||||
/// EV to add for a "normal" rendering (`BaselineExposure` + `BaselineExposureOffset`).
|
||||
/// A full CR3 decode also includes compensation for sample-derived white headroom;
|
||||
/// a header-only probe cannot determine that adjustment.
|
||||
pub baseline_exposure: f64,
|
||||
/// `BaselineSharpness`: sharpening relative to a reference camera (`None`: the DNG default,
|
||||
/// 1). Read and written back by DNG export; rendering doesn't use it yet.
|
||||
|
||||
@@ -27,6 +27,33 @@ const ABOVE_MARGIN: f32 = 0.01;
|
||||
/// How far below the plateau the "average value just below it" reaches.
|
||||
const NEIGHBOURHOOD: usize = 64;
|
||||
|
||||
// CR3 gain-normalized saturation can occupy several nearby codes, rather than one exact value.
|
||||
const CR3_BINS: usize = 256;
|
||||
const CR3_PLATEAU_BINS: usize = 8;
|
||||
const CR3_MIN_SAMPLES: u64 = 64;
|
||||
|
||||
/// The lower edge of a terminal pile-up, ignoring a few brighter outliers. A continuous
|
||||
/// highlight distribution has comparable density below it and therefore has no plateau.
|
||||
fn cr3_plateau(hist: &[[u64; 3]; CR3_BINS], first: &[[u16; 3]; CR3_BINS], colour: usize, from: usize, white: f32) -> Option<f32> {
|
||||
let (start, end, count) = (from + 1..=CR3_BINS)
|
||||
.map(|end| {
|
||||
let start = end.saturating_sub(CR3_PLATEAU_BINS).max(from);
|
||||
let count: u64 = hist[start..end].iter().map(|bin| bin[colour]).sum();
|
||||
(start, end, count)
|
||||
})
|
||||
.max_by_key(|&(_, end, count)| (count, end))?;
|
||||
let below_start = start.saturating_sub(CR3_PLATEAU_BINS);
|
||||
let below: u64 = hist[below_start..start].iter().map(|bin| bin[colour]).sum();
|
||||
let above: u64 = hist[end..].iter().map(|bin| bin[colour]).sum();
|
||||
let density = count as f64 / (end - start) as f64;
|
||||
let below_density = below as f64 / (start - below_start).max(1) as f64;
|
||||
if count < CR3_MIN_SAMPLES || (below > 0 && density < MIN_SPIKE * below_density) || above as f64 > MAX_ABOVE * count as f64 {
|
||||
return None;
|
||||
}
|
||||
let threshold = (density / MIN_SPIKE).max(MIN_SPIKE * below_density).max(1.0);
|
||||
(start..end).find(|&bin| hist[bin][colour] as f64 >= threshold).map(|bin| first[bin][colour] as f32).filter(|&point| point > white)
|
||||
}
|
||||
|
||||
impl RawImage {
|
||||
/// The value each colour's samples saturate at, when that is clearly below the stated white level
|
||||
/// (see the module docs). Only single-plane integer CFA data is examined.
|
||||
@@ -104,6 +131,68 @@ impl RawImage {
|
||||
}
|
||||
changed
|
||||
}
|
||||
/// Recover real CR3 samples beyond a conservatively stated common white level. Search
|
||||
/// coarse bins so gain-spread saturation (e.g. R100) is found too. With enough above-white
|
||||
/// data but no clear pile-up, the bit-depth ceiling keeps all that unclipped headroom.
|
||||
/// One shared range and its compensating baseline EV preserve lower tones and colour ratios.
|
||||
pub(crate) fn extend_cr3_white(&mut self) -> bool {
|
||||
if self.format != crate::RawFormat::Cr3 || !self.color.baseline_exposure.is_finite() || !(1..=16).contains(&self.bits) {
|
||||
return false;
|
||||
}
|
||||
let (RawData::U16(data), Some(cfa)) = (&self.data, &self.cfa) else { return false };
|
||||
let (old, black) = (self.white_at(0), self.black.mean());
|
||||
let ceiling = ((1u32 << self.bits) - 1) as f32;
|
||||
if self.cpp != 1
|
||||
|| !cfa.valid()
|
||||
|| self.width.checked_mul(self.height) != Some(data.len())
|
||||
|| !black.is_finite()
|
||||
|| !old.is_finite()
|
||||
|| black < 0.0
|
||||
|| old <= black
|
||||
|| old >= ceiling
|
||||
|| self.white.is_empty()
|
||||
|| self.white.iter().any(|w| *w != old)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let a = self.active_area;
|
||||
let fits = |start: usize, len: usize, max: usize| start.checked_add(len).is_some_and(|end| end <= max);
|
||||
if a.width == 0 || a.height == 0 || !fits(a.x, a.width, self.width) || !fits(a.y, a.height, self.height) {
|
||||
return false;
|
||||
}
|
||||
let step = ((ceiling - black) / CR3_BINS as f32).ceil().max(1.0);
|
||||
let mut hist = [[0u64; 3]; CR3_BINS];
|
||||
let mut first = [[u16::MAX; 3]; CR3_BINS];
|
||||
let mut over = [0u64; 3];
|
||||
for y in a.y..a.y + a.height {
|
||||
for (x, &v) in data[y * self.width + a.x..][..a.width].iter().enumerate() {
|
||||
if v as f32 > ceiling {
|
||||
return false;
|
||||
}
|
||||
let c = cfa.color_at(a.x + x, y).min(2) as usize;
|
||||
let bin = (((v as f32 - black).max(0.0) / step) as usize).min(CR3_BINS - 1);
|
||||
hist[bin][c] += 1;
|
||||
first[bin][c] = first[bin][c].min(v);
|
||||
over[c] += u64::from(v as f32 > old);
|
||||
}
|
||||
}
|
||||
let above: u64 = over.iter().sum();
|
||||
let pixels = a.width * a.height;
|
||||
if above < CR3_MIN_SAMPLES || (above as f64) < pixels as f64 * 1e-5 {
|
||||
return false;
|
||||
}
|
||||
let from = (((old - black) / step) as usize).min(CR3_BINS - 1);
|
||||
let new = (0..3)
|
||||
.map(|c| if over[c] < CR3_MIN_SAMPLES { ceiling } else { cr3_plateau(&hist, &first, c, from, old).unwrap_or(ceiling) })
|
||||
.fold(ceiling, f32::min);
|
||||
let ev = ((new - black) as f64 / (old - black) as f64).log2();
|
||||
if new <= old || !ev.is_finite() {
|
||||
return false;
|
||||
}
|
||||
self.white.fill(new);
|
||||
self.color.baseline_exposure += ev;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -269,4 +358,98 @@ mod tests {
|
||||
let after = render(&r);
|
||||
assert!(tint(after) < 0.01, "{after:?}");
|
||||
}
|
||||
|
||||
/// Canon states a white level below the sensor's real saturation (EOS RP: 14558 stated, 16383
|
||||
/// real). Samples pile up at the real saturation above the stated white; the white level must be
|
||||
/// extended to the saturation point so highlight reconstruction does not treat real highlight data
|
||||
/// between the two as clipped. The plateau above the stated white is currently outside the search
|
||||
/// range (which ends at the white level), so it is never found and the white level is never extended.
|
||||
#[test]
|
||||
fn extend_white_to_saturation_above_stated_white() {
|
||||
let mut r = raw_with(None, 14558.0);
|
||||
if let RawData::U16(d) = &mut r.data {
|
||||
for v in d.iter_mut().take(2048) {
|
||||
*v = 16383;
|
||||
}
|
||||
}
|
||||
r.format = RawFormat::Cr3;
|
||||
r.bits = 14;
|
||||
r.color.baseline_exposure = 0.5;
|
||||
let original_gain = 2f64.powf(r.color.baseline_exposure) as f32;
|
||||
let before = r.normalized().unwrap();
|
||||
let samples = r.data.clone();
|
||||
assert!(r.extend_cr3_white());
|
||||
let after = r.normalized().unwrap();
|
||||
let gain = 2f64.powf(r.color.baseline_exposure) as f32;
|
||||
for (a, b) in before.data.iter().zip(&after.data) {
|
||||
assert!((a * original_gain - b * gain).abs() < 2e-6, "unclipped exposure changed");
|
||||
}
|
||||
assert_eq!(r.data, samples);
|
||||
let ev = r.color.baseline_exposure;
|
||||
assert!(!r.extend_cr3_white(), "idempotent");
|
||||
assert_eq!(r.color.baseline_exposure, ev);
|
||||
assert_eq!(r.white_at(0), 16383.0);
|
||||
}
|
||||
#[test]
|
||||
fn cr3_headroom_does_not_change_other_formats_or_unproven_plateaus() {
|
||||
let mut r = raw_with(None, 14558.0);
|
||||
if let RawData::U16(d) = &mut r.data {
|
||||
d[..2048].fill(16383);
|
||||
}
|
||||
assert!(!r.extend_cr3_white());
|
||||
assert_eq!(r.white_at(0), 14558.0);
|
||||
r.format = RawFormat::Cr3;
|
||||
r.white = vec![14558.0, 15000.0, 14558.0];
|
||||
assert!(!r.extend_cr3_white());
|
||||
assert_eq!(r.color.baseline_exposure, 0.0);
|
||||
}
|
||||
fn cr3(white: f32) -> RawImage {
|
||||
let mut r = raw_with(None, white);
|
||||
r.format = RawFormat::Cr3;
|
||||
r.bits = 14;
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cr3_headroom_recognizes_a_spread_saturation_plateau() {
|
||||
let mut r = cr3(10439.0);
|
||||
if let RawData::U16(d) = &mut r.data {
|
||||
for (i, v) in d.iter_mut().take(3072).enumerate() {
|
||||
*v = 13300 + (i * 37 % 401) as u16;
|
||||
}
|
||||
}
|
||||
let samples = r.data.clone();
|
||||
assert!(r.extend_cr3_white(), "the R100-style plateau spans hundreds of codes");
|
||||
assert!((13300.0..=13364.0).contains(&r.white_at(0)), "{}", r.white_at(0));
|
||||
assert_eq!(r.data, samples);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cr3_headroom_keeps_valid_values_when_nothing_is_saturated() {
|
||||
let mut r = cr3(14558.0);
|
||||
if let RawData::U16(d) = &mut r.data {
|
||||
for (i, v) in d.iter_mut().enumerate() {
|
||||
*v = 528 + (i * 37 % 15855) as u16;
|
||||
}
|
||||
}
|
||||
let samples = r.data.clone();
|
||||
assert!(r.extend_cr3_white(), "unclipped data past the stated white is still real light");
|
||||
assert_eq!(r.white_at(0), 16383.0);
|
||||
assert_eq!(r.data, samples);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cr3_headroom_is_recovered_when_only_one_colour_reaches_it() {
|
||||
let mut r = cr3(14558.0);
|
||||
let cfa = r.cfa.clone().unwrap();
|
||||
if let RawData::U16(d) = &mut r.data {
|
||||
for (i, v) in d.iter_mut().enumerate() {
|
||||
if cfa.color_at(i % 64, i / 64) == 0 {
|
||||
*v = 16383;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(r.extend_cr3_white(), "a coloured highlight need not clip all three channels");
|
||||
assert_eq!(r.white_at(0), 16383.0);
|
||||
}
|
||||
}
|
||||
@@ -47,10 +47,12 @@ impl Camera {
|
||||
}
|
||||
}
|
||||
|
||||
/// `(make, model as sold, table model)`: bodies sharing a table camera's sensor that rawtoaces-data's alias list
|
||||
/// `(make, model as sold, table model)`: bodies using a table camera's data that rawtoaces-data's alias list
|
||||
/// doesn't name, kept here because the table is generated. Fujifilm's 26.1 MP X-Trans CMOS 4 bodies use the X-T3's
|
||||
/// or X-T4's sensor (X-T30 issue: a black-and-white Acros camera JPEG gives no colour to fit, and without matrices the photo
|
||||
/// opened in the muted neutral fallback).
|
||||
/// The GFX100S II has no measured data of its own: it borrows the GFX 100's matrices as the nearest medium-format
|
||||
/// body in the table, which is closer than the neutral camera-RGB-approximately-sRGB fallback but not its own sensor.
|
||||
const SAME_SENSOR: &[(&str, &str, &str)] = &[
|
||||
("Fujifilm", "X-T30", "X-T3"),
|
||||
("Fujifilm", "X-T30 II", "X-T3"),
|
||||
@@ -60,6 +62,7 @@ const SAME_SENSOR: &[(&str, &str, &str)] = &[
|
||||
("Fujifilm", "X-E4", "X-T3"),
|
||||
("Fujifilm", "X-S20", "X-T4"),
|
||||
("Fujifilm", "X-M5", "X-T3"),
|
||||
("Fujifilm", "GFX100S II", "GFX 100"),
|
||||
];
|
||||
|
||||
/// Model names compared without case, the brand, a leading `EOS` or a trailing `DIGITAL`
|
||||
@@ -178,6 +181,13 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gfx100s_ii_uses_gfx_100_matrices() {
|
||||
// GFX100S II is not in the table, so its raws never get step 4's measured matrices
|
||||
// and fall back to step 5's neutral camera-RGB-approximately-sRGB.
|
||||
assert_eq!(find(Some("FUJIFILM"), "GFX100S II").map(|c| c.model), Some("GFX 100"),);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_cameras_and_other_makes_find_nothing() {
|
||||
assert_eq!(find(Some("Canon"), "Canon EOS 7D"), None);
|
||||
|
||||
@@ -21,6 +21,7 @@ pub mod nef;
|
||||
mod nef_lens;
|
||||
pub mod nefc;
|
||||
pub mod orf;
|
||||
pub(crate) mod orfc;
|
||||
pub mod pef;
|
||||
pub mod raf;
|
||||
mod raf_lens;
|
||||
|
||||
Vendored
+6
-1
@@ -237,7 +237,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
}
|
||||
metadata.width = Some(crop.width as u32);
|
||||
metadata.height = Some(crop.height as u32);
|
||||
let image = RawImage {
|
||||
let mut image = RawImage {
|
||||
format: RawFormat::Cr3,
|
||||
width,
|
||||
height,
|
||||
@@ -258,6 +258,11 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
metadata,
|
||||
lens_metadata: Default::default(),
|
||||
};
|
||||
// Canon's stated white level can sit below the sensor's true saturation (EOS RP: 14558
|
||||
// stated, 16383 real). Extend it to a saturation pile-up above it, so highlight data
|
||||
// between the stated level and the real clip point is not treated as clipped. No-op when
|
||||
// no such pile-up exists, and for header-only decodes (no samples).
|
||||
image.extend_cr3_white();
|
||||
image.validate_for(mode)?;
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
Vendored
+26
-12
@@ -1,4 +1,4 @@
|
||||
//! Olympus ORF — uncompressed variants.
|
||||
//! Olympus ORF — uncompressed and compressed variants.
|
||||
//!
|
||||
//! Sources: TIFF 6.0 (the `IIRO`/`MMOR` container is a TIFF with a different magic number), Exif 2.3 (`CFAPattern`,
|
||||
//! tag `0xa302`), the ExifTool Olympus tag-name documentation (maker-note sub-directories `0x2020` CameraSettings —
|
||||
@@ -28,8 +28,9 @@
|
||||
//! (last), the bit order and the pixel order were fixed by measurement on the CC0 files 2878 (E-300), 3540 (E-500)
|
||||
//! and 3624 (E-330), as was the sensor-origin RGGB anchoring (the maker-note crop offsets are odd). The E-M5 Mark II
|
||||
//! and PEN-F files were only checked for smoothness, not for CFA anchoring or black level.
|
||||
//! - Olympus's compressed ORF (most interchangeable-lens bodies since ~2008) is not decoded: no permissively
|
||||
//! licensed description exists. It reports [`RawError::Unsupported`]; the embedded preview still works.
|
||||
//! - Olympus's compressed ORF (interchangeable-lens bodies and compacts using the 12/14-bit entropy coding stream):
|
||||
//! decoded clean-room in `orfc.rs` from Olympus patents US7333035B2 and US7715639B2 (Takashi Ishikawa) and black-box
|
||||
//! CC0 samples (OM-D E-M1, E-M10 Mark III). No GPL/LibRaw code was consulted. See `docs/orf-compression.md`.
|
||||
//! - The colour-filter layout is the file's Exif `CFAPattern`: GRBG on the E-1 and E-400, RGGB on the XZ-2, where
|
||||
//! the colours of the decoded mosaic follow the embedded JPEG best with exactly that layout
|
||||
//! (`corpus_orf_cfa_patterns`). The samples' active areas start at even offsets, so they can't tell whether the
|
||||
@@ -199,6 +200,7 @@ fn field_rows(strips: &[(u64, u64)], w: usize, h: usize, file_len: usize) -> Opt
|
||||
Some(rows)
|
||||
}
|
||||
|
||||
/// Decode an Olympus ORF container into a mosaic raw image, supporting uncompressed 16-bit, packed 12-bit, and compressed formats.
|
||||
pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
let tiff = Tiff::parse(bytes)?;
|
||||
let ifd0 = &tiff.ifds[0];
|
||||
@@ -209,11 +211,13 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
let total = chunks.iter().fold(0u64, |a, c| a.saturating_add(c.len));
|
||||
let stated = cfa_from_exif(&tiff);
|
||||
let mut two_field = false;
|
||||
let (mut data, bits) = if info.compression != 1 {
|
||||
let mn = maker_note(bytes, &tiff);
|
||||
let ip = mn.as_ref().and_then(|m| sub_ifd(bytes, m, IMAGE_PROCESSING));
|
||||
let (mut data, bits, from_word16) = if info.compression != 1 {
|
||||
return Err(RawError::Unsupported(format!("ORF compression {}", info.compression)));
|
||||
} else if total >= (n as u64) * 2 {
|
||||
let d = read_image(bytes, &info, tiff.order, Packing::Word16)?;
|
||||
(d, 16)
|
||||
(d, 16, true)
|
||||
} else if is_block16(w, n, total, chunks.len()) {
|
||||
let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("ORF strip outside file".into()))?;
|
||||
let stride = w / 10 * 16;
|
||||
@@ -227,7 +231,19 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
(RawData::U16(d), 12)
|
||||
(RawData::U16(d), 12, false)
|
||||
} else if let Some((params, stream)) = (|| {
|
||||
let params = super::orfc::CompressionParameters::from_ifd(ip.as_ref()?, mn.as_ref())?;
|
||||
let chunk = chunks.first()?;
|
||||
let src = chunk_bytes(bytes, chunk)?;
|
||||
if !super::orfc::validate_stream_header(src, params.header_prefix_len) {
|
||||
return None;
|
||||
}
|
||||
let stream = src.get(params.header_prefix_len.saturating_add(2)..)?;
|
||||
Some((params, stream))
|
||||
})() {
|
||||
let d = if mode == Mode::Full || stated.is_none() { super::orfc::decompress_stream(stream, w, h, ¶ms)? } else { Vec::new() };
|
||||
(RawData::U16(d), params.valid_bits, false)
|
||||
} else if total * 8 >= (n as u64) * 12 && total * 8 < (n as u64) * 13 && chunks.len() == 1 {
|
||||
let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("ORF strip outside file".into()))?;
|
||||
// the strip as it is in the file (clipped at its end), not as its tag states it: one too short
|
||||
@@ -245,7 +261,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
(RawData::U16(d), 12)
|
||||
(RawData::U16(d), 12, false)
|
||||
} else if let Some(rows) = (info.bits() == 12 && info.samples_per_pixel == 1 && info.planar != 2 && info.offsets.len() == info.byte_counts.len())
|
||||
.then(|| field_rows(&info.offsets.iter().copied().zip(info.byte_counts.iter().copied()).collect::<Vec<_>>(), w, h, bytes.len()))
|
||||
.flatten()
|
||||
@@ -265,16 +281,16 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
(RawData::U16(d), 12)
|
||||
(RawData::U16(d), 12, false)
|
||||
} else {
|
||||
return Err(RawError::Unsupported("Olympus compressed ORF".into()));
|
||||
};
|
||||
let RawData::U16(ref mut samples) = data else { return Err(RawError::Unsupported("float ORF".into())) };
|
||||
let bits = if bits == 16 && samples.iter().step_by(7).filter(|v| *v & 15 != 0).count() * 700 <= n {
|
||||
let bits = if from_word16 && bits == 16 && samples.iter().step_by(7).filter(|v| *v & 15 != 0).count() * 700 <= n {
|
||||
// 12-bit values stored in the top bits
|
||||
samples.par_iter_mut().for_each(|v| *v >>= 4);
|
||||
12
|
||||
} else if bits == 16 {
|
||||
} else if from_word16 && bits == 16 {
|
||||
let mx = samples.iter().step_by(31).max().copied().unwrap_or(0);
|
||||
if mx < 4096 {
|
||||
12
|
||||
@@ -287,8 +303,6 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
bits
|
||||
};
|
||||
|
||||
let mn = maker_note(bytes, &tiff);
|
||||
let ip = mn.as_ref().and_then(|m| sub_ifd(bytes, m, IMAGE_PROCESSING));
|
||||
let active = match ip.as_ref().map(|i| CROP.map(|tag| i.u64(tag).map(|v| v as usize))) {
|
||||
// checked: the tags are file data; `x + cw` on a hostile value would wrap past the bounds
|
||||
Some([Some(x), Some(y), Some(cw), Some(ch)])
|
||||
|
||||
Vendored
+489
@@ -0,0 +1,489 @@
|
||||
//! Olympus compressed ORF entropy and predictive decoding.
|
||||
//!
|
||||
//! Clean-room implementation derived strictly from patent specifications and black-box CC0 samples:
|
||||
//! - Olympus Patent US7333035B2 (Takashi Ishikawa): directional edge-directed prediction across Bayer channels
|
||||
//! and run-length adaptive Golomb-Rice entropy coding with quotient escape codes.
|
||||
//! - Olympus Patent US7715639B2 (Takashi Ishikawa): direct low-order bitfield splitting and residual difference
|
||||
//! correction filters.
|
||||
//! - ImageProcessing maker-note directory (`0x2040`) parameters (`0x0640`–`0x0653`) and valid sensor bit depth (`0x102c`).
|
||||
//! - Verification against CC0 sample files from raw.pixls.us (OM-D E-M1, OM-D E-M10 Mark III).
|
||||
//!
|
||||
//! No LibRaw, dcraw, darktable, RawTherapee, or other GPL/LGPL/AGPL code was consulted or used.
|
||||
//! See `docs/orf-compression.md` for format specification and verification records.
|
||||
|
||||
use crate::{RawError, Result};
|
||||
use lightcraft_tiff::Ifd;
|
||||
use lightcraft_tiff::makernote::MakerNote;
|
||||
|
||||
/// Valid bits tag in Olympus MakerNote.
|
||||
const MN_VALID_BITS: u16 = 0x102c;
|
||||
|
||||
/// Bitstream reader for big-endian, MSB-first compressed ORF bitstreams.
|
||||
struct BitStream<'a> {
|
||||
data: &'a [u8],
|
||||
cursor: usize,
|
||||
buffer: u32,
|
||||
bits_available: u32,
|
||||
bits_loaded: u64,
|
||||
}
|
||||
|
||||
impl<'a> BitStream<'a> {
|
||||
/// Create a new bitstream reader over the supplied byte slice.
|
||||
fn new(data: &'a [u8]) -> Self {
|
||||
Self { data, cursor: 0, buffer: 0, bits_available: 0, bits_loaded: 0 }
|
||||
}
|
||||
|
||||
/// Refill the bit buffer with a 32-bit big-endian word.
|
||||
fn refill_word(&mut self) {
|
||||
self.bits_loaded = self.bits_loaded.saturating_add(32);
|
||||
if let Some(chunk) = self.data.get(self.cursor..self.cursor.saturating_add(4)) {
|
||||
self.buffer = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
|
||||
self.cursor = self.cursor.saturating_add(4);
|
||||
self.bits_available = 32;
|
||||
} else {
|
||||
let mut chunk = [0u8; 4];
|
||||
let remaining = self.data.len().saturating_sub(self.cursor);
|
||||
if remaining > 0 {
|
||||
if let Some(src) = self.data.get(self.cursor..self.cursor.saturating_add(remaining)) {
|
||||
chunk[..remaining].copy_from_slice(src);
|
||||
}
|
||||
self.cursor = self.data.len();
|
||||
}
|
||||
self.buffer = u32::from_be_bytes(chunk);
|
||||
self.bits_available = 32;
|
||||
}
|
||||
}
|
||||
|
||||
/// Append up to 16 bits to the lower part of the active bit buffer.
|
||||
fn refill_halfword(&mut self) {
|
||||
self.bits_loaded = self.bits_loaded.saturating_add(16);
|
||||
let next = if let Some(chunk) = self.data.get(self.cursor..self.cursor.saturating_add(2)) {
|
||||
self.cursor = self.cursor.saturating_add(2);
|
||||
u16::from_be_bytes([chunk[0], chunk[1]])
|
||||
} else if let Some(&single) = self.data.get(self.cursor) {
|
||||
self.cursor = self.cursor.saturating_add(1);
|
||||
(single as u16) << 8
|
||||
} else {
|
||||
0
|
||||
};
|
||||
self.buffer = (self.buffer << 16) | u32::from(next);
|
||||
self.bits_available = self.bits_available.saturating_add(16);
|
||||
}
|
||||
|
||||
/// Read up to 16 bits from the bitstream.
|
||||
fn read_bits(&mut self, width: u32) -> u32 {
|
||||
if width == 0 {
|
||||
return 0;
|
||||
}
|
||||
while self.bits_available < width {
|
||||
self.refill_halfword();
|
||||
}
|
||||
let shift = self.bits_available & 0x1f;
|
||||
let value = (self.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (32 - width);
|
||||
self.bits_available = self.bits_available.saturating_sub(width);
|
||||
value
|
||||
}
|
||||
|
||||
/// Advance by one bit, refilling the 32-bit buffer if necessary.
|
||||
fn advance_single_bit(&mut self, state: &mut u32) {
|
||||
if *state == 0 {
|
||||
self.refill_word();
|
||||
self.bits_available = self.bits_available.saturating_sub(1);
|
||||
*state = self.bits_available;
|
||||
} else {
|
||||
*state = state.saturating_sub(1);
|
||||
self.bits_available = *state;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters extracted from ImageProcessing SubIFD (`0x2040`) controlling compressed ORF decoding.
|
||||
pub(crate) struct CompressionParameters {
|
||||
/// Low-order direct bits extracted without prediction (tag `0x0640`).
|
||||
pub(crate) direct_bits_low0: u32,
|
||||
/// Gradient difference exponent threshold for edge classification (tag `0x0641`).
|
||||
pub(crate) gradient_thresh_exp_641: u32,
|
||||
/// Default spatial predictor boundary value (tag `0x0642`).
|
||||
pub(crate) boundary_predictor_642: i32,
|
||||
/// Direct residual sub-bits width (tag `0x0643`).
|
||||
pub(crate) direct_bits_sub3: u32,
|
||||
/// Vertical feedback shift exponent (tag `0x0644`).
|
||||
pub(crate) feedback_shift_644: u32,
|
||||
/// Flatness threshold exponent (tag `0x0645`).
|
||||
pub(crate) flatness_thresh_exp_645: u32,
|
||||
/// Flatness run threshold (tag `0x0646`).
|
||||
pub(crate) run_thresh_646: i32,
|
||||
/// Adaptive Rice parameter table offset A (tag `0x0647`).
|
||||
pub(crate) table_647: i32,
|
||||
/// Adaptive Rice parameter table limit A (tag `0x0648`).
|
||||
pub(crate) table_648: i32,
|
||||
/// Adaptive Rice parameter table offset B (tag `0x0649`).
|
||||
pub(crate) table_649: i32,
|
||||
/// Adaptive Rice parameter table limit B (tag `0x0650`).
|
||||
pub(crate) table_650: i32,
|
||||
/// Maximum Rice parameter allowed (tag `0x0651`).
|
||||
pub(crate) max_rice_k: i32,
|
||||
/// Maximum unary quotient run length before escape coding (tag `0x0652`).
|
||||
pub(crate) max_unary_run: u32,
|
||||
/// Prefix length of the compressed stream header in bytes (tag `0x0653`).
|
||||
pub(crate) header_prefix_len: usize,
|
||||
/// Valid sensor bit depth from MakerNote `0x102c`.
|
||||
pub(crate) valid_bits: u32,
|
||||
}
|
||||
|
||||
impl CompressionParameters {
|
||||
/// Parse and validate compression parameters from the ImageProcessing IFD and MakerNote.
|
||||
pub(crate) fn from_ifd(ip: &Ifd, mn: Option<&MakerNote>) -> Option<Self> {
|
||||
let header_prefix_len = usize::try_from(ip.u64(0x0653)?).ok()?;
|
||||
if header_prefix_len == 0 || header_prefix_len > 8 {
|
||||
return None;
|
||||
}
|
||||
if ip.u64(0x0640).is_some_and(|v| v > 16) || ip.u64(0x0643).is_some_and(|v| v > 16) {
|
||||
return None;
|
||||
}
|
||||
if ip.u64(0x0644).is_some_and(|v| v == 0 || v > 15) {
|
||||
return None;
|
||||
}
|
||||
let direct_bits_low0 = ip.u64(0x0640).and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
let gradient_thresh_exp_641 = ip.u64(0x0641).and_then(|v| u32::try_from(v).ok()).unwrap_or(5);
|
||||
let boundary_predictor_642 = ip.i64(0x0642).and_then(|v| i32::try_from(v).ok()).filter(|&v| (-65536..=65536).contains(&v)).unwrap_or(0);
|
||||
let direct_bits_sub3 = ip.u64(0x0643).and_then(|v| u32::try_from(v).ok()).unwrap_or(2);
|
||||
let feedback_shift_644 = ip.u64(0x0644).and_then(|v| u32::try_from(v).ok()).unwrap_or(5);
|
||||
let flatness_thresh_exp_645 = ip.u64(0x0645).and_then(|v| u32::try_from(v).ok()).unwrap_or(4);
|
||||
let run_thresh_646 = ip.u64(0x0646).and_then(|v| i32::try_from(v).ok()).unwrap_or(3);
|
||||
let table_647 = ip.u64(0x0647).and_then(|v| i32::try_from(v).ok()).unwrap_or(2);
|
||||
let table_648 = ip.u64(0x0648).and_then(|v| i32::try_from(v).ok()).unwrap_or(3);
|
||||
let table_649 = ip.u64(0x0649).and_then(|v| i32::try_from(v).ok()).unwrap_or(4);
|
||||
let table_650 = ip.u64(0x0650).and_then(|v| i32::try_from(v).ok()).unwrap_or(7);
|
||||
let max_rice_k = ip.u64(0x0651).and_then(|v| i32::try_from(v).ok()).unwrap_or(15);
|
||||
let max_unary_run = ip.u64(0x0652).and_then(|v| u32::try_from(v).ok()).unwrap_or(12).clamp(1, 32);
|
||||
let valid_bits = mn.and_then(|m| m.ifd.u64(MN_VALID_BITS)).and_then(|v| u32::try_from(v).ok()).filter(|b| (8..=16).contains(b)).unwrap_or(12);
|
||||
|
||||
Some(Self {
|
||||
direct_bits_low0,
|
||||
gradient_thresh_exp_641,
|
||||
boundary_predictor_642,
|
||||
direct_bits_sub3,
|
||||
feedback_shift_644,
|
||||
flatness_thresh_exp_645,
|
||||
run_thresh_646,
|
||||
table_647,
|
||||
table_648,
|
||||
table_649,
|
||||
table_650,
|
||||
max_rice_k,
|
||||
max_unary_run,
|
||||
header_prefix_len,
|
||||
valid_bits,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Check the stream header prefix: $N$ big-endian bytes equal to 1, followed by two zero bytes.
|
||||
pub(crate) fn validate_stream_header(src: &[u8], prefix_bytes: usize) -> bool {
|
||||
if prefix_bytes == 0 || prefix_bytes > 8 || src.len() < prefix_bytes.saturating_add(2) {
|
||||
return false;
|
||||
}
|
||||
let mut prefix_int = 0u64;
|
||||
for &b in src.get(..prefix_bytes).unwrap_or(&[]) {
|
||||
prefix_int = (prefix_int << 8) | u64::from(b);
|
||||
}
|
||||
if prefix_int != 1 {
|
||||
return false;
|
||||
}
|
||||
let Some(delimiter) = src.get(prefix_bytes..prefix_bytes.saturating_add(2)) else {
|
||||
return false;
|
||||
};
|
||||
delimiter == [0x00, 0x00]
|
||||
}
|
||||
|
||||
/// Decoded entropy-coded symbol components for one photosite.
|
||||
struct DecodedSymbol {
|
||||
signed_residual: i32,
|
||||
raw_magnitude: u32,
|
||||
direct_bits_low0: u32,
|
||||
direct_bits_sub3: u32,
|
||||
}
|
||||
|
||||
/// Decode the next Golomb-Rice entropy residual symbol according to the patent specification.
|
||||
fn decode_entropy_symbol(reader: &mut BitStream<'_>, rice_k: u32, params: &CompressionParameters) -> DecodedSymbol {
|
||||
if reader.bits_available == 0 {
|
||||
reader.refill_word();
|
||||
}
|
||||
reader.bits_available = reader.bits_available.saturating_sub(1);
|
||||
let sign_bit = (reader.buffer >> (reader.bits_available & 0x1f)) & 1;
|
||||
|
||||
let direct_bits_sub3 = if params.direct_bits_sub3 > 0 { reader.read_bits(params.direct_bits_sub3) } else { 0 };
|
||||
let direct_bits_low0 = if params.direct_bits_low0 > 0 { reader.read_bits(params.direct_bits_low0) } else { 0 };
|
||||
|
||||
let mut state = reader.bits_available;
|
||||
let mut quotient = 0u32;
|
||||
|
||||
loop {
|
||||
reader.advance_single_bit(&mut state);
|
||||
if ((reader.buffer >> (state & 0x1f)) & 1) != 0 {
|
||||
break;
|
||||
}
|
||||
quotient = quotient.saturating_add(1);
|
||||
if quotient == params.max_unary_run {
|
||||
quotient = 0;
|
||||
if rice_k != 15 {
|
||||
let bits_needed = 15u32.saturating_sub(rice_k);
|
||||
while state < bits_needed {
|
||||
reader.refill_halfword();
|
||||
state = reader.bits_available;
|
||||
}
|
||||
let shift = state & 0x1f;
|
||||
quotient = (reader.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (rice_k + 17);
|
||||
state = state.saturating_sub(bits_needed);
|
||||
reader.bits_available = state;
|
||||
}
|
||||
reader.advance_single_bit(&mut state);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let remainder = if rice_k == 0 {
|
||||
0
|
||||
} else {
|
||||
while state < rice_k {
|
||||
reader.refill_halfword();
|
||||
state = reader.bits_available;
|
||||
}
|
||||
let shift = state & 0x1f;
|
||||
let rem = (reader.buffer.wrapping_shl((32 - shift) & 0x1f)) >> (32 - (rice_k & 0x1f));
|
||||
reader.bits_available = state.saturating_sub(rice_k);
|
||||
rem
|
||||
};
|
||||
|
||||
let raw_magnitude = remainder | (quotient << rice_k);
|
||||
let sign_mask = if sign_bit != 0 { 0xffff_ffff } else { 0 };
|
||||
let signed_residual = (raw_magnitude ^ sign_mask) as i32;
|
||||
|
||||
DecodedSymbol { signed_residual, raw_magnitude, direct_bits_low0, direct_bits_sub3 }
|
||||
}
|
||||
|
||||
/// Decompress an entire Olympus compressed entropy bitstream into mosaic sensor samples.
|
||||
pub(crate) fn decompress_stream(stream: &[u8], width: usize, height: usize, params: &CompressionParameters) -> Result<Vec<u16>> {
|
||||
let total_pixels = width.checked_mul(height).ok_or(RawError::Limit("ORF image dimensions overflow"))?;
|
||||
if total_pixels > 0 && stream.is_empty() {
|
||||
return Err(RawError::Corrupt("ORF compressed stream is empty".into()));
|
||||
}
|
||||
// Reject streams too short to encode even 1 bit per pixel (prevents large allocation
|
||||
// from a truncated file before we start decoding).
|
||||
if total_pixels > 0 && (stream.len() as u64).saturating_mul(8) < total_pixels as u64 {
|
||||
return Err(RawError::Corrupt("ORF compressed stream too short for frame".into()));
|
||||
}
|
||||
let mut pixels = vec![0u16; total_pixels];
|
||||
let mut reader = BitStream::new(stream);
|
||||
|
||||
let gradient_threshold = 1u32.checked_shl(params.gradient_thresh_exp_641.min(30)).unwrap_or(1 << 5);
|
||||
let flatness_threshold = 1i32.checked_shl(params.flatness_thresh_exp_645.min(30)).unwrap_or(1 << 4);
|
||||
|
||||
let mut context = [0i32; 4];
|
||||
let mut last_predicted_sum = 0i32;
|
||||
let mut pred1 = 0i32;
|
||||
let mut raw_magnitude = 0u32;
|
||||
let mut prev_magnitude_signed = 0i32;
|
||||
|
||||
for row in 0..height {
|
||||
let row_offset = row.checked_mul(width).ok_or(RawError::Limit("ORF row overflow"))?;
|
||||
for col in 0..width {
|
||||
let p = prev_magnitude_signed;
|
||||
prev_magnitude_signed = raw_magnitude as i32;
|
||||
|
||||
let psel = if col > 1 && flatness_threshold >= p { context[3].saturating_add(1) } else { 0 };
|
||||
context[3] = context[2];
|
||||
context[2] = psel;
|
||||
|
||||
let mut rice_k = if col > 1 {
|
||||
let p16 = (p as u32 & 0xffff) as u16;
|
||||
let high_bit_count = if p16 == 0 { 0i32 } else { (16 - p16.leading_zeros()) as i32 };
|
||||
let t1 = if psel >= params.run_thresh_646 { params.table_648 } else { params.table_650 };
|
||||
let t2 = if psel >= params.run_thresh_646 { params.table_647 } else { params.table_649 };
|
||||
let tt = (high_bit_count - t1).max(-1);
|
||||
t2.saturating_add(tt).saturating_add(1)
|
||||
} else {
|
||||
params.table_649
|
||||
};
|
||||
|
||||
if rice_k > params.max_rice_k {
|
||||
rice_k = params.max_rice_k;
|
||||
}
|
||||
if rice_k >= 16 {
|
||||
return Err(RawError::Corrupt("ORF compressed Rice parameter out of range".into()));
|
||||
}
|
||||
|
||||
let symbol = decode_entropy_symbol(&mut reader, rice_k.max(0) as u32, params);
|
||||
let residual = symbol.signed_residual;
|
||||
raw_magnitude = symbol.raw_magnitude;
|
||||
let direct_bits_low0 = symbol.direct_bits_low0;
|
||||
let direct_bits_sub3 = symbol.direct_bits_sub3;
|
||||
|
||||
let (adjusted_residual, feedback_bits) = if params.direct_bits_sub3 > 0 {
|
||||
let v = if col < 2 { 0 } else { pred1 };
|
||||
let v_plus_g = v.checked_add(residual).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
if params.direct_bits_sub3 == 1 {
|
||||
let g_mult = v_plus_g.checked_mul(2).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
let g = (direct_bits_sub3 as i32).checked_add(g_mult).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
let v_res = v.checked_add(g >> 1).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
(g, v_res)
|
||||
} else {
|
||||
let g_mult = v_plus_g.checked_mul(4).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
let g = (direct_bits_sub3 as i32).checked_add(g_mult).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
let half_g = ((g >> 1) as u32 & 0xffff_fffe) as i32;
|
||||
let v_res = half_g
|
||||
.checked_add(v)
|
||||
.and_then(|x| x.checked_add(g >> 2))
|
||||
.ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
(g, v_res)
|
||||
}
|
||||
} else {
|
||||
(residual, 0)
|
||||
};
|
||||
|
||||
pred1 = context[0];
|
||||
context[0] = feedback_bits >> params.feedback_shift_644.min(30);
|
||||
|
||||
let west = if col < 2 { params.boundary_predictor_642 } else { context[1] };
|
||||
let mut north = if row < 2 {
|
||||
params.boundary_predictor_642
|
||||
} else {
|
||||
pixels.get((row - 2) * width + col).map_or(params.boundary_predictor_642, |&v| (v as i32) >> params.direct_bits_low0.min(15))
|
||||
};
|
||||
let north_west = if row < 2 || col < 2 {
|
||||
params.boundary_predictor_642
|
||||
} else {
|
||||
pixels.get((row - 2) * width + col - 2).map_or(params.boundary_predictor_642, |&v| (v as i32) >> params.direct_bits_low0.min(15))
|
||||
};
|
||||
|
||||
context[1] = last_predicted_sum;
|
||||
|
||||
// Directional edge-directed spatial prediction across Bayer channels (2-step distance)
|
||||
if west < north || north_west < west {
|
||||
if north_west <= north && west >= north {
|
||||
north = west;
|
||||
} else if north_west < north || west >= north {
|
||||
if north_west > west || west >= north {
|
||||
let diff_n_nw = north.abs_diff(north_west);
|
||||
let diff_w_nw = west.abs_diff(north_west);
|
||||
if diff_n_nw > gradient_threshold {
|
||||
north = north.saturating_add(west.saturating_sub(north_west));
|
||||
} else if diff_w_nw <= gradient_threshold {
|
||||
north = (north.saturating_add(west)) >> 1;
|
||||
} else {
|
||||
north = north.saturating_add(west.saturating_sub(north_west));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
north = west;
|
||||
}
|
||||
}
|
||||
|
||||
let sum = adjusted_residual.checked_add(north).ok_or_else(|| RawError::Corrupt("ORF predictor overflow".into()))?;
|
||||
last_predicted_sum = sum;
|
||||
let final_sample = i64::from(direct_bits_low0).saturating_add(i64::from(sum) << params.direct_bits_low0.min(15));
|
||||
if let Some(px) = pixels.get_mut(row_offset + col) {
|
||||
*px = final_sample.clamp(0, i64::from(u16::MAX)) as u16;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let consumed_bits = reader.bits_loaded.saturating_sub(u64::from(reader.bits_available));
|
||||
if consumed_bits > (stream.len() as u64).saturating_mul(8) {
|
||||
return Err(RawError::Corrupt("ORF compressed bitstream terminates prematurely".into()));
|
||||
}
|
||||
|
||||
Ok(pixels)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stream_header_validation() {
|
||||
assert!(validate_stream_header(&[0, 0, 0, 1, 0, 0], 4));
|
||||
assert!(validate_stream_header(&[0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 8));
|
||||
assert!(!validate_stream_header(&[0, 0, 0, 2, 0, 0], 4)); // prefix != 1
|
||||
assert!(!validate_stream_header(&[0, 0, 0, 1, 0, 1], 4)); // trailer != [0, 0]
|
||||
assert!(!validate_stream_header(&[0, 0, 0, 0], 5)); // truncated
|
||||
assert!(!validate_stream_header(&[], 0)); // zero length
|
||||
assert!(!validate_stream_header(&[0; 20], 9)); // > 8 bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitstream_reader_operations() {
|
||||
let data = [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc];
|
||||
let mut stream = BitStream::new(&data);
|
||||
assert_eq!(stream.read_bits(4), 1);
|
||||
assert_eq!(stream.read_bits(4), 2);
|
||||
assert_eq!(stream.read_bits(8), 0x34);
|
||||
assert_eq!(stream.read_bits(16), 0x5678);
|
||||
assert_eq!(stream.read_bits(8), 0x9a);
|
||||
assert_eq!(stream.read_bits(8), 0xbc);
|
||||
// past EOF reads padded zeros without panicking
|
||||
assert_eq!(stream.read_bits(8), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decompress_bounds_and_safety() {
|
||||
let params = CompressionParameters {
|
||||
direct_bits_low0: 0,
|
||||
gradient_thresh_exp_641: 5,
|
||||
boundary_predictor_642: 0,
|
||||
direct_bits_sub3: 2,
|
||||
feedback_shift_644: 5,
|
||||
flatness_thresh_exp_645: 4,
|
||||
run_thresh_646: 3,
|
||||
table_647: 2,
|
||||
table_648: 3,
|
||||
table_649: 4,
|
||||
table_650: 7,
|
||||
max_rice_k: 15,
|
||||
max_unary_run: 12,
|
||||
header_prefix_len: 5,
|
||||
valid_bits: 12,
|
||||
};
|
||||
// empty stream returns error for nonempty image, succeeds for 0x0
|
||||
assert!(decompress_stream(&[], 10, 10, ¶ms).is_err());
|
||||
assert_eq!(decompress_stream(&[], 0, 0, ¶ms).unwrap(), Vec::<u16>::new());
|
||||
// truncated stream (too short for requested dimensions) returns error
|
||||
assert!(decompress_stream(&[0xff; 2], 10, 10, ¶ms).is_err());
|
||||
assert!(decompress_stream(&[0x00; 2], 10, 10, ¶ms).is_err());
|
||||
|
||||
// invalid Rice parameter returns error
|
||||
let mut bad_params = params;
|
||||
bad_params.table_649 = 20;
|
||||
bad_params.max_rice_k = 20;
|
||||
assert!(decompress_stream(&[0xff; 32], 4, 4, &bad_params).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predictor_extreme_difference_never_panics() {
|
||||
assert_eq!(i32::MIN.abs_diff(0), 2_147_483_648u32);
|
||||
assert_eq!(i32::MIN.abs_diff(i32::MAX), 4_294_967_295u32);
|
||||
|
||||
let params = CompressionParameters {
|
||||
direct_bits_low0: 0,
|
||||
gradient_thresh_exp_641: 5,
|
||||
boundary_predictor_642: 0,
|
||||
direct_bits_sub3: 0,
|
||||
feedback_shift_644: 5,
|
||||
flatness_thresh_exp_645: 4,
|
||||
run_thresh_646: 3,
|
||||
table_647: 2,
|
||||
table_648: 3,
|
||||
table_649: 4,
|
||||
table_650: 7,
|
||||
max_rice_k: 15,
|
||||
max_unary_run: 12,
|
||||
header_prefix_len: 5,
|
||||
valid_bits: 12,
|
||||
};
|
||||
for fill in [0x00, 0x55, 0xaa, 0xff] {
|
||||
let stream = vec![fill; 64];
|
||||
let _ = decompress_stream(&stream, 4, 4, ¶ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@ fn corpus_root() -> PathBuf {
|
||||
/// Variants known not to decode yet (see the crate docs): matched against the lower-case file name.
|
||||
const KNOWN_UNSUPPORTED: &[&str] = &[
|
||||
"cr3-", // Unverified CRX coding variants; exact supported cases live in cr3_corpus.rs.
|
||||
"orf-olympus-em", // Olympus compressed ORF
|
||||
"-he.nef", // Nikon High Efficiency (HE / HE★) NEF, issue #193
|
||||
"sraw", // Canon sRAW / mRAW
|
||||
"crw-canon-powershot-g5.crw", // Canon PowerShot G5 CRW: entropy coding anomaly (craft-libs crates/crw/clean-room/02-crw-format.md §4)
|
||||
|
||||
@@ -19,6 +19,13 @@
|
||||
|
||||
use lightcraft_raw::{RawData, RawError, decode, probe_info};
|
||||
|
||||
/// The header probe can't see what only the samples tell: a full CR3 decode adds the white headroom
|
||||
/// it found to `baseline_exposure`. Everything else must match.
|
||||
fn without_baseline(mut info: lightcraft_raw::RawInfo) -> lightcraft_raw::RawInfo {
|
||||
info.color.baseline_exposure = 0.0;
|
||||
info
|
||||
}
|
||||
|
||||
// --- minimal CR3 container -------------------------------------------------
|
||||
|
||||
fn box_bytes(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||
@@ -227,7 +234,7 @@ fn control_lossless_fixture_decodes_through_the_container() {
|
||||
let raw = decode(&file).unwrap();
|
||||
assert_eq!((raw.width, raw.height, raw.bits, raw.cpp), (4, 4, 14, 1));
|
||||
assert_eq!(raw.data, RawData::U16(vec![8193; 16]));
|
||||
assert_eq!(probe_info(&file).unwrap(), raw.info());
|
||||
assert_eq!(without_baseline(probe_info(&file).unwrap()), without_baseline(raw.info()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -235,11 +242,11 @@ fn control_craw_and_adaptive_fixtures_decode_through_the_container() {
|
||||
let craw = cr3_file(&craw_coding(), &craw_stream(4));
|
||||
let raw = decode(&craw).unwrap();
|
||||
assert_eq!(raw.data, RawData::U16(vec![8192; 256]));
|
||||
assert_eq!(probe_info(&craw).unwrap(), raw.info());
|
||||
assert_eq!(without_baseline(probe_info(&craw).unwrap()), without_baseline(raw.info()));
|
||||
let adaptive = cr3_file(&adaptive_coding(), &adaptive_stream(&ADAPTIVE_GAINS, 0, 0, ADAPTIVE_QP));
|
||||
let raw = decode(&adaptive).unwrap();
|
||||
assert_eq!(raw.data, RawData::U16(vec![8192; 256]));
|
||||
assert_eq!(probe_info(&adaptive).unwrap(), raw.info());
|
||||
assert_eq!(without_baseline(probe_info(&adaptive).unwrap()), without_baseline(raw.info()));
|
||||
}
|
||||
|
||||
// --- supports() gates -------------------------------------------------------
|
||||
@@ -344,7 +351,7 @@ fn uniform_quantization_edges_of_the_accepted_range_decode() {
|
||||
let file = cr3_file(&craw_coding(), &craw_stream(quant));
|
||||
let raw = decode(&file).unwrap();
|
||||
assert_eq!(raw.data, RawData::U16(vec![8192; 256]), "quant {quant}");
|
||||
assert_eq!(probe_info(&file).unwrap(), raw.info(), "quant {quant}");
|
||||
assert_eq!(without_baseline(probe_info(&file).unwrap()), without_baseline(raw.info()), "quant {quant}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -370,7 +377,7 @@ fn adaptive_qp_edges_of_the_accepted_range_decode() {
|
||||
let file = cr3_file(&adaptive_coding(), &adaptive_stream(&ADAPTIVE_GAINS, 0, 0, qp_with_literal(literal)));
|
||||
let raw = decode(&file).unwrap();
|
||||
assert_eq!(raw.data, RawData::U16(vec![8192; 256]), "QP {value}");
|
||||
assert_eq!(probe_info(&file).unwrap(), raw.info(), "QP {value}");
|
||||
assert_eq!(without_baseline(probe_info(&file).unwrap()), without_baseline(raw.info()), "QP {value}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,13 @@
|
||||
use lightcraft_raw::{RawData, RawError, RawFormat, RawImage, decode, probe, probe_info};
|
||||
use proptest::prelude::*;
|
||||
|
||||
/// The header probe can't see what only the samples tell: a full CR3 decode adds the white headroom
|
||||
/// it found to `baseline_exposure`. Everything else must match.
|
||||
fn without_baseline(mut info: lightcraft_raw::RawInfo) -> lightcraft_raw::RawInfo {
|
||||
info.color.baseline_exposure = 0.0;
|
||||
info
|
||||
}
|
||||
|
||||
// --- reference entropy coders (mirrors of the decoder's documented bitstream grammar) ---
|
||||
|
||||
/// MELCODE run-index table (crx.rs `RUN_EXPONENT`).
|
||||
@@ -771,7 +778,7 @@ proptest! {
|
||||
assert_eq!((image.width, image.height, image.bits), (tile_w * tile_count, tile_h, 14));
|
||||
let RawData::U16(samples) = &image.data else { panic!("u16 sensor data expected") };
|
||||
assert_eq!(samples, &fixture.expected, "synthesis after analysis must be exact");
|
||||
assert_eq!(probe_info(&fixture.file).unwrap(), image.info());
|
||||
assert_eq!(without_baseline(probe_info(&fixture.file).unwrap()), without_baseline(image.info()));
|
||||
}
|
||||
|
||||
/// Property 2 (lossless side): in-range planes decode exactly; a sample outside the CMP1 bit depth
|
||||
@@ -853,7 +860,14 @@ proptest! {
|
||||
let image = decode(&file).unwrap();
|
||||
let RawData::U16(samples) = &image.data else { panic!("u16 sensor data expected") };
|
||||
assert!(samples.iter().all(|&value| value <= 16383), "adaptive dequantization must stay in the bit depth");
|
||||
assert_eq!(probe_info(&file).unwrap(), image.info());
|
||||
let mut header = probe_info(&file).unwrap();
|
||||
let decoded = image.info();
|
||||
// CR3 headroom is measured from decoded samples; a header-only probe cannot infer
|
||||
// its exposure compensation. Every other metadata field must still agree.
|
||||
assert!(decoded.color.baseline_exposure.is_finite());
|
||||
assert!(decoded.color.baseline_exposure >= header.color.baseline_exposure);
|
||||
header.color.baseline_exposure = decoded.color.baseline_exposure;
|
||||
assert_eq!(header, decoded);
|
||||
}
|
||||
|
||||
/// Property 4: randomly generated IAD1 fields either decode — with `active_area ⊆ sensor dims` and
|
||||
@@ -887,7 +901,7 @@ proptest! {
|
||||
"crop outside active area: {:?} in {a:?}",
|
||||
image.crop
|
||||
);
|
||||
assert_eq!(probe_info(&file).unwrap(), image.info());
|
||||
assert_eq!(without_baseline(probe_info(&file).unwrap()), without_baseline(image.info()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -996,7 +1010,7 @@ fn every_qp_value_in_the_supported_band_dequantizes_within_the_bit_depth() {
|
||||
let image = decode(&fixture.file).unwrap();
|
||||
let RawData::U16(samples) = &image.data else { panic!("u16 sensor data expected") };
|
||||
assert!(samples.iter().all(|&sample| sample <= 16383), "QP {value}");
|
||||
assert_eq!(probe_info(&fixture.file).unwrap(), image.info());
|
||||
assert_eq!(without_baseline(probe_info(&fixture.file).unwrap()), without_baseline(image.info()));
|
||||
if value == 131 {
|
||||
first_hash = sensor_hash(&image);
|
||||
}
|
||||
@@ -1041,7 +1055,7 @@ fn odd_qp_map_height_0x200_decodes_within_range() {
|
||||
let image = decode(&fixture.file).unwrap();
|
||||
let RawData::U16(samples) = &image.data else { panic!("u16 sensor data expected") };
|
||||
assert_eq!(samples, &vec![8592u16; 16 * 12], "step 1 (base 1) keeps the LL3 coefficient exact");
|
||||
assert_eq!(probe_info(&fixture.file).unwrap(), image.info());
|
||||
assert_eq!(without_baseline(probe_info(&fixture.file).unwrap()), without_baseline(image.info()));
|
||||
}
|
||||
|
||||
/// Adaptive steps on an odd-height map: the coarser bands pair QP rows, averaging the QP values before the
|
||||
@@ -1065,7 +1079,7 @@ fn odd_height_qp_map_uses_its_last_row_alone() {
|
||||
assert_eq!(adaptive, uniform(step(151)), "QP rows 0+1 average to 151 and the unpaired row 2 is 151 alone");
|
||||
assert_ne!(adaptive, uniform(step(151) - 1));
|
||||
assert_ne!(adaptive, uniform(step(151) + 1));
|
||||
assert_eq!(probe_info(&fixture.file).unwrap(), adaptive.info());
|
||||
assert_eq!(without_baseline(probe_info(&fixture.file).unwrap()), without_baseline(adaptive.info()));
|
||||
}
|
||||
|
||||
/// A map whose neighbouring cells differ by up to 37 forces symbols past the plain Rice range, so the
|
||||
@@ -1079,7 +1093,7 @@ fn qp_map_with_large_jumps_uses_the_escape_code() {
|
||||
let image = decode(&fixture.file).unwrap();
|
||||
let RawData::U16(samples) = &image.data else { panic!("u16 sensor data expected") };
|
||||
assert!(samples.iter().all(|&sample| sample <= 16383));
|
||||
assert_eq!(probe_info(&fixture.file).unwrap(), image.info());
|
||||
assert_eq!(without_baseline(probe_info(&fixture.file).unwrap()), without_baseline(image.info()));
|
||||
}
|
||||
|
||||
/// A QP Rice prefix longer than the 23-zero escape is corrupt data, not an endless read.
|
||||
|
||||
@@ -67,6 +67,8 @@ fn olympus_and_samsung_bodies_decode_like_the_camera_jpeg() {
|
||||
("orf-olympus-e-330.orf", (3280, 2450), 0xc938_38fa_9822_c81a, true),
|
||||
("orf-olympus-e-500.orf", (3360, 2504), 0x5e22_2ac8_17ed_89d9, true),
|
||||
("orf-olympus-e-m5-mark-ii.orf", (9280, 6932), 0xa222_be38_c767_7782, true),
|
||||
("orf-olympus-em1.orf", (4640, 3472), 0xc61b_0bb3_5170_4735, true),
|
||||
("orf-olympus-em10iii.orf", (4640, 3472), 0xedc1_ec6d_15a8_a303, true),
|
||||
("orf-olympus-pen-f.orf", (10400, 7796), 0x415e_bf27_092e_9897, true),
|
||||
("orf-olympus-sh-2.orf", (4624, 3470), 0xb25b_8d24_4ade_1f3d, true),
|
||||
("orf-olympus-sp510uz.orf", (3088, 2309), 0xa885_b7ca_83ba_02f1, true),
|
||||
|
||||
@@ -5,6 +5,13 @@ use lightcraft_raw::{
|
||||
};
|
||||
use proptest::prelude::*;
|
||||
|
||||
/// The header probe can't see what only the samples tell: a full CR3 decode adds the white headroom
|
||||
/// it found to `baseline_exposure`. Everything else must match.
|
||||
fn without_baseline(mut info: lightcraft_raw::RawInfo) -> lightcraft_raw::RawInfo {
|
||||
info.color.baseline_exposure = 0.0;
|
||||
info
|
||||
}
|
||||
|
||||
fn sample(comp: DngCompression) -> Vec<u8> {
|
||||
let (w, h) = (24usize, 16usize);
|
||||
let data: Vec<u16> = (0..w * h).map(|i| (i * 97 % 4000) as u16).collect();
|
||||
@@ -289,7 +296,7 @@ fn cr3_fixtures_decode() {
|
||||
let craw = lightcraft_raw::decode(&cr3::craw_file()).unwrap();
|
||||
assert_eq!((craw.width, craw.height, craw.bits), (16, 16, 14));
|
||||
assert_eq!(craw.data.get(0), 8192.0);
|
||||
assert_eq!(lightcraft_raw::probe_info(&cr3::craw_file()).unwrap(), craw.info());
|
||||
assert_eq!(without_baseline(lightcraft_raw::probe_info(&cr3::craw_file()).unwrap()), without_baseline(craw.info()));
|
||||
}
|
||||
|
||||
proptest! {
|
||||
|
||||
@@ -320,5 +320,10 @@
|
||||
"Panel layout could not be restored: {error}": "Rozložení panelů se nepodařilo obnovit: {error}",
|
||||
"Panel move was not applied: {error}": "Přesun panelu nebyl použit: {error}",
|
||||
"{name} is installed": "{name} je nainstalován",
|
||||
"{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto"
|
||||
"{name} is installed and in use: face recognition is on": "{name} je nainstalován a používán: rozpoznávání obličejů je zapnuto",
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "Fotografie importujete přes Soubor › Importovat fotografie… ({keys}).",
|
||||
"View › Detail View ({keys}).": "Zobrazení › Zobrazení detailu ({keys}).",
|
||||
"File › Export… · File › Print… ({keys}).": "Soubor › Exportovat… · Soubor › Tisk… ({keys}).",
|
||||
"{n} folder{} could not be read": "Složky, které se nepodařilo přečíst: {n}{:.0}",
|
||||
"{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}"
|
||||
}
|
||||
@@ -954,6 +954,10 @@
|
||||
"It tests this album, so testing it back would loop": "Testuje toto album, takže zpětný test vytvoří smyčku",
|
||||
"Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Obraz s redukovaným šumem ještě není vytvořen a obrazy se nevytvářejí automaticky (Nastavení, Redukce šumu pomocí AI).",
|
||||
"JPEG (Large)": "JPEG (velký)",
|
||||
"Instagram Feed": "Instagram Feed",
|
||||
"Instagram Story / Reel": "Instagram Story / Reel",
|
||||
"Web / Portfolio": "Web / portfolio",
|
||||
"Full Resolution Master": "Master v plném rozlišení",
|
||||
"JPEG (Small)": "JPEG (malý)",
|
||||
"Join the ArtCraft Discord": "Připojit se k Discordu ArtCraft",
|
||||
"Join the ArtCraft Discord…": "Připojit se k Discordu ArtCraft…",
|
||||
@@ -2445,5 +2449,28 @@
|
||||
"Set up name suggestions…": "Nastavit návrhy jmen…",
|
||||
"Top bar": "Horní lišta",
|
||||
"Tool strip": "Pruh nástrojů",
|
||||
"Bottom bar": "Dolní lišta"
|
||||
"Bottom bar": "Dolní lišta",
|
||||
"Welcome to LightCraft": "Vítejte v LightCraft",
|
||||
"A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Rychlá a nedestruktivní knihovna fotografií a vývojář RAW: originály zůstanou nedotčené a každou úpravu lze později znovu prohlédnout nebo vrátit.",
|
||||
"Bring photos in with File › Import Photos…": "Fotografie importujete přes Soubor › Importovat fotografie…",
|
||||
"Find and organize": "Najděte a uspořádejte",
|
||||
"The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Mřížka fotografií skládá knihovnu do zarovnaných řádků: hodnoťte, označujte barevnými štítky, filtrujte a řaďte fotografie do alb.",
|
||||
"View › Photo Grid.": "Zobrazení › Mřížka fotografií.",
|
||||
"Develop a photo": "Upravte fotografii",
|
||||
"Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Otevřete fotografii a upravte ji: expozice, barvy, detaily a masky, to vše nedestruktivně. Pomocí Zobrazení › Před/Po vedle sebe porovnáte stav před a po.",
|
||||
"View › Detail View.": "Zobrazení › Zobrazení detailu.",
|
||||
"Cull a shoot": "Vytřiďte sérii snímků",
|
||||
"Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Asistované třídění hodnotí ostrost a expozici, najde série a označí rozmazané snímky jako odmítnuté, takže nejlepší fotografie rychle vyniknou.",
|
||||
"Photo › Assisted Culling…": "Fotografie › Asistované třídění…",
|
||||
"Share your work": "Sdílejte svou práci",
|
||||
"Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Exportovat vytváří JPEG, PNG, TIFF, WebP a další formáty v požadované velikosti; Tisk rozloží fotografii na stránku jako PDF.",
|
||||
"File › Export… · File › Print…": "Soubor › Exportovat… · Soubor › Tisk…",
|
||||
"File › Export…": "Soubor › Exportovat…",
|
||||
"Put agents to work": "Nechte agenty pracovat",
|
||||
"Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Vše v LightCraft je příkaz, takže AI agenti mohou přes MCP ovládat běžící aplikaci: třídit, upravovat a exportovat podle vašich pokynů.",
|
||||
"Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Aplikaci spusťte s --control 7980 (nebo LIGHTCRAFT_CONTROL_PORT), poté lightcraft-cli mcp --connect připojí jednoho agenta.",
|
||||
"Welcome": "Vítejte",
|
||||
"Next": "Další",
|
||||
"Get Started": "Začít",
|
||||
"Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie"
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
"Added {n} photo{} to My Photos": "{n} Foto{} zu „Meine Fotos“ hinzugefügt",
|
||||
"Added {n} photo{} to “{}”": "{n} Foto{0} zu „{1}“ hinzugefügt",
|
||||
"Added {what} to {name}": "{what} zu {name} hinzugefügt",
|
||||
"Adjustments: {n}": "Anpassungen: {n}",
|
||||
"Adding photos… {} of {}": "Fotos werden hinzugefügt… {} von {}",
|
||||
"All {n} selected photos move by the same amount.": "Alle {n} ausgewählten Fotos werden um denselben Betrag verschoben.",
|
||||
"Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Bereits in der Bibliothek unter „Zuletzt gelöscht“: {} Foto{} ausgewählt · Rechtsklick → Wiederherstellen, oder endgültig löschen, um neu zu importieren",
|
||||
@@ -161,6 +162,8 @@
|
||||
"{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "{n} Änderung(en) konnten nicht auf den Datenträger geschrieben werden{0:.0}: {e}\nWenn du jetzt beendest, gehen sie verloren.{1:.0}",
|
||||
"{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "{n} Änderung(en) nur im Arbeitsspeicher, nicht auf dem Datenträger gespeichert{0:.0}: {e}\nLightCraft versucht es automatisch erneut; wenn du jetzt beendest, gehen sie verloren.{1:.0}",
|
||||
"{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "{n} Änderung(en) nur im Arbeitsspeicher gespeichert{:.0}: {e} – LightCraft versucht es erneut",
|
||||
"{n} file{} skipped (not a supported photo type)": "Übersprungene Dateien (kein unterstützter Fototyp): {n}{:.0}",
|
||||
"{n} folder{} could not be read": "Ordner, die nicht gelesen werden konnten: {n}{:.0}",
|
||||
"{n} found · {sel} selected": "{n} gefunden · {sel} ausgewählt",
|
||||
"{n} photos": "Fotos: {n}",
|
||||
"{n} photos in {} are hidden by the filters above": "{n} Fotos in {} werden durch die obigen Filter ausgeblendet",
|
||||
@@ -320,5 +323,8 @@
|
||||
"Panel layout could not be restored: {error}": "Die Bereichsanordnung konnte nicht wiederhergestellt werden: {error}",
|
||||
"Panel move was not applied: {error}": "Das Verschieben des Bereichs wurde nicht ausgeführt: {error}",
|
||||
"{name} is installed": "{name} ist installiert",
|
||||
"{name} is installed and in use: face recognition is on": "{name} ist installiert und in Gebrauch: Gesichtserkennung ist eingeschaltet"
|
||||
"{name} is installed and in use: face recognition is on": "{name} ist installiert und in Gebrauch: Gesichtserkennung ist eingeschaltet",
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "Fotos holen Sie mit Datei › Fotos importieren… ({keys}) in die Bibliothek.",
|
||||
"View › Detail View ({keys}).": "Ansicht › Detailansicht ({keys}).",
|
||||
"File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys})."
|
||||
}
|
||||
@@ -754,6 +754,10 @@
|
||||
"Invert Component": "Komponente umkehren",
|
||||
"Invert Mask": "Maske umkehren",
|
||||
"JPEG (Large)": "JPEG (groß)",
|
||||
"Instagram Feed": "Instagram-Feed",
|
||||
"Instagram Story / Reel": "Instagram-Story / Reel",
|
||||
"Web / Portfolio": "Web / Portfolio",
|
||||
"Full Resolution Master": "Master in voller Auflösung",
|
||||
"JPEG (Small)": "JPEG (klein)",
|
||||
"JPEG with the same name (`IMG_0001.CR3` + `IMG_0001.JPG`) no longer share one sidecar: the raw keeps `IMG_0001.xmp`,": "JPEG mit gleichem Namen (`IMG_0001.CR3` + `IMG_0001.JPG`) keine Begleitdatei mehr: RAW verwendet `IMG_0001.xmp`,",
|
||||
"Join the ArtCraft Discord": "ArtCraft auf Discord beitreten",
|
||||
@@ -2083,6 +2087,7 @@
|
||||
"Metadata read": "Metadaten gelesen",
|
||||
"Failed": "Fehlgeschlagen",
|
||||
"Stopped": "Angehalten",
|
||||
"Stopped at the scan limit: there may be more photos": "Am Suchlimit angehalten: Es gibt möglicherweise weitere Fotos",
|
||||
"Stopped by an error (see the log)": "Durch einen Fehler angehalten (siehe Protokoll)",
|
||||
"Not saved": "Nicht gespeichert",
|
||||
"A folder is being synchronized": "Ein Ordner wird gerade synchronisiert",
|
||||
@@ -3480,5 +3485,27 @@
|
||||
"Top bar": "Obere Leiste",
|
||||
"Tool strip": "Werkzeugleiste",
|
||||
"Bottom bar": "Untere Leiste",
|
||||
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)"
|
||||
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "G-SYNC-/FreeSync-Flimmern verhindern (gilt ab dem nächsten Start)",
|
||||
"Welcome to LightCraft": "Willkommen bei LightCraft",
|
||||
"A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Eine schnelle, zerstörungsfreie Fotobibliothek und Raw-Entwickler: Ihre Originale bleiben unberührt, und jede Bearbeitung lässt sich jederzeit ansehen oder zurücksetzen.",
|
||||
"Bring photos in with File › Import Photos…": "Fotos holen Sie mit Datei › Fotos importieren…in die Bibliothek.",
|
||||
"Find and organize": "Finden und ordnen",
|
||||
"The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Das Fotoraster ordnet die Bibliothek in bündigen Zeilen an: bewerten, markieren und farbig kennzeichnen, filtern und Fotos zu Alben sammeln.",
|
||||
"View › Photo Grid.": "Ansicht › Fotoraster.",
|
||||
"Develop a photo": "Ein Foto entwickeln",
|
||||
"Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Öffnen Sie ein Foto zum Entwickeln: Belichtung, Farbe, Details und Masken, alles zerstörungsfrei. Verwenden Sie Ansicht › Vorher/Nachher nebeneinander, um vorher und nachher zu vergleichen.",
|
||||
"View › Detail View.": "Ansicht › Detailansicht.",
|
||||
"Cull a shoot": "Eine Aufnahmeserie sichten",
|
||||
"Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Die Unterstützte Fotoauswahl bewertet Schärfe und Belichtung, erkennt Serienaufnahmen und markiert unscharfe Aufnahmen zum Ablehnen, damit die besten Fotos schnell auffallen.",
|
||||
"Photo › Assisted Culling…": "Foto › Unterstützte Fotoauswahl…",
|
||||
"Share your work": "Ihre Arbeit teilen",
|
||||
"Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Export erstellt JPEG, PNG, TIFF, WebP und weitere Formate in der gewünschten Größe; Drucken ordnet ein Foto als PDF auf einer Seite an.",
|
||||
"File › Export… · File › Print…": "Datei › Exportieren… · Datei › Drucken…",
|
||||
"File › Export…": "Datei › Exportieren…",
|
||||
"Put agents to work": "Agenten an die Arbeit schicken",
|
||||
"Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Alles in LightCraft ist ein Befehl, daher können KI-Agenten die laufende App über MCP steuern: sortieren, bearbeiten und exportieren, auf Ihren Auftrag hin.",
|
||||
"Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Starten Sie die App mit --control 7980 (oder LIGHTCRAFT_CONTROL_PORT), dann verbindet lightcraft-cli mcp --connect einen Agenten mit ihr.",
|
||||
"Welcome": "Willkommen",
|
||||
"Next": "Weiter",
|
||||
"Get Started": "Loslegen"
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
"Added {n} photo{} to My Photos": "{n} foto{0} añadida{0} a Mis fotos",
|
||||
"Added {n} photo{} to “{}”": "{n} foto{0} añadida{0} a “{1}”",
|
||||
"Added {what} to {name}": "{what} añadido a {name}",
|
||||
"Adjustments: {n}": "Ajustes: {n}",
|
||||
"Adding photos… {} of {}": "Añadiendo fotos… {} de {}",
|
||||
"All {n} selected photos move by the same amount.": "Las {n} fotos seleccionadas se desplazan la misma cantidad.",
|
||||
"Already in the library, in Recently Deleted: {} photo{} selected · right-click ▸ Restore, or Delete Permanently to import afresh": "Ya en la biblioteca, en Eliminadas recientemente: {0} foto{1} seleccionada{1} · clic derecho → Restaurar, o Eliminar definitivamente para importar de nuevo",
|
||||
@@ -161,6 +162,8 @@
|
||||
"{n} change{} couldn't be written to disk: {e}\nIf you quit now, {} lost.": "Cambios que no se pudieron escribir en el disco: {n}{0:.0}: {e}\nSi se sale ahora, se perderán.{1:.0}",
|
||||
"{n} change{} saved in memory but not written to disk: {e}\nLightCraft retries automatically; quitting now would lose {}.": "Cambios guardados en memoria, pero no escritos en el disco: {n}{0:.0}: {e}\nLightCraft vuelve a intentarlo automáticamente; si se sale ahora, se perderán.{1:.0}",
|
||||
"{n} change{} saved in memory but not written to disk: {e} — LightCraft will retry": "Cambios guardados solo en memoria: {n}{:.0}: {e}; LightCraft volverá a intentarlo",
|
||||
"{n} file{} skipped (not a supported photo type)": "Archivos omitidos (no son de un tipo de foto compatible): {n}{:.0}",
|
||||
"{n} folder{} could not be read": "Carpetas que no se pudieron leer: {n}{:.0}",
|
||||
"{n} found · {sel} selected": "{n} encontradas · {sel} seleccionadas",
|
||||
"{n} photos": "{n} fotos",
|
||||
"{n} photos in {} are hidden by the filters above": "Los filtros de arriba ocultan {n} fotos en {}",
|
||||
@@ -320,5 +323,8 @@
|
||||
"Panel layout could not be restored: {error}": "No se pudo restablecer la disposición de paneles: {error}",
|
||||
"Panel move was not applied: {error}": "No se aplicó el movimiento del panel: {error}",
|
||||
"{name} is installed": "{name} está instalado",
|
||||
"{name} is installed and in use: face recognition is on": "{name} está instalado y en uso: el reconocimiento facial está activado"
|
||||
"{name} is installed and in use: face recognition is on": "{name} está instalado y en uso: el reconocimiento facial está activado",
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "Importa fotos con Archivo › Importar fotos… ({keys}).",
|
||||
"View › Detail View ({keys}).": "Vista › Vista de detalle ({keys}).",
|
||||
"File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys})."
|
||||
}
|
||||
@@ -756,6 +756,10 @@
|
||||
"Invert Component": "Invertir componente",
|
||||
"Invert Mask": "Invertir máscara",
|
||||
"JPEG (Large)": "JPEG (grande)",
|
||||
"Instagram Feed": "Feed de Instagram",
|
||||
"Instagram Story / Reel": "Historias / Reel de Instagram",
|
||||
"Web / Portfolio": "Web / Portfolio",
|
||||
"Full Resolution Master": "Máster a resolución completa",
|
||||
"JPEG (Small)": "JPEG (pequeño)",
|
||||
"Join the ArtCraft Discord": "Unirse al Discord de ArtCraft",
|
||||
"Join the ArtCraft Discord…": "Unirse al Discord de ArtCraft…",
|
||||
@@ -2110,6 +2114,7 @@
|
||||
"Metadata read": "Metadatos leídos",
|
||||
"Failed": "Con errores",
|
||||
"Stopped": "Detenido",
|
||||
"Stopped at the scan limit: there may be more photos": "Se detuvo en el límite de exploración: puede haber más fotos",
|
||||
"Stopped by an error (see the log)": "Detenido por un error (ver el registro)",
|
||||
"Not saved": "Sin guardar",
|
||||
"A folder is being synchronized": "Se está sincronizando una carpeta",
|
||||
@@ -2399,5 +2404,27 @@
|
||||
"Top bar": "Barra superior",
|
||||
"Tool strip": "Barra de herramientas",
|
||||
"Bottom bar": "Barra inferior",
|
||||
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)"
|
||||
"Prevent G-SYNC/FreeSync flicker (applies at next launch)": "Evitar el parpadeo de G-SYNC/FreeSync (se aplica al reiniciar)",
|
||||
"Welcome to LightCraft": "Bienvenido a LightCraft",
|
||||
"A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Un gestor de fotos y revelado RAW rápido y no destructivo: tus originales permanecen intactos y cada edición se puede revisar o restablecer.",
|
||||
"Bring photos in with File › Import Photos…": "Importa fotos con Archivo › Importar fotos…",
|
||||
"Find and organize": "Encuentra y organiza",
|
||||
"The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "La cuadrícula de fotos organiza la biblioteca en filas justificadas: valora, marca y etiqueta por color, filtra y reúne las fotos en álbumes.",
|
||||
"View › Photo Grid.": "Vista › Cuadrícula de fotos.",
|
||||
"Develop a photo": "Revela una foto",
|
||||
"Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Abre una foto para revelarla: exposición, color, detalle y máscaras, todo de forma no destructiva. Usa Vista › Antes/Después lado a lado para comparar antes y después.",
|
||||
"View › Detail View.": "Vista › Vista de detalle.",
|
||||
"Cull a shoot": "Selecciona una sesión",
|
||||
"Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "La selección asistida valora el enfoque y la exposición, encuentra las ráfagas y marca las tomas borrosas como rechazadas, para que las mejores destaquen enseguida.",
|
||||
"Photo › Assisted Culling…": "Foto › Selección asistida…",
|
||||
"Share your work": "Comparte tu trabajo",
|
||||
"Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Exportar genera JPEG, PNG, TIFF, WebP y más, en el tamaño que elijas; Imprimir coloca una foto en una página como PDF.",
|
||||
"File › Export… · File › Print…": "Archivo › Exportar… · Archivo › Imprimir…",
|
||||
"File › Export…": "Archivo › Exportar…",
|
||||
"Put agents to work": "Pon a trabajar a los agentes",
|
||||
"Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Todo en LightCraft es un comando, así que los agentes de IA pueden manejar la aplicación en marcha a través de MCP: seleccionar, editar y exportar cuando lo pidas.",
|
||||
"Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Inicia la aplicación con --control 7980 (o LIGHTCRAFT_CONTROL_PORT), y lightcraft-cli mcp --connect conecta un agente a ella.",
|
||||
"Welcome": "Bienvenido",
|
||||
"Next": "Siguiente",
|
||||
"Get Started": "Empezar"
|
||||
}
|
||||
@@ -317,5 +317,10 @@
|
||||
"Panel layout could not be restored: {error}": "Paneelien asettelua ei voitu palauttaa: {error}",
|
||||
"Panel move was not applied: {error}": "Paneelin siirtoa ei otettu käyttöön: {error}",
|
||||
"{name} is installed": "{name} on asennettu",
|
||||
"{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä"
|
||||
"{name} is installed and in use: face recognition is on": "{name} on asennettu ja käytössä: kasvojentunnistus on päällä",
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "Tuo kuvia valitsemalla Tiedosto › Tuo kuvia… ({keys}).",
|
||||
"View › Detail View ({keys}).": "Näytä › Tarkastelunäkymä ({keys}).",
|
||||
"File › Export… · File › Print… ({keys}).": "Tiedosto › Vie… · Tiedosto › Tulosta… ({keys}).",
|
||||
"{n} folder{} could not be read": "Kansiot, joita ei voitu lukea: {n}{:.0}",
|
||||
"{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}"
|
||||
}
|
||||
@@ -967,6 +967,10 @@
|
||||
"It tests this album, so testing it back would loop": "Se testaa tätä albumia, joten sen testaaminen takaisin muodostaisi silmukan",
|
||||
"Its denoised picture is not made yet, and pictures are not made on their own (Settings, AI Denoise).": "Sen kohinanpoistettua kuvaa ei ole vielä tehty, eikä kuvia tehdä itsestään (Asetukset, Tekoälykohinanpoisto).",
|
||||
"JPEG (Large)": "JPEG (suuri)",
|
||||
"Instagram Feed": "Instagram-syöte",
|
||||
"Instagram Story / Reel": "Instagram-story / Reel",
|
||||
"Web / Portfolio": "Web / Portfolio",
|
||||
"Full Resolution Master": "Täysresoluutioinen masteri",
|
||||
"JPEG (Small)": "JPEG (pieni)",
|
||||
"Join the ArtCraft Discord": "Liity ArtCraftin Discordiin",
|
||||
"Join the ArtCraft Discord…": "Liity ArtCraftin Discordiin…",
|
||||
@@ -2147,6 +2151,28 @@
|
||||
"Virtual Copy": "Virtuaalikopio",
|
||||
"Visible": "Näkyvä",
|
||||
"Visualize HDR": "Havainnollista HDR",
|
||||
"Welcome to LightCraft": "Tervetuloa LightCraftiin",
|
||||
"A fast, non-destructive photo library and raw developer: your originals stay untouched, and every edit can be revisited or reset.": "Nopea, ei-tuhova kuvakirjasto ja RAW-kehittäjä: alkuperäiset tiedostot säilyvät koskemattomina, ja jokaiseen muokkaukseen voi palata tai sen voi nollata.",
|
||||
"Bring photos in with File › Import Photos…": "Tuo kuvia valitsemalla Tiedosto › Tuo kuvia…",
|
||||
"Find and organize": "Etsi ja järjestä",
|
||||
"The Photo Grid lays the library out as justified rows: rate, flag and colour-label, filter, and gather photos into albums.": "Kuvaruudukko asettelee kirjaston tasattuihin riveihin: arvioi, merkitse ja väritä kuvia, suodata ja kokoaa niitä albumeihin.",
|
||||
"View › Photo Grid.": "Näytä › Kuvaruudukko.",
|
||||
"Develop a photo": "Kehitä kuva",
|
||||
"Open a photo to develop it: exposure, colour, detail and masks, all non-destructive. Use View › Before/After Side by Side to compare before and after.": "Avaa kuva kehitettäväksi: valotus, väri, yksityiskohdat ja maskit, kaikki ei-tuhovaa. Käytä Näytä › Ennen/jälkeen vierekkäin ennen- ja jälkikuvan vertailuun.",
|
||||
"View › Detail View.": "Näytä › Tarkastelunäkymä.",
|
||||
"Cull a shoot": "Karsi kuvaus",
|
||||
"Assisted Culling scores focus and exposure, finds bursts, and flags blurry shots as rejects, so the keepers surface fast.": "Avustettu valinta pisteyttää terävyyden ja valotuksen, tunnistaa kuvasarjat ja merkitsee sumeat kuvat hylätyiksi, jotta parhaat nousevat nopeasti esille.",
|
||||
"Photo › Assisted Culling…": "Kuva › Avustettu valinta…",
|
||||
"Share your work": "Jaa työsi",
|
||||
"Export renders JPEG, PNG, TIFF, WebP and more, sized as you like; Print lays a photo out on a page as PDF.": "Vienti tuottaa JPEG-, PNG-, TIFF-, WebP- ja muita tiedostomuotoja haluamassasi koossa; Tulostus somittaa kuvan sivulle PDF:nä.",
|
||||
"File › Export… · File › Print…": "Tiedosto › Vie… · Tiedosto › Tulosta…",
|
||||
"File › Export…": "Tiedosto › Vie…",
|
||||
"Put agents to work": "Pane agentit töihin",
|
||||
"Everything in LightCraft is a command, so AI agents can drive the running app over MCP: culling, editing, exporting on your word.": "Kaikki LightCraftissa on komento, joten tekoälyagentit voivat ohjata käynnissä olevaa sovellusta MCP:n kautta: karsintaa, kehitystä ja vientiä käskystäsi.",
|
||||
"Start the app with --control 7980 (or LIGHTCRAFT_CONTROL_PORT), then lightcraft-cli mcp --connect attaches one to it.": "Käynnistä sovellus valitsimella --control 7980 (tai LIGHTCRAFT_CONTROL_PORT), minkä jälkeen lightcraft-cli mcp --connect yhdistää siihen yhden agentin.",
|
||||
"Welcome": "Tervetuloa",
|
||||
"Next": "Seuraava",
|
||||
"Get Started": "Aloitetaan",
|
||||
"Visualize Spots": "Havainnollista täplät",
|
||||
"Visualize Spots (A)": "Havainnollista täplät (A)",
|
||||
"Visualize range": "Havainnollista alue",
|
||||
@@ -2356,5 +2382,6 @@
|
||||
"Set up name suggestions…": "Määritä nimiehdotukset…",
|
||||
"Top bar": "Yläpalkki",
|
||||
"Tool strip": "Työkalupalkki",
|
||||
"Bottom bar": "Alapalkki"
|
||||
"Bottom bar": "Alapalkki",
|
||||
"Stopped at the scan limit: there may be more photos": "Skannauksen raja saavutettiin: valokuvia voi olla lisää"
|
||||
}
|
||||
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user