Merge branch 'main' into fix/import-embedded-ratings

This commit is contained in:
Sebastian Berschneider committed 2026-11-11 15:40:48 +01:00
commit c8c82bca76
149 files changed
+8805 -1084

No files matched your search

+14 -4
View File
@@ -12,15 +12,21 @@ on:
type: string
default: ""
permissions:
contents: write
packages: write
# Nothing by default; each job names what it needs. Only `release` writes (the draft GitHub Release
# and its packages).
permissions: {}
concurrency:
group: release-${{ github.ref }}
cancel-in-progress: false
jobs:
# Regenerates contributors/contributors.json for the release commit; every build bundles it.
credits:
permissions:
contents: read
pull-requests: read
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
git-sources:
name: Git dependencies come from storytold
runs-on: ubuntu-latest
@@ -61,7 +67,10 @@ jobs:
PY
release:
needs: git-sources
needs: [git-sources, credits]
permissions:
contents: write
packages: write
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
@@ -70,6 +79,7 @@ jobs:
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
web-craft-fonts: true
version: ${{ inputs.version }}
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
Generated
+2 -1
View File
@@ -1246,7 +1246,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a231e517c3b371e1bf0ee8af71ed807424a9a05d#a231e517c3b371e1bf0ee8af71ed807424a9a05d"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"chrono",
"dunce",
@@ -3744,6 +3744,7 @@ dependencies = [
"ab_glyph",
"chrono",
"craft-docpath",
"crc32fast",
"fs4",
"harfrust 0.13.3",
"jxl-oxide",
+1 -1
View File
@@ -15,7 +15,7 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l
# Canon CRW decoder shared with the other Craft apps
craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f45534392376492fc5ad33047375205" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a231e517c3b371e1bf0ee8af71ed807424a9a05d", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
# internal
lightcraft-denoise-core = { path = "crates/denoise-core" }
+2 -2
View File
@@ -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;
- **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);
- **unsupported CR3 variants and Nikon High Efficiency NEFs:** these use embedded JPEG previews when present. Olympus compressed ORF is unsupported for sensor decoding and uses embedded JPEG previews when available ([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, 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)) |
| 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)) |
| 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 | ✅ |
+5 -3
View File
@@ -30,7 +30,7 @@ Each audience with its own hours (Opus 5.5 agent wall-clock hours to ~95%):
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), 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
as preview, as does compressed ORF when an embedded preview is available; 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 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
@@ -107,14 +107,16 @@ 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~~ (done 2026-11-04) and HE NEF (20–40 h)
6. Compressed ORF (support withdrawn; estimate pending provenance review) 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-11-07: Compressed ORF support withdrawn pending provenance review; uncompressed support remains. Regenerated camera coverage: 557 verified, 665 unverified, 187 preview-only and 37 unsupported; 94% use-weighted coverage. See [ORF status](docs/orf-compression.md).
- 2026-11-04: Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available.
- 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
+4
View File
@@ -201,6 +201,10 @@ impl eframe::App for App {
// app after this and the session's last writes (face data) still go out under the lock.
#[cfg(target_os = "macos")]
self.0.session.release_library_lock();
// macOS only: the process ends below without dropping the app, so a ready update's helper
// starts here. Elsewhere dropping the app starts it.
#[cfg(target_os = "macos")]
self.0.start_pending_update();
// macOS (#1331): end the process here, before eframe tears the window down, as Quit from
// the menu bar already does (PR #444). AccessKit's macOS adapter subclasses the window's
// content view and restores its class on teardown; AppKit's Touch Bar support observes
+1 -1
View File
@@ -49,7 +49,7 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::
pick_lightroom_catalog: Some(Box::new(|| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Import Lightroom Catalog"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Lightroom Classic Catalog"), &["lrcat"])
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Lightroom Classic Catalog"), &["lrcat", "zip"])
.pick_file()
.map(|p| p.to_string_lossy().to_string())
})),
+2 -1
View File
@@ -64,6 +64,7 @@
//! | 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` |
//! | 13 | Lens Blur | `DevelopSettings.lens_blur`, `Mask.adjust.lens_blur` |
//!
//! Rules:
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
@@ -88,7 +89,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 = 12;
pub const VERSION: u32 = 13;
/// When [`Journal::wants_snapshot`] says it's time to compact the log.
#[derive(Clone, Copy, Debug)]
+2 -2
View File
@@ -221,8 +221,8 @@ pub enum Op {
/// `None` = its raw data decodes (or it isn't a raw).
#[serde(default, skip_serializing_if = "Option::is_none")]
preview_only: Option<String>,
/// The app version that decided `preview_only` (see [`Photo::preview_checked`]); empty
/// when it is `None`.
/// The app version that decided `preview_only` (see [`Photo::preview_checked`]); also
/// retained for supported ORF files so their withdrawal recheck runs only once.
#[serde(default, skip_serializing_if = "String::is_empty")]
preview_checked: String,
},
+13 -8
View File
@@ -316,10 +316,10 @@ pub struct Photo {
/// picture style baked in — so it is treated as a rendered (non-raw) source.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preview_only: Option<String>,
/// The app version (`CARGO_PKG_VERSION`) whose decoder set [`Photo::preview_only`]; empty when
/// it isn't set, and in catalogs from before format v9. A preview-only photo whose stamp
/// differs from the running version is rechecked when its library opens (issue #662): newer
/// builds may decode the file, older ones may decode less.
/// The app version (`CARGO_PKG_VERSION`) whose decoder checked [`Photo::preview_only`].
/// Also set for supported ORF files: compressed ORF support was withdrawn after #3775, so
/// old sensor-decodable records need rechecking too. Empty for other supported formats and
/// legacy records. A stale stamp is rechecked when the library opens (issue #662).
#[serde(default, skip_serializing_if = "String::is_empty")]
pub preview_checked: String,
/// A Local record: the fingerprint of its state when the browse catalogued it, to tell
@@ -429,13 +429,18 @@ impl Photo {
}
/// Sets [`Photo::preview_only`] as this build decided it, with its stamp.
pub fn set_preview_only(&mut self, preview_only: Option<String>) {
self.preview_checked = preview_stamp(&preview_only);
self.preview_checked = self.preview_stamp(&preview_only);
self.preview_only = preview_only;
}
/// A preview-only photo whose flag was set by another app version (or before stamps existed),
/// so this build should probe its file again (issue #662).
/// The stamp for a fresh probe. Supported ORFs keep it too, so the support-withdrawal
/// recheck runs once, without repeatedly probing uncompressed ORFs on every library open.
pub fn preview_stamp(&self, preview_only: &Option<String>) -> String {
if self.format.eq_ignore_ascii_case("orf") { APP_VERSION.to_string() } else { preview_stamp(preview_only) }
}
/// A preview-only photo or ORF whose support was checked by another app version (or before
/// stamps existed), so this build should probe its file again (issues #662 and #3775).
pub fn preview_only_stale(&self) -> bool {
self.preview_only.is_some() && self.preview_checked != APP_VERSION
(self.preview_only.is_some() || self.format.eq_ignore_ascii_case("orf")) && self.preview_checked != APP_VERSION
}
/// A raw file developed from its sensor data: not a rendered image, and not a raw shown from
/// its embedded preview ([`Photo::preview_only`]).
+20
View File
@@ -12,6 +12,26 @@ fn photo(c: &mut Catalog, name: &str, date: &str) -> PhotoId {
id
}
/// ORF probes record both supported and preview-only outcomes, without changing other formats.
#[test]
fn orf_support_checks_keep_a_stamp_even_when_sensor_data_decodes() {
let mut p = Photo::new(PhotoId(1), Source::File { path: "a.orf".into() }, "a.orf", "ORF", 4, 3, "2026-01-01");
p.kind = MediaKind::Raw;
assert!(p.preview_only_stale(), "legacy supported ORF needs the withdrawal recheck");
p.set_preview_only(None);
assert_eq!(p.preview_checked, APP_VERSION);
assert!(!p.preview_only_stale());
assert!(p.develops_raw(), "supported uncompressed ORF remains sensor-decodable");
p.set_preview_only(Some("Olympus compressed ORF".into()));
assert_eq!(p.preview_checked, APP_VERSION);
assert!(!p.preview_only_stale());
assert!(!p.develops_raw());
p.format = "DNG".into();
p.set_preview_only(None);
assert!(p.preview_checked.is_empty(), "other supported formats keep their existing semantics");
assert!(!p.preview_only_stale());
}
#[test]
fn date_token_matches_time_part_case_insensitively() {
let mut c = Catalog::new();
+3 -3
View File
@@ -238,9 +238,9 @@ fn op_variants_are_versioned() {
Op::SetHistoryCursor { .. } => 8,
}
}
/// 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;
/// v13: Lens Blur in develop settings and mask adjustments (v12: `Catalog.grids` and `SegMask.grid`; v11: `EmbeddedLens.source`;
/// v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`).
const NEWEST_FIELDS: u32 = 13;
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");
}
+13 -2
View File
@@ -39,12 +39,16 @@ impl<'a> EncodeImage<'a> {
if self.width == 0 || self.height == 0 {
return Err(Error::Encode("zero dimension".into()));
}
let need = self.width as u64 * self.height as u64 * self.channels as u64;
// u128: 2^32 x 2^32 x 4 does not fit u64, and every later `width * height * channels` is bounded by this
let need = self.width as u128 * self.height as u128 * self.channels as u128;
if need > usize::MAX as u128 {
return Err(Error::Encode("image too large".into()));
}
let have = match self.samples {
Samples::U8(s) => s.len(),
Samples::U16(s) => s.len(),
Samples::F32(s) => s.len(),
} as u64;
} as u128;
if have < need {
return Err(Error::Encode(format!("sample buffer too short: {have} < {need}")));
}
@@ -671,6 +675,13 @@ fn avif_10bit(enc: &ravif::Encoder, img: &EncodeImage, s: &[u16]) -> Result<Vec<
mod hlg_tests {
use super::*;
#[test]
fn dimensions_whose_sample_count_wraps_are_refused() {
// 2^31 x 2^31 x 4 is 2^64 samples: zero when wrapped, which an empty buffer would satisfy
let img = EncodeImage::new(1 << 31, 1 << 31, 4, Samples::U8(&[]));
assert!(img.validate().is_err());
}
#[test]
fn hlg_reference_white_and_peak() {
// BT.2408: SDR (HDR reference) white sits at 75 % HLG signal
+19
View File
@@ -585,6 +585,10 @@ pub fn encode_jpeg(base: &EncodeImage, gain: &GainImage, m: &GainMapMeta, qualit
if !matches!(gain.channels, 1 | 3) || gain.width == 0 || gain.height == 0 || gain.data.len() < gain.width * gain.height * gain.channels {
return Err(Error::Encode("gain map image is malformed".into()));
}
// (jpeg_par::encode gives an empty JPEG past this, which would be appended as a size-0 gain map)
if gain.width > u16::MAX as usize || gain.height > u16::MAX as usize {
return Err(Error::Encode("JPEG dimensions are limited to 65535".into()));
}
if !m.is_valid() || m.multichannel != (gain.channels == 3) {
return Err(Error::Encode("gain map metadata doesn't match the map".into()));
}
@@ -786,6 +790,21 @@ mod tests {
}
}
#[test]
fn a_gain_map_wider_than_a_jpeg_allows_is_refused() {
let base = [0u8; 3];
let gain = GainImage { width: 65_536, height: 1, channels: 1, data: vec![0; 65_536] };
let r = encode_jpeg(
&EncodeImage::new(1, 1, 3, Samples::U8(&base)),
&gain,
&GainMapMeta::default(),
90,
ChromaSubsampling::S444,
&EncodeMeta::default(),
);
assert!(matches!(r, Err(Error::Encode(m)) if m.contains("65535")));
}
#[test]
fn jpeg_round_trip_and_container_structure() {
let (w, h) = (96, 64);
+13
View File
@@ -401,6 +401,12 @@ fn encode_with(
app_segments: &[(u8, Vec<u8>)],
optimize: bool,
) -> Vec<u8> {
// The public entry takes caller-sized dimensions: refuse (an empty output) what would size an allocation from
// them or index past `data`, rather than panic or allocate for them.
let fits = width.checked_mul(height).and_then(|n| n.checked_mul(channels)).is_some_and(|n| n <= data.len());
if !fits || width == 0 || height == 0 || width > 65_535 || height > 65_535 || !matches!(channels, 1 | 3 | 4) {
return Vec::new();
}
let gray = channels == 1;
let (hs, vs) = match (gray, sub) {
(true, _) | (false, ChromaSubsampling::S444) => (1usize, 1usize),
@@ -586,6 +592,13 @@ fn encode_with(
mod tests {
use super::*;
#[test]
fn hostile_dimensions_give_no_output_instead_of_a_panic_or_allocation() {
for (w, h, c) in [(1usize << 40, 1usize << 40, 3usize), (0, 8, 3), (70_000, 2, 3), (8, 8, 7), (8, 8, 3)] {
assert!(encode(&[0u8; 16], w, h, c, 90, ChromaSubsampling::S444, &[]).is_empty(), "{w} x {h} x {c}");
}
}
fn test_rgb(w: usize, h: usize) -> Vec<u8> {
let mut v = Vec::with_capacity(w * h * 3);
for y in 0..h {
+5
View File
@@ -28,6 +28,7 @@ pub enum Section {
Calibration,
PointColor,
RedEye,
LensBlur,
}
impl Section {
@@ -49,6 +50,7 @@ impl Section {
Section::Calibration => "Calibration",
Section::PointColor => "Point Color",
Section::RedEye => "Red Eye",
Section::LensBlur => "Lens Blur",
}
}
}
@@ -286,6 +288,9 @@ controls! {
"geometry.scale" => geometry.scale, "Scale", Geometry, 50, 150, 100, 1, 0, Plain;
"geometry.offsetX" => geometry.offset_x, "Offset X", Geometry, -100, 100, 0, 0.1, 1, Centered;
"geometry.offsetY" => geometry.offset_y, "Offset Y", Geometry, -100, 100, 0, 0.1, 1, Centered;
"lensBlur.amount" => lens_blur.amount, "Blur Amount", LensBlur, 0, 100, 0, 1, 0, Plain;
"lensBlur.boost" => lens_blur.boost, "Boost", LensBlur, 0, 100, 0, 1, 0, Plain;
"lensBlur.transition" => lens_blur.transition, "Transition", LensBlur, 0, 100, 50, 1, 0, Plain;
"calibration.shadowsTint" => calibration.shadows_tint, "Shadows Tint", Calibration, -100, 100, 0, 1, 0, Tint;
"calibration.redHue" => calibration.red_hue, "Red Hue", Calibration, -100, 100, 0, 1, 0, Gradient { from: "#e0306a", to: "#e08a30" };
"calibration.redSat" => calibration.red_sat, "Red Saturation", Calibration, -100, 100, 0, 1, 0, Gradient { from: "#7a7a7a", to: "#e03a3a" };
+8
View File
@@ -200,6 +200,14 @@ impl DevelopSettings {
}
}
/// The middle of the crop, in normalized photo coordinates (the photo's middle when the crop
/// isn't a usable rectangle).
pub fn crop_center(&self) -> lightcraft_geom::Point {
let r = self.crop.geometry.rect;
let (x, y) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0);
if x.is_finite() && y.is_finite() { lightcraft_geom::Point::new(x, y) } else { lightcraft_geom::Point::new(0.5, 0.5) }
}
/// Next free mask id: one past the highest, or, when that is `u32::MAX` (ids come from files,
/// pastes and agents), the lowest one no mask uses.
pub fn next_mask_id(&self) -> u32 {
+179 -3
View File
@@ -96,12 +96,18 @@ pub enum Process {
/// V5, with colour noise reduction on the linear colour differences R−Y and B−Y, leaving Y alone, with
/// edge-aware weights from a denoised guide and a brake for isolated colour specks (issue #815).
V6,
/// V6, with film grain from a stack of crystal layers (after Aurélien Pierre's model): resolution
/// independent, fading out at black and white; V1 to V6 keep their value noise.
V7,
/// V7, with the Highlights/Shadows base taken of log luminance without its fine detail (clamped
/// between a fine and a 3× wider median), so gaps in dark lettering aren't lifted into bright blocks.
V8,
}
impl Process {
/// Every process, oldest first.
pub const ALL: [Process; 6] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6];
pub const LATEST: Process = Process::V6;
pub const ALL: [Process; 8] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7, Process::V8];
pub const LATEST: Process = Process::V8;
pub const fn version(self) -> ProcessVersion {
match self {
@@ -111,6 +117,8 @@ impl Process {
Process::V4 => ProcessVersion(4),
Process::V5 => ProcessVersion(5),
Process::V6 => ProcessVersion(6),
Process::V7 => ProcessVersion(7),
Process::V8 => ProcessVersion(8),
}
}
}
@@ -890,6 +898,25 @@ pub struct LocalAdjustments {
pub noise: f64,
pub moire: f64,
pub defringe: f64,
/// Lens Blur inside the mask, 0..100 (`lightcraft_pipeline::lens_blur`): disc (bokeh) blur
/// whose radius follows the mask's strength. Omitted while 0, so masks without it keep their
/// JSON (and hash).
#[serde(skip_serializing_if = "is_zero")]
pub lens_blur: f64,
/// The mask's Lens Blur block switched off (its values kept).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub lens_blur_off: bool,
/// Blur what the mask leaves out instead of what it selects (the mask's other adjustments
/// still go where it selects).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub lens_blur_outside: bool,
/// Brighter bokeh highlights in the mask's blur, 0..100.
#[serde(skip_serializing_if = "is_zero")]
pub lens_blur_boost: f64,
/// How gradually the mask's blur grows away from what stays sharp, 0..100 (0: it follows the
/// mask's own edge).
#[serde(skip_serializing_if = "is_zero")]
pub lens_blur_transition: f64,
/// Colour overlay (hue degrees, saturation 0..100); sat 0 = none.
pub color_hue: f64,
pub color_sat: f64,
@@ -917,6 +944,11 @@ impl Default for LocalAdjustments {
noise: 0.0,
moire: 0.0,
defringe: 0.0,
lens_blur: 0.0,
lens_blur_off: false,
lens_blur_outside: false,
lens_blur_boost: 0.0,
lens_blur_transition: 0.0,
color_hue: 0.0,
color_sat: 0.0,
amount: 100.0,
@@ -1258,13 +1290,157 @@ impl Default for RedEye {
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
/// Lens Blur: a shallow depth of field added after the fact (`lightcraft_pipeline::lens_blur`).
/// What stays sharp is the photo's subject, or the selection of the mask [`LensBlur::focus_mask`]
/// names; everything else gets disc-shaped (bokeh) blur up to [`LensBlur::amount`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct LensBlur {
pub enabled: bool,
/// Blur of what is out of focus, 0..100 (100: a disc of 3.5 % of the long edge).
pub amount: f64,
/// Reserved for a depth map (not rendered yet).
pub focal_distance: f64,
/// Reserved for a depth map (not rendered yet).
pub focal_range: f64,
/// How much brighter the out-of-focus highlights turn into bokeh discs, 0..100. Omitted while
/// 0, so settings without it keep their JSON (and hash).
#[serde(skip_serializing_if = "is_zero")]
pub boost: f64,
/// The id of the mask whose selection stays in focus (any mask, shown or hidden); `None`, or a
/// mask that no longer exists: the photo's subject.
#[serde(skip_serializing_if = "Option::is_none")]
pub focus_mask: Option<u32>,
/// Brush Refinement, Focus brush: strokes painted in focus (their strength: how far; erase
/// strokes take it back). Omitted while empty.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub focus_strokes: Vec<BrushStroke>,
/// Brush Refinement, Blur brush: strokes painted out of focus, over the focus and the Focus
/// brush. Omitted while empty.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub blur_strokes: Vec<BrushStroke>,
/// How gradually the blur grows away from what is in focus, 0..100: 0 a sharp cut at the
/// focus's edge, higher a longer ramp (a stand-in for depth until there is a depth map).
/// Omitted at its default, so settings without it keep their JSON (and hash).
#[serde(skip_serializing_if = "LensBlur::is_default_transition")]
pub transition: f64,
/// What stays in focus without a focus mask: the subject estimate, or a fixed shape in the
/// middle of the framing. Omitted while automatic.
#[serde(skip_serializing_if = "FocusShape::is_auto")]
pub shape: FocusShape,
/// Where a fixed shape sits and how large it is, once moved or resized on the photo; `None`:
/// the shape's preset, in the middle of the crop.
#[serde(skip_serializing_if = "Option::is_none")]
pub area: Option<FocusArea>,
}
/// A fixed focus shape on the photo: an upright ellipse.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct FocusArea {
/// Normalized (uncropped, oriented) photo coordinates, as mask shapes.
pub center: Point,
/// Half-width and half-height, in units of the photo's long edge.
pub rx: f64,
pub ry: f64,
}
impl FocusArea {
/// Smallest and largest radius (long-edge units).
pub const MIN_RADIUS: f64 = 0.02;
pub const MAX_RADIUS: f64 = 1.0;
/// Usable values: finite, the radii within range, the centre no farther than a photo's width
/// outside it. A hostile value falls back to the middle and the default size.
pub fn sanitized(self) -> FocusArea {
let r = |v: f64, d: f64| if v.is_finite() { v.clamp(Self::MIN_RADIUS, Self::MAX_RADIUS) } else { d };
let c = |v: f64| if v.is_finite() { v.clamp(-1.0, 2.0) } else { 0.5 };
FocusArea { center: Point::new(c(self.center.x), c(self.center.y)), rx: r(self.rx, 0.22), ry: r(self.ry, 0.22) }
}
}
impl LensBlur {
/// The fixed focus shape in effect, if any: the moved / resized [`LensBlur::area`], else the
/// shape's preset centred on `crop_center`. `None` for [`FocusShape::Auto`].
pub fn focus_area(&self, crop_center: Point) -> Option<FocusArea> {
let (rx, ry) = self.shape.radii()?;
Some(self.area.unwrap_or(FocusArea { center: crop_center, rx, ry }).sanitized())
}
}
/// The focus area [`LensBlur`] uses when no mask says what is in focus.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FocusShape {
/// A circle.
Round,
/// An oval lying down (landscape).
Wide,
/// An oval standing up (portrait).
Tall,
/// The photo's subject, estimated (person mattes, else a saliency heuristic). Also what a
/// shape this build doesn't know reads as (so it is last: serde's `other`).
#[default]
#[serde(other)]
Auto,
}
impl FocusShape {
pub const ALL: [FocusShape; 4] = [FocusShape::Auto, FocusShape::Round, FocusShape::Wide, FocusShape::Tall];
/// Whether this is the default (Auto: no fixed shape), for skipping it in the JSON.
fn is_auto(&self) -> bool {
*self == FocusShape::Auto
}
/// The fixed shape's half-width and half-height, in units of the photo's long edge; `None`
/// for [`FocusShape::Auto`].
pub fn radii(self) -> Option<(f64, f64)> {
match self {
FocusShape::Auto => None,
FocusShape::Round => Some((0.22, 0.22)),
FocusShape::Wide => Some((0.32, 0.17)),
FocusShape::Tall => Some((0.17, 0.32)),
}
}
/// The name shown on the shape's button (translated by the UI).
pub fn label(self) -> &'static str {
match self {
FocusShape::Auto => "Auto",
FocusShape::Round => "Round",
FocusShape::Wide => "Horizontal",
FocusShape::Tall => "Vertical",
}
}
}
impl LensBlur {
/// [`LensBlur::transition`]'s default.
pub const DEFAULT_TRANSITION: f64 = 50.0;
/// Whether `v` is [`Self::DEFAULT_TRANSITION`], for skipping it in the JSON.
fn is_default_transition(v: &f64) -> bool {
*v == Self::DEFAULT_TRANSITION
}
}
impl Default for LensBlur {
/// Off, with the default Transition and everything else empty.
fn default() -> Self {
Self {
enabled: false,
amount: 0.0,
focal_distance: 0.0,
focal_range: 0.0,
boost: 0.0,
focus_mask: None,
focus_strokes: Vec::new(),
blur_strokes: Vec::new(),
transition: Self::DEFAULT_TRANSITION,
shape: FocusShape::Auto,
area: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+4 -4
View File
@@ -89,13 +89,13 @@ fn v1_is_left_out_when_saving_and_other_processes_are_kept() {
#[test]
fn unknown_process_numbers_load_and_render_with_the_newest_known() {
// written by a newer LightCraft: kept as it is, rendered with the latest process this build has
let s = DevelopSettings::from_json(&json!({"process": 7, "light": {"exposure": 0.5}})).unwrap();
assert_eq!(s.process, ProcessVersion(7));
let s = DevelopSettings::from_json(&json!({"process": LATEST_PLUS_ONE, "light": {"exposure": 0.5}})).unwrap();
assert_eq!(s.process, ProcessVersion(LATEST_PLUS_ONE));
assert_eq!(s.process.process(), Process::LATEST);
assert!(!s.process.is_known());
assert!(!s.process.is_outdated(), "never downgraded by Update to Current Process");
assert_eq!(s.to_json()["process"], json!(7));
assert_eq!(s.merged(&json!({"light": {"exposure": 1.0}})).unwrap().process, ProcessVersion(7));
assert_eq!(s.to_json()["process"], json!(LATEST_PLUS_ONE));
assert_eq!(s.merged(&json!({"light": {"exposure": 1.0}})).unwrap().process, ProcessVersion(LATEST_PLUS_ONE));
// below V1 (no LightCraft writes it): rendered as V1, and updatable
let zero = DevelopSettings::from_json(&json!({"process": 0})).unwrap().process;
assert_eq!((zero.process(), zero.is_known(), zero.is_outdated()), (Process::V1, false, true));
+2
View File
@@ -29,6 +29,8 @@ lightcraft-meta = { workspace = true }
lightcraft-lensdb = { workspace = true }
lightcraft-faces = { workspace = true }
miniz_oxide = { workspace = true }
# CRC-32 of a catalog unpacked from a Lightroom backup zip (lightroom_backup.rs).
crc32fast = { workspace = true }
lightcraft-merge = { workspace = true }
lightcraft-geocode = { workspace = true }
lightcraft-slideshow = { workspace = true }
+1 -1
View File
@@ -206,7 +206,7 @@ fn edit_copy(s: &mut Session, p: &Value, id: lightcraft_catalog::PhotoId, opts:
/// preview-only photo this version hasn't checked yet: its stamp is refreshed so it isn't probed
/// again (see [`lightcraft_catalog::Photo::preview_checked`]).
pub(crate) fn content_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: crate::media::ProbeInfo) -> Option<Op> {
let preview_checked = lightcraft_catalog::preview_stamp(&info.preview_only);
let preview_checked = ph.preview_stamp(&info.preview_only);
let same = info.content_hash == ph.content_hash
&& info.file_size == ph.file_size
&& (info.width, info.height) == (ph.width, ph.height)
+147
View File
@@ -8,6 +8,9 @@ use serde_json::{Value, json};
use super::{CommandSpec, always, bad, bool_or, cmd, f64_or, f64_req, has_active, has_clipboard, has_selection, index_req, ok, str_param};
use crate::{Result, Session, media::SourceLevel};
/// Strokes one Lens Blur refinement brush keeps (a document can't grow without bound).
const MAX_LENS_BLUR_STROKES: usize = 2000;
fn active(s: &Session, c: &str) -> Result<PhotoId> {
s.active().ok_or_else(|| bad(c, "no active photo"))
}
@@ -482,6 +485,150 @@ pub fn specs() -> Vec<CommandSpec> {
Ok(())
})
}),
cmd!(
"lensBlur.brushStroke",
"Lens Blur Brush Stroke",
[],
None,
"{mode: \"focus\"|\"blur\", points: [[x,y],…] normalized, size?: fraction of long edge (0.03), feather?: 0..100, flow?: 1..100, amount?: 1..100 (how far the stroke refines), erase?: bool, autoMask?: bool, pressure?: [p,…] 0..1 per point} — Lens Blur Brush Refinement: Focus strokes stay sharp, Blur strokes are blurred",
has_active,
|s, p| {
const C: &str = "lensBlur.brushStroke";
let focus = match str_param(p, "mode") {
Some("focus") => true,
Some("blur") => false,
_ => return Err(bad(C, "`mode` must be \"focus\" or \"blur\"")),
};
let points: Vec<Point> = p
.get("points")
.and_then(Value::as_array)
.ok_or_else(|| bad(C, "missing points"))?
.iter()
.filter_map(|q| Some(Point::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?)))
.filter(|q| q.x.is_finite() && q.y.is_finite())
.collect();
if points.is_empty() {
return Err(bad(C, "a stroke needs at least one point"));
}
let d = lightcraft_develop::BrushStroke::default();
let num = |key: &str, def: f64, lo: f64, hi: f64| {
let v = f64_or(p, key, def);
if v.is_finite() { v.clamp(lo, hi) } else { def }
};
let stroke = lightcraft_develop::BrushStroke {
pressure: super::masks::pressure_list(p.get("pressure"), points.len())?,
points,
size: num("size", d.size, 0.001, 0.5),
feather: num("feather", d.feather, 0.0, 100.0),
flow: num("flow", d.flow, 1.0, 100.0),
density: num("amount", d.density, 1.0, 100.0),
erase: bool_or(p, "erase", false),
auto_mask: bool_or(p, "autoMask", false),
};
edit(s, C, if focus { "Lens Blur Focus Brush" } else { "Lens Blur Blur Brush" }, |d| {
let strokes = if focus { &mut d.lens_blur.focus_strokes } else { &mut d.lens_blur.blur_strokes };
if strokes.len() >= MAX_LENS_BLUR_STROKES {
return Err(bad(C, format!("at most {MAX_LENS_BLUR_STROKES} strokes per brush: Reset the brush first")));
}
strokes.push(stroke);
Ok(())
})
}
),
cmd!(
"lensBlur.findSubject",
"Find Subject",
[],
None,
"{} — selects the photo's subject with an Object mask (SAM 3) clicked where the camera focused, when the file records it, else at the likeliest subject; Lens Blur is switched on and keeps that mask in focus → {mask, point: [x,y], from: \"camera\"|\"photo\", pending?}",
has_active,
|s, _| {
const C: &str = "lensBlur.findSubject";
let id = active(s, C)?;
let d = s.develop_of(id).unwrap_or_default();
let camera = s.catalog.photo(id).and_then(|p| p.meta.focus.clone());
let (point, from) = match camera {
// stored on the upright photo: the user's Rotate / Flip on top, as masks are
Some(f) => {
let r = d.orientation.map_norm_rect(f.rect);
(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0), "camera")
}
None => {
let src = s.source_now(id, SourceLevel::Thumb).map_err(|e| bad(C, e))?;
let info = s.source_info(id);
let p = lightcraft_pipeline::lens_blur::subject_point(&src, &d, info.mattes.as_deref())
.ok_or_else(|| bad(C, "the photo has no picture to look for a subject in"))?;
(p, "photo")
}
};
if !(point.x.is_finite() && point.y.is_finite()) {
return Err(bad(C, "the camera's focus point is not usable"));
}
let point = Point::new(point.x.clamp(0.0, 1.0), point.y.clamp(0.0, 1.0));
// an Object waiting for the subject (the photo is analyzed meanwhile); the
// segmenter fills it with the people / animals the focus falls on, or the object
// at the point
let mut out = s.execute("mask.add", &json!({"kind": "object", "name": "Lens Blur Subject"}))?;
let mask = out
.get("activeMask")
.and_then(Value::as_u64)
.and_then(|v| u32::try_from(v).ok())
.ok_or_else(|| bad(C, "the subject mask was not created"))?;
let focus = (from == "camera").then_some(point);
if let Err(e) = s.segment_subject_later(id, mask, 0, point, focus) {
// nothing half-made: the empty mask goes again
let _ = s.execute("edit.undo", &json!({}));
return Err(crate::EngineError::Other(e));
}
out["pending"] = json!(s.segmenter.background);
edit(s, C, "Lens Blur Subject", |d| {
// a mask that only says what is in focus: no adjustments of its own
if let Some(m) = d.masks.iter_mut().find(|m| m.id == mask) {
m.adjust = lightcraft_develop::LocalAdjustments::default();
}
let b = &mut d.lens_blur;
b.enabled = true;
if b.amount <= 0.0 || !b.amount.is_finite() {
b.amount = 50.0;
}
b.focus_mask = Some(mask);
d.set_section_enabled("lensBlur", true);
Ok(())
})?;
if let Some(o) = out.as_object_mut() {
o.insert("mask".into(), json!(mask));
o.insert("point".into(), json!([point.x, point.y]));
o.insert("from".into(), json!(from));
}
Ok(out)
}
),
cmd!(
"lensBlur.brushReset",
"Reset Lens Blur Brush",
[],
None,
"{mode?: \"focus\"|\"blur\"} — removes that brush's strokes (both brushes without `mode`)",
has_active,
|s, p| {
const C: &str = "lensBlur.brushReset";
let (focus, blur) = match str_param(p, "mode") {
None => (true, true),
Some("focus") => (true, false),
Some("blur") => (false, true),
Some(_) => return Err(bad(C, "`mode` must be \"focus\" or \"blur\"")),
};
edit(s, C, "Reset Lens Blur Brush", |d| {
if focus {
d.lens_blur.focus_strokes.clear();
}
if blur {
d.lens_blur.blur_strokes.clear();
}
Ok(())
})
}
),
cmd!("develop.sectionEnabled", "Toggle Section", [], None, "{section: string, enabled: bool}", has_active, |s, p| {
let sec = str_param(p, "section").ok_or_else(|| bad("develop.sectionEnabled", "missing section"))?.to_string();
let on = bool_or(p, "enabled", true);
+7 -4
View File
@@ -1302,10 +1302,13 @@ pub fn specs() -> Vec<CommandSpec> {
}),
// ---- import
cmd!(query "library.inspectLightroom", "Inspect Lightroom Catalog", [], None,
"{path: .lrcat} → {photos, collections, missing, warnings}; read-only, no Lightroom required",
always, |_, p| {
"{path: .lrcat, or a Lightroom catalog backup .zip} → {photos, collections, missing, warnings}; read-only, no Lightroom required",
always, |s, p| {
let path = str_param(p,"path").ok_or_else(|| bad("library.inspectLightroom","missing path"))?;
let data = crate::lightroom_catalog::read(std::path::Path::new(path)).map_err(|e| bad("library.inspectLightroom",e))?;
let (cancel, total, done) = Default::default();
let temp = crate::lightroom_catalog::backup_temp_root(s);
let data = crate::lightroom_catalog::read_source(std::path::Path::new(path), temp.as_deref(), &cancel, &total, &done)
.map_err(|e| bad("library.inspectLightroom",e))?;
Ok(json!({"photos":data.photos.len(),"collections":data.collections.iter().filter(|r|r.get("systemOnly").and_then(Value::as_f64).unwrap_or(0.0)==0.0).count(),"missing":data.photos.iter().filter(|p| !p.original_is_file()).map(|p|&p.path).collect::<Vec<_>>(),"warnings":data.warnings,"skipped":data.skipped}))
}),
cmd!(
@@ -1313,7 +1316,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Lightroom Catalog",
[],
None,
"{path: .lrcat, updateExisting?: false}; direct import of paths, ratings, flags, metadata, keywords, collections, virtual copies & mapped edits. Archives source settings/history first. Existing edited photos are preserved unless updateExisting=true; source catalog is read-only.",
"{path: .lrcat, or a Lightroom catalog backup .zip (unpacked to a temporary folder in the library, removed after reading; the zip is not changed), updateExisting?: false}; direct import of paths, ratings, flags, metadata, keywords, collections, virtual copies & mapped edits. Archives source settings/history first. Existing edited photos are preserved unless updateExisting=true; source catalog is read-only.",
always,
|s, p| {
let path = str_param(p, "path").ok_or_else(|| bad("library.importLightroom", "missing path"))?;
+20 -2
View File
@@ -33,6 +33,7 @@ pub const FIELDS: &[&str] = &[
"noise",
"moire",
"defringe",
"lens_blur",
"color_hue",
"color_sat",
];
@@ -118,10 +119,11 @@ pub fn get(a: &LocalAdjustments, k: &str) -> f64 {
serde_json::to_value(a).ok().and_then(|v| v.get(k).and_then(Value::as_f64)).unwrap_or(0.0)
}
/// `a` with field `k` set to `v` (unchanged for an unknown name).
/// `a` with field `k` set to `v` (unchanged for an unknown name). A [`FIELDS`] slider counts as
/// known also while its JSON leaves it out at 0 (`lens_blur`).
pub fn set(a: &LocalAdjustments, k: &str, v: f64) -> LocalAdjustments {
let Ok(Value::Object(mut o)) = serde_json::to_value(a) else { return *a };
if !o.contains_key(k) || !v.is_finite() {
if !(o.contains_key(k) || FIELDS.contains(&k)) || !v.is_finite() {
return *a;
}
o.insert(k.into(), json!(v));
@@ -707,6 +709,22 @@ mod tests {
assert!(!e.matches(&LocalAdjustments { amount: 100.0, ..out }), "Amount counts when carried");
}
/// A partial effect sets Lens Blur on a mask without any yet (its JSON leaves `lens_blur` out
/// at 0); a name no slider has still changes nothing.
#[test]
fn partial_effects_set_lens_blur_from_zero() {
let e = MaskEffect {
name: "Bokeh".into(),
adjust: LocalAdjustments { lens_blur: 60.0, ..Default::default() },
fields: vec!["lens_blur".into()],
..Default::default()
};
let out = e.apply(&LocalAdjustments::default());
assert_eq!(out.lens_blur, 60.0);
assert!(e.matches(&out));
assert_eq!(set(&LocalAdjustments::default(), "bogus", 5.0), LocalAdjustments::default());
}
#[test]
fn hue_without_saturation_still_matches() {
let e = MaskEffect {
+13 -2
View File
@@ -98,6 +98,10 @@ fn resolve_ai(s: &mut Session, shape: &mut MaskShape, c: &str) -> Result<Later>
match shape {
MaskShape::Object { seg: Some(_), .. } | MaskShape::Prompt { seg: Some(_), .. } => {}
MaskShape::Object { hint, exclude, .. } if !hint.is_empty() && background => {
// refused here, not when the worker later fails at the model's limit after "pending"
if hint.len() + exclude.len() > crate::segment::MAX_CLICKS {
return Err(ai_err(format!("an Object selection takes at most {} clicks", crate::segment::MAX_CLICKS)));
}
s.segmenter.require_model()?;
return Ok(Later::Clicks(std::mem::take(hint), std::mem::take(exclude)));
}
@@ -158,7 +162,11 @@ fn masks_edit(s: &mut Session, c: &str, label: &str, f: impl FnOnce(&mut Vec<Mas
let id = s.active().ok_or_else(|| bad(c, "no active photo"))?;
let mut d = (*s.develop_of(id).unwrap_or_default()).clone();
let mut active = s.active_mask;
// the Lens Blur focus follows its mask: a deleted one stops being the focus, so a new mask
// that gets its id (the next id is the highest + 1) doesn't turn into it
let focus = d.lens_blur.focus_mask.filter(|f| d.masks.iter().any(|m| m.id == *f));
f(&mut d.masks, &mut active)?;
d.lens_blur.focus_mask = focus.filter(|f| d.masks.iter().any(|m| m.id == *f));
s.set_develop(id, d, label)?;
s.active_mask = active;
Ok(json!({"activeMask": active}))
@@ -648,7 +656,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Mask Adjustments",
[],
None,
"{id?, values: {exposure, contrast, highlights, shadows, whites, blacks, temp, tint, texture, clarity, dehaze, hue, saturation, sharpness, noise, moire, defringe, color_hue, color_sat, amount}}",
"{id?, values: {exposure, contrast, highlights, shadows, whites, blacks, temp, tint, texture, clarity, dehaze, hue, saturation, sharpness, noise, moire, defringe, lens_blur, lens_blur_off, lens_blur_outside, lens_blur_boost, lens_blur_transition, color_hue, color_sat, amount}}",
has_active,
|s, p| {
let vals = p.get("values").cloned().ok_or_else(|| bad("mask.adjust", "missing values"))?;
@@ -1147,6 +1155,9 @@ pub(crate) fn clamp_local(mut a: LocalAdjustments) -> LocalAdjustments {
] {
c(v, -100.0, 100.0);
}
c(&mut a.lens_blur, 0.0, 100.0);
c(&mut a.lens_blur_boost, 0.0, 100.0);
c(&mut a.lens_blur_transition, 0.0, 100.0);
c(&mut a.color_hue, 0.0, 360.0);
c(&mut a.color_sat, 0.0, 100.0);
c(&mut a.amount, 0.0, 200.0);
@@ -1155,7 +1166,7 @@ pub(crate) fn clamp_local(mut a: LocalAdjustments) -> LocalAdjustments {
/// `mask.brushStroke`'s `pressure`: one number 0..1 per point (clamped), at most one per point; absent or `null`
/// is no pressure data.
fn pressure_list(v: Option<&Value>, points: usize) -> Result<Vec<f32>> {
pub(super) fn pressure_list(v: Option<&Value>, points: usize) -> Result<Vec<f32>> {
let Some(v) = v.filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
let list = v.as_array().ok_or_else(|| bad("mask.brushStroke", "pressure must be a list of numbers 0..1"))?;
if list.len() > points {
+9 -7
View File
@@ -4,6 +4,8 @@
//! library opens in another version, its stale preview-only photos are probed again and get
//! exactly what Reload from Disk would give them: a file that decodes now loses the flag, one that
//! still doesn't gets the new reason and a fresh stamp, so it isn't probed again.
//! ORF records are rechecked even when previously sensor-decodable: compressed sensor support
//! was withdrawn after #3775. Supported uncompressed ORFs also keep a stamp to avoid repeat work.
//!
//! The work is split so the app can probe on a worker thread: [`stale`] lists what to probe (no
//! file-system calls), [`probe`] reads the files without the session, and [`apply`] applies the
@@ -17,7 +19,7 @@ use super::{CommandSpec, always, bad, cmd};
use crate::media::{FileProbe, ProbeInfo};
use crate::{Result, Session};
/// A preview-only photo to probe, and what the library knew about it when it was listed (so a
/// A photo to probe, and what the library knew about it when it was listed (so a
/// result for a photo that changed meanwhile is dropped).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Stale {
@@ -40,12 +42,12 @@ impl Stale {
}
}
/// The library's preview-only photos whose flag another app version set (or every preview-only
/// photo, with `all`): library photos with a file, not virtual copies (they follow the photo they
/// were copied from). No file-system calls.
/// The library's preview-only photos and ORFs whose support another app version checked (or
/// every such photo, with `all`): library photos with a file, not virtual copies (they follow
/// the photo they were copied from). No file-system calls.
pub fn stale(cat: &Catalog, all: bool) -> Vec<Stale> {
cat.photos()
.filter(|p| p.copy_of.is_none() && p.preview_only.is_some() && (all || p.preview_only_stale()))
.filter(|p| p.copy_of.is_none() && (p.preview_only_stale() || (all && (p.preview_only.is_some() || p.format.eq_ignore_ascii_case("orf")))))
.filter_map(|p| crate::cmd::missing::checked_path(p).map(|path| Stale::of(p, path)))
.collect()
}
@@ -92,7 +94,7 @@ pub fn apply(s: &mut Session, results: Vec<(Stale, std::result::Result<ProbeInfo
let first = out.updated.len();
crate::cmd::convert::reload_ops(&s.catalog, item.id, &info, &mut ops, &mut out.updated);
if info.preview_only.is_none() {
out.cleared.extend_from_slice(&out.updated[first..]);
out.cleared.extend(out.updated[first..].iter().copied().filter(|id| s.catalog.photo(*id).is_some_and(|p| p.preview_only.is_some())));
}
}
if !ops.is_empty() {
@@ -122,7 +124,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Recheck Preview-Only Raws",
[],
None,
"{all?: bool} — probe again the raws shown from their embedded preview whose flag another LightCraft version set (the app does this in the background when a library opens; `all` rechecks every preview-only raw, e.g. when testing a decoder build of the same version), and bring each up to date as Reload from Disk would; not an undo step, develop settings and history are kept; files that can't be read are left for next time → {checked, updated: [ids], cleared: [ids] (develop from their raw data now)}",
"{all?: bool} — probe again preview-only raws and ORFs whose support another LightCraft version checked (the app does this in the background when a library opens; `all` rechecks every preview-only raw and ORF, e.g. when testing a decoder build of the same version), and bring each up to date as Reload from Disk would; not an undo step, develop settings and history are kept; files that can't be read are left for next time → {checked, updated: [ids], cleared: [ids] (develop from their raw data now)}",
always,
recheck
)]
+1
View File
@@ -51,6 +51,7 @@ pub mod lens_profiles;
pub mod lensfun_download;
pub mod library;
mod lightroom_archive;
pub mod lightroom_backup;
pub mod lightroom_catalog;
pub mod lightroom_folder;
pub mod lightroom_job;
+4
View File
@@ -519,6 +519,8 @@ mod tests {
fn data(source: String) -> CatalogImport {
CatalogImport {
source,
catalog_id: None,
catalog_path: None,
photos: Vec::new(),
collections: Vec::new(),
members: Vec::new(),
@@ -543,6 +545,8 @@ mod tests {
};
CatalogImport {
source: "source.lrcat".into(),
catalog_id: None,
catalog_path: None,
photos: vec![photo],
collections: vec![BTreeMap::from([("name".into(), serde_json::json!("Keepers"))])],
members: vec![BTreeMap::from([("image".into(), serde_json::json!(7))])],
+558
View File
@@ -0,0 +1,558 @@
//! Lightroom Classic catalog backups (issue #2592): `Backups/YYYY-MM-DD HHMM/<name>.zip`, which
//! holds the catalog `<name>.lrcat` (and, since Classic 12, a small `<name>.lrcat-data/` folder that
//! the import does not need). Someone who has left Lightroom may have nothing else: the import takes
//! the zip as it is.
//!
//! The catalog entry is inflated by streaming into a private folder ([`Extracted`]), read from
//! there like any `.lrcat`, and the folder is removed when the [`Extracted`] guard is dropped (after
//! the read, on an error and on cancel alike). The zip itself is only read. The folder is made under
//! the open library's `Interop/` when there is one (the library's disk, not a RAM-backed `/tmp`),
//! else under [`std::env::temp_dir`]; a folder left by a crash (`lc-lrbackup-*`, older than a day)
//! is removed by the next extraction there.
//!
//! Written from the ZIP application note (PKWARE APPNOTE.TXT 6.3: end of central directory,
//! ZIP64 end record and locator, central directory headers, local headers, the ZIP64 extra field
//! 0x0001) and RFC 1951 (deflate, inflated by `miniz_oxide`); no third-party zip code was used.
//! Every size and offset comes from the file and is checked before use.
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
/// The largest catalog a backup may unpack to: the SQLite reader's cap on a database file.
pub const MAX_CATALOG_BYTES: u64 = 16 << 30;
/// The most central directory entries looked at (a Lightroom backup has one to four).
const MAX_ENTRIES: u64 = 4096;
/// The largest central directory read (names of `MAX_ENTRIES` entries fit easily).
const MAX_DIRECTORY_BYTES: u64 = 4 << 20;
/// Prefix of the private extraction folders, so leftovers can be found.
const PREFIX: &str = "lc-lrbackup-";
/// Leftover folders older than this are removed (one still being read is never this old).
const STALE_SECS: u64 = 24 * 60 * 60;
/// Bytes read from the zip and written to the catalog per step.
const CHUNK: usize = 1 << 20;
/// Whether `path` names a Lightroom catalog backup: a `.zip` file (any case).
pub fn is_backup(path: &Path) -> bool {
path.extension().is_some_and(|e| e.eq_ignore_ascii_case("zip"))
}
/// Where the catalog in a backup lived, for resolving the paths it records relative to itself, and
/// whether that is known: `<catalog folder>/Backups/<date>/<name>.zip` (Lightroom's default
/// layout) → `<catalog folder>/<name>.lrcat`, known; a zip anywhere else (a backup folder of the
/// person's choosing, a zip moved away) → the `.lrcat` next to it, a guess that is only used to
/// resolve paths, never to recognise the catalog.
pub fn original_catalog(zip: &Path, entry: &str) -> (PathBuf, bool) {
let name = Path::new(entry).file_name().map_or_else(|| PathBuf::from("catalog.lrcat"), PathBuf::from);
let dated = zip.parent();
let backups = dated.and_then(Path::parent);
match backups {
Some(b) if b.file_name().is_some_and(|n| n.eq_ignore_ascii_case("backups")) => (b.parent().unwrap_or(b).join(name), true),
_ => (dated.map_or_else(|| name.clone(), |d| d.join(&name)), false),
}
}
/// A catalog unpacked from a backup; its private folder is removed when this is dropped.
#[derive(Debug)]
pub struct Extracted {
dir: PathBuf,
/// The unpacked `.lrcat`.
pub catalog: PathBuf,
/// The catalog's name inside the zip.
pub entry: String,
}
impl Drop for Extracted {
/// Removes the private folder and the catalog in it; a failure is logged, not raised (drop can't fail).
fn drop(&mut self) {
if let Err(e) = std::fs::remove_dir_all(&self.dir)
&& e.kind() != std::io::ErrorKind::NotFound
{
log::warn!("Lightroom backup: could not remove {}: {e}", self.dir.display());
}
}
}
/// One file in the zip's central directory.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Entry {
name: String,
method: u16,
crc: u32,
compressed: u64,
size: u64,
local: u64,
}
/// The little-endian `u16` at `at` in `b`, or `None` past its end.
fn u16_at(b: &[u8], at: usize) -> Option<u16> {
let s = b.get(at..at.checked_add(2)?)?;
Some(u16::from_le_bytes([s[0], s[1]]))
}
/// The little-endian `u32` at `at` in `b`, or `None` past its end.
fn u32_at(b: &[u8], at: usize) -> Option<u32> {
let s = b.get(at..at.checked_add(4)?)?;
Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
/// The little-endian `u64` at `at` in `b`, or `None` past its end.
fn u64_at(b: &[u8], at: usize) -> Option<u64> {
let s = b.get(at..at.checked_add(8)?)?;
let mut a = [0u8; 8];
a.copy_from_slice(s);
Some(u64::from_le_bytes(a))
}
/// `len` bytes of `f` from offset `at`; a length that doesn't fit memory or a short read is an error.
fn read_at(f: &mut File, at: u64, len: u64) -> Result<Vec<u8>, String> {
let len = usize::try_from(len).map_err(|_| "zip record too large".to_string())?;
f.seek(SeekFrom::Start(at)).map_err(|e| e.to_string())?;
let mut buf = vec![0u8; len];
f.read_exact(&mut buf).map_err(|e| format!("truncated zip: {e}"))?;
Ok(buf)
}
/// The central directory's entries (offset and count from the end record, or its ZIP64 record).
fn entries(f: &mut File) -> Result<Vec<Entry>, String> {
let len = f.metadata().map_err(|e| e.to_string())?.len();
// end of central directory: 22 bytes plus a comment of up to 64 KiB
let tail_len = len.min(22 + 65_535);
let tail_at = len - tail_len;
let tail = read_at(f, tail_at, tail_len)?;
let eocd = (0..tail.len().saturating_sub(21)).rev().find(|&i| tail.get(i..).is_some_and(|b| b.starts_with(b"PK\x05\x06")));
let Some(eocd) = eocd else { return Err("not a zip file (no end of central directory)".into()) };
let bad = || "damaged zip (end of central directory)".to_string();
let mut count = u64::from(u16_at(&tail, eocd + 10).ok_or_else(bad)?);
let mut dir_len = u64::from(u32_at(&tail, eocd + 12).ok_or_else(bad)?);
let mut dir_at = u64::from(u32_at(&tail, eocd + 16).ok_or_else(bad)?);
// ZIP64: a locator just before the end record points at the ZIP64 end record
if (count == 0xFFFF || dir_len == 0xFFFF_FFFF || dir_at == 0xFFFF_FFFF)
&& let Some(loc) = eocd.checked_sub(20)
&& tail.get(loc..).is_some_and(|b| b.starts_with(b"PK\x06\x07"))
{
let rec_at = u64_at(&tail, loc + 8).ok_or_else(bad)?;
let rec = read_at(f, rec_at, 56)?;
if !rec.starts_with(b"PK\x06\x06") {
return Err("damaged zip (ZIP64 end record)".into());
}
count = u64_at(&rec, 32).ok_or_else(bad)?;
dir_len = u64_at(&rec, 40).ok_or_else(bad)?;
dir_at = u64_at(&rec, 48).ok_or_else(bad)?;
}
if count > MAX_ENTRIES || dir_len > MAX_DIRECTORY_BYTES || dir_at.checked_add(dir_len).is_none_or(|end| end > len) {
return Err("damaged zip (central directory out of range)".into());
}
let dir = read_at(f, dir_at, dir_len)?;
let mut out = Vec::new();
let mut at = 0usize;
let bad = || "damaged zip (central directory)".to_string();
for _ in 0..count {
if !dir.get(at..).is_some_and(|b| b.starts_with(b"PK\x01\x02")) {
return Err(bad());
}
let method = u16_at(&dir, at + 10).ok_or_else(bad)?;
let crc = u32_at(&dir, at + 16).ok_or_else(bad)?;
let mut compressed = u64::from(u32_at(&dir, at + 20).ok_or_else(bad)?);
let mut size = u64::from(u32_at(&dir, at + 24).ok_or_else(bad)?);
let name_len = usize::from(u16_at(&dir, at + 28).ok_or_else(bad)?);
let extra_len = usize::from(u16_at(&dir, at + 30).ok_or_else(bad)?);
let comment_len = usize::from(u16_at(&dir, at + 32).ok_or_else(bad)?);
let mut local = u64::from(u32_at(&dir, at + 42).ok_or_else(bad)?);
let name_at = at + 46;
let name_end = name_at.checked_add(name_len).ok_or_else(bad)?;
let name = String::from_utf8_lossy(dir.get(name_at..name_end).ok_or_else(bad)?).replace('\\', "/");
let extra = dir.get(name_end..name_end.checked_add(extra_len).ok_or_else(bad)?).ok_or_else(bad)?;
// ZIP64 extra field: the 64-bit values, in this order, of those set to 0xFFFFFFFF
let mut e = 0usize;
while e + 4 <= extra.len() {
let (id, len) = (u16_at(extra, e).ok_or_else(bad)?, usize::from(u16_at(extra, e + 2).ok_or_else(bad)?));
let body = extra.get(e + 4..e + 4 + len).ok_or_else(bad)?;
if id == 0x0001 {
let mut v = 0usize;
for field in [&mut size, &mut compressed, &mut local] {
if *field == 0xFFFF_FFFF {
*field = u64_at(body, v).ok_or_else(bad)?;
v += 8;
}
}
}
e += 4 + len;
}
at = name_end.checked_add(extra_len).and_then(|x| x.checked_add(comment_len)).ok_or_else(bad)?;
out.push(Entry { name, method, crc, compressed, size, local });
}
Ok(out)
}
/// The backup's catalog entry: the one `*.lrcat` file in the zip, outside macOS resource forks.
fn catalog_entry(entries: &[Entry]) -> Result<&Entry, String> {
let mut found = entries.iter().filter(|e| {
let lower = e.name.to_lowercase();
lower.ends_with(".lrcat") && !lower.split('/').any(|p| p == "__macosx" || p.starts_with("._"))
});
match (found.next(), found.next()) {
(Some(e), None) => Ok(e),
(None, _) => Err("this zip holds no Lightroom catalog (.lrcat)".into()),
(Some(_), Some(_)) => Err("this zip holds more than one Lightroom catalog (.lrcat); unzip it and import one".into()),
}
}
/// Whether the zip at `path` holds exactly one Lightroom catalog, by its central directory only
/// (nothing is unpacked). Any read error means no.
pub fn holds_catalog(path: &Path) -> bool {
File::open(path).ok().and_then(|mut f| entries(&mut f).ok()).is_some_and(|all| catalog_entry(&all).is_ok())
}
/// Remove `lc-lrbackup-*` folders in `root` left by an earlier run that ended without cleaning up.
fn sweep(root: &Path) {
let Ok(dir) = std::fs::read_dir(root) else { return };
for entry in dir.take(10_000).flatten() {
if !entry.file_name().to_str().is_some_and(|n| n.starts_with(PREFIX)) {
continue;
}
// only a real folder of ours: `DirEntry::metadata` doesn't follow a link (Unix), and a link named
// like one is skipped explicitly rather than relying on `remove_dir_all` removing just the link
let Ok(meta) = entry.metadata() else { continue };
let stale = meta.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age.as_secs() > STALE_SECS);
if meta.is_dir()
&& !meta.file_type().is_symlink()
&& stale
&& let Err(e) = std::fs::remove_dir_all(entry.path())
{
log::warn!("Lightroom backup: could not remove the leftover {}: {e}", entry.path().display());
}
}
}
/// Refuse a known shortage; an unavailable space reading is left to normal write-error handling.
fn check_space(root: &Path, needed: u64, available: Option<u64>) -> Result<(), String> {
if let Some(available) = available
&& needed > available
{
return Err(format!("not enough free space in {} to unpack this catalog ({} bytes needed, {} available)", root.display(), needed, available));
}
Ok(())
}
/// Unpack the catalog of the backup `zip` into a new private folder under `root`, checking its
/// size and CRC-32. Stops with an error when `cancel` is set; the folder is removed then too.
pub fn extract(zip: &Path, root: &Path, cancel: &AtomicBool) -> Result<Extracted, String> {
let mut f = File::open(zip).map_err(|e| format!("{}: {e}", zip.display()))?;
let all = entries(&mut f)?;
let entry = catalog_entry(&all)?.clone();
if entry.size > MAX_CATALOG_BYTES {
return Err(format!("the catalog in this backup unpacks to {} GB, more than LightCraft reads", entry.size >> 30));
}
std::fs::create_dir_all(root).map_err(|e| format!("{}: {e}", root.display()))?;
check_space(root, entry.size, crate::disk_space::read(root).map(|space| space.available))?;
sweep(root);
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
let dir = root.join(format!("{PREFIX}{}-{stamp}", std::process::id()));
// owner-only from the start on Unix (a catalog holds the person's paths and metadata)
#[cfg(unix)]
let builder = {
let mut builder = std::fs::DirBuilder::new();
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
builder
};
#[cfg(not(unix))]
let builder = std::fs::DirBuilder::new();
builder.create(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
// a fixed name, not the zip's: an entry named `NUL.lrcat` or `a:b.lrcat` would be a device or an
// alternate data stream on Windows. The guard exists before the first byte is written: every
// early return below cleans up.
let out = Extracted { catalog: dir.join("catalog.lrcat"), dir, entry: entry.name.clone() };
let local = read_at(&mut f, entry.local, 30)?;
if !local.starts_with(b"PK\x03\x04") {
return Err("damaged zip (local header)".into());
}
let bad = || "damaged zip (local header)".to_string();
let skip = u64::from(u16_at(&local, 26).ok_or_else(bad)?) + u64::from(u16_at(&local, 28).ok_or_else(bad)?);
let data_at = entry.local.checked_add(30 + skip).ok_or_else(bad)?;
f.seek(SeekFrom::Start(data_at)).map_err(|e| e.to_string())?;
let mut input = f.take(entry.compressed);
// created new: a file or a link already in its place is an error, never written through
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&out.catalog).map_err(|e| format!("{}: {e}", out.catalog.display()))?;
let mut writer = std::io::BufWriter::with_capacity(CHUNK, file);
let mut crc = crc32fast::Hasher::new();
let mut written = 0u64;
let mut write = |bytes: &[u8], written: &mut u64| -> Result<(), String> {
*written = written.saturating_add(bytes.len() as u64);
if *written > entry.size {
return Err("damaged zip (the catalog is longer than the zip says)".into());
}
crc.update(bytes);
writer.write_all(bytes).map_err(|e| format!("writing {}: {e}", out.catalog.display()))
};
let mut buf = vec![0u8; CHUNK];
match entry.method {
0 => loop {
if cancel.load(Ordering::Relaxed) {
return Err("cancelled".into());
}
let n = input.read(&mut buf).map_err(|e| e.to_string())?;
if n == 0 {
break;
}
write(buf.get(..n).unwrap_or_default(), &mut written)?;
},
8 => {
use miniz_oxide::inflate::stream::{InflateState, inflate};
use miniz_oxide::{DataFormat, MZFlush, MZStatus};
let mut state = InflateState::new_boxed(DataFormat::Raw);
let mut out_buf = vec![0u8; CHUNK];
let (mut start, mut end) = (0usize, 0usize);
loop {
if cancel.load(Ordering::Relaxed) {
return Err("cancelled".into());
}
if start == end {
end = input.read(&mut buf).map_err(|e| e.to_string())?;
start = 0;
}
let flush = if end == 0 { MZFlush::Finish } else { MZFlush::None };
let r = inflate(&mut state, buf.get(start..end).unwrap_or_default(), &mut out_buf, flush);
start = start.saturating_add(r.bytes_consumed).min(end);
write(out_buf.get(..r.bytes_written).unwrap_or_default(), &mut written)?;
match r.status {
Ok(MZStatus::StreamEnd) => break,
Ok(_) => {}
// no progress with all input given: the stream is cut short
Err(miniz_oxide::MZError::Buf) if end == 0 && r.bytes_written == 0 => return Err("damaged zip (the catalog is cut short)".into()),
Err(miniz_oxide::MZError::Buf) => {}
Err(e) => return Err(format!("damaged zip (deflate: {e:?})")),
}
if r.bytes_consumed == 0 && r.bytes_written == 0 && start < end {
return Err("damaged zip (the catalog's data does not inflate)".into());
}
}
}
m => return Err(format!("this zip uses compression method {m}, which LightCraft does not read; unzip it and import the .lrcat")),
}
writer.flush().map_err(|e| format!("writing {}: {e}", out.catalog.display()))?;
drop(writer);
if written != entry.size {
return Err("damaged zip (the catalog is shorter than the zip says)".into());
}
if crc.finalize() != entry.crc {
return Err("damaged zip (the catalog's checksum does not match)".into());
}
Ok(out)
}
#[cfg(test)]
pub(crate) mod tests {
#[test]
fn free_space_check_refuses_known_shortage() {
let root = std::path::Path::new("library");
assert!(super::check_space(root, 11, Some(10)).unwrap_err().contains("not enough free space"));
assert!(super::check_space(root, 10, Some(10)).is_ok());
assert!(super::check_space(root, 11, None).is_ok());
}
use super::*;
/// A zip of `files` (name, bytes), each stored or deflated; `zip64` writes ZIP64 records and
/// extra fields (with the 32-bit fields set to 0xFFFFFFFF) as large archives do.
pub(crate) fn zip(files: &[(&str, &[u8])], deflate: bool, zip64: bool) -> Vec<u8> {
let mut out = Vec::new();
let mut central = Vec::new();
for (name, data) in files {
let body = if deflate { miniz_oxide::deflate::compress_to_vec(data, 6) } else { data.to_vec() };
let crc = crc32fast::hash(data);
let local = out.len() as u64;
let method: u16 = if deflate { 8 } else { 0 };
let big = |v: u64| if zip64 { 0xFFFF_FFFFu32 } else { v as u32 };
let mut extra = Vec::new();
if zip64 {
extra.extend_from_slice(&1u16.to_le_bytes());
extra.extend_from_slice(&24u16.to_le_bytes());
extra.extend_from_slice(&(data.len() as u64).to_le_bytes());
extra.extend_from_slice(&(body.len() as u64).to_le_bytes());
extra.extend_from_slice(&local.to_le_bytes());
}
out.extend_from_slice(b"PK\x03\x04");
out.extend_from_slice(&[20, 0, 0, 0]);
out.extend_from_slice(&method.to_le_bytes());
out.extend_from_slice(&[0; 4]);
out.extend_from_slice(&crc.to_le_bytes());
out.extend_from_slice(&big(body.len() as u64).to_le_bytes());
out.extend_from_slice(&big(data.len() as u64).to_le_bytes());
out.extend_from_slice(&(name.len() as u16).to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(name.as_bytes());
out.extend_from_slice(&body);
central.extend_from_slice(b"PK\x01\x02");
central.extend_from_slice(&[45, 0, 45, 0, 0, 0]);
central.extend_from_slice(&method.to_le_bytes());
central.extend_from_slice(&[0; 4]);
central.extend_from_slice(&crc.to_le_bytes());
central.extend_from_slice(&big(body.len() as u64).to_le_bytes());
central.extend_from_slice(&big(data.len() as u64).to_le_bytes());
central.extend_from_slice(&(name.len() as u16).to_le_bytes());
central.extend_from_slice(&(extra.len() as u16).to_le_bytes());
// comment length, disk number, internal attributes, external attributes
central.extend_from_slice(&[0; 6]);
central.extend_from_slice(&0u32.to_le_bytes());
central.extend_from_slice(&big(local).to_le_bytes());
central.extend_from_slice(name.as_bytes());
central.extend_from_slice(&extra);
}
let dir_at = out.len() as u64;
out.extend_from_slice(&central);
let count = files.len() as u64;
if zip64 {
let rec_at = out.len() as u64;
out.extend_from_slice(b"PK\x06\x06");
out.extend_from_slice(&44u64.to_le_bytes());
out.extend_from_slice(&[45, 0, 45, 0]);
out.extend_from_slice(&[0; 8]);
out.extend_from_slice(&count.to_le_bytes());
out.extend_from_slice(&count.to_le_bytes());
out.extend_from_slice(&(central.len() as u64).to_le_bytes());
out.extend_from_slice(&dir_at.to_le_bytes());
out.extend_from_slice(b"PK\x06\x07");
out.extend_from_slice(&0u32.to_le_bytes());
out.extend_from_slice(&rec_at.to_le_bytes());
out.extend_from_slice(&1u32.to_le_bytes());
}
out.extend_from_slice(b"PK\x05\x06");
out.extend_from_slice(&[0; 4]);
let c16 = if zip64 { 0xFFFF } else { count as u16 };
out.extend_from_slice(&c16.to_le_bytes());
out.extend_from_slice(&c16.to_le_bytes());
out.extend_from_slice(&(if zip64 { 0xFFFF_FFFF } else { central.len() as u32 }).to_le_bytes());
out.extend_from_slice(&(if zip64 { 0xFFFF_FFFF } else { dir_at as u32 }).to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out
}
/// A fresh, empty folder for one test.
fn temp(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("lc-lrbackup-test-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// The private extraction folders still in `root`.
fn leftovers(root: &Path) -> Vec<String> {
let Ok(dir) = std::fs::read_dir(root) else { return Vec::new() };
dir.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.starts_with(PREFIX)).collect()
}
/// Stored, deflated and ZIP64 backups give back the catalog byte for byte, under the fixed name, and leave nothing.
#[test]
fn stored_deflated_and_zip64_backups_unpack_their_catalog_and_clean_up() {
let catalog: Vec<u8> = (0..300_000u32).flat_map(|i| (i % 251).to_le_bytes()).collect();
for (deflate, zip64) in [(false, false), (true, false), (true, true), (false, true)] {
let dir = temp(&format!("ok-{deflate}-{zip64}"));
let path = dir.join("Cat.zip");
let files: [(&str, &[u8]); 3] = [("Cat.lrcat", &catalog), ("Cat.lrcat-data/CURRENT", b"MANIFEST-1\n"), ("__MACOSX/._Cat.lrcat", b"x")];
std::fs::write(&path, zip(&files, deflate, zip64)).unwrap();
let root = dir.join("tmp");
let got = extract(&path, &root, &AtomicBool::new(false)).unwrap();
assert_eq!(std::fs::read(&got.catalog).unwrap(), catalog, "deflate {deflate} zip64 {zip64}");
assert_eq!(got.entry, "Cat.lrcat");
assert_eq!(got.catalog.file_name().unwrap(), "catalog.lrcat", "a fixed name, never the zip's");
drop(got);
assert!(leftovers(&root).is_empty(), "the private folder is removed");
std::fs::remove_dir_all(&dir).unwrap();
}
}
/// Not a zip, empty, no or two catalogs, cut short, bad CRC, or cancelled: an error, and no folder left.
#[test]
fn damaged_or_wrong_zips_are_errors_and_leave_nothing_behind() {
let dir = temp("bad");
let root = dir.join("tmp");
let catalog = vec![7u8; 100_000];
let good = zip(&[("Cat.lrcat", &catalog)], true, false);
let cases: Vec<(&str, Vec<u8>)> = vec![
("not a zip", b"SQLite format 3\0".to_vec()),
("empty", Vec::new()),
("no catalog", zip(&[("notes.txt", b"hi")], false, false)),
("two catalogs", zip(&[("A.lrcat", b"a"), ("B.lrcat", b"b")], false, false)),
("cut short", good.get(..good.len() / 2).unwrap().to_vec()),
("bad crc", {
let mut z = good.clone();
// flip one byte of the deflated data (after the 30-byte local header and the name)
z[30 + 9 + 10] ^= 0xFF;
z
}),
];
for (what, bytes) in cases {
let path = dir.join("x.zip");
std::fs::write(&path, &bytes).unwrap();
assert!(extract(&path, &root, &AtomicBool::new(false)).is_err(), "{what} must fail");
if root.exists() {
assert!(leftovers(&root).is_empty(), "{what} left a folder");
}
}
std::fs::write(dir.join("x.zip"), &good).unwrap();
assert!(extract(&dir.join("x.zip"), &root, &AtomicBool::new(true)).is_err(), "cancel stops");
assert!(leftovers(&root).is_empty(), "cancel cleans up");
std::fs::remove_dir_all(&dir).unwrap();
}
/// A ZIP64 size of 1 TB is refused before anything is written.
#[test]
fn a_zip_that_lies_about_the_catalog_size_is_refused() {
let dir = temp("size");
let mut z = zip(&[("Cat.lrcat", &[1u8; 1000])], true, true);
// the ZIP64 extra field's uncompressed size: 1 TB
let at = z.windows(4).rposition(|w| w == [1, 0, 24, 0]).unwrap() + 4;
z[at..at + 8].copy_from_slice(&(1u64 << 40).to_le_bytes());
std::fs::write(dir.join("x.zip"), &z).unwrap();
let err = extract(&dir.join("x.zip"), &dir.join("tmp"), &AtomicBool::new(false)).unwrap_err();
assert!(err.contains("more than LightCraft reads"), "{err}");
std::fs::remove_dir_all(&dir).unwrap();
}
/// A day-old leftover folder is removed; a recent one (another import still reading) is kept.
#[cfg(unix)]
#[test]
fn stale_leftovers_are_swept_and_recent_ones_kept() {
let root = temp("sweep");
let old = root.join(format!("{PREFIX}1-1"));
let recent = root.join(format!("{PREFIX}2-2"));
std::fs::create_dir_all(&old).unwrap();
std::fs::create_dir_all(&recent).unwrap();
let past = std::time::SystemTime::now() - std::time::Duration::from_secs(STALE_SECS + 60);
File::open(&old).unwrap().set_modified(past).unwrap();
sweep(&root);
assert!(!old.exists() && recent.exists());
std::fs::remove_dir_all(&root).unwrap();
}
/// Paths relative to the catalog resolve from where Lightroom kept it, not from the zip.
#[test]
fn the_original_catalog_is_two_folders_above_a_dated_backup() {
let zip = Path::new("/p/Lightroom/Backups/2023-11-07 0900/Cat-v13.zip");
assert_eq!(original_catalog(zip, "Cat-v13.lrcat"), (PathBuf::from("/p/Lightroom/Cat-v13.lrcat"), true));
// a backup folder of the person's choosing: a guess for paths, not an identity
assert_eq!(original_catalog(Path::new("/elsewhere/Cat.zip"), "sub/Cat.lrcat"), (PathBuf::from("/elsewhere/Cat.lrcat"), false));
let chosen = Path::new("/Volumes/Ext/LR Backups/2026-10-22 1200/Cat.zip");
assert!(!original_catalog(chosen, "Cat.lrcat").1);
assert!(is_backup(Path::new("a/B.ZIP")) && !is_backup(Path::new("a/B.lrcat")));
}
/// Folder detection counts a zip only when its directory lists exactly one catalog.
#[test]
fn only_a_zip_with_one_catalog_holds_one() {
let dir = temp("holds");
let cases: [(&str, Vec<u8>, bool); 4] = [
("one.zip", zip(&[("Cat.lrcat", b"x"), ("Cat.lrcat-data/CURRENT", b"y")], true, false), true),
("none.zip", zip(&[("photo.jpg", b"x")], false, false), false),
("two.zip", zip(&[("A.lrcat", b"a"), ("B.lrcat", b"b")], false, false), false),
("junk.zip", b"PK".to_vec(), false),
];
for (name, bytes, want) in cases {
std::fs::write(dir.join(name), bytes).unwrap();
assert_eq!(holds_catalog(&dir.join(name)), want, "{name}");
}
assert!(!holds_catalog(&dir.join("absent.zip")));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+134 -14
View File
@@ -78,6 +78,15 @@ impl Reader {
.collect())
}
/// The catalog's `Adobe_storeProviderID` (a UUID), kept by Lightroom in its backups; `None`
/// when the table or the value is missing or doesn't look like an id.
fn catalog_id(&self) -> Option<String> {
let rows = self.table("Adobe_variablesTable", false).ok()?;
let row = rows.iter().find(|r| text(r, "name") == "Adobe_storeProviderID")?;
let id = text(row, "value").trim();
(!id.is_empty() && id.len() <= 128 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')).then(|| id.to_string())
}
fn optional_table(&self, name: &str, warnings: &mut Vec<String>) -> Result<Vec<Row>, String> {
match self.table(name, false) {
Ok(rows) => Ok(rows),
@@ -176,6 +185,16 @@ impl CatalogPhoto {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CatalogImport {
pub source: String,
/// The catalog's own id (`Adobe_storeProviderID` in `Adobe_variablesTable`), the same in the
/// catalog and in every backup of it, so a backup's collections match those of an earlier import
/// of the catalog (issue #2592). `None` when the catalog has none.
#[serde(default)]
pub catalog_id: Option<String>,
/// Where the catalog was when it isn't `source`: for a backup zip, the `.lrcat` it was backed up
/// from. Collections imported by earlier releases are keyed on that path, so a backup still finds
/// them. `None` when the catalog was read where it is.
#[serde(default)]
pub catalog_path: Option<String>,
pub photos: Vec<CatalogPhoto>,
pub collections: Vec<Row>,
pub members: Vec<Row>,
@@ -215,6 +234,11 @@ pub enum SkipReason {
pub(crate) struct ImportIndex {
pub(crate) photos: BTreeMap<String, u64>,
pub(crate) collections: BTreeMap<String, u64>,
/// The catalog id (`Adobe_storeProviderID`) each collection key was recorded for, when the
/// import had one: a path key of one catalog never matches another catalog that later sits at
/// the same path. Keys without an owner (earlier releases, catalogs without an id) match any.
#[serde(default)]
pub(crate) collection_owners: BTreeMap<String, String>,
}
pub(crate) fn load_index(path: Option<&Path>) -> crate::Result<ImportIndex> {
@@ -246,7 +270,12 @@ pub(crate) struct AppliedImport {
}
fn identity(data: &CatalogImport, photo: &CatalogPhoto) -> String {
if photo.uuid.is_empty() { format!("{}:{}", key(&data.source), photo.source_id) } else { photo.uuid.clone() }
// (a backup's photos are recognised by the catalog it was made from, as the catalog's own are)
if photo.uuid.is_empty() {
format!("{}:{}", key(data.catalog_path.as_deref().unwrap_or(&data.source)), photo.source_id)
} else {
photo.uuid.clone()
}
}
fn validate(data: &CatalogImport) -> Result<(), String> {
@@ -440,10 +469,47 @@ pub fn read(path: &Path) -> Result<CatalogImport, String> {
/// stopping when `cancel` is set. Images whose catalog records are incomplete are left out and
/// listed in [`CatalogImport::skipped`] instead of failing the read.
pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, done: &AtomicUsize) -> Result<CatalogImport, String> {
read_source(path, None, cancel, total, done)
}
/// Where a Lightroom backup's catalog is unpacked while it is read: the open library's `Interop/`
/// folder (on the library's disk), or `None` for the system's temporary folder.
pub fn backup_temp_root(s: &crate::Session) -> Option<PathBuf> {
s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Interop"))
}
/// [`read_with_progress`] of a catalog or of a Lightroom catalog backup (`.zip`, issue #2592): a
/// backup's catalog is unpacked into a private folder under `temp_root` (else the system's temporary
/// folder), read, and removed again ([`crate::lightroom_backup`]). Paths the catalog records
/// relative to itself are taken from where the catalog was before it was backed up.
pub fn read_source(
path: &Path,
temp_root: Option<&Path>,
cancel: &AtomicBool,
total: &AtomicUsize,
done: &AtomicUsize,
) -> Result<CatalogImport, String> {
// 13 catalog tables plus one validation stage; ImportJob adds one unit per original path.
total.store(14, Ordering::Relaxed);
done.store(0, Ordering::Relaxed);
ensure_read_active(cancel)?;
if crate::lightroom_backup::is_backup(path) {
let root = temp_root.map_or_else(std::env::temp_dir, Path::to_path_buf);
let extracted = crate::lightroom_backup::extract(path, &root, cancel)?;
let (document, known) = crate::lightroom_backup::original_catalog(path, &extracted.entry);
let mut data = read_file(&extracted.catalog, &document, path, cancel, done)?;
if !known {
// only a guess: it resolves relative paths, but never names the catalog
data.catalog_path = None;
}
return Ok(data);
}
read_file(path, path, path, cancel, done)
}
/// Read the catalog file `path`, resolving the paths it records with `document` as the catalog's
/// place and reporting `source` as where it came from.
fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, done: &AtomicUsize) -> Result<CatalogImport, String> {
let before = std::fs::metadata(path).map_err(|e| e.to_string())?;
let wal_path = PathBuf::from(format!("{}-wal", path.display()));
let wal_before = std::fs::metadata(&wal_path).ok().map(|m| (m.len(), m.modified().ok()));
@@ -529,7 +595,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
root_ids.sort_unstable();
for (id, root) in root_ids.iter().filter_map(|id| Some((*id, roots.get(id)?))) {
let absolute = text(root, "absolutePath");
let resolved = match relocated_root(absolute, text(root, "relativePathFromCatalog"), path) {
let resolved = match relocated_root(absolute, text(root, "relativePathFromCatalog"), document) {
Some(found) => {
let found = found.to_string_lossy().to_string();
warnings.push(format!("root folder {}: {absolute} not found; using {found} (relative to the catalog)", text(root, "name")));
@@ -537,7 +603,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
}
None => absolute.to_string(),
};
if let Err(crate::doc_path::NotFollowed::Refused(why)) = crate::doc_path::resolve(&resolved, Some(path)) {
if let Err(crate::doc_path::NotFollowed::Refused(why)) = crate::doc_path::resolve(&resolved, Some(document)) {
warnings
.push(format!("root folder {}: {resolved} is not opened: {why}; its photos are listed as missing and not added", text(root, "name")));
refused_roots.insert(id);
@@ -547,7 +613,9 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
let mut history = group(optional_table("Adobe_libraryImageDevelopHistoryStep", &mut warnings)?);
let mut snapshots = group(optional_table("Adobe_libraryImageDevelopSnapshot", &mut warnings)?);
let mut out = CatalogImport {
source: path.to_string_lossy().into(),
source: source.to_string_lossy().into(),
catalog_id: reader.catalog_id(),
catalog_path: (document != source).then(|| document.to_string_lossy().into()),
photos: Vec::new(),
collections: optional_table("AgLibraryCollection", &mut warnings)?,
members: optional_table("AgLibraryCollectionImage", &mut warnings)?,
@@ -584,7 +652,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize,
orphans.insert(id);
continue;
}
let (photo_path, original) = original_path(root_path, folder_path, name, path);
let (photo_path, original) = original_path(root_path, folder_path, name, document);
if let Original::Refused(why) = &original
&& !refused_roots.contains(&root_id)
{
@@ -705,7 +773,12 @@ fn mapped_settings(
) -> Result<(Value, Vec<String>), String> {
let mut root = crate::preset_import::parse_lua(text)?;
let deferred = strip_lua_sentinels(&mut root);
let (mut props, values) = crate::preset_import::lua_settings_props(&root)?;
let (mut props, mut values) = crate::preset_import::lua_settings_props(&root)?;
// Catalog Lua names the component inversion `Inverted` while XMP's is `MaskInverted`;
// rename it so an inverted mask keeps its inversion instead of importing as normal.
for v in values.values_mut() {
alias_catalog_inverted(v);
}
// A catalog's develop settings carry the crop edges and angle but no `HasCrop` (XMP has it):
// any crop field means the photo is cropped.
const CROP: [&str; 5] = ["crs:CropLeft", "crs:CropTop", "crs:CropRight", "crs:CropBottom", "crs:CropAngle"];
@@ -787,6 +860,24 @@ fn in_photo_frame(catalog: Orientation, user: Orientation) -> Orientation {
(0..turns).fold(o, |o, _| o.rotated(true))
}
/// Rename a catalog Lua component's `Inverted` to XMP's `MaskInverted` (see [`mapped_settings`]);
/// a `crs:MaskInverted` already present wins, and this does not touch `Flipped`.
fn alias_catalog_inverted(v: &mut lightcraft_meta::XmpValue) {
use lightcraft_meta::XmpValue;
match v {
XmpValue::Array(items) => items.iter_mut().for_each(alias_catalog_inverted),
XmpValue::Struct(map) => {
if let Some(inverted) = map.remove("crs:Inverted")
&& !map.contains_key("crs:MaskInverted")
{
map.insert("crs:MaskInverted".into(), inverted);
}
map.values_mut().for_each(alias_catalog_inverted);
}
XmpValue::Text(_) => {}
}
}
/// Lightroom's masks in LightCraft's frame. Like the crop's corners, their positions are on the
/// stored image (before orientation), normalized to its size; LightCraft's are on the oriented
/// image. So the points go through the orientation, a radial's radii (in long-edge units, from the
@@ -983,14 +1074,34 @@ fn stage_collections(
if number(collection, "systemOnly") != 0 {
continue;
}
let collection_key = format!("{}:{}", key(&data.source), number(collection, "id_local"));
let indexed = index
.collections
.get(&collection_key)
.copied()
// keyed on the catalog's own id (the same in its backups); imports made before that was
// read are keyed on the catalog's path, and are still found by it, also from a backup (the
// path of the catalog it was backed up from)
let path_key = format!("{}:{}", key(&data.source), number(collection, "id_local"));
let original_key = data.catalog_path.as_ref().map(|p| format!("{}:{}", key(p), number(collection, "id_local")));
let collection_key = data.catalog_id.as_ref().map_or_else(|| path_key.clone(), |c| format!("lrcat:{c}:{}", number(collection, "id_local")));
// A path can be reused by a different catalog. Without an ID we cannot prove that an
// owned path key belongs to this input, so refuse instead of silently mixing albums.
if data.catalog_id.is_none()
&& [Some(&path_key), original_key.as_ref()].into_iter().flatten().any(|k| index.collection_owners.contains_key(k))
{
return Err(error(
"the Lightroom catalog has no stable identity and its path was previously associated with a catalog; cannot safely match collections",
));
}
// a key recorded for another catalog (by its id) is not this one, whatever its path
let mine = |k: &String| match (data.catalog_id.as_ref(), index.collection_owners.get(k)) {
(Some(c), Some(owner)) => owner == c,
_ => true,
};
let id = [Some(&collection_key), Some(&path_key), original_key.as_ref()]
.into_iter()
.flatten()
.filter(|k| mine(k))
.filter_map(|k| index.collections.get(k).copied())
.map(lightcraft_catalog::AlbumId)
.filter(|id| s.catalog.album(*id).is_some() && !assigned.contains(id));
let id = match indexed {
.find(|id| s.catalog.album(*id).is_some() && !assigned.contains(id));
let id = match id {
Some(id) => id,
None => {
let id = s.catalog.alloc_album_id();
@@ -1004,7 +1115,16 @@ fn stage_collections(
}
};
assigned.insert(id);
index.collections.insert(collection_key, id.0);
// recorded under its id and the live catalog's path (a backup's: the catalog it was made
// from), so a later import of the same catalog finds it in either order; a zip's own path
// is not kept when the catalog's is known (every dated backup has a new one)
let path_kept = if data.catalog_path.is_some() { None } else { Some(path_key) };
for k in [Some(collection_key), path_kept, original_key].into_iter().flatten() {
if let Some(c) = &data.catalog_id {
index.collection_owners.insert(k.clone(), c.clone());
}
index.collections.insert(k, id.0);
}
albums.insert(number(collection, "id_local"), id);
}
let parents: HashMap<_, _> = rows.iter().map(|r| (number(r, "id_local"), number(r, "parent"))).collect();
+194 -2
View File
@@ -24,6 +24,8 @@ fn sample() -> CatalogImport {
photo.image.insert("captureTime".into(), json!("2024-01-16T12:34:56"));
CatalogImport {
source: "test.lrcat".into(),
catalog_id: None,
catalog_path: None,
photos: vec![copy, photo],
collections: vec![
row(json!({"id_local":9,"name":"Travel","creationId":"collection.group"})),
@@ -850,6 +852,22 @@ fn catalog_masks_follow_the_photo_orientation() {
assert!(close(&radial["rx"], 0.1) && close(&radial["ry"], 0.1), "{radial}");
}
#[test]
fn inverted_radial_mask_keeps_its_inversion_on_import() {
// #2475: an inverted radial (LocalExposure2012 applies outside the ellipse) keeps its
// inversion when the catalog import also turns the mask for the photo's orientation
let s = r#"s = { MaskGroupBasedCorrections = { { What = "Correction", CorrectionAmount = 1, LocalExposure2012 = 0.1, CorrectionMasks = {
{ What = "Mask/CircularGradient", Left = 0, Right = 0.2, Top = 0.1, Bottom = 0.3, Angle = 10, Feather = 50, Version = 2, Flipped = true, Inverted = true } } } } }"#;
let (partial, _) = mapped_settings(s, crate::crs::Target::RawAbsolute, 1.5, Orientation::Rotate90, 1.5, Orientation::Normal).unwrap();
let c = &partial["masks"][0]["components"][0];
let close = |v: &Value, want: f64| (v.as_f64().unwrap() - want).abs() < 1e-9;
// the orientation is applied: (x, y) → (1 − y, x), a quarter turn clockwise; the radii swap
let shape = &c["shape"];
assert!(close(&shape["center"]["x"], 0.8) && close(&shape["center"]["y"], 0.1), "{shape}");
// but the effect stays outside the ellipse
assert!(c["invert"].as_bool().unwrap_or(false) || shape["invert"].as_bool().unwrap_or(false), "{c}");
}
/// The `crs` corners and angle Lightroom would store for LightCraft crop `g` on a stored image
/// of aspect `w` (height 1) shown with orientation `o`.
fn lightroom_crop(g: CropGeometry, o: Orientation, w: f64) -> String {
@@ -1072,6 +1090,178 @@ fn wal_checksums_cover_commits_without_materializing_historical_databases() {
}
}
/// Issue #2592: a catalog in Lightroom's backup layout (`Backups/<date>/<name>.zip`), with one
/// collection and the catalog's own id.
fn backup_fixture(root: &Path, catalog_id: &str) -> (PathBuf, PathBuf) {
use SqlValue::{Integer as I, Null as N, Text as T};
let mut tables: Vec<(&str, &str, Vec<Vec<SqlValue>>)> = one_row(photo_tables(("/catalog/", "")));
tables.push((
"AgLibraryCollection",
"id_local INTEGER PRIMARY KEY, creationId, name, parent, systemOnly",
vec![vec![N, T("com.adobe.ag.library.collection".into()), T("Keepers".into()), N, I(0)]],
));
tables.push(("AgLibraryCollectionImage", "id_local INTEGER PRIMARY KEY, collection, image", vec![vec![N, I(1), I(1)]]));
tables.push((
"Adobe_variablesTable",
"id_local INTEGER PRIMARY KEY, id_global, name, type, value",
vec![vec![N, T("v1".into()), T("Adobe_storeProviderID".into()), N, T(catalog_id.into())]],
));
let bytes = native_catalog_rows(&tables, None);
let folder = root.join("Lightroom");
let dated = folder.join("Backups").join("2023-11-07 0900");
std::fs::create_dir_all(&dated).unwrap();
let live = folder.join("Cat.lrcat");
std::fs::write(&live, &bytes).unwrap();
let zip = dated.join("Cat.zip");
let files: [(&str, &[u8]); 2] = [("Cat.lrcat", &bytes), ("Cat.lrcat-data/CURRENT", b"MANIFEST-000005\n")];
std::fs::write(&zip, crate::lightroom_backup::tests::zip(&files, true, false)).unwrap();
(live, zip)
}
/// How many albums the library has.
fn albums(s: &crate::Session) -> usize {
s.catalog.albums().count()
}
/// The zip imports the same photos and collections as its catalog, with the zip as source, no temp files and the zip unchanged.
#[test]
fn a_backup_zip_imports_like_its_catalog_and_leaves_no_temporary_files() {
let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-zip-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49");
let zip_before = std::fs::read(&zip).unwrap();
let from_zip = read(&zip).unwrap();
let from_live = read(&live).unwrap();
assert_eq!(from_zip.source, zip.to_string_lossy(), "the zip is the import's source");
assert_eq!(from_zip.catalog_id.as_deref(), Some("968AF29B-EEE2-481E-8AF9-55DD82965F49"));
assert_eq!((from_zip.photos.len(), from_zip.collections.len()), (from_live.photos.len(), from_live.collections.len()));
assert_eq!(from_zip.photos[0].path, from_live.photos[0].path);
// the live catalog is gone (Lightroom uninstalled): the backup alone imports into a library
std::fs::remove_file(&live).unwrap();
let lib = root.join("Library");
let mut s = crate::Session::new();
s.open_library(&lib, false).unwrap();
let report = import(&mut s, &zip, false).unwrap();
assert_eq!((report["photos"].as_u64(), report["collections"].as_u64()), (Some(1), Some(1)));
assert_eq!(report["source"], json!(zip.to_string_lossy()));
assert_eq!(albums(&s), 1);
let interop: Vec<_> = std::fs::read_dir(lib.join("Interop")).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
assert!(!interop.iter().any(|n| n.starts_with("lc-lrbackup-")), "the unpacked catalog is removed: {interop:?}");
assert_eq!(std::fs::read(&zip).unwrap(), zip_before, "the backup is only read");
let _ = std::fs::remove_dir_all(&root);
}
/// Issue #2606: the backup of an imported catalog matches its collections by the catalog id.
#[test]
fn importing_a_backup_after_its_catalog_adds_no_album_twice() {
let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-twice-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49");
let mut s = crate::Session::new();
s.open_library(root.join("Library"), false).unwrap();
import(&mut s, &live, false).unwrap();
assert_eq!(albums(&s), 1);
let again = import(&mut s, &zip, false).unwrap();
assert_eq!(again["imported"], 0, "the photos are matched by their Lightroom id");
assert_eq!(albums(&s), 1, "the collections are matched by the catalog's id, not its path");
let _ = std::fs::remove_dir_all(&root);
}
/// A backup of a catalog that an earlier release imported (collections keyed on the live
/// `.lrcat` path, no catalog id) finds those albums through the path it was backed up from.
#[test]
fn a_backup_finds_collections_an_earlier_release_keyed_on_the_live_catalog_path() {
let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-legacy-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49");
let mut s = crate::Session::new();
s.open_library(root.join("Library"), false).unwrap();
// an earlier release: the live catalog imported without its id (path keys only)
let mut old = read(&live).unwrap();
old.catalog_id = None;
apply(&mut s, old, false).unwrap();
assert_eq!(albums(&s), 1);
let backup = read(&zip).unwrap();
assert_eq!(backup.catalog_path.as_deref(), Some(live.to_string_lossy().as_ref()), "where the zip's catalog was");
apply(&mut s, backup, false).unwrap();
assert_eq!(albums(&s), 1, "the backup finds the albums keyed on the live catalog's path");
let _ = std::fs::remove_dir_all(&root);
}
/// Issue #2606, the other order: a backup without a catalog id imported first, then the live
/// catalog (no id either) finds the same albums through the live path the backup recorded.
#[test]
fn the_live_catalog_after_a_backup_without_an_id_adds_no_album_twice() {
let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-noid-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49");
let mut s = crate::Session::new();
s.open_library(root.join("Library"), false).unwrap();
let mut backup = read(&zip).unwrap();
backup.catalog_id = None;
apply(&mut s, backup, false).unwrap();
assert_eq!(albums(&s), 1);
let mut current = read(&live).unwrap();
current.catalog_id = None;
apply(&mut s, current, false).unwrap();
assert_eq!(albums(&s), 1, "the live catalog finds the albums the backup imported");
let _ = std::fs::remove_dir_all(&root);
}
/// Issue #2606, the reviewer's second order: a backup with an id, then the live catalog read
/// without one, is rejected rather than risk matching a different catalog at the same path.
#[test]
fn the_live_catalog_without_an_id_after_a_backup_with_one_adds_no_album_twice() {
let root = std::env::temp_dir().join(format!("lightcraft-lrbackup-idthennone-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (live, zip) = backup_fixture(&root, "968AF29B-EEE2-481E-8AF9-55DD82965F49");
let mut s = crate::Session::new();
s.open_library(root.join("Library"), false).unwrap();
apply(&mut s, read(&zip).unwrap(), false).unwrap();
let mut current = read(&live).unwrap();
current.catalog_id = None;
let err = apply(&mut s, current, false).unwrap_err();
assert!(err.to_string().contains("no stable identity"));
assert_eq!(albums(&s), 1, "an ambiguous path must not change albums");
let _ = std::fs::remove_dir_all(&root);
}
/// Two different catalogs (different ids) that sat at the same path, one after the other (a
/// new computer's default location, a catalog recreated), keep their own albums even with the
/// same collection `id_local`.
#[test]
fn two_catalogs_at_the_same_path_keep_their_own_albums() {
let root = std::env::temp_dir().join(format!("lightcraft-lrcat-samepath-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (live, _) = backup_fixture(&root, "AAAAAAAA-0000-0000-0000-000000000001");
let mut s = crate::Session::new();
s.open_library(root.join("Library"), false).unwrap();
apply(&mut s, read(&live).unwrap(), false).unwrap();
// another catalog, now at the same path
let (live2, _) = backup_fixture(&root, "BBBBBBBB-0000-0000-0000-000000000002");
assert_eq!(live, live2);
apply(&mut s, read(&live2).unwrap(), false).unwrap();
assert_eq!(albums(&s), 2, "the second catalog's collection is its own album");
let _ = std::fs::remove_dir_all(&root);
}
/// Libraries imported by earlier releases (path keys) still find their albums.
#[test]
fn collections_imported_before_the_catalog_id_was_read_are_still_matched_by_path() {
let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-pathkey-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut s = crate::Session::new();
s.open_library(&dir, false).unwrap();
// an import made by an earlier release: no catalog id, keys on the path
apply(&mut s, sample(), false).unwrap();
let before = albums(&s);
let mut data = sample();
data.catalog_id = Some("A-B".into());
apply(&mut s, data, false).unwrap();
assert_eq!(albums(&s), before, "the old path keys still find the albums");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn persistent_reimport_keeps_copy_and_collection_ids_and_capture_time() {
let dir = std::env::temp_dir().join(format!("lightcraft-lrcat-reimport-{}", std::process::id()));
@@ -1159,7 +1349,9 @@ fn native_catalog_with_last_table_page(tables: &[(&str, &str, Vec<SqlValue>)], l
/// table's root page.
fn native_catalog_rows(tables: &[(&str, &str, Vec<Vec<SqlValue>>)], last_page: Option<i64>) -> Vec<u8> {
use SqlValue::{Integer as I, Text as T};
let mut bytes = vec![0u8; 5 * 2048];
// the schema page, then one page per table (at least four: the photo tables)
let pages = (tables.len() + 1).max(5);
let mut bytes = vec![0u8; pages * 2048];
bytes[..16].copy_from_slice(b"SQLite format 3\0");
bytes[16..18].copy_from_slice(&2048u16.to_be_bytes());
bytes[18] = 1;
@@ -1167,7 +1359,7 @@ fn native_catalog_rows(tables: &[(&str, &str, Vec<Vec<SqlValue>>)], last_page: O
bytes[21] = 64;
bytes[22] = 32;
bytes[23] = 32;
bytes[28..32].copy_from_slice(&5u32.to_be_bytes());
bytes[28..32].copy_from_slice(&(pages as u32).to_be_bytes());
bytes[44..48].copy_from_slice(&4u32.to_be_bytes());
bytes[56..60].copy_from_slice(&1u32.to_be_bytes());
let mut schema = Vec::new();
+43 -2
View File
@@ -6,14 +6,20 @@
//! an empty LightCraft library inside Lightroom's folder; [`Session::open_library`] refuses with
//! [`EngineError::LightroomCatalog`] instead, and the app offers File ▸ Import Lightroom Catalog….
//!
//! What counts (only names are looked at; no catalog is opened or read):
//! What counts (only names are looked at, and a backup zip's list of files; no catalog is opened
//! or read):
//! - a LightCraft library (`catalog.snap` or `catalog.log` in the folder) is never a Lightroom
//! catalog, whatever else the folder holds: it opens as before;
//! - a path named `*.lrcat` or one of its companions (`*.lrcat-wal`, `*.lrcat-shm`,
//! `*.lrcat-journal`, `*.lrcat.lock`);
//! - a folder named `*.lrdata` or `*.lrcat-data` (Lightroom's previews and data);
//! - a folder holding a `*.lrcat` at its top level (the catalog folder itself), or `Backups/`
//! next to one.
//! next to one;
//! - Lightroom's backups (issue #2592), even with the catalog itself gone: a `Backups/` folder or
//! one of its dated folders, `Backups/YYYY-MM-DD HHMM/`, holding a `*.zip` with one `.lrcat` in
//! it ([`crate::lightroom_backup::holds_catalog`]). A dated folder names
//! its zip; `Backups/` names one only when it holds a single backup, since the person has to choose
//! among several (the import then asks for the file).
//!
//! The folder scan is bounded ([`SCAN_LIMIT`] entries, top level only) and every I/O error just
//! means "not found": this never fails and never panics.
@@ -133,6 +139,41 @@ pub fn lightroom_catalog_at(path: &Path) -> Option<LightroomPlace> {
{
return Some(LightroomPlace { catalog: Some(catalog) });
}
// `Backups/` alone (the catalog deleted): its backup when there is only one; with several,
// which one to import is the person's choice
if lower == "backups"
&& let Some(backups) = backup_zips(path)
{
let catalog = if backups.len() == 1 { backups.into_iter().next() } else { None };
return Some(LightroomPlace { catalog });
}
// a dated backup folder, `Backups/2023-11-07 0900/`
if parent.and_then(lower_name).as_deref() == Some("backups")
&& let Some(zip) = find_backup_zip(path)
{
return Some(LightroomPlace { catalog: Some(zip) });
}
}
None
}
/// The first `*.zip` file (by name) at the top level of `dir` that holds a Lightroom catalog,
/// looking at no more than [`SCAN_LIMIT`] entries.
fn find_backup_zip(dir: &Path) -> Option<PathBuf> {
let entries = std::fs::read_dir(dir).ok()?;
entries
.take(SCAN_LIMIT)
.flatten()
.map(|e| e.path())
.filter(|p| crate::lightroom_backup::is_backup(p) && p.is_file())
.filter(|p| crate::lightroom_backup::holds_catalog(p))
.min()
}
/// The backup zips in the dated folders of `backups`, one per folder; `None` when there are none.
fn backup_zips(backups: &Path) -> Option<Vec<PathBuf>> {
let entries = std::fs::read_dir(backups).ok()?;
let zips: Vec<PathBuf> =
entries.take(SCAN_LIMIT).flatten().map(|e| e.path()).filter(|p| p.is_dir()).filter_map(|d| find_backup_zip(&d)).collect();
(!zips.is_empty()).then_some(zips)
}
+12 -2
View File
@@ -241,8 +241,14 @@ impl LightroomJob {
return Err(cancelled());
}
// (reading stops with a message when `cancel` is set: the flag says it was cancelled)
let mut data = lightroom_catalog::read_with_progress(&self.path, cancel, &self.progress.catalog_total, &self.progress.catalog_done)
.map_err(|e| if cancel.load(Ordering::Relaxed) { cancelled() } else { error(e) })?;
let mut data = lightroom_catalog::read_source(
&self.path,
self.archive_dir.as_deref(),
cancel,
&self.progress.catalog_total,
&self.progress.catalog_done,
)
.map_err(|e| if cancel.load(Ordering::Relaxed) { cancelled() } else { error(e) })?;
lightroom_catalog::validate_for_job(&data).map_err(error)?;
if cancel.load(Ordering::Relaxed) {
return Err(cancelled());
@@ -350,6 +356,8 @@ mod tests {
fn empty_data() -> CatalogImport {
CatalogImport {
source: "fixture.lrcat".into(),
catalog_id: None,
catalog_path: None,
photos: Vec::new(),
collections: Vec::new(),
members: Vec::new(),
@@ -384,6 +392,8 @@ mod tests {
PreparedLightroom {
data: CatalogImport {
source: "fixture.lrcat".into(),
catalog_id: None,
catalog_path: None,
photos: vec![lightroom_catalog::CatalogPhoto {
source_id: 1,
uuid: "fixture-photo".into(),
+19 -2
View File
@@ -131,14 +131,31 @@ pub(super) fn embedded_thumb_key(k: Hash128) -> Hash128 {
Hasher128::new().str("embedded-thumb").u64((k.0 >> 64) as u64).u64(k.0 as u64).finish()
}
/// What identifies a photo's pixels for caching: its content hash, else its source.
/// Which decode of a photo a loaded source is: its file's content and, when it has one, its database lens profile
/// ORF decoding changed when compressed sensor support was withdrawn. Keep its old renders
/// out even before catalog rechecking finishes, and distinguish sensor from preview-only
/// pixels after Reload. Other formats keep their existing keys. This is deliberately not
/// part of `content_key`: smart previews and denoise products identify the original file.
pub(super) fn decoder_key(p: &Photo) -> u64 {
if !p.format.eq_ignore_ascii_case("ORF") {
return 0;
}
// Spread the status bit: this salt is XORed with frontend dimensions, so adjacent
// integers could cancel a small resize occurring at the same time as a recheck.
let h = Hasher128::new().str("orf-withdrawal-v1").u64(u64::from(p.preview_only.is_some())).finish();
((h.0 as u64) ^ ((h.0 >> 64) as u64)) | 1
}
/// Which decode of a photo a loaded source is: its file's content, decoder identity and database lens profile
/// ([`lens_key`]; the decode fits the starting colour through it). A job's source is kept only when this still
/// matches when the job finishes ([`super::Session::accept`]), so a decode started before a profile change never
/// returns to the cache after `cmd::lens_refresh` has dropped the photo's sources.
pub fn source_identity(p: &Photo) -> Hash128 {
let mut k = Hasher128::new();
k.str(&content_key(p));
let decoder = decoder_key(p);
if decoder != 0 {
k.str("decoder").u64(decoder);
}
let lens = lens_key(p);
if lens != 0 {
k.u64(lens);
+18 -3
View File
@@ -57,6 +57,7 @@ impl crate::Session {
let content_key = content_key(&p);
let content = Hasher128::new().str(&content_key).finish().0 as u64;
let source_key = super::quick::source_identity(&p);
let decoder = super::quick::decoder_key(&p);
// Temporary "before" settings must not replace the photo's cached develop hash.
let settings_hash =
if before { settings.hash64() ^ crate::files::hot_pixel_key(&settings) } else { self.media.settings_hashes.get(id, &settings) };
@@ -72,7 +73,8 @@ impl crate::Session {
^ content.rotate_left(17)
^ salt
^ profile_salt.rotate_left(29)
^ lens.rotate_left(37);
^ lens.rotate_left(37)
^ decoder.rotate_left(43);
let cache = thumb_bucket.map(|b| {
let mut k = Hasher128::new();
k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION);
@@ -89,6 +91,9 @@ impl crate::Session {
if lens != 0 {
k.u64(lens);
}
if decoder != 0 {
k.str("decoder").u64(decoder);
}
(self.media.rendered.clone(), k.finish())
});
Some(RenderJob {
@@ -131,6 +136,7 @@ impl crate::Session {
let profile_salt = self.media.camera_profile_salt(&settings.profile.id);
// (the photo's database lens profile stays part of it: a profile looked up again renders afresh)
let lens = self.catalog.photo(id).map_or(0, |p| super::quick::lens_key(p));
let decoder = super::quick::decoder_key(&p);
job.key = settings.hash64()
^ crate::files::hot_pixel_key(settings)
^ ((max_w as u64) << 40)
@@ -138,7 +144,8 @@ impl crate::Session {
^ (apply_crop as u64)
^ (job.level as u64) << 60
^ profile_salt.rotate_left(29)
^ lens.rotate_left(37);
^ lens.rotate_left(37)
^ decoder.rotate_left(43);
Some(job)
}
@@ -159,6 +166,10 @@ impl crate::Session {
if lens != 0 {
k.u64(lens);
}
let decoder = super::quick::decoder_key(p);
if decoder != 0 {
k.str("decoder").u64(decoder);
}
k.finish()
}
@@ -294,6 +305,10 @@ impl crate::Session {
if lens != 0 {
k.u64(lens);
}
let decoder = super::quick::decoder_key(p);
if decoder != 0 {
k.str("decoder").u64(decoder);
}
k.finish()
}
@@ -422,7 +437,7 @@ impl crate::Session {
.u64(id.0)
.u64(profile_salt)
.finish();
let key = h.0 as u64;
let key = h.0 as u64 ^ super::quick::decoder_key(&p).rotate_left(43);
let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge())));
let embedded_cache = embedded.as_ref().map(|(_, _, edge)| {
let cache = self.media.rendered.clone();
+114 -11
View File
@@ -42,7 +42,13 @@ pub fn read_zip(bytes: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
read_zip_limited(bytes, MAX_ZIP_ENTRY, MAX_ZIP_TOTAL)
}
fn read_zip_limited(bytes: &[u8], max_entry: usize, max_total: usize) -> Result<Vec<(String, Vec<u8>)>, String> {
pub(crate) fn read_zip_limited(bytes: &[u8], max_entry: usize, max_total: usize) -> Result<Vec<(String, Vec<u8>)>, String> {
read_zip_spending(bytes, max_entry, max_total, &mut 0)
}
/// [`read_zip_limited`] that adds to `spent` the bytes of each entry as it is unpacked, so they
/// are counted when a later entry fails; an entry that fails for size spends its whole limit.
pub(crate) fn read_zip_spending(bytes: &[u8], max_entry: usize, max_total: usize, spent: &mut usize) -> Result<Vec<(String, Vec<u8>)>, String> {
let u16_at = |o: usize| bytes.get(o..o.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]) as usize);
let u32_at = |o: usize| bytes.get(o..o.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize);
// offsets from the file, added up without overflowing (a 32-bit build reads them too)
@@ -53,7 +59,7 @@ fn read_zip_limited(bytes: &[u8], max_entry: usize, max_total: usize) -> Result<
let count = u16_at(eocd + 10).ok_or("bad zip")?;
let mut at = u32_at(eocd + 16).ok_or("bad zip")?;
let mut out = Vec::new();
let mut total = 0usize;
let total = spent;
for _ in 0..count {
if !bytes.get(at..).is_some_and(|b| b.starts_with(b"PK\x01\x02")) {
return Err("bad zip central directory".into());
@@ -76,18 +82,40 @@ fn read_zip_limited(bytes: &[u8], max_entry: usize, max_total: usize) -> Result<
}
let data_at = add(add(add(local, 30)?, u16_at(add(local, 26)?).ok_or("bad zip")?)?, u16_at(add(local, 28)?).ok_or("bad zip")?)?;
let data = bytes.get(data_at..add(data_at, csize)?).ok_or_else(|| format!("{name}: truncated"))?;
let left = max_total.saturating_sub(total);
let left = max_total.saturating_sub(*total);
let limit = max_entry.min(left);
let too_big = || format!("{name}: unpacks to more than {} MB, too much for a preset", limit >> 20);
let content = match method {
0 if data.len() > limit => return Err(too_big()),
0 if data.len() > limit => {
*total = total.saturating_add(limit);
return Err(too_big());
}
0 => data.to_vec(),
8 => miniz_oxide::inflate::decompress_to_vec_with_limit(data, usize_.max(1).saturating_mul(2).saturating_add(1024).min(limit)).map_err(
|e| if matches!(e.status, miniz_oxide::inflate::TINFLStatus::HasMoreOutput) { too_big() } else { format!("{name}: {e:?}") },
)?,
8 => {
// the entry's own stated size, with slack, caps the inflate below `limit`
let cap = usize_.max(1).saturating_mul(2).saturating_add(1024);
match miniz_oxide::inflate::decompress_to_vec_with_limit(data, cap.min(limit)) {
Ok(v) => v,
Err(e) if matches!(e.status, miniz_oxide::inflate::TINFLStatus::HasMoreOutput) && cap < limit => {
// not over the budget: only what was unpacked is spent
*total = total.saturating_add(e.output.len());
return Err(format!("{name}: unpacks to more than its stated size"));
}
Err(e) if matches!(e.status, miniz_oxide::inflate::TINFLStatus::HasMoreOutput) => {
// past the budget (or the entry limit): its whole limit is spent
*total = total.saturating_add(limit);
return Err(too_big());
}
Err(e) => {
// what a corrupt stream unpacked before failing was still unpacked: charge it
*total = total.saturating_add(e.output.len());
return Err(format!("{name}: {:?}", e.status));
}
}
}
m => return Err(format!("{name}: unsupported compression method {m}")),
};
total = total.saturating_add(content.len());
*total = total.saturating_add(content.len());
out.push((name, content));
}
Ok(out)
@@ -139,7 +167,11 @@ impl LuaParser<'_> {
if self.s[self.i..].starts_with(b"--") {
self.i += 2;
if let Some(level) = self.long_bracket_level() {
let _ = self.long_string(level);
// an unterminated long comment runs to the end (as in Lua): going on past its
// opening would search the rest of the file again for every such opening
if self.long_string(level).is_err() {
self.i = self.s.len();
}
} else {
while self.i < self.s.len() && self.s[self.i] != b'\n' {
self.i += 1;
@@ -546,14 +578,23 @@ pub fn read_presets(name: &str, bytes: &[u8], group: Option<String>) -> Result<V
"zip" => {
let mut out = Vec::new();
let mut errors = Vec::new();
for (inner, data) in read_zip(bytes)? {
let entries = read_zip(bytes)?;
// what the archive's entries left of the unpack budget: the Luminar packs inside it
// (archives themselves) unpack within it, not each with a budget of its own
let mut budget = MAX_ZIP_TOTAL.saturating_sub(entries.iter().map(|(_, d)| d.len()).sum());
for (inner, data) in entries {
let iext = Path::new(&inner).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
if !(PRESET_EXTS.contains(&iext.as_str()) || iext == crate::presets::LCPRESET_EXT) || iext == "zip" {
continue;
}
let dir_group =
inner.rsplit_once('/').and_then(|(d, _)| group_from_dir(d)).or_else(|| group_from_dir(&stem)).or_else(|| group.clone());
match read_presets(&inner, &data, dir_group) {
let read = if iext == "mplumpack" {
crate::preset_luminar::read_mplumpack_within(&inner, &data, &mut budget)
} else {
read_presets(&inner, &data, dir_group)
};
match read {
Ok(v) => out.extend(v),
Err(e) => errors.push(format!("{inner}: {e}")),
}
@@ -771,6 +812,68 @@ text]], z = ZSTR "loc" }"#,
assert!(photo(r#"crs:WhiteBalance="As Shot""#).unmapped.is_empty());
}
#[test]
fn packs_inside_a_zip_share_its_unpack_budget() {
// two packs unpacking to 2 MB each on a 3 MB budget: the first spends it, the second is refused
let pad = vec![b' '; 2 << 20];
let pack = zip(&[("a.lmp", b"<plist/>"), ("pad.txt", &pad)], true);
let mut budget = 3 << 20;
let first = crate::preset_luminar::read_mplumpack_within("one.mplumpack", &pack, &mut budget).unwrap_err();
assert!(!first.contains("too much"), "{first}");
assert_eq!(budget, (1 << 20) - 8);
let second = crate::preset_luminar::read_mplumpack_within("two.mplumpack", &pack, &mut budget).unwrap_err();
assert!(second.contains("too much"), "{second}");
}
#[test]
fn a_pack_that_fails_part_way_still_spends_what_it_unpacked() {
// 2 MB unpacks, then an entry that does not fit the 3 MB budget: the next pack gets nothing
let pad = vec![b' '; 2 << 20];
let pack = zip(&[("a.txt", &pad), ("b.txt", &pad)], true);
let mut budget = 3 << 20;
let first = crate::preset_luminar::read_mplumpack_within("one.mplumpack", &pack, &mut budget).unwrap_err();
assert!(first.contains("too much"), "{first}");
assert_eq!(budget, 0);
}
#[test]
fn a_corrupt_deflate_entry_spends_what_it_unpacked() {
// 2 MB declared, the stream cut in half: it unpacks a part, then fails; the budget keeps the part
let pad = vec![b' '; 2 << 20];
let deflated = miniz_oxide::deflate::compress_to_vec(&pad, 6);
let mut pack = zip(&[("a.txt", &deflated[..deflated.len() / 2])], false);
let central = 30 + "a.txt".len() + deflated.len() / 2;
pack[8] = 8; // local header: method deflate
pack[central + 10] = 8; // central header: method deflate
pack[central + 24..central + 28].copy_from_slice(&(pad.len() as u32).to_le_bytes());
let mut budget = 3 << 20;
let err = crate::preset_luminar::read_mplumpack_within("one.mplumpack", &pack, &mut budget).unwrap_err();
assert!(!err.contains("too much"), "{err}");
assert!(budget < 3 << 20, "{budget}");
}
#[test]
fn an_unterminated_long_comment_ends_the_template() {
// 20 000 openings of a long comment that never closes: each used to search the rest of
// the file for its close (seconds to minutes); now the first ends the file
let text = format!("s = {{ a = 1 }} {}", "--[==[ ".repeat(20_000));
let t = std::time::Instant::now();
let _ = parse_lua(&text);
assert!(t.elapsed().as_secs() < 5, "took {:?}", t.elapsed());
}
#[test]
fn an_entry_past_its_stated_size_spends_only_what_it_unpacked() {
// the stated size (1 byte) caps the inflate at 1026 bytes, far below the 1 MB limit
let mut lying = zip(&[("a.xmp", &vec![b' '; 10_000])], true);
let cd = lying.windows(4).position(|w| w == b"PK\x01\x02").unwrap();
lying[cd + 24..cd + 28].copy_from_slice(&1u32.to_le_bytes());
let mut spent = 0;
let e = read_zip_spending(&lying, 1 << 20, 1 << 20, &mut spent).unwrap_err();
assert!(e.contains("stated size"), "{e}");
assert!(spent > 0 && spent <= 2048, "{spent}");
}
#[test]
fn zip_bombs_are_refused() {
// an entry unpacking past the limit (3 MB of zeros pack into a few kB): refused, named
+43 -4
View File
@@ -19,7 +19,7 @@ use std::collections::BTreeMap;
use std::path::Path;
use crate::crs::Props;
use crate::preset_import::{Imported, build, group_from_dir, read_zip};
use crate::preset_import::{Imported, MAX_ZIP_ENTRY, MAX_ZIP_TOTAL, build, group_from_dir, read_zip_spending};
// ----------------------------------------------------------------------------- property lists
@@ -72,13 +72,26 @@ struct Parser<'a> {
/// Deepest `<dict>` / `<array>` nesting read (real looks nest a handful of levels).
const MAX_DEPTH: usize = 64;
/// Index of the `;` that ends a reference starting at `rest` (its `&`). The scan stops at the first
/// byte that cannot appear in a name or a numeric reference, so zero-padded references such as
/// `&#000000097;` are found and each run of name bytes is read once, not once per `&`.
fn entity_end(rest: &str) -> Option<usize> {
let n = rest.bytes().skip(1).take_while(|b| b.is_ascii_alphanumeric() || *b == b'#').count();
(rest.as_bytes().get(n + 1) == Some(&b';')).then_some(n + 1)
}
fn unescape(t: &str) -> String {
let mut out = String::with_capacity(t.len());
let mut rest = t;
while let Some(p) = rest.find('&') {
out.push_str(&rest[..p]);
rest = &rest[p..];
let Some(end) = rest.find(';') else { break };
// no `;` within a reference's reach: the `&` is kept and the search goes on after it
let Some(end) = entity_end(rest) else {
out.push('&');
rest = &rest[1..];
continue;
};
let ent = &rest[1..end];
let c = match ent {
"amp" => Some('&'),
@@ -335,11 +348,13 @@ struct Acc {
sums: BTreeMap<String, (f64, (f64, f64))>,
curves: BTreeMap<String, Vec<(f64, f64)>>,
unmapped: Vec<String>,
/// What `unmapped` holds, for the look-up (a look names each unsupported setting once).
seen: std::collections::HashSet<String>,
}
impl Acc {
fn skip(&mut self, what: String) {
if !self.unmapped.contains(&what) {
if self.seen.insert(what.clone()) {
self.unmapped.push(what);
}
}
@@ -455,7 +470,18 @@ pub fn read_lmp(path: &str, bytes: &[u8], group: Option<String>) -> Result<Impor
/// Read a Luminar looks collection (`.mplumpack`, a zip): every look, grouped by the pack's
/// `GroupName` (else the pack's file name).
pub fn read_mplumpack(path: &str, bytes: &[u8]) -> Result<Vec<Imported>, String> {
let entries = read_zip(bytes)?;
let mut budget = MAX_ZIP_TOTAL;
read_mplumpack_within(path, bytes, &mut budget)
}
/// [`read_mplumpack`] unpacking at most `budget` bytes, which it spends: packs inside one zip
/// share the zip's budget.
pub(crate) fn read_mplumpack_within(path: &str, bytes: &[u8], budget: &mut usize) -> Result<Vec<Imported>, String> {
// spent as each entry unpacks: a pack that fails part way still used its budget
let mut spent = 0;
let entries = read_zip_spending(bytes, MAX_ZIP_ENTRY, *budget, &mut spent);
*budget = budget.saturating_sub(spent);
let entries = entries?;
let info = entries
.iter()
.find(|(n, _)| n.rsplit('/').next().is_some_and(|b| b.eq_ignore_ascii_case("PresetsInfo.plist")))
@@ -486,6 +512,19 @@ mod tests {
use crate::preset_import::read_presets;
use serde_json::json;
#[test]
fn many_ampersands_before_one_semicolon_are_read_once() {
let hostile = format!("{};&amp;", "&".repeat(200_000));
assert_eq!(unescape(&hostile), format!("{};&", "&".repeat(200_000)));
assert_eq!(unescape("&lt;a&gt; &#x10FFFF; &unknownreference;"), "<a> \u{10FFFF} &unknownreference;");
}
#[test]
fn zero_padded_numeric_references_decode() {
assert_eq!(unescape("C&#0000000097;non &#x0000041; &#000000065;"), "Canon A A");
assert_eq!(unescape("&abc&#xyz;&;"), "&abc&#xyz;&;");
}
#[test]
fn unescape_rejects_signed_numeric_references() {
assert_eq!(unescape("&#+65;&#x+41;"), "&#+65;&#x+41;");
+121
View File
@@ -64,6 +64,9 @@ pub(crate) enum Tag {
NewPrompt { photo: PhotoId, mask: Option<u32>, op: String, name: Option<String>, text: String },
/// A zoomed-in pass for a component, computed from `shape` (without its detail).
Detail { photo: PhotoId, mask: u32, comp: usize, shape: MaskShape },
/// Find Subject for component `comp` of mask `mask` (an Object waiting for it): the people /
/// animals found become a "person" Describe selection; none, the object at `point`.
Subject { photo: PhotoId, mask: u32, comp: usize, point: Point },
}
/// The model input: 8-bit RGB.
@@ -498,6 +501,9 @@ impl Session {
if !clicks.iter().any(|c| c.include) {
return Err("click the object to include it first".into());
}
if clicks.len() > MAX_CLICKS {
return Err(format!("an Object selection takes at most {MAX_CLICKS} clicks"));
}
#[cfg(feature = "sam")]
{
self.segment_wait(id, worker::Kind::Clicks(Self::model_clicks(clicks)), None)?.ok_or_else(|| "nothing was selected".to_string())
@@ -570,6 +576,35 @@ impl Session {
}
}
/// Find Subject for component `comp` of mask `mask` on photo `id` (an Object without clicks):
/// the photo's main people / animals ([`worker::Kind::Subject`]), those the camera's `focus`
/// falls on when the file records it; when the subject is neither, the object at `point`. In
/// background mode [`Session::segment_poll`] applies the result; otherwise it is applied
/// before this returns.
pub(crate) fn segment_subject_later(&mut self, id: PhotoId, mask: u32, comp: usize, point: Point, focus: Option<Point>) -> Result<(), String> {
self.segmenter.model_dir()?;
#[cfg(feature = "sam")]
{
let kind = worker::Kind::Subject { focus: focus.map(|p| (p.x as f32, p.y as f32)) };
let tag = Tag::Subject { photo: id, mask, comp, point };
if self.segmenter.background {
return self.segment_queue(id, kind, tag, None);
}
let seg = self.segment_wait(id, kind, None)?;
let mut polled = Polled::default();
self.apply_outcome(worker::Outcome { tag, result: Ok(seg), superseded: false, notice: None }, &mut polled);
match polled.messages.into_iter().next() {
Some(e) => Err(e),
None => Ok(()),
}
}
#[cfg(not(feature = "sam"))]
{
let _ = (id, mask, comp, point, focus);
Err("AI masks are not available in this build".into())
}
}
/// Start a zoomed-in pass for component `comp` of mask `mask` on photo `id` (an Object or
/// Describe selection): the photo around the selection is rendered at a higher resolution
/// and segmented again. In background mode [`Session::segment_poll`] applies the result;
@@ -706,6 +741,51 @@ impl Session {
Err(e) => polled.messages.push(e.to_string()),
}
}
Tag::Subject { photo, mask, comp, point } => {
let found = match o.result {
Ok(found) => found,
Err(e) => return polled.messages.push(e),
};
let Some(d) = self.develop_of(photo) else { return };
let mut d = (*d).clone();
let Some(c) = d.masks.iter_mut().find(|m| m.id == mask).and_then(|m| m.components.get_mut(comp)) else { return };
// still the Object waiting for it (not clicked or replaced meanwhile)
let MaskShape::Object { hint, seg: None, edge, .. } = &c.shape else { return };
if !hint.is_empty() {
return;
}
let edge = *edge;
let seg = match found {
Some(seg) => seg,
// neither a person nor an animal: the object at the point
None if self.segmenter.background => {
if let Err(e) = self.segment_clicks_later(photo, mask, comp, vec![point], Vec::new()) {
polled.messages.push(e);
}
return;
}
None => {
match self.segment_clicks(photo, &clicks_of(&[point], &[])) {
Ok(seg) => {
c.shape = MaskShape::Object { hint: vec![point], exclude: Vec::new(), seg: Some(seg), detail: Vec::new(), edge }
}
Err(e) => return polled.messages.push(e),
}
if let Err(e) = self.set_develop(photo, d, "Find Subject") {
polled.messages.push(e.to_string());
} else {
polled.changed = true;
}
return;
}
};
let text = lightcraft_segment::SUBJECT_CONCEPTS.join(", ");
c.shape = MaskShape::Prompt { text, seg: Some(seg), detail: Vec::new(), edge };
match self.set_develop(photo, d, "Find Subject") {
Ok(()) => polled.changed = true,
Err(e) => polled.messages.push(e.to_string()),
}
}
Tag::Detail { photo, mask, comp, shape } => {
let patch = match o.result {
Ok(Some(p)) => p,
@@ -747,6 +827,47 @@ mod tests {
assert!(s.segment_poll().messages.is_empty(), "once");
}
/// Find Subject's result: people / animals found become a Describe selection of the waiting
/// Object (one undo step), not after it was clicked meanwhile; nothing found queues the object
/// at the point (here: no model, so a message, and the mask still waits).
#[cfg(feature = "sam")]
#[test]
fn find_subject_results_fill_the_waiting_mask() {
use lightcraft_develop::{Mask, MaskComponent, MaskOp};
let mut s = Session::with_demo();
s.segmenter.dir = Some(std::env::temp_dir().join(format!("lc-no-sam3-subject-{}", std::process::id())));
let id = s.active().unwrap();
let waiting = || MaskShape::Object { hint: vec![], exclude: vec![], seg: None, detail: vec![], edge: 0.0 };
let mut d = (*s.develop_of(id).unwrap()).clone();
d.masks.push(Mask {
id: 3,
components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: waiting() }],
..Default::default()
});
s.set_develop(id, d, "test").unwrap();
let point = Point::new(0.4, 0.5);
let send = |s: &mut Session, result| {
let tag = Tag::Subject { photo: id, mask: 3, comp: 0, point };
s.segmenter.results.0.send(worker::Outcome { tag, result, superseded: false, notice: None }).unwrap();
s.segment_poll()
};
let shape = |s: &Session| s.develop_of(id).unwrap().masks[0].components[0].shape.clone();
// nothing found, no model to click with: said so, and the mask still waits
let polled = send(&mut s, Ok(None));
assert!(!polled.messages.is_empty() && shape(&s) == waiting(), "{:?}", polled.messages);
// people found: a Describe selection of them
let polled = send(&mut s, Ok(Some(seg_box(20, 5, 5, 15, 15))));
assert!(polled.changed && polled.messages.is_empty());
let MaskShape::Prompt { text, seg: Some(_), .. } = shape(&s) else { panic!("{:?}", shape(&s)) };
assert_eq!(text, "person, animal");
// a result for a mask that changed meanwhile is dropped
let before = shape(&s);
assert!(!send(&mut s, Ok(Some(seg_box(20, 0, 0, 4, 4)))).changed);
assert_eq!(shape(&s), before);
// an error reaches the user
assert_eq!(send(&mut s, Err("boom".into())).messages, vec!["boom".to_string()]);
}
fn seg_box(side: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> SegMask {
let l: Vec<f32> =
(0..side * side).map(|i| if (x0..x1).contains(&(i % side)) && (y0..y1).contains(&(i / side)) { 8.0 } else { -8.0 }).collect();
+12
View File
@@ -42,6 +42,12 @@ pub enum Kind {
Prepare,
Clicks(Vec<lightcraft_segment::Click>),
Text(String),
/// The photo's subject among its people and animals (`Sam3::segment_subject`); `focus`: where
/// the camera focused (normalized), when the file records it. No result: the subject is
/// something else.
Subject {
focus: Option<(f32, f32)>,
},
/// A zoomed-in pass over `region` (normalized) of the photo, rendered by the job's `render`.
Detail {
prompt: Prompt,
@@ -420,6 +426,7 @@ fn remote_job(state: &mut State, shared: &Shared, job: &mut Job, endpoint: &str)
let operation = match std::mem::replace(&mut job.kind, Kind::Prepare) {
Kind::Prepare => Operation::Prepare,
Kind::Text(text) => Operation::Text(text),
Kind::Subject { focus } => Operation::Subject(focus.map(|(x, y)| [x, y])),
Kind::Clicks(clicks) => Operation::Clicks(clicks.iter().map(|c| [c.x, c.y, if c.positive { 1.0 } else { 0.0 }]).collect()),
Kind::Detail { prompt, region: r } => {
region = Some(r);
@@ -480,6 +487,11 @@ fn run_job(state: &mut State, shared: &Shared, job: &mut Job, placement: Placeme
let (m, enc) = encoded(state, shared, job, placement)?;
Ok(text_logits(m, enc, &text)?.map(|l| SegMask::from_logits(side, &l)))
}
Kind::Subject { focus } => {
let (m, enc) = encoded(state, shared, job, placement)?;
// (the reference score threshold, as Describe uses)
Ok(m.segment_subject(enc, focus, 0.5)?.map(|p| SegMask::from_logits(side, &p.logits)))
}
#[cfg(test)]
#[allow(clippy::panic)]
Kind::Panic => panic!("a test panic"),
+78
View File
@@ -385,6 +385,84 @@ fn permanently_deleting_explicit_targets_keeps_the_surviving_selection() {
assert_eq!(s.catalog.to_snapshot(), snapshot);
}
/// `lensBlur.brushStroke` adds a stroke to the Focus or the Blur brush (clamped, undoable); hostile
/// input is an error; `lensBlur.brushReset` clears one brush or both.
#[test]
fn lens_blur_brush_strokes_and_reset() {
let mut s = demo();
let id = s.active().unwrap();
s.execute(
"lensBlur.brushStroke",
&json!({"mode": "focus", "points": [[0.2, 0.3], [0.25, 0.3]], "size": 9.0, "amount": 40, "feather": f64::NAN, "autoMask": true}),
)
.unwrap();
s.execute("lensBlur.brushStroke", &json!({"mode": "blur", "points": [[0.7, 0.6]]})).unwrap();
let d = s.develop_of(id).unwrap();
let (f, b) = (&d.lens_blur.focus_strokes, &d.lens_blur.blur_strokes);
assert_eq!((f.len(), b.len()), (1, 1));
assert_eq!(f[0].points.len(), 2);
assert!(f[0].size == 0.5 && f[0].density == 40.0 && f[0].feather == lightcraft_develop::BrushStroke::default().feather && f[0].auto_mask);
for bad in [
json!({"mode": "sideways", "points": [[0.5, 0.5]]}),
json!({"mode": "focus", "points": []}),
json!({"mode": "focus"}),
json!({"mode": "blur", "points": [[0.5, 0.5]], "pressure": [0.5, 0.5]}),
] {
assert!(s.execute("lensBlur.brushStroke", &bad).is_err(), "{bad}");
}
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.develop_of(id).unwrap().lens_blur.blur_strokes.is_empty(), "a stroke is one undo step");
s.execute("lensBlur.brushStroke", &json!({"mode": "blur", "points": [[0.7, 0.6]]})).unwrap();
s.execute("lensBlur.brushReset", &json!({"mode": "blur"})).unwrap();
let d = s.develop_of(id).unwrap();
assert!(d.lens_blur.blur_strokes.is_empty() && d.lens_blur.focus_strokes.len() == 1);
assert!(s.execute("lensBlur.brushReset", &json!({"mode": "nope"})).is_err());
s.execute("lensBlur.brushReset", &json!({})).unwrap();
assert!(s.develop_of(id).unwrap().lens_blur.focus_strokes.is_empty());
}
/// `lensBlur.findSubject` without the SAM 3 model (or in a build without AI masks) is an error that
/// leaves the photo as it was: no empty mask, the blur not switched on.
#[test]
fn find_subject_without_the_model_changes_nothing() {
let mut s = demo();
let id = s.active().unwrap();
// (never the machine's own model: a folder that has none)
s.segmenter.dir = Some(std::env::temp_dir().join(format!("lc-no-sam3-{}", std::process::id())));
let before = s.develop_of(id).unwrap();
let e = s.execute("lensBlur.findSubject", &json!({})).unwrap_err();
assert!(e.to_string().contains("SAM 3") || e.to_string().contains("AI masks"), "{e}");
let after = s.develop_of(id).unwrap();
assert!(after.masks.is_empty() && !after.lens_blur.enabled);
assert_eq!(*before, *after);
}
/// Deleting the mask that is the Lens Blur focus clears the focus, so a new mask that gets the same
/// id doesn't become the focus; undo brings both back.
#[test]
fn deleting_the_focus_mask_clears_the_lens_blur_focus() {
let mut s = demo();
let id = s.active().unwrap();
let radial = json!({"kind": "radial", "center": [0.5, 0.5], "rx": 0.2, "ry": 0.2});
s.execute("mask.add", &radial).unwrap();
let mid = s.develop_of(id).unwrap().masks[0].id;
s.execute("develop.merge", &json!({"settings": {"lens_blur": {"enabled": true, "amount": 50, "focus_mask": mid}}})).unwrap();
s.execute("mask.delete", &json!({"id": mid})).unwrap();
assert_eq!(s.develop_of(id).unwrap().lens_blur.focus_mask, None);
// a new mask takes the freed id, and stays an ordinary mask
s.execute("mask.add", &radial).unwrap();
let d = s.develop_of(id).unwrap();
assert_eq!(d.masks[0].id, mid);
assert_eq!(d.lens_blur.focus_mask, None);
// undoing the add and the delete brings the focus back with its mask
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.develop_of(id).unwrap().lens_blur.focus_mask, Some(mid));
// other mask edits keep it
s.execute("mask.adjust", &json!({"values": {"exposure": 0.5}})).unwrap();
assert_eq!(s.develop_of(id).unwrap().lens_blur.focus_mask, Some(mid));
}
/// `mask.brushStroke {connect: true}` (a ⇧-click) starts from the last point of the mask's last stroke: one straight
/// stroke when the brush is unchanged, pieces whose size, feather and flow step from the last stroke's to the new
/// values when it changed, and a plain dab when there is nothing to connect to.
@@ -98,6 +98,37 @@ fn an_lrdata_folder_whose_catalog_was_renamed_finds_the_one_next_to_it() {
let _ = std::fs::remove_dir_all(&root);
}
/// Issue #2592: someone who deleted Lightroom and its catalog keeps only `Backups/`; that folder and
/// each dated folder in it are refused. A dated folder names its zip; `Backups/` names one only when
/// it is the only backup (with several, the import asks which).
#[test]
fn lightroom_backups_without_their_catalog_are_refused_and_name_the_zip() {
let root = temp_dir("backups");
let backups = root.join("Lightroom").join("Backups");
let backup = crate::lightroom_backup::tests::zip(&[("Cat.lrcat", b"SQLite format 3\0")], true, false);
for (dated, zip) in [("2019-03-26 0751", "Cat-2.lrcat.zip"), ("2023-11-07 0900", "Cat-v13.zip")] {
std::fs::create_dir_all(backups.join(dated)).unwrap();
std::fs::write(backups.join(dated).join(zip), &backup).unwrap();
}
// a zip without a catalog in a dated folder is not a backup
std::fs::create_dir_all(backups.join("2024-01-01 1200")).unwrap();
std::fs::write(backups.join("2024-01-01 1200").join("photos.zip"), crate::lightroom_backup::tests::zip(&[("a.jpg", b"x")], false, false))
.unwrap();
assert_eq!(lightroom_catalog_at(&backups.join("2024-01-01 1200")), None, "no catalog in the zip");
let newest = backups.join("2023-11-07 0900").join("Cat-v13.zip");
assert_eq!(lightroom_catalog_at(&backups), Some(LightroomPlace { catalog: None }), "two backups: no arbitrary pick");
refused(&root, &backups.join("2023-11-07 0900"), &newest);
refused(&root, &backups.join("2019-03-26 0751"), &backups.join("2019-03-26 0751").join("Cat-2.lrcat.zip"));
std::fs::remove_dir_all(backups.join("2019-03-26 0751")).unwrap();
refused(&root, &backups, &newest);
// a folder of zips that isn't in a `Backups/` folder is not Lightroom's
let other = root.join("Downloads");
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("photos.zip"), &backup).unwrap();
assert_eq!(lightroom_catalog_at(&other), None);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn an_empty_folder_still_becomes_a_library() {
let root = temp_dir("empty");
+19
View File
@@ -240,6 +240,25 @@ fn object_clicks_are_capped() {
let _ = std::fs::remove_dir_all(&dir);
}
/// In background mode a new Object mask with too many clicks is refused up front, not queued.
#[test]
fn background_object_clicks_over_the_cap_are_refused_before_queueing() {
if !Segmenter::AVAILABLE {
return;
}
let mut s = Session::with_demo();
s.segmenter.background = true;
let dir = damaged_model("later-clicks");
s.segmenter.dir = Some(dir.clone());
let id = s.active().unwrap();
let points: Vec<_> = (0..=crate::segment::MAX_CLICKS).map(|_| json!([0.5, 0.5])).collect();
let e = s.execute("mask.add", &json!({"kind": "object", "points": points})).unwrap_err().to_string();
assert!(e.contains("at most"), "{e}");
assert!(s.develop_of(id).unwrap().masks.is_empty());
assert!(!s.segmenter.busy());
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(feature = "sam")]
#[test]
fn a_running_model_download_shows_in_activity_and_cancels() {
+1
View File
@@ -4,4 +4,5 @@
mod denoise_cpu;
#[cfg(feature = "denoise")]
mod denoise_real;
mod orf_withdrawal;
mod preview_read;
+207
View File
@@ -0,0 +1,207 @@
//! Compressed ORF withdrawal: public import/recheck and render identities stay consistent.
use std::path::PathBuf;
use std::sync::Arc;
use lightcraft_catalog::{APP_VERSION, MediaKind, Op, Photo, PhotoId, Source};
use lightcraft_engine::{Session, cmd::recheck, media::content_key};
use lightcraft_pipeline::SourceInfo;
use lightcraft_preview::Hash128;
use lightcraft_raster::Rgb32f;
use serde_json::json;
struct OrfLibrary {
s: Session,
dir: PathBuf,
lib: PathBuf,
id: PhotoId,
}
impl Drop for OrfLibrary {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
/// A fixed original and settings isolate decoder status from every other render-key input.
fn decoder_session(format: &str) -> Session {
let mut s = Session::new();
let mut p = Photo::new(PhotoId(1), Source::File { path: "same-original.orf".into() }, "same-original.orf", format, 6000, 4000, "2026-01-01");
p.kind = MediaKind::Raw;
p.content_hash = Some("unchanged-file-bytes".into());
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
s
}
/// Include the frontend's ordinary, hover and quick-view identities as well as all persistent
/// render families. The original-file identity must not change along with any of these.
fn decoder_keys(s: &mut Session) -> (Vec<u64>, Vec<Hash128>, String) {
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
let thumb = s.thumb_job(p.id, 256).unwrap();
let render = s.render_job(p.id, 640, 480, false, true).unwrap();
let hover = s.preview_job(p.id, 640, 480, true, &p.develop).unwrap();
let quick = s.quick_view_job(p.id, 640, true).unwrap();
(
vec![thumb.key, render.key, hover.key, quick.key],
vec![
thumb.cache.unwrap().1,
s.loupe_job(p.id, 640, 480, true).unwrap().view_cache.unwrap().1,
Session::variant_key(&p, &p.develop, 256, 0),
render.source_key.unwrap(),
],
content_key(&p),
)
}
/// Old ORF renders cannot stand in after withdrawal; other formats and original-file identities stay stable.
#[test]
fn withdrawn_orf_decoder_has_distinct_render_keys_without_changing_file_identity() {
// Before the withdrawal, format was not part of any of these keys: an otherwise identical
// non-ORF photo gives the old keys, preserved for every other camera and ordinary image.
let legacy = decoder_keys(&mut decoder_session("DNG"));
assert_eq!(legacy, decoder_keys(&mut decoder_session("JPEG")));
let orf = decoder_keys(&mut decoder_session("ORF"));
for (old, new) in legacy.0.iter().zip(&orf.0) {
assert_ne!(old, new, "old ORF frontend render must not be reused");
}
for (old, new) in legacy.1.iter().zip(&orf.1) {
assert_ne!(old, new, "old ORF persistent render or decoded source must not be reused");
}
assert_eq!(legacy.2, orf.2, "smart previews and denoise products still identify the original file");
assert_eq!(orf, decoder_keys(&mut decoder_session("orf")));
}
/// Apply the same-byte capability transition that Reload or the background recheck records.
fn mark_orf_preview_only(s: &mut Session) {
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
s.catalog
.apply(Op::SetContent {
id: p.id,
width: p.width,
height: p.height,
file_size: p.file_size,
content_hash: p.content_hash.clone(),
preview_only: Some("Olympus compressed ORF".into()),
preview_checked: lightcraft_catalog::APP_VERSION.into(),
})
.unwrap();
s.media.forget(p.id);
}
/// A support-status change invalidates every render family, even when a resize happens at the same time.
#[test]
fn orf_preview_transition_changes_render_keys_with_identical_bytes_and_settings() {
let mut s = decoder_session("ORF");
let before = decoder_keys(&mut s);
mark_orf_preview_only(&mut s);
let after = decoder_keys(&mut s);
for (old, new) in before.0.iter().zip(&after.0) {
assert_ne!(old, new, "Reload changes frontend render identity");
}
for (old, new) in before.1.iter().zip(&after.1) {
assert_ne!(old, new, "Reload changes persistent render and decoded source identity");
}
assert_eq!(before.2, after.2, "Reload does not change the original file's identity");
let p = s.catalog.photo(PhotoId(1)).unwrap().clone();
assert_ne!(before.0[1], s.render_job(p.id, 648, 480, false, true).unwrap().key, "a resize must not cancel the status salt");
assert_ne!(before.0[2], s.preview_job(p.id, 648, 480, true, &p.develop).unwrap().key, "a hover resize must not cancel the status salt");
}
/// An in-flight sensor decode must not refill a source cache cleared by the preview-only transition.
#[test]
fn source_from_before_orf_preview_transition_is_not_accepted() {
let mut s = decoder_session("ORF");
s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::new(8, 8), SourceInfo::default()))));
let old = s.thumb_job(PhotoId(1), 256).unwrap().run();
assert!(old.loaded.is_some());
mark_orf_preview_only(&mut s);
s.accept(&old);
assert_eq!(s.media.source_usage().0, 0, "a sensor decode finishing after Reload cannot repopulate its source cache");
}
/// A legacy ORF record and a controlled probe let the upgrade tests exercise catalog migration
/// without downloading camera files. The raw crate separately tests the actual ORF probe.
fn legacy_orf(name: &str, preview_only: Option<String>) -> OrfLibrary {
let dir = std::env::temp_dir().join(format!("lc-orf-recheck-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let lib = dir.join("lib");
let file = dir.join("legacy.orf");
let mut s = Session::new();
s.open_library(&lib, false).unwrap();
let id = s.catalog.alloc_photo_id();
let mut p = Photo::new(id, Source::File { path: file.to_string_lossy().into() }, "legacy.orf", "ORF", 96, 64, "2026-01-01");
p.kind = MediaKind::Raw;
p.file_size = 1024;
p.content_hash = Some("same-file".into());
let info = lightcraft_engine::media::ProbeInfo {
width: p.width,
height: p.height,
file_size: p.file_size,
content_hash: p.content_hash.clone(),
format: p.format.clone(),
kind: p.kind,
preview_only,
..Default::default()
};
s.commit("Legacy ORF", Op::AddPhoto { photo: Box::new(p) }).unwrap();
s.selection = lightcraft_engine::Selection::single(id);
s.media.file_probe = Some(Arc::new(move |_| Ok(info.clone())));
OrfLibrary { s, dir, lib, id }
}
/// Previously supported compressed ORFs and their copies migrate without losing edits, history or persistence.
#[test]
fn legacy_compressed_orf_and_copies_become_preview_only_without_losing_edits() {
let mut x = legacy_orf("compressed", Some("Olympus compressed ORF".into()));
x.s.execute("develop.set", &json!({"ids": [x.id.0], "control": "light.exposure", "value": 0.5})).unwrap();
let r = x.s.execute("photo.virtualCopy", &json!({"ids": [x.id.0]})).unwrap();
let copy = PhotoId(r["ids"][0].as_u64().unwrap());
let before = x.s.catalog.photo(x.id).unwrap().clone();
let undo = x.s.undo.len();
let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap();
assert_eq!(r, json!({"checked": 1, "updated": [x.id.0, copy.0], "cleared": []}));
for id in [x.id, copy] {
let p = x.s.catalog.photo(id).unwrap();
assert_eq!(p.preview_only.as_deref(), Some("Olympus compressed ORF"));
assert_eq!(p.preview_checked, APP_VERSION);
assert!(!p.develops_raw());
assert_eq!(*p.develop, *before.develop);
}
assert_eq!(x.s.catalog.photo(x.id).unwrap().history, before.history);
assert_eq!(x.s.undo.len(), undo, "bookkeeping is not an undo step");
x.s.persist().unwrap();
x.s = Session::new();
x.s.open_library(&x.lib, false).unwrap();
assert!(x.s.catalog.photo(x.id).unwrap().preview_only.is_some());
assert!(recheck::stale(&x.s.catalog, false).is_empty());
}
/// Supported uncompressed ORF is checked once and never reported as newly recovered sensor support.
#[test]
fn legacy_uncompressed_orf_is_stamped_once_without_a_false_recovery_notice() {
let mut x = legacy_orf("supported", None);
let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap();
assert_eq!(r, json!({"checked": 1, "updated": [x.id.0], "cleared": []}));
let p = x.s.catalog.photo(x.id).unwrap();
assert!(p.develops_raw());
assert_eq!(p.preview_checked, APP_VERSION);
assert!(recheck::stale(&x.s.catalog, false).is_empty());
assert_eq!(recheck::stale(&x.s.catalog, true).len(), 1);
x.s.persist().unwrap();
x.s = Session::new();
x.s.open_library(&x.lib, false).unwrap();
assert!(recheck::stale(&x.s.catalog, false).is_empty());
assert!(x.s.catalog.photo(x.id).unwrap().develops_raw());
}
/// An offline original keeps its catalog state and remains eligible for a later recheck.
#[test]
fn unavailable_legacy_orf_is_unchanged_and_retried() {
let mut x = legacy_orf("offline", None);
x.s.media.file_probe = Some(std::sync::Arc::new(|_| Err("offline".into())));
let before = x.s.catalog.photo(x.id).unwrap().clone();
let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap();
assert_eq!(r, json!({"checked": 1, "updated": [], "cleared": []}));
assert_eq!(x.s.catalog.photo(x.id).unwrap(), &before);
assert_eq!(recheck::stale(&x.s.catalog, false).len(), 1);
}
+56
View File
@@ -0,0 +1,56 @@
//! Grain slider drags on the GPU: the time per frame of the draft renders the loupe makes while
//! Amount or Size is dragged, on a ~2.5 MP preview (1936 × 1290, the procedural demo photo).
//! `cargo run --release -p lightcraft-gpu --example grain_drag_bench` (`FRAMES=n`, default 40).
//!
//! The same source, settings and request on every build, so it can be copied unchanged into
//! another branch to compare grain models (see `docs/grain.md` → Performance). Each drag first
//! renders four frames that aren't counted (stage cache, GPU pipelines), then moves the slider one
//! step a frame; prints the median, fastest and slowest frame.
#![allow(clippy::unwrap_used, clippy::expect_used)]
use std::sync::Arc;
use std::time::Instant;
use lightcraft_develop::DevelopSettings;
use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, StageCache};
fn main() {
let frames: usize = std::env::var("FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(40).max(1);
let (w, h) = (1936, 1290);
let src = Arc::new(lightcraft_scenes::demo_library()[3].render(w, h));
let info = SourceInfo { raw: true, ..Default::default() };
let draft = RenderRequest { quality: Quality::Draft, ..RenderRequest::fit(w, h) };
let Some(adapter) = lightcraft_gpu::adapter_name() else {
eprintln!("no GPU adapter: nothing to measure");
return;
};
println!("gpu: {adapter}; {w}×{h} draft renders, {frames} frames per drag");
let mut s = DevelopSettings::default();
s.light.exposure = 0.3;
let mut drag = |label: &str, step: &dyn Fn(&mut DevelopSettings, usize)| {
let cache = StageCache::default();
let mut ms = Vec::with_capacity(frames);
for i in 0..frames + 4 {
step(&mut s, i);
let t = Instant::now();
assert!(lightcraft_gpu::render(&src, &info, &s, &draft, Some(&cache)).is_some(), "GPU render failed");
if i >= 4 {
ms.push(t.elapsed().as_secs_f64() * 1e3);
}
}
ms.sort_by(f64::total_cmp);
println!("{label:<30} median {:5.1} ms min {:5.1} max {:5.1}", ms[ms.len() / 2], ms[0], ms[ms.len() - 1]);
};
drag("exposure drag, no grain", &|s, i| {
s.grain.amount = 0.0;
s.light.exposure = 0.3 + i as f64 * 0.01;
});
drag("Amount drag (20 → 100)", &|s, i| {
s.grain.size = 25.0;
s.grain.amount = 20.0 + (i * 2 % 80) as f64;
});
drag("Size drag (amount 50, 0 → 100)", &|s, i| {
s.grain.amount = 50.0;
s.grain.size = (i * 2 % 100) as f64;
});
}
+84 -2
View File
@@ -51,6 +51,7 @@ const MODULES: &[Module] = &[
"guided_pre",
"guided_ab",
"guided_apply",
"clamp_between_k",
"wb_k",
"nr_lum",
"chroma_k",
@@ -197,7 +198,11 @@ fn build_jobs(
layout: Some(&p.pipeline_layout),
module: &p.module,
entry_point: Some(entry),
compilation_options: Default::default(),
// Only the median kernels (`blur.wgsl`, `med_tile`) use workgroup memory, and they
// load every element they read before the barrier, so wgpu's default zeroing is not
// needed. On DX12 it is written out as one assignment per element, which made FXC take
// about 87 s over these kernels at every start of a release build.
compilation_options: wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() },
cache: None,
});
let kernel = Kernel { pipeline, layout: p.layout.clone(), nbuf: p.nbuf };
@@ -382,6 +387,11 @@ pub struct Gpu {
free: std::sync::Mutex<Vec<Tracked>>,
/// Largest storage buffer the device accepts (bytes).
pub max_buffer: u64,
/// The crystal grain tables of the last grain pattern, resident: a render (each Amount step
/// of a drag) copies them on the GPU instead of uploading their 12 MB again ([`Gpu::grain_tables`]).
/// Shared with each render that recorded a copy from them until it submits: replacing them
/// while another thread's copy is unsubmitted must not hand the buffer back to the pool.
grain: std::sync::Mutex<Option<(std::sync::Arc<lightcraft_pipeline::crystal::CrystalTile>, std::sync::Arc<Buf>)>>,
/// The device is the window's (eframe's): renders can hand it textures to draw directly.
pub window: bool,
}
@@ -430,6 +440,11 @@ fn constants() -> String {
for (i, h) in GRAIN_HASH.iter().enumerate() {
s += &format!("const GRAIN_H{i}: u32 = {h}u;\n");
}
use lightcraft_pipeline::crystal::{TILE_PER_LONG, TORI};
s += &format!(
"const CRYSTAL_T0: u32 = {}u;\nconst CRYSTAL_T1: u32 = {}u;\nconst CRYSTAL_TPL: f32 = {:?};\n",
TORI[0], TORI[1], TILE_PER_LONG as f32
);
s += &format!("const DEEP_WRITTEN: u32 = {}u;\n", crate::params::DEEP_WRITTEN);
for (name, idx) in crate::params::finish_fields() {
s += &format!("const F_{name}: u32 = {idx}u;\n");
@@ -543,7 +558,7 @@ impl Gpu {
max_buffer >> 20,
if window { ", the window's device" } else { "" }
);
Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, window })
Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, window, grain: Default::default() })
}
/// A buffer of `len` 32-bit values with undefined contents (a recycled one when possible).
@@ -718,6 +733,44 @@ impl Gpu {
);
}
/// Record into `enc` a copy of `tile`'s summed-area tables (both tori, back to back) into
/// `dst` at value offset `at`, uploading them first unless they are the resident ones.
/// Returns the buffer copied from, which the caller keeps until it has submitted `enc` (another
/// render may replace the resident tables meanwhile). None when `dst` can't hold them (an
/// over-limit placeholder: the render has failed already).
pub fn grain_tables(
&self,
enc: &mut wgpu::CommandEncoder,
tile: &std::sync::Arc<lightcraft_pipeline::crystal::CrystalTile>,
dst: &Buf,
at: usize,
) -> Option<std::sync::Arc<Buf>> {
let len: usize = tile.sats.iter().map(Vec::len).sum();
let (start, bytes) = ((at as u64) * 4, (len as u64) * 4);
if len == 0 || dst.raw().size() < start.saturating_add(bytes) {
return None;
}
let mut resident = self.grain.lock().unwrap_or_else(|e| e.into_inner());
if !resident.as_ref().is_some_and(|(t, b)| std::sync::Arc::ptr_eq(t, tile) && b.raw().size() >= bytes) {
// the old tables go back to the pool first (once no unsubmitted copy holds them): one
// pattern's tables are resident at a time
*resident = None;
let buf = self.buffer(len);
if buf.raw().size() < bytes {
return None;
}
let mut off = 0u64;
for sat in &tile.sats {
self.queue.write_buffer(buf.raw(), off, bytemuck::cast_slice(sat));
off += (sat.len() as u64) * 4;
}
*resident = Some((tile.clone(), std::sync::Arc::new(buf)));
}
let (_, src) = resident.as_ref()?;
enc.copy_buffer_to_buffer(src.raw(), 0, dst.raw(), start, bytes);
Some(src.clone())
}
/// Stands in for a buffer that could not be created (the render has failed already).
fn placeholder(&self) -> wgpu::Buffer {
self.device.create_buffer(&wgpu::BufferDescriptor {
@@ -1321,6 +1374,35 @@ mod tests {
}
}
/// Resident grain tables replaced by another pattern stay out of the pool while a render
/// that recorded a copy from them hasn't submitted it: reusing them then would hand that
/// render another tile's tables.
#[test]
fn replaced_grain_tables_stay_alive_until_their_copy_is_submitted() {
use lightcraft_pipeline::crystal::{CrystalLook, CrystalTile};
let Some(g) = crate::device() else {
lightcraft_testkit::skip!(Gpu, "no GPU device");
return;
};
let look = CrystalLook::new(25.0, 50.0);
let (Some(a), Some(b)) = (CrystalTile::new(look, 0x7ab1_0001), CrystalTile::new(look, 0x7ab1_0002)) else { panic!("tiles") };
let (a, b) = (std::sync::Arc::new(a), std::sync::Arc::new(b));
let len: usize = a.sats.iter().map(Vec::len).sum();
let (dst_a, dst_b) = (g.buffer(len), g.buffer(len));
let mut first = g.encoder();
let held = g.grain_tables(&mut first, &a, &dst_a, 0).expect("tables copied");
// another render replaces the resident tables before `first` is submitted
let mut second = g.encoder();
assert!(g.grain_tables(&mut second, &b, &dst_b, 0).is_some());
let next = g.buffer(len);
assert!(next.raw() != held.raw(), "the replaced tables went back to the pool before their copy was submitted");
g.submit([first.finish()]);
// each render read its own tile's tables
let tables = |t: &lightcraft_pipeline::crystal::CrystalTile| t.sats.concat();
assert!(g.finish_and_read::<f32>(second, &dst_a, len) == tables(&a), "the first render copied other tables");
assert!(g.finish_and_read::<f32>(g.encoder(), &dst_b, len) == tables(&b), "the second render copied other tables");
}
/// A GPU retired by another failure (a validation error) keeps a live device: its buffers are
/// still released, which takes a poll.
#[test]
+39 -7
View File
@@ -3,7 +3,7 @@
use lightcraft_develop::VignetteStyle;
use lightcraft_pipeline::colorops::POINT_WORDS;
use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, srgb_lut};
use lightcraft_pipeline::finish::{FinishParams, GrainModel, MASK_TERMS, srgb_lut};
use crate::ctx::{FailKind, fail};
@@ -71,6 +71,12 @@ const FIELDS: &[(&str, usize)] = &[
// the window's offset in the whole output and the whole output's size (pixels)
("VIG_VIEW", 4),
("GRAIN", 1),
// 0 = value noise (processes V1 to V6: GRAIN_AMT, GRAIN_SC, GRAIN_ROUGH), 1 = crystal layers (V7)
("GRAIN_MODEL", 1),
// crystal grain: amplitude, footprint (tile px per output px), the tori's tables in `aux`
("GRAIN_K", 1),
("GRAIN_FOOT", 1),
("GRAIN_SAT", 2),
("GRAIN_AMT", 1),
("GRAIN_SC", 1),
("GRAIN_ROUGH", 1),
@@ -178,7 +184,8 @@ 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).
/// mask terms | light operator tables) for `fp` with `masks` (their local adjustments' terms). The crystal
/// grain's tables go after `aux` in the kernel's buffer ([`crate::render`] copies them there).
///
/// `deep`: the kernel writes float samples, as the pipeline's `finish_deep` does.
///
@@ -220,6 +227,16 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
if let Some((l, _)) = &fp.lut {
aux.extend(l.data.iter().flatten());
}
// the crystal grain's tables follow `aux` on the GPU without being part of it: they stay
// resident between renders ([`crate::Gpu::grain_tables`]) and the render copies them in
let mut sat_off = [0u32; 2];
if let Some(GrainModel::Crystal(g)) = &fp.grain {
let mut off = aux.len();
for (slot, sat) in sat_off.iter_mut().zip(&g.tile.sats) {
*slot = off as u32;
off += sat.len();
}
}
let mut p = Block::new();
p.u("LIGHT_OPS", light.len() as u32);
@@ -330,12 +347,27 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
p.b("PROOF_DEST_WARN", pp.dest_warning);
p.b("PROOF_DISP_WARN", pp.display_warning);
}
if let Some((amt, cell, rough, seed)) = fp.grain {
if let Some(model) = &fp.grain {
p.b("GRAIN", true);
p.f("GRAIN_AMT", amt);
p.f("GRAIN_SC", fp.px_per_long as f32 / cell);
p.f("GRAIN_ROUGH", rough);
p.u("GRAIN_SEED", seed);
match model {
GrainModel::Value(g) => {
p.u("GRAIN_MODEL", 0);
p.f("GRAIN_AMT", g.amt);
p.f("GRAIN_SC", fp.px_per_long as f32 / g.cell);
p.f("GRAIN_ROUGH", g.rough);
p.u("GRAIN_SEED", g.seed);
}
GrainModel::Crystal(g) => {
p.u("GRAIN_MODEL", 1);
p.f("GRAIN_K", g.k);
p.f("GRAIN_FOOT", g.foot);
if let Some(i) = index("GRAIN_SAT") {
for (slot, off) in p.0.iter_mut().skip(i).zip(sat_off) {
*slot = off;
}
}
}
}
let long = fp.ow.max(fp.oh);
let [a, b, c, d, e, f] = fp.out_to_norm.0;
let (kx, ky) = (fp.ow / long, fp.oh / long);
+130 -10
View File
@@ -136,6 +136,10 @@ pub(crate) struct Cx<'a> {
enc: Option<wgpu::CommandEncoder>,
/// Kernel invocations recorded since the last submit.
pending: u64,
/// Buffers shared with other renders that recorded commands read from (the resident grain
/// tables): kept until those commands are submitted. Declared after `enc`, so an unsubmitted
/// encoder is dropped before them.
held: Vec<std::sync::Arc<Buf>>,
}
/// Kernel invocations recorded before a render submits them (under one full-size pass over a
@@ -147,7 +151,7 @@ const BAND_PIXELS: usize = 4 << 20;
impl<'a> Cx<'a> {
pub fn new(gpu: &'a Gpu) -> Cx<'a> {
Cx { gpu, enc: Some(gpu.encoder()), pending: 0 }
Cx { gpu, enc: Some(gpu.encoder()), pending: 0, held: Vec::new() }
}
/// Record kernel `name` (see [`Gpu::run`]).
@@ -161,11 +165,27 @@ impl<'a> Cx<'a> {
}
}
/// The finish kernel's `aux` buffer: `aux`, then the crystal grain's tables when it has them
/// (copied on the GPU from the resident ones, see [`Gpu::grain_tables`]).
pub fn finish_aux(&mut self, aux: &[f32], grain: Option<&lightcraft_pipeline::finish::GrainModel>) -> Buf {
let Some(lightcraft_pipeline::finish::GrainModel::Crystal(g)) = grain else { return self.gpu.upload(aux) };
let tables: usize = g.tile.sats.iter().map(Vec::len).sum();
let out = self.gpu.buffer(aux.len().saturating_add(tables));
if !aux.is_empty() && out.raw().size() >= (aux.len() as u64) * 4 {
self.gpu.queue.write_buffer(out.raw(), 0, bytemuck::cast_slice(aux));
}
let enc = self.enc.get_or_insert_with(|| self.gpu.encoder());
self.held.extend(self.gpu.grain_tables(enc, &g.tile, &out, aux.len()));
out
}
/// Submit what is recorded and read back `len` values of `b`.
pub fn read<T: bytemuck::Pod>(&mut self, b: &Buf, len: usize) -> Vec<T> {
self.pending = 0;
let enc = self.enc.take().unwrap_or_else(|| self.gpu.encoder());
self.gpu.finish_and_read(enc, b, len)
let out = self.gpu.finish_and_read(enc, b, len);
self.held.clear();
out
}
/// Submit what is recorded so far without waiting. Renders submit stage by stage and every
@@ -177,6 +197,7 @@ impl<'a> Cx<'a> {
if let Some(enc) = self.enc.take() {
self.gpu.submit([enc.finish()]);
}
self.held.clear();
}
/// Submit what is recorded and wait for it (profiling only: stage timings).
@@ -185,6 +206,7 @@ impl<'a> Cx<'a> {
if let Some(enc) = self.enc.take() {
self.gpu.submit([enc.finish()]);
}
self.held.clear();
let _ = self.gpu.poll(wgpu::PollType::wait_indefinitely());
}
@@ -349,6 +371,9 @@ fn guided_coeffs(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, sigma: f32, eps:
gaussian(cx, &ab, w, h, 2, sigma)
}
/// Pixels per thread along the pass of `median_h` / `median_v` (`MED_K` in `blur.wgsl`).
const MEDIAN_K: usize = 4;
/// Separable median of a plane (`local::median_hv`).
fn median_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf {
if r == 0 || w * h == 0 {
@@ -356,21 +381,38 @@ fn median_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf {
}
let pr = [w as u32, h as u32, 1, r.min(local::BASE_DETAIL_MAX) as u32];
let tmp = cx.gpu.buffer(w * h);
cx.run("median_h", &pr, &[Some(p), Some(&tmp)], groups2(w, h, [16, 16]));
cx.run("median_h", &pr, &[Some(p), Some(&tmp)], groups2(w.div_ceil(MEDIAN_K), h, [16, 16]));
let out = cx.gpu.buffer(w * h);
cx.run("median_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16]));
cx.run("median_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h.div_ceil(MEDIAN_K), [16, 16]));
out
}
/// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no median).
fn tone_base(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, sigma: f32, detail: usize) -> Buf {
/// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no detail removal).
fn tone_base(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, sigma: f32, detail: usize, keeps_gaps: bool) -> Buf {
if detail == 0 {
return guided_fast(cx, l, w, h, sigma, local::BASE_EPS);
}
let m = median_hv(cx, l, w, h, detail);
let m = if keeps_gaps { detail_free(cx, l, w, h, detail) } else { median_hv(cx, l, w, h, detail) };
guided_fast(cx, &m, w, h, sigma, local::BASE_EPS)
}
/// Log luminance without detail finer than `r` px (`local::detail_free`): clamped between its
/// median at `r` and the median of a `local::BASE_COARSE_STEP`× downscaled copy, enlarged.
fn detail_free(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, r: usize) -> Buf {
if r == 0 || w * h == 0 {
return cx.copy(l);
}
let fine = median_hv(cx, l, w, h, r);
let s = local::BASE_COARSE_STEP;
let (lw, lh) = (w.div_ceil(s).max(1), h.div_ceil(s).max(1));
let lo = resize(cx, l, (w, h), (lw, lh), 1, Filter::Box);
let lo_median = median_hv(cx, &lo, lw, lh, r);
let coarse = resize(cx, &lo_median, (lw, lh), (w, h), 1, Filter::Bilinear);
let out = cx.gpu.buffer(w * h);
map(cx, "clamp_between_k", w * h, &[], [Some(l), Some(&fine), Some(&coarse)], &out);
out
}
/// Fast guided filter (`local::guided_fast`): coefficients on a subsampled grid.
fn guided_fast(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, sigma: f32, eps: f32) -> Buf {
let s = local::guided_fast_step(sigma);
@@ -749,6 +791,7 @@ pub fn render(
px_per_long: plan.px_per_long,
air_pre: prep.air,
space: req.space,
draft: req.quality == lightcraft_pipeline::Quality::Draft,
});
// soft proofing as the CPU's `finish` sets it up (an output-device table never gets here: see `render`)
fp.proof = req.proof.map(|pr| pr.params(req.space));
@@ -780,7 +823,7 @@ pub fn render(
if crate::ctx::failed() {
return None; // a malformed parameter block failed the render: the CPU fallback redoes it
}
let aux = gpu.upload(&aux);
let aux = cx.finish_aux(&aux, fp.grain.as_ref());
// cleared, so that work which never ran cannot pass for an image (see the check below)
let out = cx.zeroed(if deep { 3 * n } else { n });
if fault == Some(crate::Fault::Validation) {
@@ -1011,7 +1054,14 @@ fn linear(cx: &mut Cx<'_>, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, ho
eyed
}
};
denoise(cx, img, plan, colour_noise)
let img = denoise(cx, img, plan, colour_noise);
if !lightcraft_pipeline::lens_blur::renders(s) {
return img;
}
// Lens Blur (global or a mask's): on the CPU, like the CPU renderer's (`lens_blur::apply`)
let mut host_img = cx.read_rgb(&img, w, h);
lightcraft_pipeline::lens_blur::apply_with(&mut host_img, s, &plan.frame, plan.px_per_long, plan.mattes.as_deref(), plan.lens_subject.as_deref());
cx.gpu.upload(rgb_words(&host_img))
}
/// Defringe (`optics::defringe`) of the white-balanced image.
@@ -1395,7 +1445,7 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla
let base = match sig.base {
Some(sg) => {
let key = local::base_key(&plan.settings, sg, sig.base_detail);
plane_at(&mut planes.base, key, || tone_base(cx, &log_l, w, h, sg, sig.base_detail))
plane_at(&mut planes.base, key, || tone_base(cx, &log_l, w, h, sg, sig.base_detail, local::base_keeps_gaps(&plan.settings)))
}
None => log_l.clone(),
};
@@ -1818,6 +1868,76 @@ mod tests {
time("guided sigma=1.75", &mut |cx| drop(guided(cx, &src, w, h, 1.75, 0.01)));
}
/// The tiled median kernels select exactly what the CPU's sorted window does: edge tiles,
/// planes smaller than a tile or a window, every radius and many ties.
#[test]
fn median_matches_cpu_bit_for_bit() {
// (creating the device writes the crash sentinel another test swaps out)
let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let Some(gpu) = crate::device() else { return lightcraft_testkit::skip!(Gpu, "no GPU adapter") };
let _scope = crate::ctx::RenderScope::new(gpu);
let mut seed = 0x9e37_79b9_u32;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
seed
};
for (w, h) in [(1, 1), (2, 3), (5, 70), (70, 5), (63, 65), (130, 67), (200, 129)] {
// a coarse level set gives ties; a smooth ramp and fine noise give distinct values
let mut p = Plane::new(w, h);
for (i, o) in p.data.iter_mut().enumerate() {
let (x, y) = (i % w, i / w);
*o = match (next() % 3, next()) {
(0, v) => (v % 7) as f32 * 0.5 - 2.0,
(1, v) => (x + 2 * y) as f32 * 0.01 + (v % 100) as f32 * 1e-4,
(_, v) => (v % 10_000) as f32 * 1e-3 - 5.0,
};
}
let src = gpu.upload(&p.data);
for r in 1..=local::BASE_DETAIL_MAX {
let mut cx = Cx::new(gpu);
let out = median_hv(&mut cx, &src, w, h, r);
let got: Vec<f32> = cx.read(&out, w * h);
let want = local::median_hv(&p, r);
let bad = got.iter().zip(&want.data).position(|(g, c)| g.to_bits() != c.to_bits());
assert!(bad.is_none(), "{w}×{h} r={r}: pixel {bad:?}");
}
}
}
/// Highlights/shadows base timings on the #3460 frame size:
/// `cargo test --release -p lightcraft-gpu bench_tone_base -- --ignored --nocapture`.
#[test]
#[ignore]
fn bench_tone_base() {
let Some(gpu) = crate::device() else { return eprintln!("no gpu: {:?}", crate::unavailable_reason()) };
let _scope = crate::ctx::RenderScope::new(gpu);
let (w, h) = (6960, 4640);
let r = local::base_detail_radius(w as f64);
eprintln!("{} ({:?}) r={r}", gpu.info.name, gpu.info.backend);
let l: Vec<f32> = (0..w * h).map(|i: usize| ((i.wrapping_mul(2_654_435_761)) % 1000) as f32 / 250.0 - 6.0).collect();
let src = gpu.upload(&l);
let time = |name: &str, f: &mut dyn FnMut(&mut Cx<'_>)| {
let mut ts = Vec::new();
for _ in 0..9 {
let mut cx = Cx::new(gpu);
cx.sync();
let t = std::time::Instant::now();
f(&mut cx);
cx.sync();
ts.push(t.elapsed().as_secs_f64() * 1e3);
}
ts.sort_by(f64::total_cmp);
eprintln!("{name:<40} min {:.1} ms median {:.1} ms", ts[0], ts[4]);
};
let sigma = 0.015 * w as f32;
time("median_hv", &mut |cx| drop(median_hv(cx, &src, w, h, r)));
time("detail_free", &mut |cx| drop(detail_free(cx, &src, w, h, r)));
time("guided_fast", &mut |cx| drop(guided_fast(cx, &src, w, h, sigma, local::BASE_EPS)));
time("tone_base", &mut |cx| drop(tone_base(cx, &src, w, h, sigma, r, true)));
}
/// The device scores Remove's candidate sources like the CPU and picks the same one.
#[test]
fn auto_source_picks_the_cpu_candidate() {
+89 -31
View File
@@ -113,56 +113,114 @@ fn minmax(@builtin(global_invocation_id) g: vec3<u32>) {
}
// Separable median of a single-channel plane (`lightcraft_pipeline::local::median_hv`): 2r+1
// taps (r ≤ 24, clamped edges) along a row (median_h) or a column (median_v), one thread per
// pixel. The median is a selection, so the result matches the CPU's bit for bit.
// taps (1 ≤ r ≤ 24, clamped edges) along a row (median_h) or a column (median_v). The median is a
// selection, so the result matches the CPU's bit for bit.
// P: w, h, nc (unused), r.
fn median_of(n: u32, r: u32, v: ptr<function, array<f32, 49>>) -> f32 {
// partial selection sort up to the middle
for (var i = 0u; i <= r; i++) {
var m = i;
for (var j = i + 1u; j < n; j++) {
if ((*v)[j] < (*v)[m]) {
m = j;
}
//
// Each thread finds the medians of 4 neighbouring pixels along the pass by rank: a tap is the
// median of a window when fewer than r+1 of its taps are smaller and at least r+1 are smaller or
// equal. The 4 windows share all but their first and last 3 taps, so one count over the shared
// taps serves all four. A 16×16 workgroup (64 pixels along the pass, 16 lines across) first loads
// its taps into `med_tile`. On a 6960×4640 plane at r = 10 this takes 47 ms on an M2 Max, against
// 191 ms for a partial selection sort per pixel over a private array of taps, which drivers keep in
// scratch memory because it is indexed dynamically.
const MED_K: u32 = 4u;
const MED_LINE: u32 = 113u; // 16·MED_K + 2·24, odd
// Not zero-initialised (`build_jobs` in ctx.rs turns that off): write every element read.
var<workgroup> med_tile: array<f32, 1808>; // 16 lines
// The medians of the 2r+1-tap windows starting at `med_tile[base + k]`, k < 4 (r ≥ 1). Taps 3 to
// n-1 are in all four windows; the three at each end are in some.
fn median4(base: u32, r: u32) -> vec4<f32> {
let n = 2u * r + 1u;
let e0 = vec3<f32>(med_tile[base], med_tile[base + 1u], med_tile[base + 2u]);
let e1 = vec3<f32>(med_tile[base + n], med_tile[base + n + 1u], med_tile[base + n + 2u]);
var out = vec4<f32>(0.0);
var found = vec4<bool>(false);
for (var i = 0u; i < n + 3u; i++) {
let c = med_tile[base + i];
var less = 0u;
var le = 0u;
for (var j = 3u; j < n; j++) {
let v = med_tile[base + j];
less += select(0u, 1u, v < c);
le += select(0u, 1u, v <= c);
}
let l0 = select(vec3<u32>(0u), vec3<u32>(1u), e0 < vec3<f32>(c));
let l1 = select(vec3<u32>(0u), vec3<u32>(1u), e1 < vec3<f32>(c));
let q0 = select(vec3<u32>(0u), vec3<u32>(1u), e0 <= vec3<f32>(c));
let q1 = select(vec3<u32>(0u), vec3<u32>(1u), e1 <= vec3<f32>(c));
// window k: taps k..k+n-1 = taps k..2 of the start, the middle, taps n..n+k-1 of the end
let lw = vec4<u32>(l0.x + l0.y + l0.z, l0.y + l0.z + l1.x, l0.z + l1.x + l1.y, l1.x + l1.y + l1.z) + vec4<u32>(less);
let qw = vec4<u32>(q0.x + q0.y + q0.z, q0.y + q0.z + q1.x, q0.z + q1.x + q1.y, q1.x + q1.y + q1.z) + vec4<u32>(le);
let has = vec4<bool>((i < n), (i >= 1u) && (i < n + 1u), (i >= 2u) && (i < n + 2u), (i >= 3u));
let hit = has & !found & (lw <= vec4<u32>(r)) & (qw > vec4<u32>(r));
out = select(out, vec4<f32>(c), hit);
found = found | hit;
if (all(found)) {
break;
}
let t = (*v)[i];
(*v)[i] = (*v)[m];
(*v)[m] = t;
}
return (*v)[r];
return out;
}
// Thread (l.x, l.y) of a workgroup takes line l.x and pixels 4·l.y to 4·l.y + 3 along it, so the
// threads of a SIMD group read 16 different lines at once; with an odd line length those fall in
// different banks of workgroup memory.
@compute @workgroup_size(16, 16)
fn median_h(@builtin(global_invocation_id) g: vec3<u32>) {
fn median_h(@builtin(local_invocation_id) l: vec3<u32>, @builtin(workgroup_id) wg: vec3<u32>) {
let w = pu(0u);
let h = pu(1u);
let r = min(pu(3u), 24u);
if (g.x >= w || g.y >= h) {
let span = 16u * MED_K + 2u * r;
let x0 = i32(wg.x * 16u * MED_K) - i32(r);
// load: consecutive threads read consecutive pixels of a row
for (var e = l.y * 16u + l.x; e < 16u * span; e += 256u) {
let line = e / span;
let k = e % span;
let y = min(wg.y * 16u + line, h - 1u);
let x = clamp(x0 + i32(k), 0, i32(w) - 1);
med_tile[line * MED_LINE + k] = src[y * w + u32(x)];
}
workgroupBarrier();
let y = wg.y * 16u + l.x;
let x = (wg.x * 16u + l.y) * MED_K;
if (x >= w || y >= h) {
return;
}
let n = 2u * r + 1u;
var v: array<f32, 49>;
let row = g.y * w;
for (var k = 0u; k < n; k++) {
let x = clamp(i32(g.x + k) - i32(r), 0, i32(w) - 1);
v[k] = src[row + u32(x)];
let m = median4(l.x * MED_LINE + l.y * MED_K, r);
for (var k = 0u; k < MED_K; k++) {
if (x + k < w) {
dst[y * w + x + k] = m[k];
}
}
dst[row + g.x] = median_of(n, r, &v);
}
@compute @workgroup_size(16, 16)
fn median_v(@builtin(global_invocation_id) g: vec3<u32>) {
fn median_v(@builtin(local_invocation_id) l: vec3<u32>, @builtin(workgroup_id) wg: vec3<u32>) {
let w = pu(0u);
let h = pu(1u);
let r = min(pu(3u), 24u);
if (g.x >= w || g.y >= h) {
let span = 16u * MED_K + 2u * r;
let y0 = i32(wg.y * 16u * MED_K) - i32(r);
// load: consecutive threads read consecutive pixels of a row (16 columns)
for (var e = l.y * 16u + l.x; e < 16u * span; e += 256u) {
let line = e % 16u;
let k = e / 16u;
let x = min(wg.x * 16u + line, w - 1u);
let y = clamp(y0 + i32(k), 0, i32(h) - 1);
med_tile[line * MED_LINE + k] = src[u32(y) * w + x];
}
workgroupBarrier();
let x = wg.x * 16u + l.x;
let y = (wg.y * 16u + l.y) * MED_K;
if (x >= w || y >= h) {
return;
}
let n = 2u * r + 1u;
var v: array<f32, 49>;
for (var k = 0u; k < n; k++) {
let y = clamp(i32(g.y + k) - i32(r), 0, i32(h) - 1);
v[k] = src[u32(y) * w + g.x];
let m = median4(l.x * MED_LINE + l.y * MED_K, r);
for (var k = 0u; k < MED_K; k++) {
if (y + k < h) {
dst[(y + k) * w + x] = m[k];
}
}
dst[g.y * w + g.x] = median_of(n, r, &v);
}
+73 -10
View File
@@ -291,6 +291,65 @@ fn ghash(i: i32, j: i32, seed: u32) -> f32 {
return f32(v & 0xffffu) / 32768.0 - 1.0;
}
// Crystal grain (process V4): `lightcraft_pipeline::crystal` (keep in step with it). The tori's
// summed-area tables follow the other tables in `aux` (offsets F_GRAIN_SAT).
fn cg_bilinear(o: u32, t: u32, x: f32, y: f32) -> f32 {
let s = t + 1u;
let i = min(u32(max(x, 0.0)), t - 1u);
let j = min(u32(max(y, 0.0)), t - 1u);
let fx = x - f32(i);
let fy = y - f32(j);
let b = o + j * s + i;
let a = aux[b] + (aux[b + 1u] - aux[b]) * fx;
let c = aux[b + s] + (aux[b + s + 1u] - aux[b + s]) * fx;
return a + (c - a) * fy;
}
fn cg_integral(o: u32, t: u32, x: f32, y: f32) -> f32 {
let tf = f32(t);
let wx = x >= tf;
let wy = y >= tf;
let rx = select(x, x - tf, wx);
let ry = select(y, y - tf, wy);
var v = cg_bilinear(o, t, rx, ry);
if (wx) {
v += cg_bilinear(o, t, tf, ry);
}
if (wy) {
v += cg_bilinear(o, t, rx, tf);
}
if (wx && wy) {
v += cg_bilinear(o, t, tf, tf);
}
return v;
}
fn cg_box(o: u32, t: u32, x0_: f32, y0_: f32, w: f32) -> f32 {
let tf = f32(t);
let x0 = x0_ - floor(x0_ / tf) * tf;
let y0 = y0_ - floor(y0_ / tf) * tf;
return cg_integral(o, t, x0 + w, y0 + w) - cg_integral(o, t, x0, y0 + w) - cg_integral(o, t, x0 + w, y0) + cg_integral(o, t, x0, y0);
}
fn cg_lift(v: f32) -> f32 {
let c = clamp(v, 0.0, 1.0);
return select((c + 0.055) / 2.4, c, c <= 0.04045);
}
fn cg_srgb_to_linear(v: f32) -> f32 {
return select(pow((v + 0.055) / 1.055, 2.4), v / 12.92, v <= 0.04045);
}
fn crystal_grain(e: vec3<f32>, gx: f32, gy: f32) -> vec3<f32> {
let w = pf(F_GRAIN_FOOT);
let x0 = gx * CRYSTAL_TPL - 0.5 * w;
let y0 = gy * CRYSTAL_TPL - 0.5 * w;
let g = (cg_box(pu(F_GRAIN_SAT), CRYSTAL_T0, x0, y0, w) + cg_box(pu(F_GRAIN_SAT + 1u), CRYSTAL_T1, x0, y0, w)) / (w * w);
let lum = clamp(0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z, 0.0, 1.0);
let k = pf(F_GRAIN_K) * g * (1.0 - cg_srgb_to_linear(lum));
return e + k * vec3<f32>(cg_lift(e.x), cg_lift(e.y), cg_lift(e.z));
}
fn grain_noise(x: f32, y: f32, seed: u32) -> f32 {
let x0 = floor(x);
let y0 = floor(y);
@@ -694,17 +753,21 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let py = f32(y) + 0.5;
let gx = pf(F_GRAIN_AFF) * px + pf(F_GRAIN_AFF + 2u) * py + pf(F_GRAIN_AFF + 4u);
let gy = pf(F_GRAIN_AFF + 1u) * px + pf(F_GRAIN_AFF + 3u) * py + pf(F_GRAIN_AFF + 5u);
let sc = pf(F_GRAIN_SC);
let rough = pf(F_GRAIN_ROUGH);
let seed = pu(F_GRAIN_SEED);
var g = grain_noise(gx * sc, gy * sc, seed);
g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55u) * rough * 0.7;
var lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z;
if (hdr) {
lum = clamp(lum, 0.0, 1.0);
if (pu(F_GRAIN_MODEL) == 1u) {
e = crystal_grain(e, gx, gy);
} else {
let sc = pf(F_GRAIN_SC);
let rough = pf(F_GRAIN_ROUGH);
let seed = pu(F_GRAIN_SEED);
var g = grain_noise(gx * sc, gy * sc, seed);
g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55u) * rough * 0.7;
var lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z;
if (hdr) {
lum = clamp(lum, 0.0, 1.0);
}
let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum));
e = e + k;
}
let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum));
e = e + k;
}
if (pu(F_LUT) != 0u) {
let lc = clamp(e, vec3<f32>(0.0), vec3<f32>(1.0));
+19
View File
@@ -70,6 +70,25 @@ fn guided_apply(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgr
dst[i] = b[2u * i] * a[i] + b[2u * i + 1u];
}
// `clamp_between` (`local::detail_free`): a clamped between b and c, in either order.
@compute @workgroup_size(256)
fn clamp_between_k(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
let i = lin_index(g, nw);
if (i >= pu(0u)) {
return;
}
let lo = min(b[i], c[i]);
let hi = max(b[i], c[i]);
let v = a[i];
if (v < lo) {
dst[i] = lo;
} else if (v > hi) {
dst[i] = hi;
} else {
dst[i] = v;
}
}
// Cross guided filter (`masks::guided_cross`), a: guide, b: input. P[1] = 0: (guide, input);
// 1: (guide·input, guide²).
@compute @workgroup_size(256)
+48 -2
View File
@@ -210,6 +210,33 @@ fn banded_full_size_render_matches() {
check("banded 3000×2000", &src, &SourceInfo { raw: true, ..Default::default() }, &s, &RenderRequest::fit(w, h));
}
/// The crystal grain's tables stay on the GPU between renders: an Amount change reuses them,
/// another pattern (Size, Roughness, seed) replaces them, and going back draws the first again.
#[test]
fn grain_patterns_in_turn_match() {
if !gpu() {
return;
}
let src = scene(1, 480, 320);
let info = SourceInfo { raw: true, ..Default::default() };
let steps: [(&str, f64, f64, f64, u32); 6] = [
("grain 50/25/50", 50.0, 25.0, 50.0, 1),
("grain 90/25/50 (same pattern)", 90.0, 25.0, 50.0, 1),
("grain 50/70/50 (new size)", 50.0, 70.0, 50.0, 1),
("grain 50/70/0 (new roughness)", 50.0, 70.0, 0.0, 1),
("grain 50/70/0 seed 7", 50.0, 70.0, 0.0, 7),
("grain 50/25/50 again", 50.0, 25.0, 50.0, 1),
];
for (name, amount, size, roughness, seed) in steps {
let mut s = DevelopSettings::default();
s.grain.amount = amount;
s.grain.size = size;
s.grain.roughness = roughness;
s.grain.seed = seed;
check(name, &src, &info, &s, &RenderRequest::fit(480, 320));
}
}
fn cases() -> Vec<(&'static str, Edit)> {
vec![
("default", |_| {}),
@@ -287,6 +314,25 @@ fn cases() -> Vec<(&'static str, Edit)> {
s.grain.size = 40.0;
s.grain.roughness = 60.0;
}),
// the frozen value-noise grain of the earlier processes (the default is V7's crystals)
("grain, process V6", |s| {
s.process = Process::V6.version();
s.grain.amount = 50.0;
s.grain.size = 40.0;
s.grain.roughness = 60.0;
}),
("grain, process V1", |s| {
s.process = Process::V1.version();
s.grain.amount = 50.0;
s.grain.size = 40.0;
s.grain.roughness = 60.0;
}),
("grain, process V2", |s| {
s.process = Process::V2.version();
s.grain.amount = 50.0;
s.grain.size = 40.0;
s.grain.roughness = 60.0;
}),
("dehaze -", |s| s.effects.dehaze = -50.0),
("dehaze +", |s| s.effects.dehaze = 60.0),
("clarity/texture -", |s| {
@@ -761,7 +807,7 @@ fn light_v3_operators_match() {
}
/// Issue #632: the Highlights / Shadows base of each process (V1: the edge-aware filter of log
/// luminance; V2: of its fine median, a radius that grows with the render) matches the CPU's, and
/// luminance; V2 to V7: of its fine median, V8 on: of its detail-free plane, a radius that grows with the render) matches the CPU's, and
/// a warm cache never hands one process the other's base.
#[test]
fn highlights_shadows_base_matches_on_every_process() {
@@ -792,7 +838,7 @@ fn highlights_shadows_base_matches_on_every_process() {
}];
check(&format!("{p:?} local highlights {w}"), &src, &raw, &s, &req);
}
for p in [Process::V1, Process::V2, Process::V4, Process::V1, Process::V2, Process::V4] {
for p in [Process::V1, Process::V2, Process::V4, Process::V8, Process::V1, Process::V2, Process::V4, Process::V8] {
let mut s = DevelopSettings { process: p.version(), ..DevelopSettings::default() };
s.light.highlights = -100.0;
let warm = lightcraft_gpu::render(&src, &raw, &s, &req, Some(&cache)).expect("gpu");
+81 -4
View File
@@ -162,13 +162,22 @@ fn probe_unguarded(bytes: &[u8]) -> Result<Info, Error> {
// items (`iloc` construction method 2) is rebuilt once per extent, so a chain of such items
// multiplies at every level while each result stays small. Count those visits from the
// `iloc` table before reconstructing anything: the primary item first (`heic_rs::probe` and
// `Context::grid` both rebuild its descriptor), then its alpha plane, then every tile
// reference, repeats included.
// `Context::grid` both rebuild its descriptor), then its alpha plane and, when that is a grid,
// its tiles, then every tile reference, repeats included.
let mut visits = 0_usize;
item_visits(&ctx, id, 0, &mut visits)?;
// `heic_rs::probe` reads an item without `ispe` from its parameter sets
check_item_parameter_sets(&ctx.props(id).map_err(err)?)?;
let info = heic_rs::probe(bytes).map_err(open_error)?;
if let Some(alpha) = ctx.alpha_item(id).map_err(err)? {
let alpha = ctx.alpha_item(id).map_err(err)?;
if let Some(alpha) = alpha {
item_visits(&ctx, alpha, 0, &mut visits)?;
// an alpha plane may be a grid too: its tiles are rebuilt when it is decoded
if let Some((_, tiles)) = ctx.grid(alpha).map_err(err)? {
for &tile in tiles.iter().filter(|&&tile| tile != alpha) {
item_visits(&ctx, tile, 0, &mut visits)?;
}
}
}
let mut coded = match ctx.grid(id).map_err(err)? {
Some((_, tiles)) => tiles,
@@ -257,6 +266,25 @@ pub fn decode_thumbnail(bytes: &[u8], min_edge: u32, options: &Options) -> Resul
continue;
}
let Ok(p) = ctx.props(r.from) else { continue };
if check_item_parameter_sets(&p).is_err() {
continue;
}
// A grid whose tile would fail the same check must not win and then fail in
// `decode_item`, with no fallback to a larger valid thumbnail.
let grid = match ctx.grid(r.from) {
Ok(grid) => grid,
// an unreadable grid fails in `decode_item` too: not a candidate
Err(_) => continue,
};
if let Some((_, tiles)) = grid {
let mut seen = std::collections::HashSet::new();
let tiles_ok = tiles.iter().filter(|t| seen.insert(**t)).all(|&t| {
item_visits(&ctx, t, 0, &mut candidate_visits).is_ok() && ctx.props(t).is_ok_and(|tp| check_item_parameter_sets(&tp).is_ok())
});
if !tiles_ok {
continue;
}
}
let Ok((w, h)) = ctx.coded_size(r.from, &p) else { continue };
let edge = w.max(h);
if edge >= min_edge && best.is_none_or(|(_, e)| edge < e) {
@@ -316,7 +344,9 @@ fn decode_item(ctx: &Context<'_>, id: u32, options: &Options, with_alpha: bool)
return Err(Error::Limit(format!("the image carries {} transform properties, over the {MAX_TRANSFORMS}-property cap", p.transforms.len())));
}
let limit = options.max_pixels;
// The declared sizes are refused before anything is decoded or allocated.
// The declared sizes are refused before anything is decoded or allocated (an item without
// `ispe` takes its size from its parameter sets, checked first).
check_item_parameter_sets(&p)?;
let (cw, ch) = ctx.coded_size(id, &p).map_err(err)?;
heic_rs::image::check_pixels(cw, ch, limit).map_err(err)?;
let (tw, th) = heic_rs::transform::transformed_size(cw, ch, &p.transforms).map_err(err)?;
@@ -376,6 +406,44 @@ const GRID_BUDGET: u64 = 2;
/// most one of each, so anything approaching this is a reordered or hostile association list.
const MAX_TRANSFORMS: usize = 12;
/// The most parameter sets one `hvcC` may carry: one per id H.265 allows (16 VPS, 16 SPS, 64 PPS).
/// heic-rs 0.1.4 replaces a repeated id by scanning every set kept so far, so more sets (repeats,
/// or ids past the standard's range) only make that collection quadratic.
const MAX_PARAMETER_SETS: usize = 16 + 16 + 64;
/// Highest `pps_pic_parameter_set_id` H.265 allows (7.4.3.3.1).
const MAX_PPS_ID: u32 = 63;
/// Most tile columns and rows a picture may have: H.265's level limits (Table A.8, levels 6 to
/// 6.2). heic-rs 0.1.4 builds its tile tables by walking the tile boundaries for every coding tree
/// block, so its work grows with blocks × tiles; these keep that a small multiple of the blocks.
const MAX_TILE_COLS: u32 = 20;
const MAX_TILE_ROWS: u32 = 22;
/// Refuses parameter sets that would make heic-rs's set collection or tile tables cost far more
/// than the picture: too many sets, a PPS id out of range, or more tiles than any level allows.
fn check_parameter_sets(sets: &[&[u8]]) -> Result<(), Error> {
if sets.len() > MAX_PARAMETER_SETS {
return Err(Error::Limit(format!("the hvcC record carries {} parameter sets, over the {MAX_PARAMETER_SETS}-set cap", sets.len())));
}
let layouts = vui::pps_layouts(sets).ok_or_else(|| Error::Malformed("unreadable picture parameter set".into()))?;
for p in layouts {
if p.id > MAX_PPS_ID {
return Err(Error::Malformed(format!("picture parameter set id {} is out of range", p.id)));
}
if p.tile_cols > MAX_TILE_COLS || p.tile_rows > MAX_TILE_ROWS {
return Err(Error::Limit(format!(
"a picture of {} × {} tiles, over the {MAX_TILE_COLS} × {MAX_TILE_ROWS} H.265 allows",
p.tile_cols, p.tile_rows
)));
}
}
Ok(())
}
/// [`check_parameter_sets`] of a coded item's `hvcC`, if it has one.
fn check_item_parameter_sets(p: &ItemProps<'_>) -> Result<(), Error> {
p.hvcc.as_ref().map_or(Ok(()), |h| check_parameter_sets(&h.parameter_sets()))
}
/// The decoded pictures of an item: one, or a grid's tiles in `dimg` order.
struct Coded<'a> {
frames: Vec<Frame>,
@@ -400,15 +468,24 @@ impl<'a> Coded<'a> {
// conformance window (or a slice picking another SPS) can make far larger than the
// declared one, and a grid holds all its tiles at once. Both are refused before decoding.
let mut total = 0u64;
// A grid may list one tile thousands of times: each distinct tile is read and checked
// once, so the work follows the file's items, not the grid's cell count.
let mut largest_of: std::collections::HashMap<u32, u64> = std::collections::HashMap::new();
for t in &ids {
if let Some(largest) = largest_of.get(t) {
total = total.saturating_add(*largest);
continue;
}
let tp = ctx.props(*t).map_err(err)?;
let hvcc = tp.hvcc.as_ref().ok_or(heic_rs::Error::MissingBox("hvcC")).map_err(err)?;
check_parameter_sets(&hvcc.parameter_sets())?;
let sizes = vui::coded_sizes(&hvcc.parameter_sets()).ok_or_else(|| Error::Malformed("unreadable sequence parameter set".into()))?;
let mut largest = 0u64;
for (w, h) in sizes {
heic_rs::image::check_pixels(w, h, limit).map_err(err)?;
largest = largest.max(u64::from(w) * u64::from(h));
}
largest_of.insert(*t, largest);
total = total.saturating_add(largest);
}
if total > limit.saturating_mul(GRID_BUDGET) {
+29 -2
View File
@@ -47,11 +47,25 @@ pub struct Spec<'a> {
pub thumbnail: Option<Sampler<'a>>,
/// Auxiliary images of these types the decoder must ignore (HDR gain map, depth…).
pub ignored_aux: Vec<&'static str>,
/// When nonzero, the alpha image is instead a grid of `n` × `n` references to one alpha tile
/// (a hostile file: the same stored picture rebuilt for every reference).
pub alpha_tile_repeats: u8,
}
impl<'a> Spec<'a> {
pub fn new(width: u32, height: u32, sample: Sampler<'a>) -> Spec<'a> {
Spec { width, height, bit_depth: 8, sample, props: Vec::new(), exif: None, alpha: None, thumbnail: None, ignored_aux: Vec::new() }
Spec {
width,
height,
bit_depth: 8,
sample,
props: Vec::new(),
exif: None,
alpha: None,
thumbnail: None,
ignored_aux: Vec::new(),
alpha_tile_repeats: 0,
}
}
}
@@ -524,7 +538,20 @@ pub fn build(spec: &Spec<'_>) -> Vec<u8> {
}
f.refs.push((b"auxl", id, vec![primary]));
};
if let Some(alpha) = spec.alpha {
if let (Some(alpha), n @ 1..) = (spec.alpha, spec.alpha_tile_repeats) {
let tile = f.image(TILE, TILE, bd, true, &|x, y| [alpha(x, y), 0, 0]);
if let Some(it) = f.items.iter_mut().find(|i| i.id == tile) {
it.hidden = true;
}
let side = u32::from(n) * TILE;
let mut g = vec![0u8, 0, n - 1, n - 1];
g.extend_from_slice(&(side as u16).to_be_bytes());
g.extend_from_slice(&(side as u16).to_be_bytes());
let auxc = f.prop(full_box(b"auxC", 0, b"urn:mpeg:hevc:2015:auxid:1\0"));
let id = f.add(b"grid", g, vec![(auxc, true)]);
f.refs.push((b"dimg", id, vec![tile; usize::from(n) * usize::from(n)]));
f.refs.push((b"auxl", id, vec![primary]));
} else if let Some(alpha) = spec.alpha {
aux(&mut f, "urn:mpeg:hevc:2015:auxid:1", &|x, y| [alpha(x, y), 0, 0]);
}
for urn in &spec.ignored_aux {
+14
View File
@@ -139,6 +139,20 @@ fn alpha_comes_from_its_auxiliary_image() {
assert_eq!(d.data[..3], [luma(0, 0) * 257; 3]);
}
#[test]
fn an_alpha_grid_decodes_and_its_tile_references_share_the_visit_budget() {
let alpha = |x: u32, _: u32| (x * 4) as u16;
// a 2 × 2 alpha grid naming one tile four times: a valid file
let d = decoded(&Spec { alpha: Some(&alpha), alpha_tile_repeats: 2, ..Spec::new(64, 64, &grey) });
assert!(d.has_alpha);
assert_eq!((d.data[10 * 4 + 3], d.data[42 * 4 + 3]), (40 * 257, 40 * 257));
// 70 × 70 references to that tile: each would be rebuilt and decoded, so it is refused first
let bytes = build(&Spec { alpha: Some(&alpha), alpha_tile_repeats: 70, ..Spec::new(32, 32, &grey) });
for r in [probe(&bytes).map(|_| ()), decode(&bytes, &Options::default()).map(|_| ())] {
assert!(matches!(&r, Err(Error::Limit(m)) if m.contains("extent reads")), "{r:?}");
}
}
#[test]
fn limits_are_checked_before_decoding() {
let bytes = build(&Spec::new(96, 64, &grey));
+108
View File
@@ -49,6 +49,55 @@ pub fn coded_sizes(parameter_sets: &[&[u8]]) -> Option<Vec<(u32, u32)>> {
.collect()
}
/// NAL unit type of a picture parameter set.
const PPS_NUT: u8 = 34;
/// What [`pps_layouts`] reads of a picture parameter set.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PpsLayout {
/// `pps_pic_parameter_set_id`.
pub id: u32,
/// `num_tile_columns_minus1 + 1` (1 without tiles).
pub tile_cols: u32,
/// `num_tile_rows_minus1 + 1` (1 without tiles).
pub tile_rows: u32,
}
/// The id and tile layout of every PPS among `parameter_sets`, read up to the tile counts
/// (H.265 7.3.2.3.1). `None`: a PPS this reader can't follow.
pub fn pps_layouts(parameter_sets: &[&[u8]]) -> Option<Vec<PpsLayout>> {
parameter_sets
.iter()
.filter(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == PPS_NUT))
.map(|pps| {
let rbsp = unescape(pps.get(2..)?);
pps_layout(&mut Bits { data: &rbsp, pos: 0 })
})
.collect()
}
fn pps_layout(r: &mut Bits) -> Option<PpsLayout> {
let id = r.ue()?; // pps_pic_parameter_set_id
r.ue()?; // pps_seq_parameter_set_id
// dependent slices, output flag, 3 extra slice header bits, sign hiding, cabac_init_present
r.skip(7)?;
r.ue()?; // num_ref_idx_l0_default_active_minus1
r.ue()?; // num_ref_idx_l1_default_active_minus1
r.se()?; // init_qp_minus26
r.skip(2)?; // constrained_intra_pred_flag, transform_skip_enabled_flag
if r.flag()? {
r.ue()?; // diff_cu_qp_delta_depth
}
r.se()?; // pps_cb_qp_offset
r.se()?; // pps_cr_qp_offset
// slice chroma qp offsets present, weighted pred, weighted bipred, transquant bypass
r.skip(4)?;
let tiles = r.flag()?; // tiles_enabled_flag
r.skip(1)?; // entropy_coding_sync_enabled_flag
let (tile_cols, tile_rows) = if tiles { (r.ue()?.checked_add(1)?, r.ue()?.checked_add(1)?) } else { (1, 1) };
Some(PpsLayout { id, tile_cols, tile_rows })
}
/// Reads an SPS up to and including the picture size, leaving `r` after it: width, height and
/// `sps_max_sub_layers_minus1`.
fn sps_size(r: &mut Bits) -> Option<(u32, u32, u32)> {
@@ -456,4 +505,63 @@ mod tests {
}
assert_eq!(signal(&[&[SPS_NUT << 1, 1, 0xff, 0xff, 0xff]]), None);
}
/// A PPS NAL as encoders write it, with `tiles` (columns, rows) when tiles are enabled.
fn pps(id: u32, cu_qp_delta: bool, tiles: Option<(u32, u32)>) -> Vec<u8> {
let mut w = Writer::default();
w.ue(id);
w.ue(0); // sps id
w.u(0, 7);
w.ue(0);
w.ue(0);
w.ue(3); // init_qp_minus26 = -2
w.u(0, 2);
w.u(u32::from(cu_qp_delta), 1);
if cu_qp_delta {
w.ue(1);
}
w.ue(1); // cb offset +1
w.ue(2); // cr offset -1
w.u(0, 4);
w.u(u32::from(tiles.is_some()), 1);
w.u(0, 1);
if let Some((c, r)) = tiles {
w.ue(c - 1);
w.ue(r - 1);
w.u(1, 1); // uniform spacing
w.u(1, 1);
}
w.u(0, 3);
[vec![PPS_NUT << 1, 1], w.bytes()].concat()
}
#[test]
fn reads_pps_ids_and_tile_counts() {
let plain = pps(5, true, None);
let tiled = pps(63, false, Some((4, 3)));
let sps_nal = sps(|w| w.u(0, 1), |w| w.ue(0));
assert_eq!(
pps_layouts(&[&sps_nal, &plain, &tiled]),
Some(vec![PpsLayout { id: 5, tile_cols: 1, tile_rows: 1 }, PpsLayout { id: 63, tile_cols: 4, tile_rows: 3 }])
);
assert_eq!(pps_layouts(&[&[PPS_NUT << 1, 1]]), None);
assert!(crate::check_parameter_sets(&[&sps_nal, &plain, &tiled]).is_ok());
assert!(crate::check_parameter_sets(&[&pps(0, false, Some((20, 22)))]).is_ok());
}
#[test]
fn refuses_parameter_sets_that_multiply_decoder_work() {
// a PPS id past 63: heic-rs would keep every distinct one and rescan them all for each
let r = crate::check_parameter_sets(&[&pps(64, false, None)]);
assert!(matches!(r, Err(crate::Error::Malformed(_))), "{r:?}");
// thousands of PPS records (even with valid, repeated ids): quadratic collection
let one = pps(1, false, None);
let many: Vec<&[u8]> = vec![&one; 5000];
assert!(matches!(crate::check_parameter_sets(&many), Err(crate::Error::Limit(_))));
// more tiles than any H.265 level allows: tile tables cost blocks × tiles
for (c, r) in [(21, 1), (1, 23), (1024, 1024)] {
let r = crate::check_parameter_sets(&[&pps(0, false, Some((c, r)))]);
assert!(matches!(r, Err(crate::Error::Limit(_))), "{r:?}");
}
}
}
+10
View File
@@ -169,6 +169,10 @@ pub fn membrane_fill(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool])
if Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) {
return img.to_vec();
}
// no pixels: nothing to fill (and `ch` would otherwise size one plane per channel, whatever it claims)
if hole.is_empty() {
return img.to_vec();
}
per_channel(w, h, ch, |c| {
let mut v: Vec<f32> = (0..w * h).map(|i| if hole[i] { 0.0 } else { img[i * ch + c] }).collect();
solve_membrane(w, h, hole, &mut v);
@@ -183,6 +187,12 @@ mod tests {
(0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect()
}
#[test]
fn a_zero_area_image_comes_back_unchanged_whatever_its_channel_count() {
assert!(membrane_fill(0, 5, usize::MAX, &[], &[]).is_empty());
assert!(membrane_fill(3, 0, 1 << 40, &[], &[]).is_empty());
}
#[test]
fn membrane_reproduces_linear_boundary() {
// A linear function is harmonic: the solve must reproduce it exactly inside the hole.
+23 -1
View File
@@ -53,13 +53,21 @@ fn entity(name: &str) -> Option<char> {
})
}
/// Index of the `;` that ends a reference starting at `rest` (its `&`). The scan stops at the first
/// byte that cannot appear in a name or a numeric reference, so zero-padded references such as
/// `&#000000097;` are found and each run of name bytes is read once, not once per `&`.
fn entity_end(rest: &str) -> Option<usize> {
let n = rest.bytes().skip(1).take_while(|b| b.is_ascii_alphanumeric() || *b == b'#').count();
(rest.as_bytes().get(n + 1) == Some(&b';')).then_some(n + 1)
}
fn unescape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(i) = rest.find('&') {
out.push_str(rest.get(..i).unwrap_or_default());
let tail = rest.get(i..).unwrap_or_default();
match tail.find(';').and_then(|j| entity(tail.get(1..j)?).map(|c| (c, j))) {
match entity_end(tail).and_then(|j| entity(tail.get(1..j)?).map(|c| (c, j))) {
Some((c, j)) => {
out.push(c);
rest = tail.get(j + 1..).unwrap_or_default();
@@ -140,6 +148,20 @@ fn close(stack: &mut Vec<Node>) {
mod tests {
use super::*;
#[test]
fn many_ampersands_before_one_semicolon_are_read_once() {
// 200 000 `&` then a `;`: each `&` once searched the whole rest for the `;`
let hostile = format!("{};&amp;", "&".repeat(200_000));
assert_eq!(unescape(&hostile), format!("{};&", "&".repeat(200_000)));
assert_eq!(unescape("&lt;a&gt; &#x10FFFF; &unknownreference;"), "<a> \u{10FFFF} &unknownreference;");
}
#[test]
fn zero_padded_numeric_references_decode() {
assert_eq!(unescape("C&#0000000097;non &#x0000041; &#000000065;"), "Canon A A");
assert_eq!(unescape("&abc&#xyz;&;"), "&abc&#xyz;&;");
}
#[test]
fn entity_rejects_signed_numeric_references() {
assert_eq!(entity("#+65"), None);
+4
View File
@@ -119,6 +119,10 @@ pub fn merge_hdr(mut frames: Vec<Frame>, opts: &HdrOptions, progress: &Progress)
if frames.iter().any(|f| f.width() != w || f.height() != h) {
return Err(MergeError::Mismatch("HDR merge needs photos of the same size".into()));
}
// every buffer must hold exactly its frame's pixels before anything is sized from the dimensions
if frames.iter().any(|f| w.checked_mul(h) != Some(f.image.data.len())) {
return Err(MergeError::Mismatch("an HDR frame's pixels do not match its size".into()));
}
if frames.iter().any(|f| f.orientation != frames[0].orientation) {
for f in frames.iter_mut() {
f.orient();
+14 -1
View File
@@ -20,6 +20,7 @@ pub fn parse_iptc(b: &[u8]) -> Metadata {
let mut utf8 = false;
let mut date: Option<String> = None;
let mut time: Option<String> = None;
let mut seen_keywords = std::collections::HashSet::new();
let mut i = 0usize;
while i + 5 <= b.len() {
if b[i] != 0x1c {
@@ -43,7 +44,7 @@ pub fn parse_iptc(b: &[u8]) -> Metadata {
(2, 5) => m.title = Some(decode(data, utf8)).filter(|s| !s.is_empty()),
(2, 25) => {
let k = decode(data, utf8);
if !k.is_empty() && !m.keywords.contains(&k) {
if !k.is_empty() && seen_keywords.insert(k.clone()) {
m.keywords.push(k);
}
}
@@ -79,6 +80,18 @@ pub(crate) mod tests {
out.extend_from_slice(data);
}
#[test]
fn distinct_keywords_are_kept_once_each_without_rescanning() {
let mut b = Vec::new();
for i in 0..50_000u32 {
ds(&mut b, 2, 25, format!("k{i}").as_bytes());
ds(&mut b, 2, 25, b"same");
}
let m = parse_iptc(&b);
assert_eq!(m.keywords.len(), 50_001);
assert_eq!(m.keywords.iter().filter(|k| *k == "same").count(), 1);
}
pub(crate) fn sample_iim() -> Vec<u8> {
let mut v = Vec::new();
ds(&mut v, 1, 90, b"\x1b%G");
+27 -4
View File
@@ -240,14 +240,21 @@ fn xml_safe(s: &str) -> String {
s.chars().filter(|&c| is_xml_char(c)).collect()
}
/// Unescape attribute values (predefined + numeric references; unknown references kept verbatim).
/// Index of the `;` that ends a reference starting at `rest` (its `&`). The scan stops at the first
/// byte that cannot appear in a name or a numeric reference, so zero-padded references such as
/// `&#000000097;` are found and each run of name bytes is read once, not once per `&`.
fn entity_end(rest: &str) -> Option<usize> {
let n = rest.bytes().skip(1).take_while(|b| b.is_ascii_alphanumeric() || *b == b'#').count();
(rest.as_bytes().get(n + 1) == Some(&b';')).then_some(n + 1)
}
pub(crate) fn unescape_attr(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(i) = rest.find('&') {
out.push_str(&rest[..i]);
rest = &rest[i..];
match rest.find(';').and_then(|j| entity(&rest[1..j]).map(|c| (c, j))) {
match entity_end(rest).and_then(|j| entity(&rest[1..j]).map(|c| (c, j))) {
Some((c, j)) => {
out.push(c);
rest = &rest[j + 1..];
@@ -353,8 +360,13 @@ fn is_rdf_meta_attr(k: &str) -> bool {
fn collect_description(d: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<String>>, budget: &mut usize) {
for (k, v) in &d.attrs {
if !is_rdf_meta_attr(k) && take_key_bytes(&format!("{prefix}{k}"), budget) {
props.entry(format!("{prefix}{k}")).or_default().push(v.clone());
// the budget is checked before the path is built, not after
if is_rdf_meta_attr(k) || *budget < prefix.len().saturating_add(k.len()) {
continue;
}
let key = format!("{prefix}{k}");
if take_key_bytes(&key, budget) {
props.entry(key).or_default().push(v.clone());
}
}
for c in &d.children {
@@ -374,6 +386,11 @@ fn take_key_bytes(key: &str, budget: &mut usize) -> bool {
}
fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<String>>, budget: &mut usize) {
// a path that can't fit the budget isn't built (a long ancestor path shared by many children
// would otherwise be copied for each of them after the budget is spent)
if *budget < prefix.len().saturating_add(p.name.len()) {
return;
}
let key = format!("{prefix}{}", p.name);
if let Some(arr) = p.children.iter().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt")) {
let mut items: Vec<(bool, String)> = arr
@@ -393,6 +410,12 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<Str
return;
}
let struct_prefix = format!("{key}/");
// a struct's path is charged like a key before its fields copy it: that work too is bounded
// by the budget, kept fields or not
let is_struct = p.attr("rdf:parseType") == Some("Resource") || p.children.iter().any(|c| c.name == "rdf:Description");
if is_struct && !take_key_bytes(&key, budget) {
return;
}
if p.attr("rdf:parseType") == Some("Resource") {
for c in &p.children {
collect_property(c, &struct_prefix, props, budget);
+37
View File
@@ -530,6 +530,12 @@ fn flattened_keys_stay_within_the_cumulative_budget() {
assert!(!d.properties.is_empty(), "properties parsed before the budget are kept");
}
#[test]
fn zero_padded_numeric_references_decode() {
assert_eq!(unescape_attr("C&#0000000097;non &#x0000041; &#000000065;"), "Canon A A");
assert_eq!(unescape_attr("&abc&#xyz;&;"), "&abc&#xyz;&;");
}
#[test]
fn entity_rejects_signed_numeric_references() {
assert_eq!(entity("#+65"), None);
@@ -556,3 +562,34 @@ fn malformed_capture_time_without_fallback_is_not_projected() {
assert_eq!(parsed.metadata.capture_time, None);
assert_eq!(parsed.properties["exif:DateTimeOriginal"], vec!["2026-01-01T".to_string()]);
}
#[test]
fn many_ampersands_before_one_semicolon_are_read_once() {
// 200 000 `&` then a `;`: each `&` once searched the whole rest of the attribute for the `;`
let hostile = format!("{};&amp;", "&".repeat(200_000));
assert_eq!(unescape_attr(&hostile), format!("{};&", "&".repeat(200_000)));
assert_eq!(unescape_attr("&lt;a&gt; &#x10FFFF; &unknownreference;"), "<a> \u{10FFFF} &unknownreference;");
}
/// Children that add no key (empty structs) still had their whole ancestor path copied, each,
/// after the budget was spent: a 250 KB path under 100 000 such children was 25 GB of copying.
#[test]
fn paths_are_not_built_past_the_key_budget() {
let level = "n".repeat(60_000);
let mut doc = String::from(
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:lc=\"https://lightcraft.example/lc/\"><rdf:RDF><rdf:Description>",
);
for _ in 0..4 {
doc.push_str(&format!("<lc:{level} rdf:parseType=\"Resource\">"));
}
for _ in 0..100_000 {
doc.push_str("<lc:e rdf:parseType=\"Resource\"/>");
}
for _ in 0..4 {
doc.push_str(&format!("</lc:{level}>"));
}
doc.push_str("</rdf:Description></rdf:RDF></x:xmpmeta>");
let t = std::time::Instant::now();
let _ = parse_xmp(&doc);
assert!(t.elapsed().as_secs() < 10, "took {:?}", t.elapsed());
}
File diff suppressed because it is too large. Load diff
+118 -43
View File
@@ -110,6 +110,50 @@ fn vignette(s: &DevelopSettings) -> Option<Vig> {
/// Hash constants of [`grain_noise`] (shared with the GPU kernel).
pub const GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_e995];
/// The grain of processes V1 to V3: two octaves of value noise. Frozen: photos on those
/// processes keep rendering with it (`docs/process-versions.md`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ValueGrain {
/// Amplitude (display-encoded).
pub amt: f32,
/// Noise cell size (output pixels).
pub cell: f32,
/// Roughness 0..1: weight of the finer octave.
pub rough: f32,
pub seed: u32,
}
/// A render's film grain. The model follows the photo's process: changing it would change how
/// existing photos look, so the crystal grain came with process V4.
#[derive(Clone, Debug)]
pub enum GrainModel {
/// V1 to V3: value noise.
Value(ValueGrain),
/// V4 and later: crystal layers ([`crate::crystal`]).
Crystal(crate::crystal::CrystalGrain),
}
impl GrainModel {
/// The grain `s` renders with at `px_per_long` output pixels per long edge (`None`: none);
/// `draft`: for a drag ([`crate::crystal::CrystalGrain::draft`]).
pub fn new(s: &DevelopSettings, px_per_long: f64, draft: bool) -> Option<GrainModel> {
let g = &s.grain;
match s.process.process() {
Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => (g.amount > 0.0).then(|| {
let cell = (0.0006 + (g.size / 100.0) as f32 * 0.0024) * px_per_long as f32;
GrainModel::Value(ValueGrain {
amt: (g.amount / 100.0) as f32 * 0.13,
cell: cell.max(0.6),
rough: (g.roughness / 100.0) as f32,
seed: g.seed,
})
}),
Process::V7 | Process::V8 if draft => crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal),
Process::V7 | Process::V8 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal),
}
}
}
#[inline]
fn grain_noise(x: f32, y: f32, seed: u32) -> f32 {
// A degenerate frame (zero-width crop) maps pixels to NaN/inf coordinates: no grain there.
@@ -132,6 +176,21 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 {
a + (b - a) * v
}
/// The crystal grain of output row `y` (`w` pixels) when its pixels are axis-aligned; empty
/// otherwise (and without crystal grain): the pixels then take it one by one.
fn crystal_row(fp: &FinishParams, y: usize, w: usize) -> Vec<f32> {
let Some(GrainModel::Crystal(g)) = &fp.grain else { return Vec::new() };
let long = fp.ow.max(fp.oh);
let (a, b) = (fp.out_to_norm.apply(Point::new(0.5, y as f64 + 0.5)), fp.out_to_norm.apply(Point::new(1.5, y as f64 + 0.5)));
let (gx, gy) = (a.x * fp.ow / long, a.y * fp.oh / long);
let (dx, dy) = ((b.x - a.x) * fp.ow / long, (b.y - a.y) * fp.oh / long);
let mut out = vec![0.0; w];
if !g.row(gx, gy, dx, dy, &mut out) {
out.clear();
}
out
}
/// Number of per-mask terms in [`mask_terms`].
pub const MASK_TERMS: usize = 21;
@@ -217,8 +276,8 @@ pub struct FinishParams {
pub air_pre: f32,
pub gain: f32,
pub ev: f32,
/// Grain: amount, cell size (px), roughness, seed.
pub grain: Option<(f32, f32, f32, u32)>,
/// Film grain: the model of the photo's process ([`GrainModel`]).
pub grain: Option<GrainModel>,
/// Output px → normalized oriented coordinates.
pub out_to_norm: lightcraft_geom::Affine,
pub ow: f64,
@@ -241,12 +300,14 @@ pub struct FinishParamsInput<'a> {
pub px_per_long: f64,
pub air_pre: f32,
pub space: OutputSpace,
/// A draft render (a drag, [`crate::Quality::Draft`]): see [`GrainModel::new`].
pub draft: bool,
}
impl FinishParams {
/// Parameters for a `w × h` render into `space`; `ev`/`air_pre` as in [`crate::Prepared`].
pub fn new(input: FinishParamsInput<'_>) -> FinishParams {
let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, space } = input;
let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, space, draft } = input;
let effects = s.section_enabled("effects");
let (clar, tex, dehaze) = if effects {
((s.effects.clarity / 100.0) as f32, (s.effects.texture / 100.0) as f32, (s.effects.dehaze / 100.0) as f32)
@@ -263,10 +324,7 @@ impl FinishParams {
&& frame.oh.is_finite()
&& frame.ow.max(frame.oh) > 0.0
&& out_to_norm.0.iter().all(|v| v.is_finite());
let grain = (s.grain.amount > 0.0 && effects && finite_frame).then(|| {
let cell = (0.0006 + (s.grain.size / 100.0) as f32 * 0.0024) * px_per_long as f32;
((s.grain.amount / 100.0) as f32 * 0.13, cell.max(0.6), (s.grain.roughness / 100.0) as f32, s.grain.seed)
});
let grain = if effects && finite_frame { GrainModel::new(s, px_per_long, draft) } else { None };
let calibration = s.section_enabled("calibration");
let peak = s.hdr.peak();
FinishParams {
@@ -349,7 +407,7 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap {
},
// 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 | Process::V6 => match info.camera_tone.as_ref().filter(|_| info.raw) {
Process::V5 | Process::V6 | Process::V7 | Process::V8 => 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),
@@ -358,18 +416,20 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap {
}
/// Finish the prepared pipeline stages into an 8-bit RGBA image in `space` (or `display`).
pub(crate) fn finish(
p: &Prepared,
s: &DevelopSettings,
frame: &Frame,
info: &SourceInfo,
space: OutputSpace,
display: Option<&crate::DisplaySpace>,
proof: Option<crate::Proof>,
) -> Rgba8 {
pub(crate) fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo, req: &crate::RenderRequest) -> Rgba8 {
let (space, display, proof) = (req.space, req.display.as_ref(), req.proof);
let (w, h) = (p.img.width, p.img.height);
let mut fp =
FinishParams::new(FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, space });
let draft = req.quality == crate::Quality::Draft;
let mut fp = FinishParams::new(FinishParamsInput {
settings: s,
frame,
info,
image_size: (w, h),
px_per_long: p.px_per_long,
air_pre: p.air,
space,
draft,
});
fp.proof = proof.map(|pr| pr.params(space));
if let Some(d) = display {
fp.for_display(d, proof);
@@ -389,19 +449,21 @@ pub(crate) fn finish(
}
/// [`finish`] into 16-bit display-encoded or 32-bit float linear samples (output primaries).
pub(crate) fn finish_deep(
p: &Prepared,
s: &DevelopSettings,
frame: &Frame,
info: &SourceInfo,
space: OutputSpace,
depth: OutputDepth,
proof: Option<crate::Proof>,
) -> DeepImage {
pub(crate) fn finish_deep(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo, req: &crate::RenderRequest) -> DeepImage {
use lightcraft_color::transfer::srgb_to_linear;
let (space, depth, proof) = (req.space, req.depth, req.proof);
let (w, h) = (p.img.width, p.img.height);
let mut fp =
FinishParams::new(FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, space });
let draft = req.quality == crate::Quality::Draft;
let mut fp = FinishParams::new(FinishParamsInput {
settings: s,
frame,
info,
image_size: (w, h),
px_per_long: p.px_per_long,
air_pre: p.air,
space,
draft,
});
fp.proof = proof.map(|pr| pr.params(space));
let trc = fp.out_trc;
let samples = match depth {
@@ -453,6 +515,8 @@ pub(crate) fn finish_with<T: Copy + Default + Send>(
let hdr = peak > 1.0;
let mut out = vec![T::default(); w * h];
for_rows(&mut out, w, |y, row| {
// the crystal grain of the whole row at once when its pixels are axis-aligned
let crystal_row = crystal_row(fp, y, row.len());
for (x, px) in row.iter_mut().enumerate() {
let i = y * w + x;
let raw = p.img.data[i];
@@ -587,20 +651,31 @@ pub(crate) fn finish_with<T: Copy + Default + Send>(
e = refine_saturation(e0, e, fp.refine_sat);
}
}
if let Some((amt, cell, rough, seed)) = *grain {
let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5));
let (gx, gy) = ((n.x * fp.ow) as f32 / long as f32, (n.y * fp.oh) as f32 / long as f32);
let sc = fp.px_per_long as f32 / cell;
let mut g = grain_noise(gx * sc, gy * sc, seed);
g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55) * rough * 0.7;
let mut lum = 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2];
if hdr {
lum = lum.clamp(0.0, 1.0);
}
let k = amt * g * (0.35 + 2.6 * lum * (1.0 - lum));
if k.is_finite() {
e = e.map(|v| v + k);
match grain {
Some(GrainModel::Value(g)) => {
// V1/V2 (frozen): exactly the arithmetic those processes always had
let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5));
let (gx, gy) = ((n.x * fp.ow) as f32 / long as f32, (n.y * fp.oh) as f32 / long as f32);
let sc = fp.px_per_long as f32 / g.cell;
let mut v = grain_noise(gx * sc, gy * sc, g.seed);
v = v * (1.0 - g.rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, g.seed ^ 0x55) * g.rough * 0.7;
let mut lum = 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2];
if hdr {
lum = lum.clamp(0.0, 1.0);
}
let k = g.amt * v * (0.35 + 2.6 * lum * (1.0 - lum));
if k.is_finite() {
e = e.map(|v| v + k);
}
}
Some(GrainModel::Crystal(g)) => match crystal_row.get(x) {
Some(&f) => e = g.apply_field(e, f),
None => {
let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5));
e = g.apply(e, (n.x * fp.ow / long) as f32, (n.y * fp.oh / long) as f32);
}
},
None => {}
}
let e = match &p_lut {
Some((l, k)) if hdr => {
File diff suppressed because it is too large. Load diff
+18 -4
View File
@@ -26,11 +26,13 @@
pub mod auto;
pub mod blemish;
pub mod colorops;
pub mod crystal;
pub mod cull;
pub mod curve;
pub mod dust;
pub mod finish;
pub mod geometry;
pub mod lens_blur;
pub mod light_v3;
// generated (`light_v3_params.rs`), kept in its own compact layout
#[rustfmt::skip]
@@ -443,6 +445,8 @@ pub struct Plan<'a> {
pub keep: Option<PixelWindow>,
/// The source's segmentation mattes ([`SourceInfo::mattes`]).
pub mattes: Option<Arc<masks::Mattes>>,
/// The whole photo's subject estimate a lens blur focuses on ([`lens_blur::subject_estimate`]).
pub lens_subject: Option<Arc<lens_blur::SubjectEstimate>>,
/// The whole frame and its output size (a windowed render's [`Self::frame`] is part of it).
pub full: (geometry::Frame, usize, usize),
}
@@ -486,8 +490,10 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
let (pw, ph) = (((full_w as f64 * k).round() as usize).max(1), ((full_h as f64 * k).round() as usize).max(1));
fixed_air = Some(local::frame_airlight(src, info, s, &frame, pw, ph));
}
// (spots grow the rendered window of 8-bit renders; a grown window is cut back to the request)
let mut work = if req.depth == OutputDepth::U8 { spots::window_for_reads(s, &frame, full_w, full_h, px_per_long, win) } else { win };
// (spots grow the rendered window of 8-bit renders, the lens blur that of every
// render; a grown window is cut back to the request)
let work = if req.depth == OutputDepth::U8 { spots::window_for_reads(s, &frame, full_w, full_h, px_per_long, win) } else { win };
let mut work = lens_blur::window_for_reads(s, full_w, full_h, px_per_long, work);
if local::joint_colour_nr(s)
&& let Some(params) = local::nrc_params(s, detail_scale)
{
@@ -521,6 +527,8 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
// and the local tone mapping
local_tone::enabled(info, s),
src_long,
// and the lens blur (after noise reduction, but a draft must not reuse planes without it)
lens_blur::key(s),
));
let lin_key = hash_of((
pre_nr_key,
@@ -529,6 +537,7 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
// the process picks the colour filter (Update to Current Process, undo)
local::joint_colour_nr(s),
));
let lens_subject = lens_blur::subject_estimate(src, s, info.mattes.as_deref()).map(Arc::new);
let noise_key = hash_of((pre_nr_key, [d.nr_luminance, d.nr_detail].map(f64::to_bits), detail_scale.to_bits()));
Plan {
settings,
@@ -547,6 +556,7 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
fixed_air,
keep,
mattes: info.mattes.clone(),
lens_subject,
full,
}
}
@@ -584,6 +594,7 @@ pub fn colour_noise(src: &Rgb32f, info: &SourceInfo, p: &Plan<'_>) -> Option<nrc
fixed_air: None,
keep: None,
mattes: None,
lens_subject: None,
full: p.full.clone(),
..*p
};
@@ -721,6 +732,7 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
colour_noise = self::colour_noise(src_img, info, &plan).map(|n| (plan.noise_key, n));
}
local::denoise(&mut img, s, detail_scale, colour_noise.as_ref().map(|c| &c.1));
lens_blur::apply_with(&mut img, s, frame, px_per_long, plan.mattes.as_deref(), plan.lens_subject.as_deref());
Arc::new(img)
}
};
@@ -743,7 +755,7 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
c.put(CacheEntry { src: a.clone(), geo, sampled, lin: Some((lin_key, lin)), colour_noise, planes });
}
if req.depth != OutputDepth::U8 {
let deep = finish::finish_deep(&prep, s, frame, info, req.space, req.depth, req.proof);
let deep = finish::finish_deep(&prep, s, frame, info, req);
let deep = match plan.keep {
Some(k) => deep.crop(k.x, k.y, k.w, k.h),
None => deep,
@@ -753,7 +765,7 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
lap("finish (deep)", &mut t);
return Rendered { image, histogram, deep: Some(deep) };
}
let image = finish::finish(&prep, s, frame, info, req.space, req.display.as_ref(), req.proof);
let image = finish::finish(&prep, s, frame, info, req);
lap("finish", &mut t);
let cut = |i: &Rgba8| match plan.keep {
Some(k) => i.crop(k.x, k.y, k.w, k.h),
@@ -905,6 +917,8 @@ mod tests;
#[cfg(test)]
mod tests_geometry;
#[cfg(test)]
mod tests_grain;
#[cfg(test)]
mod tests_hdr;
#[cfg(test)]
mod tests_legacy;
+1 -1
View File
@@ -284,7 +284,7 @@ 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 | Process::V5 | Process::V6 => camera_look,
Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 => camera_look,
}
}
+119 -10
View File
@@ -357,7 +357,7 @@ fn transpose(p: &Plane) -> Plane {
}
/// Detail scale of the highlights/shadows base from process V2, as a fraction of the long edge:
/// the base is the edge-aware filter of the [`median_hv`] of log luminance at this radius, so
/// the base is the edge-aware filter of log luminance without its detail at this radius, so
/// twigs, lines and fine texture brighter or darker than their surroundings take their
/// surroundings' shift (and keep their contrast, as with Exposure) while region boundaries stay
/// sharp (no halos). V1's base is the edge-aware filter of log luminance itself (issue #632).
@@ -375,17 +375,76 @@ 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 | Process::V5 | Process::V6 => base_detail_radius(px_per_long),
Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 => base_detail_radius(px_per_long),
}
}
/// The highlights/shadows base layer of log luminance `l`: the fast guided filter ([`BASE_EPS`])
/// of its [`median_hv`] at `detail` px ([`tone_base_detail`]); at 0, of `l` itself (V1).
pub fn tone_base(l: &Plane, sigma: f32, detail: usize) -> Plane {
/// at `detail` px ([`tone_base_detail`]) of its [`detail_free`] plane when `keeps_gaps`
/// ([`base_keeps_gaps`], V8 on), else of its [`median_hv`] (V2 to V7); at 0, of `l` itself (V1).
pub fn tone_base(l: &Plane, sigma: f32, detail: usize, keeps_gaps: bool) -> Plane {
if detail == 0 {
return guided_fast(l, sigma, BASE_EPS);
}
guided_fast(&median_hv(l, detail), sigma, BASE_EPS)
let m = if keeps_gaps { detail_free(l, detail) } else { median_hv(l, detail) };
guided_fast(&m, sigma, BASE_EPS)
}
/// Downscale factor of the coarse median in [`detail_free`]: its radius at full size is this many
/// times the fine one's.
pub const BASE_COARSE_STEP: usize = 3;
/// Log luminance `l` without detail finer than `r` px (the highlights/shadows base of process V8
/// on takes its edge-aware filter): each value moves toward its [`median_hv`] at `r` only as far as the
/// median of a [`BASE_COARSE_STEP`]× wider neighbourhood agrees (`l` clamped between the two).
/// A twig, line or speck in an even surround has both medians on the surround's side and takes
/// its tone, as #632 wants. The gap between two letter strokes, which a median at `r` fills with the
/// strokes' tone, sits in a wider neighbourhood mostly of the panel's tone: the two medians
/// disagree and the gap keeps its own. The coarse median is taken at `r` of a box-downscaled copy and
/// enlarged bilinearly, like [`guided_fast`]'s coefficients.
pub fn detail_free(l: &Plane, r: usize) -> Plane {
use lightcraft_raster::resample::{Filter, resize};
if r == 0 || l.data.is_empty() {
return l.clone();
}
let (w, h) = (l.width, l.height);
let (lw, lh) = (w.div_ceil(BASE_COARSE_STEP).max(1), h.div_ceil(BASE_COARSE_STEP).max(1));
if (lw, lh) == (w, h) {
// nothing to downscale: both medians are the same
return median_hv(l, r);
}
let lo = median_hv(&resize(l, lw, lh, Filter::Box), r);
// The bilinear enlargement of `lo` (`resize`'s horizontal pass, then its vertical pass taken
// row by row with the same sums) is clamped into `out` as it is made, not stored.
let wide = resize(&lo, w, lh, Filter::Bilinear);
let wy = lightcraft_raster::resample::weights(lh, h, Filter::Bilinear);
let mut out = median_hv(l, r);
for_rows(&mut out.data, w, |y, row| {
let Some((y0, ws)) = wy.get(y) else { return };
let mut coarse = vec![0.0f32; w];
for (k, &wt) in ws.iter().enumerate() {
let Some(t) = wide.data.get((y0 + k) * w..(y0 + k + 1) * w) else { continue };
for (c, &v) in coarse.iter_mut().zip(t) {
*c += v * wt;
}
}
for ((o, &v), &c) in row.iter_mut().zip(l.row(y)).zip(&coarse) {
*o = clamp_between(v, *o, c);
}
});
out
}
/// `v` clamped between `a` and `b` (in either order); a NaN bound is ignored, not a panic.
fn clamp_between(v: f32, a: f32, b: f32) -> f32 {
let (lo, hi) = (a.min(b), a.max(b));
if v < lo {
lo
} else if v > hi {
hi
} else {
v
}
}
/// Subsampling step of [`guided_fast`] for `sigma` (1 = no subsampling: the plain guided filter).
@@ -638,6 +697,12 @@ pub fn sharpen_key(s: &DevelopSettings, sigma: f32) -> SharpenKey {
(sigma.to_bits(), s.process.process())
}
/// Whether `s`'s highlights/shadows base takes [`detail_free`] (process V8 on) instead of V2's plain
/// [`median_hv`] (V2 to V7, which shipped with it and stay frozen).
pub fn base_keeps_gaps(s: &DevelopSettings) -> bool {
s.process.process() >= Process::V8
}
pub fn pixel_sharpen(s: &DevelopSettings) -> bool {
s.process.process() >= Process::V3
}
@@ -677,7 +742,7 @@ pub const CHROMA_SIGMA: f32 = 0.004;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PlaneSigmas {
/// Edge-aware base for highlights/shadows ([`tone_base`]: fast guided filter, [`BASE_EPS`]; from
/// process V2 of the [`BASE_DETAIL`] median).
/// process V2 of a median at [`BASE_DETAIL`], from V8 of a detail-free plane).
pub base: Option<f32>,
/// Median radius (px) of that base ([`tone_base_detail`]: 0 under V1).
pub base_detail: usize,
@@ -806,7 +871,7 @@ pub(crate) fn prepare(
});
let l = &log_l;
let (base, (clarity_blur, ((texture_blur, sharpen_blur), dark))) = par_join(
|| base_sigma.map(|sg| plane_at(sb, base_key(s, sg, base_detail), || timed("base", || tone_base(l, sg, base_detail)))),
|| base_sigma.map(|sg| plane_at(sb, base_key(s, sg, base_detail), || timed("base", || tone_base(l, sg, base_detail, base_keeps_gaps(s))))),
|| {
par_join(
|| clarity_sigma.map(|sg| plane_at(sc, sg.to_bits(), || timed("clarity", || guided_fast(l, sg, CLARITY_EPS)))),
@@ -1309,6 +1374,50 @@ mod tests {
mod fast_tests {
use super::*;
/// [`detail_free`] enlarges the coarse median as it clamps; the result is the plain
/// composition of `resize` and [`median_hv`], bit for bit.
#[test]
fn detail_free_matches_its_reference() {
use lightcraft_raster::resample::{Filter, resize};
for (w, h) in [(1, 1), (2, 1), (3, 3), (4, 7), (61, 47), (200, 31)] {
let p = Plane::from_fn(w, h, |x, y| ((x * 37 + y * 101) % 23) as f32 * 0.4 - 4.0 + if (x / 5 + y / 7) % 2 == 0 { 2.0 } else { 0.0 });
for r in [1, 2, 5, 10] {
let fine = median_hv(&p, r);
let (lw, lh) = (w.div_ceil(BASE_COARSE_STEP), h.div_ceil(BASE_COARSE_STEP));
let coarse = resize(&median_hv(&resize(&p, lw, lh, Filter::Box), r), w, h, Filter::Bilinear);
let want: Vec<u32> = (0..w * h).map(|i| clamp_between(p.data[i], fine.data[i], coarse.data[i]).to_bits()).collect();
let got: Vec<u32> = detail_free(&p, r).data.iter().map(|v| v.to_bits()).collect();
assert_eq!(got, want, "{w}×{h} r={r}");
}
}
}
/// CPU highlights/shadows base timings on the #3460 frame size:
/// `cargo test --release -p lightcraft-pipeline bench_tone_base_cpu -- --ignored --nocapture`.
#[test]
#[ignore]
fn bench_tone_base_cpu() {
let (w, h) = (6960, 4640);
let r = base_detail_radius(w as f64);
let p = Plane::from_fn(w, h, |x, y| ((x * 7 + y * 13) % 1000) as f32 / 250.0 - 6.0 + if (x / 40 + y / 40) % 2 == 0 { 1.0 } else { 0.0 });
let sigma = 0.015 * w as f32;
let time = |name: &str, f: &dyn Fn() -> Plane| {
let mut ts: Vec<f64> = (0..5)
.map(|_| {
let t = std::time::Instant::now();
std::hint::black_box(f());
t.elapsed().as_secs_f64() * 1e3
})
.collect();
ts.sort_by(f64::total_cmp);
eprintln!("{name:<20} min {:.1} ms median {:.1} ms", ts[0], ts[2]);
};
time("median_hv", &|| median_hv(&p, r));
time("detail_free", &|| detail_free(&p, r));
time("guided_fast", &|| guided_fast(&p, sigma, BASE_EPS));
time("tone_base", &|| tone_base(&p, sigma, r, true));
}
/// The previous fast path, including its two materialized coefficient resizes.
fn resized_reference(p: &Plane, sigma: f32, eps: f32) -> Plane {
use lightcraft_raster::resample::{Filter, resize};
@@ -1353,12 +1462,12 @@ mod fast_tests {
}
#[test]
fn sampled_tone_base_keeps_the_median_before_the_guided_filter() {
fn sampled_tone_base_keeps_the_detail_free_plane_before_the_guided_filter() {
let p = Plane::from_fn(73, 51, |x, y| if x % 9 == 0 { 3.0 } else { -4.0 + ((x + y) % 7) as f32 * 0.03 });
for sigma in [6.0, 24.0, 120.0] {
for detail in [0, 1, 3, BASE_DETAIL_MAX] {
let median = median_hv(&p, detail);
assert_eq!(tone_base(&p, sigma, detail).data, resized_reference(&median, sigma, BASE_EPS).data, "{sigma}, {detail}");
let free = detail_free(&p, detail);
assert_eq!(tone_base(&p, sigma, detail, true).data, resized_reference(&free, sigma, BASE_EPS).data, "{sigma}, {detail}");
}
}
}
+6
View File
@@ -93,6 +93,12 @@ impl Mattes {
self.mattes.iter().filter(|(k, _)| kinds.contains(k)).map(|(_, m)| m).collect()
}
/// Whether a mask of the photo's Subject comes from these mattes (a person, or a person's
/// parts) rather than from the saliency heuristic.
pub fn selects_subject(&self) -> bool {
!self.for_shape(&MaskShape::Subject).is_empty()
}
/// The mattes a shape uses instead of its heuristic (empty: none fits).
fn for_shape(&self, shape: &MaskShape) -> Vec<&Image<u8>> {
use MatteKind::*;
+41 -21
View File
@@ -346,6 +346,30 @@ pub struct DeepImage {
}
impl DeepImage {
/// The `w × h` part of the image at (`x`, `y`), clamped to the image (at least 1 × 1 when the
/// image has pixels). Samples are RGB, three per pixel, row-major.
pub fn crop(&self, x: usize, y: usize, w: usize, h: usize) -> DeepImage {
let x = x.min(self.width.saturating_sub(1));
let y = y.min(self.height.saturating_sub(1));
let w = w.min(self.width.saturating_sub(x)).max(usize::from(self.width > 0));
let h = h.min(self.height.saturating_sub(y)).max(usize::from(self.height > 0));
fn cut<T: Copy>(v: &[T], width: usize, x: usize, y: usize, w: usize, h: usize) -> Vec<T> {
let mut out = Vec::with_capacity(w.saturating_mul(h).saturating_mul(3));
for row in y..y + h {
let start = row.saturating_mul(width).saturating_add(x).saturating_mul(3);
if let Some(r) = v.get(start..start.saturating_add(w * 3)) {
out.extend_from_slice(r);
}
}
out
}
let samples = match &self.samples {
DeepSamples::U16(v) => DeepSamples::U16(cut(v, self.width, x, y, w, h)),
DeepSamples::F32(v) => DeepSamples::F32(cut(v, self.width, x, y, w, h)),
};
DeepImage { width: w, height: h, space: self.space, samples }
}
/// The same image reduced to 8 bits, display-encoded with the space's curve.
pub fn to_rgba8(&self) -> lightcraft_raster::Rgba8 {
let mut out = lightcraft_raster::Rgba8::new(self.width, self.height);
@@ -364,27 +388,6 @@ impl DeepImage {
}
out
}
/// Crop to `[x0, x0+w) × [y0, y0+h)` (clamped to the image).
pub fn crop(&self, x0: usize, y0: usize, w: usize, h: usize) -> Self {
let x0 = x0.min(self.width);
let y0 = y0.min(self.height);
let w = w.min(self.width - x0);
let h = h.min(self.height - y0);
fn rows<T: Copy>(v: &[T], width: usize, x0: usize, y0: usize, w: usize, h: usize) -> Vec<T> {
let mut out = Vec::with_capacity(3 * w * h);
for y in y0..y0 + h {
let at = 3 * (y * width + x0);
out.extend_from_slice(v.get(at..at + 3 * w).unwrap_or_default());
}
out
}
let samples = match &self.samples {
DeepSamples::U16(v) => DeepSamples::U16(rows(v, self.width, x0, y0, w, h)),
DeepSamples::F32(v) => DeepSamples::F32(rows(v, self.width, x0, y0, w, h)),
};
Self { width: w, height: h, space: self.space, samples }
}
}
trait IntoRgba {
@@ -401,6 +404,23 @@ impl IntoRgba for [u8; 3] {
mod tests {
use super::*;
/// A crop keeps the right pixels and never reads past the image, whatever the request.
#[test]
fn deep_crop_keeps_the_window_and_clamps() {
// 4 × 3, pixel (x, y) holds x + 10 y in every channel
let v: Vec<u16> = (0..3).flat_map(|y| (0..4).flat_map(move |x| [x + 10 * y; 3])).collect();
let d = DeepImage { width: 4, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::U16(v) };
let c = d.crop(1, 1, 2, 2);
assert_eq!((c.width, c.height), (2, 2));
assert_eq!(c.samples, DeepSamples::U16(vec![11, 11, 11, 12, 12, 12, 21, 21, 21, 22, 22, 22]));
for (x, y, w, h) in [(9, 9, 5, 5), (0, 0, usize::MAX, usize::MAX), (3, 2, 0, 0)] {
let c = d.crop(x, y, w, h);
let DeepSamples::U16(s) = &c.samples else { panic!("a U16 image crops to U16") };
assert!(c.width >= 1 && c.height >= 1 && c.width <= 4 && c.height <= 3);
assert_eq!(s.len(), c.width * c.height * 3, "{x} {y} {w} {h}");
}
}
#[test]
fn trcs_invert() {
for o in OutputSpace::ALL {
+661
View File
@@ -0,0 +1,661 @@
use super::*;
/// The draws [`hold_for_waiters`] holds, by cache: how many renders wait for each, and how many
/// draws are left to hold.
static HOLDS: Mutex<Vec<(usize, usize, usize)>> = Mutex::new(Vec::new());
/// Holds the draw of `d` until the renders [`HOLDS`] names for its cache are waiting for it (each
/// holds a clone of its slot, as do the drawing and its in-flight entry), so a test can make
/// renders miss a tile together.
pub(super) fn hold_for_waiters(d: &Drawing) {
let waiters = {
let mut holds = HOLDS.lock().unwrap_or_else(PoisonError::into_inner);
let Some(h) = holds.iter_mut().find(|h| h.0 == d.id.0 && h.2 > 0) else { return };
h.2 -= 1;
h.1
};
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while Arc::strong_count(&d.done) < 2 + waiters {
assert!(std::time::Instant::now() < deadline, "the renders never waited");
std::thread::sleep(std::time::Duration::from_millis(1));
}
}
/// The caches [`evict_before_waking`] empties.
static EVICTS: Mutex<Vec<usize>> = Mutex::new(Vec::new());
/// Empties `cache` if [`EVICTS`] names it, after its drawer `d` has cached its tile and before it
/// wakes the renders waiting for it, as other renders' tiles can push it out in that gap.
pub(super) fn evict_before_waking(cache: &Cache, d: &Drawing) {
if EVICTS.lock().unwrap_or_else(PoisonError::into_inner).contains(&d.id.0) {
cache.lock().unwrap_or_else(PoisonError::into_inner).clear();
}
}
/// Waits until `n` renders wait for the draw of `d`.
fn until_waiting(d: &Drawing, n: usize) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while Arc::strong_count(&d.done) < 2 + n {
assert!(std::time::Instant::now() < deadline, "the renders never waited");
std::thread::sleep(std::time::Duration::from_millis(1));
}
}
/// The field rendered at `long` px per long edge on an `n × n` patch starting at pixel `origin`.
fn patch(tile: &CrystalTile, long: f64, n: usize, origin: usize) -> Vec<f32> {
let w = (TILE_PER_LONG / long) as f32;
(0..n * n).map(|k| tile.field(((origin + k % n) as f32 + 0.5) * w, ((origin + k / n) as f32 + 0.5) * w, w)).collect()
}
fn std(v: &[f32]) -> f64 {
let m = v.iter().map(|&x| x as f64).sum::<f64>() / v.len() as f64;
(v.iter().map(|&x| (x as f64 - m).powi(2)).sum::<f64>() / v.len() as f64).sqrt()
}
/// Lag (px) at which the autocorrelation (mean of horizontal and vertical) falls to ½.
fn half_width(v: &[f32], n: usize) -> f64 {
let m = v.iter().map(|&x| x as f64).sum::<f64>() / v.len() as f64;
let d: Vec<f64> = v.iter().map(|&x| x as f64 - m).collect();
let var = d.iter().map(|x| x * x).sum::<f64>() / d.len() as f64;
let corr = |k: usize, horizontal: bool| {
let mut s = 0.0;
let mut c = 0usize;
for y in 0..n - if horizontal { 0 } else { k } {
for x in 0..n - if horizontal { k } else { 0 } {
let b = if horizontal { y * n + x + k } else { (y + k) * n + x };
s += d[y * n + x] * d[b];
c += 1;
}
}
s / c as f64 / var
};
let mut out = 0.0;
for horizontal in [true, false] {
let mut prev = 1.0;
let mut w = 16.0;
for k in 1..16 {
let c = corr(k, horizontal);
if c <= 0.5 {
w = k as f64 - 1.0 + (prev - 0.5) / (prev - c).max(1e-9);
break;
}
prev = c;
}
out += w / 2.0;
}
out
}
fn tile_of(size: f64, roughness: f64) -> Arc<CrystalTile> {
tile(CrystalLook::new(size, roughness), 7, true).expect("a tile")
}
#[test]
fn reference_render_has_unit_variance_and_no_mean() {
let t = tile_of(25.0, 50.0);
let v = patch(&t, REF_LONG, 600, 37);
let m = v.iter().map(|&x| x as f64).sum::<f64>() / v.len() as f64;
assert!((std(&v) - 1.0).abs() < 0.05, "std {}", std(&v));
assert!(m.abs() < 0.03, "mean {m}");
}
#[test]
fn small_render_is_the_downscaled_reference() {
for (size, rough) in [(0.0, 50.0), (25.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] {
let t = tile_of(size, rough);
for k in [2usize, 4, 8] {
let full = patch(&t, REF_LONG, 120 * k, 0);
let n = 120;
let down: Vec<f32> = (0..n * n)
.map(|q| {
let (x, y) = (q % n, q / n);
let mut s = 0.0;
for dy in 0..k {
for dx in 0..k {
s += full[(y * k + dy) * n * k + x * k + dx];
}
}
s / (k * k) as f32
})
.collect();
let small = patch(&t, REF_LONG / k as f64, n, 0);
let worst = down.iter().zip(&small).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max);
assert!(worst < 2e-3, "size {size} roughness {rough} 1/{k}: differs by {worst}");
}
}
}
#[test]
fn strength_matches_the_target_at_mid_grey() {
for (a, s, r) in [(50.0, 25.0, 50.0), (25.0, 25.0, 50.0), (50.0, 0.0, 50.0), (50.0, 100.0, 50.0), (50.0, 25.0, 0.0)] {
let g = CrystalGrain::new(&Grain { amount: a, size: s, roughness: r, seed: 3 }, REF_LONG).expect("grain");
let n = 500;
let lum: Vec<f32> = (0..n * n)
.map(|k| {
let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5);
let e = g.apply([MID_GREY; 3], x / REF_LONG as f32, y / REF_LONG as f32);
(0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]) * 255.0
})
.collect();
let want = strength_levels(a, s, r);
assert!((std(&lum) / want - 1.0).abs() < 0.06, "{a}/{s}/{r}: {} levels, want {want}", std(&lum));
}
}
#[test]
fn tones_keep_their_mean() {
// the strongest settings in the shadows; near white, strong grain clips at 255 like any grain
let cases = [
(100.0, 0.0, &[5.0f32, 20.0, 40.0, 60.0, 128.0, 255.0][..]),
(50.0, 0.0, &[200.0, 245.0][..]),
(50.0, 25.0, &[20.0, 128.0, 245.0, 255.0][..]),
];
for (amount, size, levels) in cases {
let g = CrystalGrain::new(&Grain { amount, size, roughness: 50.0, seed: 3 }, REF_LONG).expect("grain");
for &level in levels {
let n = 400;
let mut sum = 0.0f64;
for k in 0..n * n {
let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5);
let e = g.apply([level / 255.0; 3], x / REF_LONG as f32, y / REF_LONG as f32);
sum += (e[1].clamp(0.0, 1.0) * 255.0) as f64;
}
let shift = sum / (n * n) as f64 - level as f64;
assert!(shift.abs() < 0.5, "{amount}/{size}: level {level} moved {shift:+.2}");
}
}
}
#[test]
fn hostile_settings_render_finite_or_no_grain() {
let bad = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1e9, 1e9, 0.0];
for &a in &bad {
for &s in &bad {
for &ppl in &[f64::NAN, 0.0, -5.0, 1.0, 24.0, 1e12, 6000.0] {
let g = Grain { amount: if a == 0.0 { 50.0 } else { a }, size: s, roughness: s, seed: u32::MAX };
if let Some(c) = CrystalGrain::new(&g, ppl) {
for (x, y) in [(0.0, 0.0), (-3.5, 1e7), (f32::NAN, 0.2), (0.5, f32::INFINITY), (1.0, 0.6667)] {
let e = c.apply([0.5, 0.2, 0.9], x, y);
assert!(e.iter().all(|v| v.is_finite()), "{g:?} at {ppl}: {e:?}");
}
}
}
}
}
}
#[test]
fn seed_picks_the_pattern() {
let look = CrystalLook::new(25.0, 50.0);
let (Some(a), Some(c)) = (tile(look, 1, true), tile(look, 2, true)) else { panic!("tiles") };
assert_ne!(patch(&a, REF_LONG, 64, 0), patch(&c, REF_LONG, 64, 0));
}
/// A tile drawn again (its cache entry evicted, another process, an export after a preview) is the
/// same to the bit, however many threads draw it. These draw directly: through [`tile`], the second
/// would be the first one out of the cache.
#[test]
fn a_tile_draws_the_same_every_time() {
let look = CrystalLook::new(25.0, 50.0);
let one_thread = rayon::ThreadPoolBuilder::new().num_threads(1).build().expect("a pool");
let (Some(a), Some(b)) = (CrystalTile::new(look, 1), one_thread.install(|| CrystalTile::new(look, 1))) else { panic!("tiles") };
assert!(a.sats == b.sats, "the same seed drew different tiles");
}
/// Every seed has the same mix of crystal sizes, dealt to the layers in its own order.
#[test]
fn seeds_share_the_mix_of_crystal_sizes() {
let look = CrystalLook::new(50.0, 80.0);
let radii = |seed| emulsion(seed, &look).iter().map(|l| l.r).collect::<Vec<f64>>();
let sorted = |mut v: Vec<f64>| {
v.sort_by(f64::total_cmp);
v
};
let (a, b) = (radii(1), radii(2));
assert_eq!(a.len(), look.layers);
assert_eq!(a, radii(1), "the same seed deals the same order");
assert_ne!(a, b, "another seed deals another order");
assert_eq!(sorted(a), sorted(b));
assert_eq!(emulsion(1, &CrystalLook { layers: 0, ..look }).len(), 1, "an emulsion has a layer");
}
#[test]
fn sliders_clamp_and_fall_back() {
let look = CrystalLook::new;
assert_eq!(look(f64::NAN, f64::NAN), look(25.0, 50.0), "NaN is the default");
assert_eq!(look(-1e9, f64::NEG_INFINITY), look(0.0, 0.0));
assert_eq!(look(1e9, f64::INFINITY), look(100.0, 100.0));
// the ends of the tables
assert_eq!((look(0.0, 50.0).width, look(0.0, 50.0).layers), (0.55, 16));
assert_eq!((look(100.0, 50.0).width, look(100.0, 50.0).layers), (12.38, 70));
assert_eq!(look(100.0, 0.0).width, 12.38 * 0.734);
assert_eq!(look(100.0, 100.0).width, 12.38 * 1.422);
assert!(look(25.0, 100.0).spread > look(25.0, 0.0).spread);
let default = strength_levels(50.0, 25.0, 50.0);
assert_eq!(strength_levels(f64::NAN, 25.0, 50.0), 0.0, "a NaN Amount is no grain");
assert_eq!(strength_levels(-5.0, 25.0, 50.0), 0.0);
assert_eq!(strength_levels(50.0, f64::NAN, f64::NAN), default);
assert_eq!(strength_levels(1e9, 25.0, 50.0), 2.0 * default);
assert_eq!(strength_levels(50.0, -1e9, 50.0), strength_levels(50.0, 0.0, 50.0));
assert_eq!(strength_levels(50.0, 25.0, f64::INFINITY), strength_levels(50.0, 25.0, 100.0));
// Lightroom Classic's at the ends of each slider (`docs/grain.md`)
for (want, (a, s, r)) in [(23.08, (50.0, 0.0, 50.0)), (5.83, (50.0, 100.0, 50.0)), (12.42, (50.0, 25.0, 0.0)), (11.68, (50.0, 25.0, 100.0))] {
let got = strength_levels(a, s, r);
assert!((got / want - 1.0).abs() < 0.01, "{a}/{s}/{r}: {got}, want {want}");
}
}
#[test]
fn interp_is_linear_between_knots_and_constant_outside() {
let knots = [(0.0, 1.0), (10.0, 3.0), (20.0, 2.0)];
for (x, want) in [(-5.0, 1.0), (0.0, 1.0), (5.0, 2.0), (10.0, 3.0), (15.0, 2.5), (20.0, 2.0), (99.0, 2.0)] {
assert_eq!(interp(&knots, x), want, "at {x}");
}
assert_eq!(interp(&[], 5.0), 0.0);
assert_eq!(interp(&[(3.0, 7.0)], 5.0), 7.0);
}
#[test]
fn normal_quantile_matches_the_table() {
for (p, z) in [(0.5, 0.0), (0.975, 1.959_963_985), (0.841_344_746, 1.0), (0.001, -3.090_232_306), (1e-6, -4.753_424_309)] {
assert!((normal_quantile(p) - z).abs() < 1e-7, "at {p}: {}, want {z}", normal_quantile(p));
assert!((normal_quantile(1.0 - p) + z).abs() < 1e-7, "at 1 - {p}");
}
// increasing across the approximation's joins (0.02425 and its mirror), finite at the ends
let sweep: Vec<f64> = (0..=1000).map(|k| normal_quantile(k as f64 / 1000.0)).collect();
assert!(sweep.iter().all(|z| z.is_finite()));
assert!(sweep.windows(2).all(|w| w[0] < w[1]));
}
#[test]
fn poisson_counts_have_the_mean_and_variance_of_mu() {
let n = 40_000u32;
for mu in [0.5, 4.0, 40.0, 150.0] {
let cdf = poisson_cdf(mu);
assert!(cdf.windows(2).all(|w| w[0] <= w[1]), "mu {mu}: the distribution must not fall");
assert!(cdf.last().is_some_and(|&c| c >= 1.0 - 1e-12), "mu {mu}: the distribution must reach 1");
let draws: Vec<f64> = (0..n).map(|i| poisson(&cdf, mix(i)) as f64).collect();
let mean = draws.iter().sum::<f64>() / n as f64;
let var = draws.iter().map(|d| (d - mean).powi(2)).sum::<f64>() / n as f64;
assert!((mean - mu).abs() < 4.0 * (mu / n as f64).sqrt(), "mu {mu}: mean {mean}");
assert!((var / mu - 1.0).abs() < 0.05, "mu {mu}: variance {var}");
}
}
#[test]
fn poisson_stays_in_range_at_the_ends() {
for h in [0, u32::MAX] {
assert_eq!(poisson(&poisson_cdf(0.0), h), 0, "mean 0 is never a crystal");
// past what the model uses, e^-mu underflows: a capped count, not a panic
assert!(poisson(&poisson_cdf(1e6), h) <= 512);
assert_eq!(poisson(&[], h), 0);
}
}
#[test]
fn summed_area_matches_brute_force() {
let t = 7;
let count: Vec<u8> = (0..t * t).map(|i| (mix(i as u32) % 71) as u8).collect();
let sat = summed_area(&count, t);
assert_eq!(sat.len(), (t + 1) * (t + 1));
for y in 0..=t {
for x in 0..=t {
let want: u32 = (0..y).flat_map(|j| (0..x).map(move |i| (i, j))).map(|(i, j)| count[j * t + i] as u32).sum();
assert_eq!(sat[y * (t + 1) + x], want, "[0, {x}) × [0, {y})");
}
}
}
/// Boxes against the emulsion's own pixels (each table's counts, less their mean, scaled to unit
/// variance as [`CrystalTile::new`] does), integrated by hand. Whole and fractional boxes, across
/// the torus's seams, at negative coordinates and periods away.
#[test]
fn box_sum_is_the_integral_of_the_emulsion() {
let (look, seed) = (CrystalLook::new(25.0, 50.0), 7);
let tile = CrystalTile::new(look, seed).expect("a tile");
let counts = [0, 1].map(|which| draw_torus(which, TORI[which], seed, &look));
let means: [f64; 2] = [0, 1].map(|w| counts[w].iter().map(|&c| c as f64).sum::<f64>() / (TORI[w] * TORI[w]) as f64);
let var: f64 = [0, 1]
.map(|w| {
let (sq, n) = reference_square_sum(&counts[w], TORI[w], means[w]);
sq / n as f64
})
.iter()
.sum();
let k = 1.0 / var.sqrt();
// The overlap of the cell at `i` with `[a, a + w]`.
let overlap = |i: i64, a: f64, w: f64| ((i + 1) as f64).min(a + w) - (i as f64).max(a);
let integral_by_hand = |which: usize, x0: f32, y0: f32, w: f32| {
let (x0, y0, w, t) = (x0 as f64, y0 as f64, w as f64, TORI[which] as i64);
let mut sum = 0.0;
for j in y0.floor() as i64..(y0 + w).ceil() as i64 {
for i in x0.floor() as i64..(x0 + w).ceil() as i64 {
let c = counts[which][(j.rem_euclid(t) * t + i.rem_euclid(t)) as usize] as f64;
sum += (c - means[which]) * k * overlap(i, x0, w) * overlap(j, y0, w);
}
}
sum
};
for which in [0, 1] {
let t = TORI[which] as f32;
for (x0, y0, w) in [
(0.0, 0.0, 2.0),
(100.0, 200.0, 37.0),
(3.25, 7.5, 2.0),
(10.6, 11.3, 0.7),
(50.5, 60.25, 400.0),
(t - 1.5, 20.0, 4.0),
(20.0, t - 1.5, 4.0),
(t - 0.5, t - 0.25, 31.0),
(-1.5, -2.25, 8.0),
(3.0 * t + 12.5, -2.0 * t + 40.5, 8.0),
] {
let (got, want) = (tile.box_sum(which, x0, y0, w) as f64, integral_by_hand(which, x0, y0, w));
let area = (w * w) as f64;
assert!((got - want).abs() / area < 2e-3, "torus {which}, ({x0}, {y0}) side {w}: {got} vs {want}");
}
}
// the field is the two tori's mean, centred on its position
let (x, y, w) = (640.25, 1133.5, 3.0);
let want = (integral_by_hand(0, x - 0.5 * w, y - 0.5 * w, w) + integral_by_hand(1, x - 0.5 * w, y - 0.5 * w, w)) / (w * w) as f64;
assert!((tile.field(x, y, w) as f64 - want).abs() < 2e-3, "field {} vs {want}", tile.field(x, y, w));
}
/// A render under the footprint limit gets grain, one at or past it none, whatever else it asks.
#[test]
fn only_a_render_past_the_footprint_limit_loses_its_grain() {
let g = Grain { amount: 50.0, size: 25.0, roughness: 50.0, seed: 3 };
let limit = TILE_PER_LONG / MAX_FOOTPRINT as f64;
assert_eq!(limit, 24.0);
for none in [limit, limit - 1.0, 1.0, 0.0, -5.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
assert!(CrystalGrain::new(&g, none).is_none(), "{none} px per long edge");
}
assert_eq!(CrystalGrain::new(&g, limit + 1.0).expect("grain").foot, 480.0);
assert_eq!(CrystalGrain::new(&g, REF_LONG).expect("grain").foot, 2.0);
assert!(CrystalGrain::new(&Grain { amount: 0.0, ..g }, REF_LONG).is_none(), "no grain at Amount 0");
}
/// A draft (a Size or Roughness drag) doesn't wait for a new tile: the last tile of the seed stands
/// in while the new one is drawn in the background, and then the drag gets it. A render that
/// waits always gets the exact tile, as does a draft for a seed with no tile yet.
#[test]
fn a_drag_takes_the_last_tile_while_the_next_is_drawn() {
// a cache of its own: other tests' tiles (through any V7 render) would evict from the shared one
static OWN: Cache = Mutex::new(Vec::new());
let tile = |look, seed, wait| tile_in(&OWN, look, seed, wait);
let (seed, fresh) = (0x0d4a_0001, 0x0d4a_0002);
let (a, b) = (CrystalLook::new(30.0, 50.0), CrystalLook::new(31.0, 50.0));
let exact = |look: CrystalLook, seed: u32| patch(&CrystalTile::new(look, seed).expect("tile"), REF_LONG, 32, 0);
let first = tile(a, seed, true).expect("tile");
assert_eq!(first.look, a);
let stand_in = tile(b, seed, false).expect("tile");
assert_eq!(stand_in.look, a, "the draft waited for its tile");
// the drag's next renders get the new tile once it is drawn
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
let drawn = loop {
let t = tile(b, seed, false).expect("tile");
if t.look == b {
break t;
}
assert!(std::time::Instant::now() < deadline, "the background tile never arrived");
std::thread::sleep(std::time::Duration::from_millis(5));
};
assert_eq!(patch(&drawn, REF_LONG, 32, 0), exact(b, seed));
assert_eq!(patch(&tile(b, seed, true).expect("tile"), REF_LONG, 32, 0), exact(b, seed));
// nothing drawn for this seed: nothing to stand in, the draft draws it
assert_eq!(patch(&tile(a, fresh, false).expect("tile"), REF_LONG, 32, 0), exact(a, fresh));
}
/// A render that misses a tile another thread is drawing waits for that tile rather than drawing
/// it a second time.
#[test]
fn a_render_waits_for_a_tile_being_drawn() {
static OWN: Cache = Mutex::new(Vec::new());
let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0003);
let key = key_of(look, seed);
let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet");
let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true));
until_waiting(&marker, 1);
let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile"));
keep(&OWN, key, drawn.clone());
drop(marker);
let got = render.join().expect("render thread").expect("tile");
assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again");
}
/// A render waiting for a tile gets it from its drawer even when the cache evicted it before the
/// render woke.
#[test]
fn a_waiting_render_gets_the_tile_the_cache_evicted() {
static OWN: Cache = Mutex::new(Vec::new());
let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0004);
let key = key_of(look, seed);
let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet");
let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true));
until_waiting(&marker, 1);
let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile"));
marker.finish(&drawn);
keep(&OWN, key, drawn.clone());
// other renders' tiles push it out of the cache before the waiter wakes
// (each its own tile: a waiter that took another key's would fail the check below)
for other in 1..=CACHE as u32 {
keep(&OWN, key_of(look, seed + other), Arc::new(CrystalTile::new(look, seed + other).expect("tile")));
}
assert!(cached(&OWN, key).is_none(), "the tile is still cached");
drop(marker);
let got = render.join().expect("render thread").expect("tile");
assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again");
}
/// A render waiting for a tile another render is drawing gets the drawer's tile even when the
/// cache drops it before the waiter wakes.
#[test]
fn a_render_drawing_a_tile_hands_it_to_its_waiter() {
static OWN: Cache = Mutex::new(Vec::new());
let id = std::ptr::from_ref(&OWN) as usize;
// the first render's draw (only: a second would be the waiter drawing it again) waits for the
// second render to wait for it, and the cache empties before the second wakes
HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((id, 1, 1));
EVICTS.lock().unwrap_or_else(PoisonError::into_inner).push(id);
let (look, seed) = (CrystalLook::new(0.0, 50.0), 0x0d4a_0005);
let renders: Vec<_> = (0..2).map(|_| std::thread::spawn(move || tile_in(&OWN, look, seed, true))).collect();
let got: Vec<_> = renders.into_iter().map(|r| r.join().expect("render thread").expect("tile")).collect();
assert!(cached(&OWN, key_of(look, seed)).is_none(), "the cache kept the tile");
assert!(Arc::ptr_eq(&got[0], &got[1]), "the waiter drew the tile again");
}
/// Renders that miss the same tile together draw it once: the first registers the draw and the
/// others wait for it, as no gap lets a second render find it neither cached nor being drawn.
/// The first draw is held until the other renders all wait for it, so the misses overlap.
#[test]
fn renders_that_miss_a_tile_together_draw_it_once() {
static OWN: Cache = Mutex::new(Vec::new());
const N: usize = 8;
// the first render's draw waits for the other seven to miss the tile too
const SEEDS: u32 = 40;
HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((std::ptr::from_ref(&OWN) as usize, N - 1, SEEDS as usize));
let look = CrystalLook::new(0.0, 50.0);
for seed in 0x0d4a_1000..0x0d4a_1000 + SEEDS {
let start = Arc::new(std::sync::Barrier::new(N));
let renders: Vec<_> = (0..N)
.map(|_| {
let start = start.clone();
std::thread::spawn(move || {
start.wait();
tile_in(&OWN, look, seed, true)
})
})
.collect();
let got: Vec<_> = renders.into_iter().map(|r| r.join().expect("render thread").expect("tile")).collect();
assert!(got.iter().all(|t| Arc::ptr_eq(t, &got[0])), "seed {seed:#x}: a render drew the tile again");
}
}
/// Grain width (autocorrelation half-width at mid grey, 6000 px) at Lightroom Classic's
/// measured settings (open PR #1060's table); Size 0 is as fine as uncorrelated pixels get (0.5).
#[test]
fn width_matches_lightroom_classic() {
let lrc = [(0.0, 50.0, 0.5), (25.0, 50.0, 1.13), (100.0, 50.0, 3.38), (25.0, 0.0, 0.86), (25.0, 100.0, 1.54)];
for (s, r, want) in lrc {
let got = half_width(&patch(&tile_of(s, r), REF_LONG, 360, 0), 360);
assert!((got / want - 1.0).abs() < 0.1, "size {s} roughness {r}: width {got:.3}, want {want}");
}
}
/// Prints how long drawing a tile takes per setting (`--ignored --nocapture`, alone).
#[test]
#[ignore]
fn tile_timing_report() {
for (s, r) in [(0.0, 50.0), (10.0, 50.0), (25.0, 50.0), (50.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0), (100.0, 100.0)] {
let look = CrystalLook::new(s, r);
let mut best = f64::INFINITY;
for seed in 0..5 {
let start = std::time::Instant::now();
let t = CrystalTile::new(look, 100 + seed);
best = best.min(start.elapsed().as_secs_f64() * 1e3);
assert!(t.is_some());
}
eprintln!("size {s:>5} roughness {r:>5}: {best:.1} ms ({:?})", look);
}
}
/// Fits the median crystal width per Size (Roughness 50) and the Roughness factors at Size 25 to
/// Lightroom Classic's grain widths (`--ignored --nocapture`; paste into the look tables).
#[test]
#[ignore]
fn fit_widths() {
let width_of = |look: CrystalLook| {
let mut w = 0.0;
for seed in [11, 12] {
let t = CrystalTile::new(look, seed).expect("tile");
w += half_width(&patch(&t, REF_LONG, 360, 0), 360) / 2.0;
}
w
};
let fit = |s: f64, r: f64, want: f64| {
let base = CrystalLook::new(s, r);
let (mut lo, mut hi) = (0.05f64, 40.0f64);
for _ in 0..18 {
let mid = (lo * hi).sqrt();
if width_of(CrystalLook { width: mid, ..base }) < want { lo = mid } else { hi = mid }
}
let d = (lo * hi).sqrt();
(d, width_of(CrystalLook { width: d, ..base }))
};
for (s, want) in [(0.0, 0.43), (10.0, 0.71), (25.0, 1.13), (50.0, 1.70), (75.0, 2.54), (100.0, 3.38)] {
let (d, got) = fit(s, 50.0, want);
eprintln!("size {s}: width {d:.3} gives {got:.3} (want {want})");
}
let (d50, _) = fit(25.0, 50.0, 1.13);
for (r, want) in [(0.0, 0.86), (100.0, 1.54)] {
let (d, got) = fit(25.0, r, want);
eprintln!("roughness {r}: factor {:.3} gives {got:.3} (want {want})", d / d50);
}
}
/// Autocorrelation at lags 1–4 and the strength kept by box downscales of 2–16 (relative), of
/// candidate looks (`--ignored --nocapture`): compares a look's texture with a reference's.
#[test]
#[ignore]
fn texture_report() {
let profile = |look: CrystalLook| {
let n = 512;
let (mut acf, mut down) = ([0.0; 4], [0.0; 4]);
for seed in [21, 22] {
let t = CrystalTile::new(look, seed).expect("tile");
let v = patch(&t, REF_LONG, n, 0);
let s0 = std(&v);
for (k, a) in acf.iter_mut().enumerate() {
let lag = k + 1;
let mut s = 0.0f64;
for y in 0..n {
for x in 0..n - lag {
s += (v[y * n + x] * v[y * n + x + lag] + v[x * n + y] * v[(x + lag) * n + y]) as f64;
}
}
*a += s / (2 * n * (n - lag)) as f64 / (s0 * s0) / 2.0;
}
for (k, d) in down.iter_mut().enumerate() {
let f = 2usize << k;
let m = n / f;
let b: Vec<f32> = (0..m * m)
.map(|q| {
let (x, y) = (q % m * f, q / m * f);
(0..f * f).map(|i| v[(y + i / f) * n + x + i % f]).sum::<f32>() / (f * f) as f32
})
.collect();
*d += std(&b) / s0 / 2.0;
}
}
(acf, down)
};
for (s, r) in [(25.0, 50.0), (50.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] {
let (a, d) = profile(CrystalLook::new(s, r));
eprintln!(
"size {s} roughness {r}: acf {:.2} {:.2} {:.2} {:.2} down {:.2} {:.2} {:.2} {:.3}",
a[0], a[1], a[2], a[3], d[0], d[1], d[2], d[3]
);
}
}
/// A row computed with shared box edges equals the per-pixel boxes: any size, mirrored rows, rows
/// across the tori's seams and far from the origin.
#[test]
fn row_field_matches_per_pixel_field() {
let t = tile_of(25.0, 50.0);
for (w, sign, x, y) in [
(2.0f32, 1.0f32, 3.3f32, 7.9f32),
(2.0, -1.0, 9000.2, 1275.0),
(8.0, 1.0, 11990.0, 2260.5),
(0.7, 1.0, 1279.6, 0.1),
(31.0, -1.0, 400.0, 1133.9),
] {
for along_x in [true, false] {
let mut row = vec![0.0f32; 700];
t.row_field(x, y, w, sign * w, along_x, &mut row);
for (k, &v) in row.iter().enumerate() {
let d = sign * w * k as f32;
let want = if along_x { t.field(x + d, y, w) } else { t.field(x, y + d, w) };
assert!((v - want).abs() < 2e-3, "w {w} sign {sign} x {along_x} from ({x}, {y}), pixel {k}: {v} vs {want}");
}
}
}
}
/// Per-pixel cost of the grain on one thread (`--ignored --nocapture`).
#[test]
#[ignore]
fn pixel_cost_report() {
let g = CrystalGrain::new(&Grain { amount: 50.0, size: 25.0, roughness: 50.0, seed: 1 }, REF_LONG).expect("grain");
let (w, h) = (4000usize, 600usize);
let mut sink = 0.0f32;
let t0 = std::time::Instant::now();
for y in 0..h {
for x in 0..w {
sink += g.tile.field((x as f32 + 0.5) * 2.0, (y as f32 + 0.5) * 2.0, 2.0);
}
}
let per_pixel = t0.elapsed().as_secs_f64() / (w * h) as f64 * 1e9;
let mut row = vec![0.0; w];
let t1 = std::time::Instant::now();
for y in 0..h {
g.tile.row_field(1.0, (y as f32 + 0.5) * 2.0, 2.0, 2.0, true, &mut row);
sink += row[7];
}
let per_row = t1.elapsed().as_secs_f64() / (w * h) as f64 * 1e9;
let t3 = std::time::Instant::now();
for y in 0..h {
g.tile.row_field((y as f32 + 0.5) * 2.0, 1.0, 2.0, 2.0, false, &mut row);
sink += row[7];
}
eprintln!("column {:.1} ns/px", t3.elapsed().as_secs_f64() / (w * h) as f64 * 1e9);
let t2 = std::time::Instant::now();
for y in 0..h {
for x in 0..w {
sink += g.apply_field([0.4, 0.5, 0.6], (x + y) as f32 * 1e-4)[1];
}
}
let tone = t2.elapsed().as_secs_f64() / (w * h) as f64 * 1e9;
eprintln!("field {per_pixel:.1} ns/px, row {per_row:.1} ns/px, tone {tone:.1} ns/px ({sink})");
}
+99
View File
@@ -0,0 +1,99 @@
//! Film grain through the whole pipeline: which model each process renders with, and the crystal
//! grain's resolution independence (`crate::crystal`).
use lightcraft_develop::{DevelopSettings, Process};
use lightcraft_raster::Rgb32f;
use crate::finish::GrainModel;
use crate::{OutputDepth, RenderRequest, SourceInfo, render};
fn on(process: Process, amount: f64) -> DevelopSettings {
let mut s = DevelopSettings { process: process.version(), ..Default::default() };
s.grain.amount = amount;
s
}
/// Display-encoded luminance (0..255, 16-bit precision) of a render of `src` at `w × h`.
fn luma(src: &Rgb32f, s: &DevelopSettings, w: usize, h: usize) -> Vec<f64> {
let mut req = RenderRequest::fit(w, h);
req.depth = OutputDepth::U16;
let r = render(src, &SourceInfo::default(), s, &req);
let Some(crate::DeepSamples::U16(v)) = r.deep.map(|d| d.samples) else { panic!("no 16-bit render") };
v.chunks(3).map(|p| (0.2126 * p[0] as f64 + 0.7152 * p[1] as f64 + 0.0722 * p[2] as f64) / 257.0).collect()
}
fn std(v: &[f64]) -> f64 {
let m = v.iter().sum::<f64>() / v.len() as f64;
(v.iter().map(|x| (x - m).powi(2)).sum::<f64>() / v.len() as f64).sqrt()
}
#[test]
fn processes_before_v7_keep_the_value_noise() {
for p in Process::ALL {
let model = GrainModel::new(&on(p, 40.0), 2000.0, false);
match p {
Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => {
assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}")
}
Process::V7 | Process::V8 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"),
}
assert!(GrainModel::new(&on(p, 0.0), 2000.0, false).is_none(), "{p:?}: no grain at Amount 0");
}
let src = Rgb32f::filled(160, 120, [0.18; 3]);
let (v6, v7) = (luma(&src, &on(Process::V6, 50.0), 160, 120), luma(&src, &on(Process::V7, 50.0), 160, 120));
assert_ne!(v6, v7, "V7 renders the crystal grain");
}
/// Grain is all that V7 changes: without it, a photo renders as under V6.
#[test]
fn without_grain_v7_renders_as_v6() {
let src = Rgb32f::filled(160, 120, [0.18, 0.4, 0.7]);
assert_eq!(luma(&src, &on(Process::V6, 0.0), 160, 120), luma(&src, &on(Process::V7, 0.0), 160, 120));
}
/// A preview shows what the export shows, box-downscaled to its size (whole pipeline).
#[test]
fn small_render_matches_the_downscaled_large_render() {
let src = Rgb32f::filled(300, 200, [0.18; 3]);
let (w, h, k) = (1200, 800, 4);
for size in [0.0, 25.0, 100.0] {
let mut s = on(Process::V7, 60.0);
s.grain.size = size;
let base = luma(&src, &on(Process::V7, 0.0), w, h);
let big: Vec<f64> = luma(&src, &s, w, h).iter().zip(&base).map(|(a, b)| a - b).collect();
let down: Vec<f64> = (0..(w / k) * (h / k))
.map(|q| {
let (x, y) = (q % (w / k) * k, q / (w / k) * k);
(0..k * k).map(|i| big[(y + i / k) * w + x + i % k]).sum::<f64>() / (k * k) as f64
})
.collect();
let small = luma(&src, &s, w / k, h / k);
let ratio = std(&small) / std(&down);
assert!((0.95..1.05).contains(&ratio), "size {size}: preview / export grain {ratio:.3}");
// and the same grain pixel by pixel, not just as strong: the preview's grain (less its
// no-grain render) against the downscaled export's
let small_base = luma(&src, &on(Process::V7, 0.0), w / k, h / k);
let delta: Vec<f64> = small.iter().zip(&small_base).map(|(a, b)| a - b).collect();
// (measured: at most 0.003 of 255 levels apart, the 16-bit output's rounding; the grain's
// standard deviation is 1.4–2.9 levels, so a shifted or reseeded pattern is far outside)
let worst = delta.iter().zip(&down).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
assert!(worst < 0.01, "size {size}: preview grain {worst:.4} levels from the downscaled export's");
}
}
/// Degenerate and hostile grain settings render finite pixels under V7.
#[test]
fn hostile_grain_settings_render() {
let src = Rgb32f::filled(40, 30, [0.5, 0.2, 0.05]);
for (amount, size, rough) in
[(f64::NAN, 25.0, 50.0), (1e9, -1e9, f64::INFINITY), (50.0, f64::NAN, f64::NAN), (100.0, 100.0, 100.0), (-5.0, 0.0, 0.0)]
{
let mut s = on(Process::V7, amount);
s.grain.size = size;
s.grain.roughness = rough;
s.grain.seed = u32::MAX;
for (w, h) in [(40, 30), (1, 1), (3, 400)] {
assert!(luma(&src, &s, w, h).iter().all(|v| v.is_finite()), "{amount}/{size}/{rough} at {w}×{h}");
}
}
}
+93 -1
View File
@@ -208,6 +208,98 @@ fn median_orders_special_values_and_ties_like_total_cmp() {
}
}
/// A row of "8"s (two rings each, strokes 1.3 detail radii `r` wide, neighbours 0.8 radii apart):
/// dark lettering on a bright panel at the size of a bus number, as log luminance.
fn lettering(r: usize) -> (Plane, impl Fn(usize, usize) -> bool) {
let rf = r as f32;
let ring = move |x: f32, y: f32, cx: f32, cy: f32, outer: f32| {
let d = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt();
d <= outer && d >= outer - 1.3 * rf
};
let stroke = move |x: usize, y: usize| {
let (x, y) = (x as f32, y as f32);
(0..5).any(|i| {
let cx = 150.0 + i as f32 * 7.4 * rf;
ring(x, y, cx, 200.0 - 2.8 * rf, 2.9 * rf) || ring(x, y, cx, 200.0 + 3.2 * rf, 3.3 * rf)
})
};
(Plane::from_fn(900, 400, |x, y| if stroke(x, y) { -4.6 } else { -1.3 }), stroke)
}
#[test]
fn gaps_between_letters_keep_their_own_tone_in_the_base() {
// At the size of a bus number in a 7000 px photo, a median at the detail radius filled the
// gaps between the digits and around their waists with the letters' tone: 360 panel pixels
// sat over 1 EV (up to 2.3 EV) above their base, so Shadows lifted them by up to 1.3 EV into
// bright blocks. The wider median sees the panel there, so the gaps keep their own tone.
let ppl = 6960.0;
let r = local::base_detail_radius(ppl);
assert_eq!(r, 10);
let (l, stroke) = lettering(r);
let (w, h) = (l.width, l.height);
let base = local::tone_base(&l, 0.015 * ppl as f32, r, true);
// panel pixels at least 3 px from a stroke (the guided filter's own edge softness aside)
let panel = |x: usize, y: usize| !(x.saturating_sub(2)..(x + 3).min(w)).any(|a| (y.saturating_sub(2)..(y + 3).min(h)).any(|b| stroke(a, b)));
let (mut worst, mut under) = (0.0f32, 0usize);
for y in 0..h {
for x in (0..w).filter(|&x| panel(x, y)) {
let d = l.get(x, y) - base.get(x, y);
worst = worst.max(d);
under += usize::from(d > 1.0);
}
}
assert!(under == 0 && worst < 1.0, "{under} panel px over 1 EV above their base; worst {worst} EV");
}
#[test]
fn isolated_lines_up_to_the_detail_radius_stay_out_of_the_base() {
// Light lines 1 to 9 px wide on a dark ground (twigs against a dark wall, r = 10): the base
// keeps the ground's tone under each, as under the median (#632), so Shadows lifts them with
// the ground and they keep their contrast. Clamping to the window's quartiles instead let lines
// of 6 px and more a third to two thirds of the way into the base.
let ppl = 6960.0;
let r = local::base_detail_radius(ppl);
let widths = [1usize, 2, 3, 4, 5, 6, 7, 8, 9];
let l = Plane::from_fn(1300, 200, |x, _| {
let (i, off) = (x / 130, x % 130);
if i < widths.len() && (60..60 + widths[i]).contains(&off) { -2.0 } else { -6.0 }
});
let base = local::tone_base(&l, 0.015 * ppl as f32, r, true);
for (i, wd) in widths.iter().enumerate() {
let leak = (base.get(i * 130 + 60 + wd / 2, 100) + 6.0) / 4.0;
assert!(leak.abs() < 0.05, "a {wd} px line is {leak} of the way into the base");
}
}
#[test]
fn only_process_v8_on_takes_the_detail_free_base() {
// V2 to V7 keep the plain median (V1 has none): they are released and frozen (`tests_legacy`)
for p in Process::ALL {
let s = DevelopSettings { process: p.version(), ..Default::default() };
assert_eq!(local::base_keeps_gaps(&s), p >= Process::V8, "{p:?}");
}
let (l, _) = lettering(10);
let plain = local::guided_fast(&local::median_hv(&l, 10), 100.0, local::BASE_EPS);
assert_eq!(local::tone_base(&l, 100.0, 10, false).data, plain.data);
assert_ne!(local::tone_base(&l, 100.0, 10, true).data, plain.data);
}
#[test]
fn detail_free_keeps_steps_and_regions() {
// a step between two flat regions, and a flat field, come out as they went in
let step = Plane::from_fn(90, 60, |x, _| if x < 45 { -4.0 } else { 0.5 });
assert_eq!(local::detail_free(&step, 6).data, step.data);
let flat = Plane::from_fn(31, 17, |_, _| -1.25);
assert_eq!(local::detail_free(&flat, 3).data, flat.data);
assert_eq!(local::detail_free(&step, 0).data, step.data);
// tiny and empty planes, and NaNs, are not a panic
for (w, h) in [(1, 1), (2, 3), (5, 1)] {
let p = Plane::from_fn(w, h, |x, y| if (x + y) % 2 == 0 { f32::NAN } else { 1.0 });
assert_eq!(local::detail_free(&p, 4).data.len(), w * h);
}
assert!(local::detail_free(&Plane::new(0, 0), 4).data.is_empty());
}
#[test]
fn v1_keeps_the_base_it_always_had() {
// V1's base is the edge-aware filter of log luminance itself, as before process V2: no median
@@ -225,7 +317,7 @@ fn v1_keeps_the_base_it_always_had() {
let l =
Plane::from_fn(301, 157, |x, y| (((x * 31 + y * 17) * 2_654_435_761usize) % 1000) as f32 / 250.0 - 2.0 + if x % 5 == 0 { 0.5 } else { 0.0 });
for sg in [1.0f32, 4.5, 18.0] {
assert_eq!(local::tone_base(&l, sg, 0).data, local::guided_fast(&l, sg, local::BASE_EPS).data, "sigma {sg}");
assert_eq!(local::tone_base(&l, sg, 0, true).data, local::guided_fast(&l, sg, local::BASE_EPS).data, "sigma {sg}");
}
// V2 takes the median wherever the image is big enough for one
let v2 = with("light.highlights", -100.0);
+68 -1
View File
@@ -6,7 +6,7 @@ use lightcraft_develop::{DevelopSettings, controls};
use lightcraft_geom::{Orientation, Rect};
use lightcraft_raster::{Rgb32f, Rgba8};
use crate::{PixelWindow, RenderRequest, SourceInfo, render};
use crate::{OutputDepth, PixelWindow, RenderRequest, SourceInfo, render};
const W: usize = 960;
const H: usize = 640;
@@ -422,6 +422,73 @@ fn auto_mask_strokes_match_the_whole_render() {
check_noisy("auto mask", &s, PixelWindow { x: 400, y: 300, w: 300, h: 250 }, 2, 0.1);
}
// Given a lens blur, a window (zoomed view) blurs right up to its edges as the whole render does:
// it is rendered with the blur's reach around it
#[test]
fn lens_blur_matches_the_whole_render_up_to_the_window_edges() {
lens_blur_window_matches(OutputDepth::U8);
lens_blur_window_matches(OutputDepth::U16);
}
/// A high-bit-depth window grows for the lens blur too, and is cut back to the request.
fn lens_blur_window_matches(depth: OutputDepth) {
use lightcraft_develop::{Mask, MaskComponent, MaskOp, MaskShape};
use lightcraft_geom::Point;
let radial = MaskShape::Radial { center: Point::new(0.5, 0.5), rx: 0.15, ry: 0.2, angle: 0.0, feather: 30.0, invert: false };
let mut s = DevelopSettings {
masks: vec![Mask {
id: 4,
components: vec![MaskComponent { name: None, op: MaskOp::Add, invert: false, shape: radial }],
..Default::default()
}],
..Default::default()
};
s.lens_blur.enabled = true;
s.lens_blur.amount = 80.0;
s.lens_blur.boost = 40.0;
s.lens_blur.focus_mask = Some(4);
let deep = |win: Option<PixelWindow>| {
let r = render(&scene(), &SourceInfo::default(), &s, &RenderRequest { window: win, depth, ..RenderRequest::fit(W, H) });
if let Some(d) = &r.deep {
assert_eq!((d.width, d.height), (r.image.width, r.image.height));
}
r.image
};
let (f, w) = (deep(None), deep(Some(MID)));
assert_eq!((w.width, w.height), (MID.w, MID.h));
let (max, mean) = compare_inset(&f, &w, MID, 0);
assert!(max <= 6 && mean <= 0.4, "max {max}, mean {mean:.3}");
// and the blur shows: the whole render differs from the one without it
let mut off = s.clone();
off.lens_blur.enabled = false;
let (_, mean) = compare_inset(&full(&off), &f, PixelWindow { x: 0, y: 0, w: f.width, h: f.height }, 0);
assert!(mean > 1.0, "{mean:.3}");
}
/// With the automatic subject focus (no focus mask, no fixed shape, no person matte) a window
/// focuses where the whole render does: the estimate comes from the whole photo, not from the
/// pixels the window holds.
#[test]
fn lens_blur_on_the_estimated_subject_matches_the_whole_render() {
let mut s = DevelopSettings::default();
s.lens_blur.enabled = true;
s.lens_blur.amount = 80.0;
// a sharp cut: the window then grows only by the blur's radius, less than the estimate reads
s.lens_blur.transition = 0.0;
for depth in [OutputDepth::U8, OutputDepth::U16] {
let r = |win: Option<PixelWindow>| {
render(&scene(), &SourceInfo::default(), &s, &RenderRequest { window: win, depth, ..RenderRequest::fit(W, H) }).image
};
// a window at the middle and one at an edge, where the estimate's neighbourhood is cut off
for win in [MID, PixelWindow { x: 0, y: 0, w: 300, h: 220 }] {
let (f, w) = (r(None), r(Some(win)));
assert_eq!((w.width, w.height), (win.w, win.h));
let (max, mean) = compare_inset(&f, &w, win, 0);
assert!(max <= 6 && mean <= 0.4, "{depth:?} {win:?}: max {max}, mean {mean:.3}");
}
}
}
// Given the joint colour NR, a window is filtered with the whole frame's noise model: a quiet part of
// the frame does not make a window of its noisy part (or the other way round) smooth differently
#[test]
+11 -1
View File
@@ -82,7 +82,9 @@ pub fn covers(make: Option<&str>, model: &str) -> bool {
.map_or(model, |(_, rest)| rest.trim_start())
};
let listed = MODELS.iter().any(|(b, m)| brand.is_none_or(|x| x.eq_ignore_ascii_case(b)) && bare_of(b).eq_ignore_ascii_case(m));
let fuji = brand.is_none_or(|b| b.eq_ignore_ascii_case("FUJIFILM")) && FUJI_MODELS.iter().any(|m| bare_of("FUJIFILM").eq_ignore_ascii_case(m));
// A DxO demosaiced DNG keeps the Fujifilm model but carries DxO as its make.
let fuji = brand.is_none_or(|b| b.eq_ignore_ascii_case("FUJIFILM") || b.eq_ignore_ascii_case("DxO"))
&& FUJI_MODELS.iter().any(|m| bare_of("FUJIFILM").eq_ignore_ascii_case(m));
listed || fuji
}
@@ -408,6 +410,14 @@ mod tests {
}
}
#[test]
fn dxo_dng_fujifilm_model_is_covered_for_kelvin() {
// A DxO demosaiced DNG carries DxO as its make, not FUJIFILM, but it is still a Fujifilm model.
assert!(covers(Some("DxO"), "X-T2"));
assert!(covers(Some("DxO"), "FUJIFILM X-T2"));
assert!(covers_camera("DxO X-T2"));
}
#[test]
fn covered_models() {
assert!(covers_camera("NIKON CORPORATION NIKON Z5_2") && covers_camera("NIKON Z5_2") && !covers_camera("NIKON CORPORATION NIKON Z6"));
+3 -2
View File
@@ -18,8 +18,9 @@
//! 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; 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
//! 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,
//! two-field 12-bit samples and 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 Olympus ORF, 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.
-1
View File
@@ -21,7 +21,6 @@ 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;
+3 -1
View File
@@ -358,7 +358,9 @@ fn read_quad_tiles(bytes: &[u8], info: &ImageInfo) -> Result<Vec<u16>> {
.map(|c| {
let src = chunk_bytes(bytes, c).ok_or_else(|| RawError::Corrupt("tile offset past end of file".into()))?;
let f = ljpeg::decode(src, (c.width as usize * c.height as usize).max(1 << 16))?;
if f.components != 4 || f.data.len() < f.width * f.height * 4 {
// a tile's frame is half its nominal width and height: a larger one (which the sample cap above would
// still let through when the tile is small) is no Sony tile
if f.components != 4 || f.data.len() < f.width * f.height * 4 || f.width * 2 > c.width as usize || f.height * 2 > c.height as usize {
return Err(RawError::Corrupt(format!(
"lossless ARW tile: {} samples in a {}×{}×{} frame",
f.data.len(),
+12
View File
@@ -215,10 +215,22 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
let maker = static_maker.as_ref().and_then(|m| m.ifds.first());
// Retain only the first useful timed maker note: repeated CTMD records must not accumulate
// independent copies of every bounded TIFF value in memory.
// Records aliasing the same bytes are parsed once, and all parses share a budget of twice the file (at least 1 MiB);
// a record past what is left is skipped, a later smaller one still parsed.
let mut seen = std::collections::HashSet::new();
let mut left = bytes.len().saturating_mul(2).max(1 << 20);
let timed_maker = container
.timed_exif(bytes)
.into_iter()
.filter(|b| b.tag == 0x927c)
.filter(|b| seen.insert((b.data.as_ptr() as usize, b.data.len())))
.filter(|b| match left.checked_sub(b.data.len()) {
Some(rest) => {
left = rest;
true
}
None => false,
})
.filter_map(|b| Tiff::parse(b.data).ok())
.find(|t| t.ifds.first().is_some_and(|m| m.contains(COLOR_DATA)));
let color_maker = timed_maker.as_ref().and_then(|t| t.ifds.first()).or(maker);
+18 -18
View File
@@ -1,4 +1,4 @@
//! Olympus ORF — uncompressed and compressed variants.
//! Olympus ORF — uncompressed variants; compressed sensor data is unsupported.
//!
//! 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,9 +28,8 @@
//! (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 (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`.
//! - Compressed ORF sensor data is unsupported. The previous decoder was removed pending provenance
//! resolution; embedded previews remain available. 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
@@ -200,7 +199,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.
/// Decode the supported uncompressed Olympus ORF layouts into a mosaic raw image.
pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
let tiff = Tiff::parse(bytes)?;
let ifd0 = &tiff.ifds[0];
@@ -232,20 +231,10 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
Vec::new()
};
(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, &params)? } 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 {
} else if info.bits() == 12 && 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()))?;
// Only the declared 12-bit layout is supported here. A compressed stream in a 16-bit
// ORF container must not fall through to packed decoding just because its length fits.
// the strip as it is in the file (clipped at its end), not as its tag states it: one too short
// for the samples is a truncated file, refused before they are allocated
if (src.len() as u64).saturating_mul(8) < (n as u64).saturating_mul(12) {
@@ -413,6 +402,17 @@ mod tests {
b
}
/// A 16-bit container with a short sensor stream is not the supported 12-bit packed layout.
/// Both entry points must report unsupported rather than returning fabricated sensor pixels.
#[test]
fn compressed_sensor_data_is_unsupported_in_probe_and_decode() {
for strip_len in [8, 24, 25] {
let bytes = orf_with(4, 4, 16, vec![0; strip_len], Some(&[2, 0, 2, 0, 0, 1, 1, 2]));
assert!(matches!(crate::decode(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"));
assert!(matches!(crate::probe_info(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"));
}
}
/// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow.
#[test]
fn strip_byte_counts_past_u64_max_do_not_overflow() {
-489
View File
@@ -1,489 +0,0 @@
//! 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, &params).is_err());
assert_eq!(decompress_stream(&[], 0, 0, &params).unwrap(), Vec::<u16>::new());
// truncated stream (too short for requested dimensions) returns error
assert!(decompress_stream(&[0xff; 2], 10, 10, &params).is_err());
assert!(decompress_stream(&[0x00; 2], 10, 10, &params).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, &params);
}
}
}
+2
View File
@@ -17,6 +17,8 @@ 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] = &[
"orf-olympus-em1.orf", // Compressed Olympus sensor decoding withdrawn pending provenance resolution.
"orf-olympus-em10iii.orf",
"cr3-", // Unverified CRX coding variants; exact supported cases live in cr3_corpus.rs.
"-he.nef", // Nikon High Efficiency (HE / HE★) NEF, issue #193
"sraw", // Canon sRAW / mRAW
+19 -3
View File
@@ -8,7 +8,7 @@
//! pinned only (its small JPEG gives r 0.59); its render was inspected by eye.
//! Missing files are reported as skipped.
use lightcraft_raw::{RawData, decode, embedded_preview, probe_info};
use lightcraft_raw::{RawData, RawError, RawFormat, decode, embedded_preview, probe, probe_info};
use std::path::{Path, PathBuf};
fn corpus() -> PathBuf {
@@ -67,8 +67,6 @@ 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),
@@ -114,3 +112,21 @@ fn olympus_and_samsung_bodies_decode_like_the_camera_jpeg() {
}
eprintln!("Olympus / Samsung bodies checked on {seen} files");
}
/// The withdrawn compressed decoder must stay out of both sensor-decode and import-probe paths.
/// Camera JPEG extraction is independent of sensor decoding and remains available for preview-only imports.
#[test]
fn compressed_olympus_bodies_are_unsupported_with_embedded_previews() {
for name in ["orf-olympus-em1.orf", "orf-olympus-em10iii.orf"] {
let path = corpus().join("raw").join(name);
let Ok(bytes) = std::fs::read(&path) else {
lightcraft_testkit::skip!(Corpus, "{} absent", path.display());
continue;
};
assert_eq!(probe(&bytes), Some(RawFormat::Orf), "{name}");
assert!(matches!(decode(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"), "{name}");
assert!(matches!(probe_info(&bytes), Err(RawError::Unsupported(why)) if why == "Olympus compressed ORF"), "{name}");
let jpeg = embedded_preview(&bytes).unwrap_or_else(|| panic!("{name}: no camera JPEG"));
assert!(jpeg.starts_with(&[0xff, 0xd8]) && jpeg.ends_with(&[0xff, 0xd9]), "{name}: invalid camera JPEG");
}
}
+107
View File
@@ -333,10 +333,117 @@ pub fn merge(out: &Output, threshold: f32) -> Option<Prediction> {
merged.map(|logits| Prediction { logits, score: best })
}
/// Share of the largest candidate's area another needs to count among the photo's main subjects
/// (people in front, not the crowd behind them).
pub const PROMINENT: f32 = 0.25;
/// Which candidates are the photo's subject, given each one's area (cells it selects) and, when the
/// camera recorded where it focused, whether it covers that point. The focus decides: the
/// candidates it falls on, with the others about as large either way (a group at the same
/// distance); a focus on none of them means the subject is something else (empty: the caller
/// selects what is at the point).
/// Without a focus: the largest, and the others about as large.
pub fn pick_prominent(areas: &[usize], on_focus: Option<&[bool]>) -> Vec<usize> {
let largest = |ks: &mut dyn Iterator<Item = usize>| ks.filter_map(|k| areas.get(k).copied()).max().unwrap_or(0);
let near = |a: usize, of: usize| of > 0 && a as f32 >= PROMINENT * of as f32;
match on_focus {
Some(hit) => {
let focused: Vec<usize> = (0..areas.len()).filter(|k| hit.get(*k).copied().unwrap_or(false) && areas[*k] > 0).collect();
if focused.is_empty() {
return Vec::new();
}
// about as large as what is in focus, either way: much larger is nearer the camera
// than the focus, so out of focus too
let of = largest(&mut focused.iter().copied());
let alike = |a: usize| near(a, of) && (a as f32) * PROMINENT <= of as f32;
(0..areas.len()).filter(|k| focused.contains(k) || alike(areas[*k])).collect()
}
None => {
let of = largest(&mut (0..areas.len()));
(0..areas.len()).filter(|k| near(areas[*k], of)).collect()
}
}
}
/// The instances of several detector outputs (one per concept: "person", "animal") above
/// `threshold` that [`pick_prominent`] keeps, each with its share of its concept's semantic mask,
/// merged into one mask. `focus`: where the camera focused (normalized). `None` when nothing is kept.
pub fn subject(outs: &[Output], threshold: f32, focus: Option<(f32, f32)>) -> Option<Prediction> {
let s = |x: f32| 1.0 / (1.0 + (-x).exp());
// (mask, score, concept)
let mut cands: Vec<(Vec<f32>, f32, usize)> = Vec::new();
for (c, out) in outs.iter().enumerate() {
let presence = s(out.presence);
for (i, l) in out.logits.iter().enumerate() {
let p = s(*l) * presence;
if p > threshold
&& let Some(m) = out.masks.i(i).ok().and_then(|t| to_vec(&t).ok())
{
cands.push((m, p, c));
}
}
}
let n = cands.first()?.0.len();
let side = (n as f64).sqrt() as usize;
if side == 0 || side * side != n || cands.iter().any(|c| c.0.len() != n) {
return None;
}
let areas: Vec<usize> = cands.iter().map(|c| c.0.iter().filter(|l| **l > 0.0).count()).collect();
let cell = focus.filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| {
let at = |v: f32| ((v.clamp(0.0, 1.0) * side as f32) as usize).min(side - 1);
at(y) * side + at(x)
});
let hits: Option<Vec<bool>> = cell.map(|i| cands.iter().map(|c| c.0.get(i).is_some_and(|l| *l > 0.0)).collect());
let keep = pick_prominent(&areas, hits.as_deref());
if keep.is_empty() {
return None;
}
let best = keep.iter().filter_map(|k| cands.get(*k)).map(|c| c.1).fold(0f32, f32::max);
let mut merged: Option<Vec<f32>> = None;
for (c, out) in outs.iter().enumerate() {
let mut masks: Vec<Vec<f32>> = keep.iter().filter_map(|k| cands.get(*k)).filter(|x| x.2 == c).map(|x| x.0.clone()).collect();
if masks.is_empty() {
continue;
}
share(&mut masks, &out.semantic);
for m in masks {
merged = Some(match merged {
Some(acc) => acc.iter().zip(&m).map(|(a, b)| a.max(*b)).collect(),
None => m,
});
}
}
merged.map(|logits| Prediction { logits, score: best })
}
#[cfg(test)]
mod tests {
use super::*;
/// A group in front is kept, the crowd behind isn't; the camera's focus decides: on a person,
/// that person and the others as large; on nobody, nothing (the object there is the subject).
#[test]
fn prominent_subjects() {
// four people in front, two small ones far behind
let areas = [900, 1000, 800, 950, 60, 40];
assert_eq!(pick_prominent(&areas, None), vec![0, 1, 2, 3]);
// focused on the first: the group
let hit = [true, false, false, false, false, false];
assert_eq!(pick_prominent(&areas, Some(&hit)), vec![0, 1, 2, 3]);
// focused on someone small behind: that one and whoever is about as large, not the
// (much larger, so nearer and out of focus) group in front
let hit = [false, false, false, false, true, false];
assert_eq!(pick_prominent(&areas, Some(&hit)), vec![4, 5]);
// a product in front of people: the focus is on none of them
assert!(pick_prominent(&areas, Some(&[false; 6])).is_empty());
// nobody at all, or empty masks
assert!(pick_prominent(&[], None).is_empty());
assert!(pick_prominent(&[0, 0], None).is_empty());
assert!(pick_prominent(&[0, 5], Some(&[true, false])).is_empty());
// a mismatched focus list is read as "not on it"
assert_eq!(pick_prominent(&[10, 9], Some(&[true])), vec![0, 1]);
}
/// Two people side by side on a row of cells, each only weakly sure of themself and both fading where
/// they touch; the semantic mask is sure of both and runs across. Each takes the semantic logits where
/// it is the strongest instance, a third region nobody is near keeps its own.
+19
View File
@@ -76,9 +76,15 @@ pub type Result<T> = std::result::Result<T, Error>;
pub const INPUT: usize = 1008;
/// Side of the low-resolution masks the model predicts.
pub const MASK_SIDE: usize = 288;
/// Most clicks one Object selection may carry (the engine's `MAX_CLICKS`).
pub const MAX_CLICKS: usize = 64;
#[cfg(not(target_arch = "wasm32"))]
const _: () = assert!(MASK_SIDE == tracker::LOW_RES && INPUT == vit::IMAGE);
/// What a photo's subject usually is, as concept prompts ([`Sam3::segment_subject`]); anything else
/// (an object, a landscape's feature) is selected at the focus point instead.
pub const SUBJECT_CONCEPTS: &[&str] = &["person", "animal"];
/// The files of a model directory.
pub const WEIGHTS_FILE: &str = "model.safetensors";
@@ -203,6 +209,10 @@ impl Sam3 {
if clicks.is_empty() {
return Err(Error::Model("no clicks".into()));
}
// the prompt grows with every click: the editor takes at most this many (the engine's `MAX_CLICKS`)
if clicks.len() > MAX_CLICKS {
return Err(Error::Model(format!("at most {MAX_CLICKS} clicks, not {}", clicks.len())));
}
let (neck, tracker) = self.tracker_parts()?;
if enc.tracker.is_none() {
let levels = neck.forward(&enc.backbone, 3)?;
@@ -241,6 +251,15 @@ impl Sam3 {
Ok(detector::merge(&out, threshold))
}
/// The photo's subject among its people and animals ([`detector::subject`]): the ones the
/// camera's focus (`focus`, normalized; `None` when the file doesn't record it) falls on, or
/// without it the most prominent, with whoever is about as large. `None` when the subject is
/// neither (a focus on something else, or nobody in the photo): select what is at the point.
pub fn segment_subject(&mut self, enc: &mut Encoded, focus: Option<(f32, f32)>, threshold: f32) -> Result<Option<Prediction>> {
let outs = SUBJECT_CONCEPTS.iter().map(|c| self.detect(enc, c)).collect::<Result<Vec<_>>>()?;
Ok(detector::subject(&outs, threshold, focus))
}
/// Raw detector outputs for `text` (tests and tools).
pub fn detect(&mut self, enc: &mut Encoded, text: &str) -> Result<detector::Output> {
let (det, tok) = self.detector_parts()?;
+10 -1
View File
@@ -17,6 +17,9 @@ pub enum Operation {
Prepare,
Clicks(Vec<[f32; 3]>),
Text(String),
/// The photo's subject among its people and animals ([`Sam3::segment_subject`]), from where
/// the camera focused (normalized `[x, y]`) when the file records it.
Subject(Option<[f32; 2]>),
}
#[derive(Serialize, Deserialize)]
@@ -36,7 +39,8 @@ impl Request {
return Err("detail pass requires an image".into());
}
match &self.operation {
Operation::Prepare => {}
Operation::Prepare | Operation::Subject(None) => {}
Operation::Subject(Some(f)) if f.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)) => {}
Operation::Text(text) if text.len() <= 4096 && text.split([',', ';']).any(|p| !p.trim().is_empty()) => {}
Operation::Clicks(clicks)
if !clicks.is_empty()
@@ -131,6 +135,11 @@ fn predict(model: &mut Sam3, enc: &mut Encoded, operation: Operation) -> Result<
Ok(None)
}
Operation::Text(text) => text_logits(model, enc, &text).map_err(|e| e.to_string()),
// (the reference score threshold, as a local Find Subject uses)
Operation::Subject(focus) => {
let p = model.segment_subject(enc, focus.map(|f| (f[0], f[1])), 0.5).map_err(|e| e.to_string())?;
Ok(p.map(|p| p.logits))
}
Operation::Clicks(points) => {
let clicks: Vec<_> = points.into_iter().map(|p| Click { x: p[0], y: p[1], positive: p[2] == 1.0 }).collect();
Ok(Some(model.segment_clicks(enc, &clicks).map_err(|e| e.to_string())?.logits))
+6
View File
@@ -18,4 +18,10 @@ fn validates_images_and_prompt_boundaries() {
assert!(request(4, 3, Operation::Clicks(vec![[0.5, f32::NAN, 1.0]])).validate().is_err());
assert!(request(4, 3, Operation::Clicks(vec![[0.5, 0.5, 0.0]])).validate().is_err());
assert!(request(4, 3, Operation::Text(" ".into())).validate().is_err());
// Find Subject: with or without the camera's focus point, which must lie in the photo
assert!(request(4, 3, Operation::Subject(None)).validate().is_ok());
assert!(request(4, 3, Operation::Subject(Some([0.3, 0.7]))).validate().is_ok());
for bad in [[1.5, 0.5], [0.5, -0.1], [f32::NAN, 0.5], [0.5, f32::INFINITY]] {
assert!(request(4, 3, Operation::Subject(Some(bad))).validate().is_err(), "{bad:?}");
}
}
+1 -1
View File
@@ -220,7 +220,7 @@ pub fn compose_with(
) -> (Rgba8, Layout) {
let s = s.clone().sanitized();
let (w, h) = slide_size(out_w, out_h);
let has_photo = photo.width > 0 && photo.height > 0 && photo.data.len() == photo.width * photo.height;
let has_photo = photo.width > 0 && photo.height > 0 && Some(photo.data.len()) == photo.width.checked_mul(photo.height);
let aspect = if has_photo { photo.width as f64 / photo.height as f64 } else { f64::NAN };
let l = layout(&s, aspect, w, h);
let c = s.backdrop_color;
+28
View File
@@ -2400,6 +2400,34 @@
"Save Current Settings as New Effect Preset…": "Uložit aktuální nastavení jako nové přednastavení efektu…",
"Manage Effect Presets…": "Spravovat přednastavení efektů…",
"Export Effect Presets…": "Exportovat přednastavení efektů…",
"Blur Amount": "Míra rozostření",
"Boost": "Zesílení",
"In Focus": "Zaostřeno",
"Blur what is out of focus, as a wide aperture would": "Rozostří, co je mimo zaostření, jako by to udělala široce otevřená clona",
"What stays sharp: the photo's subject, or the selection of one of its masks": "Co zůstane ostré: subjekt fotky nebo výběr jedné z jejích masek",
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Tip: subjekt přesně vyberte maskou Objekt (Maskování, M) a pak tu masku zvolte zde.",
"Brush Refinement": "Doladění štětcem",
"Blur": "Rozostření",
"Paint what should stay sharp": "Namalujte, co má zůstat ostré",
"Paint what should be blurred": "Namalujte, co se má rozostřit",
"Remove the strokes of both brushes": "Odstranit tahy obou štětců",
"Find Subject": "Najít subjekt",
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Vybrat subjekt pomocí AI (SAM 3), od místa, kam zaostřil fotoaparát, pokud ho soubor uvádí, a ponechat ho zaostřený",
"Selecting the subject at the camera's focus point…": "Vybírá se subjekt v bodě zaostření fotoaparátu…",
"Selecting the subject…": "Vybírá se subjekt…",
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Dolaďte ho v Maskování (M): + → Objekt přidá, co chybí, − → Objekt část vynechá.",
"Finding the subject… The first time on a photo takes a while.": "Hledá se subjekt… Poprvé to u fotky chvíli trvá.",
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Subjekt nebyl vybrán. Zkuste znovu Najít subjekt, nebo na něj klikněte v Maskování (M).",
"Transition": "Přechod",
"Selection": "Výběr",
"Outside": "Mimo výběr",
"Shape": "Tvar",
"Round": "Kruh",
"Auto: the photo's subject, estimated": "Automaticky: odhadnutý subjekt fotky",
"Horizontal oval": "Vodorovný ovál",
"Vertical oval": "Svislý ovál",
"Move & Resize": "Přesunout a změnit velikost",
"Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Tažením tvaru na fotce ho přesunete; tažením boční nebo spodní úchytky ho roztáhnete. Tlačítko tvaru ho vrátí doprostřed.",
"Before/After Side by Side": "Před/Po vedle sebe",
"Clipping": "Ořezání tónů",
"Mask Overlay": "Překrytí masky",
+28
View File
@@ -3433,6 +3433,34 @@
"Optional remote SAM 3: keep the native editor local and run Object, Describe, and detail": "Optionales entferntes SAM 3: Der native Editor bleibt lokal, und Objekt-, Beschreibungs- und Detail-",
"inference on a Mac through SSH. Saved masks still render and export offline.": "Inferenz laufen über SSH auf einem Mac. Gespeicherte Masken werden weiterhin offline gerendert und exportiert.",
"See [remote Metal inference](ai-masks.md#remote-metal-inference).": "Siehe [remote Metal inference](ai-masks.md#remote-metal-inference).",
"Blur Amount": "Unschärfestärke",
"Boost": "Verstärkung",
"In Focus": "Im Fokus",
"Blur what is out of focus, as a wide aperture would": "Zeichnet unscharf, was außerhalb des Fokus liegt, wie eine weit geöffnete Blende",
"What stays sharp: the photo's subject, or the selection of one of its masks": "Was scharf bleibt: das Motiv des Fotos oder die Auswahl einer seiner Masken",
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Tipp: Wählen Sie das Motiv mit einer Objekt-Maske (Maskieren, M) genau aus und wählen Sie diese Maske dann hier.",
"Brush Refinement": "Pinselkorrektur",
"Blur": "Unschärfe",
"Paint what should stay sharp": "Malen, was scharf bleiben soll",
"Paint what should be blurred": "Malen, was unscharf werden soll",
"Remove the strokes of both brushes": "Die Striche beider Pinsel entfernen",
"Find Subject": "Motiv finden",
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Das Motiv per KI (SAM 3) auswählen, ausgehend vom Fokuspunkt der Kamera, wenn die Datei ihn enthält, und scharf halten",
"Selecting the subject at the camera's focus point…": "Motiv am Fokuspunkt der Kamera wird ausgewählt…",
"Selecting the subject…": "Motiv wird ausgewählt…",
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "In Maskieren (M) verfeinern: + → Objekt fügt Fehlendes hinzu, − → Objekt lässt einen Teil weg.",
"Finding the subject… The first time on a photo takes a while.": "Motiv wird gesucht… Beim ersten Mal dauert das bei einem Foto eine Weile.",
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Das Motiv wurde nicht ausgewählt. Versuchen Sie erneut „Motiv finden“ oder klicken Sie es in Maskieren (M) an.",
"Transition": "Übergang",
"Selection": "Auswahl",
"Outside": "Außerhalb",
"Shape": "Form",
"Round": "Rund",
"Auto: the photo's subject, estimated": "Automatisch: das geschätzte Motiv des Fotos",
"Horizontal oval": "Liegendes Oval",
"Vertical oval": "Stehendes Oval",
"Move & Resize": "Verschieben & Größe",
"Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Ziehen Sie die Form auf dem Foto, um sie zu verschieben; ziehen Sie den seitlichen oder unteren Griff, um sie zu dehnen. Eine Form-Schaltfläche setzt sie wieder in die Mitte.",
"Before/After Side by Side": "Vorher/Nachher nebeneinander",
"Clipping": "Beschneidung",
"Mask Overlay": "Maskenüberlagerung",
+1 -1
View File
@@ -172,7 +172,7 @@
"{n} photo{} now · updates automatically as photos change": "{n} foto{} ahora · se actualiza automáticamente cuando cambian las fotos",
"{n} selected photo{} · {pages} page{}": "{n} foto{0} seleccionada{0} · {pages} página{1}",
"{pid} (missing)": "{pid} (falta)",
"{sel_n} selected · {counted}": "{sel_n} seleccionadas · {counted}",
"{sel_n} selected · {counted}": "Seleccionadas: {sel_n} · {counted}",
"{stage}… {:.0}%": "{stage}… {:.0}%",
"{verb} {n} Photo{}": "{verb} {n} foto{}",
"{weekday}, {day}": "{weekday}, {day}",
+28
View File
@@ -2358,6 +2358,34 @@
"CPU": "CPU",
"A face model uses the GPU only when a check shows it gives the same results faster.": "Un modelo de caras usa la GPU solo cuando una comprobación muestra que da los mismos resultados más rápido.",
"Checking the GPU for faces": "Comprobando la GPU para las caras",
"Blur Amount": "Cantidad de desenfoque",
"Boost": "Realce",
"In Focus": "Enfocado",
"Blur what is out of focus, as a wide aperture would": "Desenfoca lo que está fuera de foco, como lo haría una apertura amplia",
"What stays sharp: the photo's subject, or the selection of one of its masks": "Lo que queda nítido: el sujeto de la foto o la selección de una de sus máscaras",
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Consejo: selecciona el sujeto con precisión con una máscara Objeto (Máscaras, M) y luego elige esa máscara aquí.",
"Brush Refinement": "Refinamiento con pincel",
"Blur": "Desenfoque",
"Paint what should stay sharp": "Pinta lo que debe quedar nítido",
"Paint what should be blurred": "Pinta lo que debe desenfocarse",
"Remove the strokes of both brushes": "Quitar los trazos de ambos pinceles",
"Find Subject": "Buscar sujeto",
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Selecciona el sujeto con IA (SAM 3), empezando donde enfocó la cámara si el archivo lo registra, y lo mantiene enfocado",
"Selecting the subject at the camera's focus point…": "Seleccionando el sujeto en el punto de enfoque de la cámara…",
"Selecting the subject…": "Seleccionando el sujeto…",
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Ajústalo en Máscaras (M): + → Objeto añade lo que faltó, − → Objeto excluye una parte.",
"Finding the subject… The first time on a photo takes a while.": "Buscando el sujeto… La primera vez en una foto tarda un poco.",
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "No se seleccionó el sujeto. Vuelve a probar Buscar sujeto o haz clic en él en Máscaras (M).",
"Transition": "Transición",
"Selection": "Selección",
"Outside": "Fuera",
"Shape": "Forma",
"Round": "Redonda",
"Auto: the photo's subject, estimated": "Automático: el sujeto estimado de la foto",
"Horizontal oval": "Óvalo horizontal",
"Vertical oval": "Óvalo vertical",
"Move & Resize": "Mover y redimensionar",
"Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Arrastra la forma en la foto para moverla; arrastra su tirador lateral o inferior para estirarla. Un botón de forma la devuelve al centro.",
"Layout Image": "Imagen de diseño",
"Detail View": "Vista de detalle",
"Edit Panel": "Panel Editar",
+28
View File
@@ -2340,6 +2340,34 @@
"≤ at most": "≤ enintään",
"≥ at least": "≥ vähintään",
"★ Favorites": "★ Suosikit",
"Blur Amount": "Epätarkkuuden määrä",
"Boost": "Korostus",
"In Focus": "Tarkka alue",
"Blur what is out of focus, as a wide aperture would": "Sumentaa tarkennuksen ulkopuolisen alueen, kuten suuri aukko tekisi",
"What stays sharp: the photo's subject, or the selection of one of its masks": "Mikä pysyy tarkkana: kuvan kohde tai jonkin sen maskin valinta",
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Vinkki: valitse kohde tarkasti Kohde-maskilla (Maskaus, M) ja valitse sitten se maski tästä.",
"Brush Refinement": "Siveltimellä tarkennus",
"Blur": "Sumennus",
"Paint what should stay sharp": "Maalaa, minkä pitää pysyä tarkkana",
"Paint what should be blurred": "Maalaa, minkä pitää sumentua",
"Remove the strokes of both brushes": "Poista molempien siveltimien vedot",
"Find Subject": "Etsi kohde",
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Valitse kohde tekoälyllä (SAM 3) aloittaen kameran tarkennuskohdasta, jos tiedosto kertoo sen, ja pidä se tarkkana",
"Selecting the subject at the camera's focus point…": "Valitaan kohdetta kameran tarkennuspisteestä…",
"Selecting the subject…": "Valitaan kohdetta…",
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Hienosäädä Maskauksessa (M): + → Kohde lisää puuttuvan, − → Kohde jättää osan pois.",
"Finding the subject… The first time on a photo takes a while.": "Etsitään kohdetta… Ensimmäisellä kerralla kuvassa tämä kestää hetken.",
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Kohdetta ei valittu. Kokeile Etsi kohde uudelleen tai napsauta sitä Maskauksessa (M).",
"Transition": "Siirtymä",
"Selection": "Valinta",
"Outside": "Ulkopuoli",
"Shape": "Muoto",
"Round": "Pyöreä",
"Auto: the photo's subject, estimated": "Automaattinen: kuvan arvioitu kohde",
"Horizontal oval": "Vaakasuora soikio",
"Vertical oval": "Pystysuora soikio",
"Move & Resize": "Siirrä ja muuta kokoa",
"Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Siirrä muotoa vetämällä sitä kuvassa; venytä sitä vetämällä sivu- tai alakahvasta. Muotopainike palauttaa sen keskelle.",
"All Mask Overlays": "Kaikki maskien peittokuvat",
"Before/After Side by Side": "Ennen/jälkeen vierekkäin",
"Clipping": "Leikkautuminen",
+28
View File
@@ -2353,6 +2353,34 @@
"CPU": "Processeur",
"A face model uses the GPU only when a check shows it gives the same results faster.": "Un modèle de visages n’utilise le GPU que si une vérification montre qu’il donne les mêmes résultats plus vite.",
"Checking the GPU for faces": "Vérification du GPU pour les visages",
"Blur Amount": "Quantité de flou",
"Boost": "Accentuation",
"In Focus": "Zone nette",
"Blur what is out of focus, as a wide aperture would": "Floute ce qui est hors de la mise au point, comme le ferait une grande ouverture",
"What stays sharp: the photo's subject, or the selection of one of its masks": "Ce qui reste net : le sujet de la photo ou la sélection de l'un de ses masques",
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Astuce : sélectionnez précisément le sujet avec un masque Objet (Masquage, M), puis choisissez ce masque ici.",
"Brush Refinement": "Affinage au pinceau",
"Blur": "Flou",
"Paint what should stay sharp": "Peignez ce qui doit rester net",
"Paint what should be blurred": "Peignez ce qui doit être flou",
"Remove the strokes of both brushes": "Supprimer les traits des deux pinceaux",
"Find Subject": "Trouver le sujet",
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Sélectionne le sujet par IA (SAM 3), à partir de l'endroit où l'appareil a fait la mise au point si le fichier l'indique, et le garde net",
"Selecting the subject at the camera's focus point…": "Sélection du sujet au point de mise au point de l'appareil…",
"Selecting the subject…": "Sélection du sujet…",
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Affinez-le dans Masquage (M) : + → Objet ajoute ce qui manque, − → Objet exclut une partie.",
"Finding the subject… The first time on a photo takes a while.": "Recherche du sujet… La première fois sur une photo, cela prend un moment.",
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Le sujet n'a pas été sélectionné. Réessayez Trouver le sujet, ou cliquez dessus dans Masquage (M).",
"Transition": "Transition",
"Selection": "Sélection",
"Outside": "Extérieur",
"Shape": "Forme",
"Round": "Ronde",
"Auto: the photo's subject, estimated": "Auto : le sujet estimé de la photo",
"Horizontal oval": "Ovale horizontal",
"Vertical oval": "Ovale vertical",
"Move & Resize": "Déplacer et redimensionner",
"Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Faites glisser la forme sur la photo pour la déplacer ; faites glisser sa poignée latérale ou inférieure pour l'étirer. Un bouton de forme la remet au centre.",
"Layout Image": "Image de mise en page",
"Detail View": "Vue de détail",
"Edit Panel": "Panneau Modifier",
+28
View File
@@ -2353,6 +2353,34 @@
"≥ at least": "≥ minimal",
"日本語": "日本語",
"繁體中文(台灣)": "繁體中文(台灣)",
"Blur Amount": "Jumlah buram",
"Boost": "Penguatan",
"In Focus": "Dalam fokus",
"Blur what is out of focus, as a wide aperture would": "Memburamkan bagian di luar fokus, seperti bukaan lebar",
"What stays sharp: the photo's subject, or the selection of one of its masks": "Yang tetap tajam: subjek foto, atau seleksi salah satu maskernya",
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Tips: pilih subjek dengan tepat memakai masker Objek (Masker, M), lalu pilih masker itu di sini.",
"Brush Refinement": "Penyempurnaan kuas",
"Blur": "Buram",
"Paint what should stay sharp": "Lukis bagian yang harus tetap tajam",
"Paint what should be blurred": "Lukis bagian yang harus diburamkan",
"Remove the strokes of both brushes": "Hapus goresan kedua kuas",
"Find Subject": "Cari subjek",
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Pilih subjek dengan AI (SAM 3), mulai dari titik fokus kamera bila file mencatatnya, lalu jaga tetap fokus",
"Selecting the subject at the camera's focus point…": "Memilih subjek di titik fokus kamera…",
"Selecting the subject…": "Memilih subjek…",
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Sempurnakan di Masker (M): + → Objek menambah yang terlewat, − → Objek mengecualikan bagian.",
"Finding the subject… The first time on a photo takes a while.": "Mencari subjek… Pertama kali pada sebuah foto butuh waktu.",
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Subjek tidak terpilih. Coba Cari subjek lagi, atau klik subjeknya di Masker (M).",
"Transition": "Transisi",
"Selection": "Seleksi",
"Outside": "Luar",
"Shape": "Bentuk",
"Round": "Bulat",
"Auto: the photo's subject, estimated": "Otomatis: perkiraan subjek foto",
"Horizontal oval": "Oval horizontal",
"Vertical oval": "Oval vertikal",
"Move & Resize": "Pindah & ubah ukuran",
"Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Seret bentuk di foto untuk memindahkannya; seret pegangan samping atau bawahnya untuk merenggangkannya. Tombol bentuk mengembalikannya ke tengah.",
"All Mask Overlays": "Semua overlay masker",
"Before/After Side by Side": "Sebelum/Sesudah berdampingan",
"Clipping": "Clipping",
+28
View File
@@ -2394,6 +2394,34 @@
"Show briefly when photo changes": "Mostra brevemente al cambio di foto",
"Camera & Lens": "Fotocamera e obiettivo",
"View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2.",
"Blur Amount": "Quantità di sfocatura",
"Boost": "Enfasi",
"In Focus": "A fuoco",
"Blur what is out of focus, as a wide aperture would": "Sfoca ciò che è fuori fuoco, come farebbe un diaframma molto aperto",
"What stays sharp: the photo's subject, or the selection of one of its masks": "Cosa resta nitido: il soggetto della foto o la selezione di una delle sue maschere",
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Suggerimento: seleziona con precisione il soggetto con una maschera Oggetto (Mascheratura, M), poi scegli qui quella maschera.",
"Brush Refinement": "Rifinitura a pennello",
"Blur": "Sfocatura",
"Paint what should stay sharp": "Dipingi ciò che deve restare nitido",
"Paint what should be blurred": "Dipingi ciò che deve essere sfocato",
"Remove the strokes of both brushes": "Rimuovi le pennellate di entrambi i pennelli",
"Find Subject": "Trova soggetto",
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Seleziona il soggetto con l'IA (SAM 3), partendo dal punto di messa a fuoco della fotocamera se il file lo registra, e lo mantiene a fuoco",
"Selecting the subject at the camera's focus point…": "Selezione del soggetto nel punto di messa a fuoco della fotocamera…",
"Selecting the subject…": "Selezione del soggetto…",
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Rifiniscilo in Mascheratura (M): + → Oggetto aggiunge ciò che manca, − → Oggetto esclude una parte.",
"Finding the subject… The first time on a photo takes a while.": "Ricerca del soggetto… La prima volta su una foto richiede un po' di tempo.",
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Il soggetto non è stato selezionato. Riprova Trova soggetto, oppure fai clic su di esso in Mascheratura (M).",
"Transition": "Transizione",
"Selection": "Selezione",
"Outside": "Esterno",
"Shape": "Forma",
"Round": "Rotonda",
"Auto: the photo's subject, estimated": "Automatico: il soggetto stimato della foto",
"Horizontal oval": "Ovale orizzontale",
"Vertical oval": "Ovale verticale",
"Move & Resize": "Sposta e ridimensiona",
"Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Trascina la forma sulla foto per spostarla; trascina la maniglia laterale o inferiore per allungarla. Un pulsante di forma la riporta al centro.",
"Before/After Side by Side": "Prima/Dopo affiancati",
"Clipping": "Tagli tonali",
"Mask Overlay": "Sovrapposizione maschera",
+28
View File
@@ -2356,6 +2356,34 @@
"CPU": "CPU",
"A face model uses the GPU only when a check shows it gives the same results faster.": "顔モデルが GPU を使うのは、同じ結果をより速く出せると確認できた場合だけです。",
"Checking the GPU for faces": "顔用の GPU を確認中",
"Blur Amount": "ぼかしの量",
"Boost": "ブースト",
"In Focus": "ピントを合わせる対象",
"Blur what is out of focus, as a wide aperture would": "絞りを大きく開いたように、ピントの外側をぼかします",
"What stays sharp: the photo's subject, or the selection of one of its masks": "シャープに残す部分:写真の被写体、またはいずれかのマスクの選択範囲",
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "ヒント:オブジェクトマスク(マスク、M)で被写体を正確に選択してから、ここでそのマスクを選びます。",
"Brush Refinement": "ブラシで調整",
"Blur": "ぼかし",
"Paint what should stay sharp": "シャープに残す部分をペイント",
"Paint what should be blurred": "ぼかす部分をペイント",
"Remove the strokes of both brushes": "両方のブラシのストロークを削除",
"Find Subject": "被写体を検出",
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "AI(SAM 3)で被写体を選択します。ファイルにカメラのフォーカス位置があればそこから始め、被写体にピントを保ちます",
"Selecting the subject at the camera's focus point…": "カメラのフォーカス位置で被写体を選択しています…",
"Selecting the subject…": "被写体を選択しています…",
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "マスク(M)で調整:+ → オブジェクトで不足分を追加、− → オブジェクトで一部を除外します。",
"Finding the subject… The first time on a photo takes a while.": "被写体を探しています… 写真ごとに初回は時間がかかります。",
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "被写体を選択できませんでした。もう一度「被写体を検出」を試すか、マスク(M)で被写体をクリックしてください。",
"Transition": "トランジション",
"Selection": "選択範囲",
"Outside": "外側",
"Shape": "形",
"Round": "円形",
"Auto: the photo's subject, estimated": "自動:推定した写真の被写体",
"Horizontal oval": "横長の楕円",
"Vertical oval": "縦長の楕円",
"Move & Resize": "移動とサイズ変更",
"Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "写真上の形をドラッグして移動します。横または下のハンドルをドラッグして伸ばします。形のボタンで中央に戻ります。",
"Layout Image": "レイアウト画像",
"Detail View": "詳細表示",
"Edit Panel": "編集パネル",
+28
View File
@@ -2751,6 +2751,34 @@
"⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-გადათრევა გასასწორებლად, ⇧G მართვადი Upright, ბადე გარდაქმნისას.",
"日本語": "日本語",
"繁體中文(台灣)": "繁體中文(台灣)",
"Blur Amount": "ბუნდოვნების რაოდენობა",
"Boost": "გაძლიერება",
"In Focus": "ფოკუსში",
"Blur what is out of focus, as a wide aperture would": "აბუნდოვნებს იმას, რაც ფოკუსის გარეთაა, როგორც ფართოდ გახსნილი დიაფრაგმა",
"What stays sharp: the photo's subject, or the selection of one of its masks": "რა რჩება მკვეთრი: ფოტოს საგანი ან მისი ერთ-ერთი ნიღბის მონიშვნა",
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "რჩევა: საგანი ზუსტად მონიშნეთ ობიექტის ნიღბით (ნიღბვა, M), შემდეგ კი აქ აირჩიეთ ეს ნიღაბი.",
"Brush Refinement": "ფუნჯით დახვეწა",
"Blur": "ბუნდოვნება",
"Paint what should stay sharp": "მოხატეთ ის, რაც მკვეთრი უნდა დარჩეს",
"Paint what should be blurred": "მოხატეთ ის, რაც უნდა გაბუნდოვნდეს",
"Remove the strokes of both brushes": "ორივე ფუნჯის შტრიხების წაშლა",
"Find Subject": "საგნის პოვნა",
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "საგნის მონიშვნა AI-ით (SAM 3) იქიდან, სადაც კამერამ ფოკუსირება მოახდინა, თუ ფაილი ამას ინახავს, და მისი ფოკუსში დატოვება",
"Selecting the subject at the camera's focus point…": "საგანი ინიშნება კამერის ფოკუსის წერტილში…",
"Selecting the subject…": "საგანი ინიშნება…",
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "დახვეწეთ ნიღბვაში (M): + → ობიექტი ამატებს გამორჩენილს, − → ობიექტი ნაწილს გამორიცხავს.",
"Finding the subject… The first time on a photo takes a while.": "საგანი იძებნება… ფოტოზე პირველად ამას გარკვეული დრო სჭირდება.",
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "საგანი ვერ მოინიშნა. სცადეთ „საგნის პოვნა“ ხელახლა, ან დააწკაპეთ მასზე ნიღბვაში (M).",
"Transition": "გადასვლა",
"Selection": "მონიშნული",
"Outside": "გარეთ",
"Shape": "ფორმა",
"Round": "მრგვალი",
"Auto: the photo's subject, estimated": "ავტომატური: ფოტოს სავარაუდო საგანი",
"Horizontal oval": "ჰორიზონტალური ოვალი",
"Vertical oval": "ვერტიკალური ოვალი",
"Move & Resize": "გადატანა და ზომის შეცვლა",
"Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "გადაიტანეთ ფორმა ფოტოზე მის გადასაადგილებლად; გაწიეთ გვერდითი ან ქვედა სახელური მის გასაჭიმად. ფორმის ღილაკი მას შუაში დააბრუნებს.",
"Focus Point": "ფოკუსის წერტილი",
"Layout Image": "განლაგების სურათი",
"Detail View": "დეტალური ხედი",
+29
View File
@@ -2275,6 +2275,35 @@
"SDR Whites": "Biele SDR",
"SDR Clarity": "Przejrzystość SDR",
"Face Models on the GPU": "Modele twarzy przetwarzane na GPU",
"Blur Amount": "Siła rozmycia",
"Boost": "Wzmocnienie",
"In Focus": "Ostrość na",
"Blur what is out of focus, as a wide aperture would": "Rozmywa to, co jest poza ostrością, jak szeroko otwarta przysłona",
"What stays sharp: the photo's subject, or the selection of one of its masks": "Co pozostaje ostre: główny obiekt zdjęcia lub zaznaczenie jednej z jego masek",
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Wskazówka: precyzyjnie zaznacz obiekt maską Obiekt (Maskowanie, M), a potem wybierz tę maskę tutaj.",
"Brush Refinement": "Korekta pędzlem",
"Focus": "Ostrość",
"Blur": "Rozmycie",
"Paint what should stay sharp": "Zamaluj to, co ma pozostać ostre",
"Paint what should be blurred": "Zamaluj to, co ma zostać rozmyte",
"Remove the strokes of both brushes": "Usuń pociągnięcia obu pędzli",
"Find Subject": "Znajdź obiekt",
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Zaznacz główny obiekt za pomocą AI (SAM 3), zaczynając od punktu ostrości aparatu, jeśli plik go zapisuje, i zachowaj go ostrym",
"Selecting the subject at the camera's focus point…": "Zaznaczanie obiektu w punkcie ostrości aparatu…",
"Selecting the subject…": "Zaznaczanie obiektu…",
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Popraw w Maskowaniu (M): + → Obiekt dodaje to, czego brakuje, − → Obiekt pomija część.",
"Finding the subject… The first time on a photo takes a while.": "Wyszukiwanie obiektu… Za pierwszym razem na zdjęciu trwa to chwilę.",
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Nie zaznaczono obiektu. Spróbuj ponownie Znajdź obiekt lub kliknij go w Maskowaniu (M).",
"Transition": "Przejście",
"Selection": "Zaznaczenie",
"Outside": "Na zewnątrz",
"Shape": "Kształt",
"Round": "Okrągły",
"Auto: the photo's subject, estimated": "Automatycznie: szacowany główny obiekt zdjęcia",
"Horizontal oval": "Owal poziomy",
"Vertical oval": "Owal pionowy",
"Move & Resize": "Przesuń i zmień rozmiar",
"Drag the shape on the photo to move it; drag its side or bottom handle to stretch it. A shape button puts it back in the middle.": "Przeciągnij kształt na zdjęciu, aby go przesunąć; przeciągnij uchwyt boczny lub dolny, aby go rozciągnąć. Przycisk kształtu przywraca go na środek.",
"Before/After Side by Side": "Przed/Po obok siebie",
"Clipping": "Prześwietlenia i niedoświetlenia",
"Mask Overlay": "Nakładka maski",
+1 -1
View File
@@ -130,7 +130,7 @@
"{n} photo{} match · updates automatically as photos change": "{n} foto{0} correspondente{0} · atualiza automaticamente conforme as fotos mudam",
"{n} photo{} now · updates automatically as photos change": "{n} foto{} agora · atualiza automaticamente conforme as fotos mudam",
"{n} selected photo{} · {pages} page{}": "{n} foto{0} selecionada{0} · {pages} página{1}",
"{sel_n} selected · {counted}": "{sel_n} selecionadas · {counted}",
"{sel_n} selected · {counted}": "Selecionadas: {sel_n} · {counted}",
"{stage}… {:.0}%": "{stage}… {:.0}%",
"{verb} {n} Photo{}": "{verb} {n} foto{}",
"{weekday}, {day}": "{weekday}, {day}",
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more