mirror of
https://github.com/storytold/lightcraft.git
synced 2026-12-03 04:26:03 -05:00
Merge upstream/main into fix/brush-flow-per-radius; Flow becomes process V9
Main took V8 for the Highlights/Shadows base (#3460), so brush Flow per radius travelled is V9; V1 to V8 keep the flow per dab. The Lens Blur brush that main added paints its live stroke with the same rule.
This commit is contained in:
116 files changed
+5036
-291
No files matched your search
@@ -23,6 +23,10 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
|
||||
@@ -28,6 +28,10 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install WiX
|
||||
shell: pwsh
|
||||
@@ -43,6 +47,10 @@ jobs:
|
||||
name: Windows installation policy (no app build)
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
@@ -12,9 +12,9 @@ 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 }}
|
||||
@@ -33,6 +33,10 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
@@ -68,6 +72,9 @@ jobs:
|
||||
|
||||
release:
|
||||
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:
|
||||
|
||||
Generated
+37
-36
@@ -1246,7 +1246,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1256,6 +1256,7 @@ dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
"plist",
|
||||
"rustix 1.1.5",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3587,7 +3588,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-update",
|
||||
@@ -3616,7 +3617,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-catalog"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"crc32fast",
|
||||
@@ -3637,7 +3638,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-cli"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"dhat",
|
||||
"lightcraft-codecs",
|
||||
@@ -3654,7 +3655,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-codecs"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"avif-serialize",
|
||||
"bytemuck",
|
||||
@@ -3685,7 +3686,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-color"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"lightcraft-geom",
|
||||
"proptest",
|
||||
@@ -3694,7 +3695,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-denoise"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"faer-core",
|
||||
"lightcraft-denoise-core",
|
||||
@@ -3711,7 +3712,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-denoise-core"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"dhat",
|
||||
"lightcraft-raster",
|
||||
@@ -3727,7 +3728,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-develop"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
@@ -3739,7 +3740,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-engine"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"ab_glyph",
|
||||
"chrono",
|
||||
@@ -3786,7 +3787,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-faces"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"lightcraft-testkit",
|
||||
"matrixmultiply",
|
||||
@@ -3801,7 +3802,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-fetch"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"rustls",
|
||||
@@ -3812,14 +3813,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-film"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-geocode"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"miniz_oxide 0.9.1",
|
||||
"serde",
|
||||
@@ -3827,7 +3828,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-geom"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -3835,7 +3836,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-gpu"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"lightcraft-color",
|
||||
@@ -3855,7 +3856,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-heif"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"heic-rs",
|
||||
"rayon",
|
||||
@@ -3863,14 +3864,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-inpaint"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-lensdb"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"lightcraft-develop",
|
||||
"lightcraft-geom",
|
||||
@@ -3879,7 +3880,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-mcp"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"lightcraft-codecs",
|
||||
"lightcraft-engine",
|
||||
@@ -3890,7 +3891,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-merge"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"lightcraft-codecs",
|
||||
"lightcraft-color",
|
||||
@@ -3906,7 +3907,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-meta"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"lightcraft-geom",
|
||||
@@ -3920,7 +3921,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-pipeline"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"dhat",
|
||||
"image",
|
||||
@@ -3939,7 +3940,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-preview"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"jpeg-encoder",
|
||||
"lightcraft-raster",
|
||||
@@ -3951,7 +3952,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-raster"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"lightcraft-color",
|
||||
@@ -3963,7 +3964,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-raw"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-crw",
|
||||
@@ -3989,7 +3990,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-scenes"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"lightcraft-color",
|
||||
@@ -4000,7 +4001,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-segment"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"candle-core",
|
||||
"candle-nn",
|
||||
@@ -4014,7 +4015,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-slideshow"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"lightcraft-raster",
|
||||
"serde",
|
||||
@@ -4023,15 +4024,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-sysmem"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-testkit"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-tiff"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -4040,7 +4041,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-ui-egui"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
@@ -4073,7 +4074,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-web"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"eframe",
|
||||
@@ -4096,7 +4097,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-wincolor"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"lightcraft-testkit",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -7915,7 +7916,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"flate2",
|
||||
|
||||
+2
-2
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.18.0"
|
||||
version = "0.21.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -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 = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
|
||||
# internal
|
||||
lightcraft-denoise-core = { path = "crates/denoise-core" }
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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" };
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -99,16 +99,20 @@ pub enum Process {
|
||||
/// 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 brush Flow as the coverage a stroke adds per brush radius it travels, as in
|
||||
/// Lightroom: a dab adds `1 − (1 − flow)^(distance from the previous dab / radius)`, so a
|
||||
/// stroke's strength no longer depends on how densely its dabs lie; V1 to V7 add `flow` per dab.
|
||||
/// 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,
|
||||
/// V8, with brush Flow as the coverage a stroke adds per brush radius it travels, as in
|
||||
/// Lightroom: a dab adds `1 − (1 − flow)^(distance from the previous dab / radius)`, so a
|
||||
/// stroke's strength no longer depends on how densely its dabs lie; V1 to V8 add `flow` per dab.
|
||||
V9,
|
||||
}
|
||||
|
||||
impl Process {
|
||||
/// Every process, oldest first.
|
||||
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 ALL: [Process; 9] =
|
||||
[Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7, Process::V8, Process::V9];
|
||||
pub const LATEST: Process = Process::V9;
|
||||
|
||||
pub const fn version(self) -> ProcessVersion {
|
||||
match self {
|
||||
@@ -120,6 +124,7 @@ impl Process {
|
||||
Process::V6 => ProcessVersion(6),
|
||||
Process::V7 => ProcessVersion(7),
|
||||
Process::V8 => ProcessVersion(8),
|
||||
Process::V9 => ProcessVersion(9),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -899,6 +904,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,
|
||||
@@ -926,6 +950,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,
|
||||
@@ -1267,13 +1296,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)]
|
||||
|
||||
@@ -89,14 +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 newer = Process::LATEST.version().0 + 1;
|
||||
let s = DevelopSettings::from_json(&json!({"process": newer, "light": {"exposure": 0.5}})).unwrap();
|
||||
assert_eq!(s.process, ProcessVersion(newer));
|
||||
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!(newer));
|
||||
assert_eq!(s.merged(&json!({"light": {"exposure": 1.0}})).unwrap().process, ProcessVersion(newer));
|
||||
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));
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -64,6 +64,9 @@ fn set_names_ops(s: &crate::Session, names: &[String; 5]) -> Vec<Op> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Most bytes of a track log file.
|
||||
const MAX_GPX_BYTES: u64 = 256 << 20;
|
||||
|
||||
/// Geotag photos from a GPX track log by capture time (Lightroom Classic's Map ▸ Tracklog ▸
|
||||
/// Auto-Tag Photos). GPX times are UTC; capture times are the camera's local clock, so a photo's
|
||||
/// recorded zone (Exif `OffsetTimeOriginal`) or the `offset` parameter converts them.
|
||||
@@ -72,7 +75,9 @@ fn auto_tag_tracklog(s: &mut crate::Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "photo.autoTagTracklog";
|
||||
let text = match (str_param(p, "gpx"), str_param(p, "path")) {
|
||||
(Some(t), _) => t.to_string(),
|
||||
(None, Some(path)) => std::fs::read_to_string(path).map_err(|e| bad(C, format!("can't read {path}: {e}")))?,
|
||||
(None, Some(path)) => crate::read_file::read_regular(path, MAX_GPX_BYTES)
|
||||
.map(|b| String::from_utf8_lossy(&b).into_owned())
|
||||
.map_err(|e| bad(C, format!("can't read {path}: {e}")))?,
|
||||
(None, None) => return Err(bad(C, "missing `path` (a .gpx file) or `gpx` (its text)")),
|
||||
};
|
||||
let log = parse_gpx(&text).map_err(|e| bad(C, e.to_string()))?;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -363,7 +363,7 @@ fn template_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if meta.len() > MAX_FILE {
|
||||
return Err(bad(ID, format!("{}: {} bytes is too large for a print template (at most {} KB)", path.display(), meta.len(), MAX_FILE / 1024)));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?;
|
||||
let bytes = crate::read_file::read_regular(path, MAX_FILE).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?;
|
||||
let mut t = PrintTemplate::from_file(&bytes).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?;
|
||||
if s.print_templates.len() >= MAX_TEMPLATES {
|
||||
return Err(bad(ID, format!("at most {MAX_TEMPLATES} templates; delete one first")));
|
||||
|
||||
@@ -29,11 +29,7 @@ impl Display {
|
||||
/// Load the ICC profile at `path`.
|
||||
pub fn load(path: &str) -> Result<Display, String> {
|
||||
let path = path.trim();
|
||||
let meta = std::fs::metadata(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
if meta.len() > MAX_PROFILE_BYTES as u64 {
|
||||
return Err(format!("{path}: too large for an ICC profile"));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let bytes = crate::read_file::read_regular(path, MAX_PROFILE_BYTES as u64).map_err(|e| format!("{path}: {e} (an ICC profile)"))?;
|
||||
Display::from_bytes(path, &bytes)
|
||||
}
|
||||
|
||||
|
||||
@@ -236,11 +236,14 @@ pub(crate) fn watermark_logo(path: &str) -> Option<std::sync::Arc<Rgba8>> {
|
||||
Some(img)
|
||||
}
|
||||
|
||||
/// Most bytes of a watermark or layout graphic file.
|
||||
const MAX_GRAPHIC_BYTES: u64 = 256 << 20;
|
||||
|
||||
/// A graphic file (a PNG with transparency, typically) as 8-bit sRGB with its alpha: the
|
||||
/// watermark logo, the loupe's layout image. Applies EXIF orientation before either consumer sizes it.
|
||||
/// The error says why it couldn't be read or decoded.
|
||||
pub fn read_graphic(path: &str) -> Result<Rgba8, String> {
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("can't read {path}: {e}"))?;
|
||||
let bytes = crate::read_file::read_regular(path, MAX_GRAPHIC_BYTES).map_err(|e| format!("can't read {path}: {e}"))?;
|
||||
let decoded = lightcraft_codecs::decode(&bytes, Default::default()).map_err(|e| format!("can't decode {path}: {e}"))?;
|
||||
Ok(decoded.to_srgb8().into_oriented(lightcraft_geom::Orientation::from_exif(decoded.orientation)))
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ pub fn fs_pair_loader() -> PairLoader {
|
||||
let weight = len * if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 4 } else { 10 };
|
||||
let gate = crate::memory::work_gate();
|
||||
let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) };
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let bytes = crate::read_file::read_regular(path, crate::read_file::MAX_MEDIA_BYTES).map_err(|e| format!("{path}: {e}"))?;
|
||||
let r = load_vec_pair(bytes, max_edge, spec, with);
|
||||
crate::memory::release();
|
||||
r
|
||||
@@ -84,15 +84,13 @@ pub fn fs_hooks() -> (FileLoader, FileProbe) {
|
||||
let loader: FileLoader =
|
||||
Arc::new(|path: &str, max_edge: usize, with: RawDecode<'_>| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge, with)));
|
||||
let probe: FileProbe = Arc::new(|path: &str| {
|
||||
use std::io::Read;
|
||||
// one open, then everything from the open file: its size and modification time are not
|
||||
// round trips of their own (on a network share each of them is one)
|
||||
let mut file = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let file = crate::read_file::open_for_read(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let meta = file.metadata().ok();
|
||||
let len = meta.as_ref().map_or(0, |m| usize::try_from(m.len()).unwrap_or(usize::MAX));
|
||||
let _permit = crate::memory::work_gate().acquire(len);
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes).map_err(|e| format!("{path}: {e}"))?;
|
||||
let bytes = crate::read_file::read_open(file, crate::read_file::MAX_MEDIA_BYTES).map_err(|e| format!("{path}: {e}"))?;
|
||||
let mut info = probe_bytes(path, &bytes)?;
|
||||
info.file_modified = meta.as_ref().and_then(modified_iso);
|
||||
Ok(info)
|
||||
@@ -111,7 +109,7 @@ fn fs_load<T>(path: &str, max_edge: usize, load: impl FnOnce(Vec<u8>) -> Result<
|
||||
let weight = len.saturating_mul(if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 3 } else { 6 });
|
||||
let gate = crate::memory::work_gate();
|
||||
let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) };
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let bytes = crate::read_file::read_regular(path, crate::read_file::MAX_MEDIA_BYTES).map_err(|e| format!("{path}: {e}"))?;
|
||||
let r = load(bytes);
|
||||
// the file, the samples and the intermediate images are gone: give their pages back
|
||||
crate::memory::release();
|
||||
|
||||
@@ -492,8 +492,14 @@ fn a_probe_of_a_file_that_cannot_be_read_names_the_path_and_the_cause() {
|
||||
for path in [dir.join("no-such-file.jpg"), dir.clone()] {
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let e = probe(&path).unwrap_err();
|
||||
assert_eq!(e, format!("{path}: {}", std::fs::read(&path).unwrap_err()));
|
||||
// a folder is refused as "not a regular file" before any read, so only the path and a cause are pinned
|
||||
assert!(e.starts_with(&format!("{path}: ")), "{e}");
|
||||
}
|
||||
// the system's own words for it, whatever the platform says
|
||||
let missing = dir.join("no-such-file.jpg");
|
||||
let want = std::fs::read(&missing).unwrap_err().to_string();
|
||||
let got = probe(&missing.to_string_lossy()).unwrap_err();
|
||||
assert_eq!(got.strip_prefix(&format!("{}: ", missing.to_string_lossy())), Some(want.as_str()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@ pub mod print_color;
|
||||
pub mod print_pdf;
|
||||
pub mod profile_refs;
|
||||
pub mod proof;
|
||||
pub(crate) mod read_file;
|
||||
pub mod rename;
|
||||
pub mod segment;
|
||||
pub mod sidecar;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
/// `a` 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!("{};&", "&".repeat(200_000));
|
||||
assert_eq!(unescape(&hostile), format!("{};&", "&".repeat(200_000)));
|
||||
assert_eq!(unescape("<a>  &unknownreference;"), "<a> \u{10FFFF} &unknownreference;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_padded_numeric_references_decode() {
|
||||
assert_eq!(unescape("Canon A A"), "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;");
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Reads of files named by a user, a sidecar or a library: the OPENED file must be a regular file within a byte
|
||||
//! cap, and no more than the cap is ever read. (A size taken from the pathname, then a second open and a read to EOF,
|
||||
//! lets a link, a FIFO, a device or a file that grows in between turn into an unbounded read.)
|
||||
|
||||
use std::io::{self, Read};
|
||||
use std::path::Path;
|
||||
|
||||
/// Most bytes of a photo, video or other media file read into memory.
|
||||
pub(crate) const MAX_MEDIA_BYTES: u64 = 8 << 30;
|
||||
|
||||
/// `O_NONBLOCK` of the platforms that have a FIFO to wait on (std has no name for it, and libc is a
|
||||
/// dev-dependency only); 0 elsewhere, where a FIFO open still waits for a writer.
|
||||
#[cfg(unix)]
|
||||
const O_NONBLOCK: i32 = if cfg!(all(
|
||||
any(target_os = "linux", target_os = "android"),
|
||||
not(any(
|
||||
target_arch = "mips",
|
||||
target_arch = "mips32r6",
|
||||
target_arch = "mips64",
|
||||
target_arch = "mips64r6",
|
||||
target_arch = "sparc",
|
||||
target_arch = "sparc64"
|
||||
))
|
||||
)) {
|
||||
0x800
|
||||
} else if cfg!(any(
|
||||
target_os = "macos",
|
||||
target_os = "ios",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "dragonfly"
|
||||
)) {
|
||||
0x4
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
/// Opens `path` for reading without waiting for a FIFO's writer (a FIFO is refused by [`read_open`], not waited on). A
|
||||
/// regular file is unaffected by the flag.
|
||||
pub(crate) fn open_for_read(path: impl AsRef<Path>) -> io::Result<std::fs::File> {
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.read(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, O_NONBLOCK);
|
||||
options.open(path)
|
||||
}
|
||||
|
||||
/// The whole of the regular file at `path`, at most `max` bytes.
|
||||
pub(crate) fn read_regular(path: impl AsRef<Path>, max: u64) -> io::Result<Vec<u8>> {
|
||||
read_open(open_for_read(path)?, max)
|
||||
}
|
||||
|
||||
/// The whole of an already opened regular file, at most `max` bytes.
|
||||
pub(crate) fn read_open(file: std::fs::File, max: u64) -> io::Result<Vec<u8>> {
|
||||
let meta = file.metadata()?;
|
||||
if !meta.is_file() {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file"));
|
||||
}
|
||||
if meta.len() > max {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("{} bytes is more than the {max} allowed", meta.len())));
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(usize::try_from(meta.len()).unwrap_or(0));
|
||||
file.take(max.saturating_add(1)).read_to_end(&mut bytes)?;
|
||||
if bytes.len() as u64 > max {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("more than the {max} bytes allowed")));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_regular_file_within_the_cap_is_read_and_others_are_refused() {
|
||||
let dir = std::env::temp_dir().join(format!("read-file-{}", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let f = dir.join("a");
|
||||
std::fs::write(&f, b"abcd").unwrap();
|
||||
assert_eq!(read_regular(&f, 4).unwrap(), b"abcd");
|
||||
assert!(read_regular(&f, 3).is_err());
|
||||
assert!(read_regular(&dir, 100).is_err());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink("/dev/zero", dir.join("z")).unwrap();
|
||||
assert!(read_regular(dir.join("z"), 1 << 20).is_err());
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// A FIFO with no writer is refused, not waited on forever in `open`.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_fifo_without_a_writer_is_refused_without_blocking() {
|
||||
let dir = std::env::temp_dir().join(format!("read-file-fifo-{}", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let fifo = dir.join("pipe");
|
||||
// (no unsafe code in this crate: the coreutils tool makes the FIFO)
|
||||
if !std::process::Command::new("mkfifo").arg(&fifo).status().is_ok_and(|s| s.success()) {
|
||||
eprintln!("skipped: no mkfifo");
|
||||
return;
|
||||
}
|
||||
let err = read_regular(&fifo, 1 << 20).unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{err}");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -389,7 +389,7 @@ fn read_user(file: &str, path: &Path) -> Result<Template, String> {
|
||||
if meta.len() > MAX_FILE {
|
||||
return Err(format!("{} bytes is too large for a slideshow template (at most {} KB)", meta.len(), MAX_FILE / 1024));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
let bytes = crate::read_file::read_regular(path, MAX_FILE).map_err(|e| e.to_string())?;
|
||||
let p = parse(&bytes)?;
|
||||
Ok(Template {
|
||||
id: format!("{USER}{stem}"),
|
||||
@@ -411,7 +411,7 @@ pub fn read_file(path: &Path) -> Result<Parsed, String> {
|
||||
if meta.len() > MAX_FILE {
|
||||
return Err(format!("{}: {} bytes is too large for a slideshow template (at most {} KB)", path.display(), meta.len(), MAX_FILE / 1024));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let bytes = crate::read_file::read_regular(path, MAX_FILE).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let mut p = parse(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
if p.name.is_none() {
|
||||
let stem = path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -242,6 +242,7 @@ fn validate_files(files: &[FileSpec<'_>]) -> Result<u64, DownloadError> {
|
||||
if files.len() > 256 {
|
||||
return Err(DownloadError::Invalid("too many files".into()));
|
||||
}
|
||||
// (names that differ only in case are one file on a case-insensitive file system)
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut total = 0u64;
|
||||
for f in files {
|
||||
@@ -259,7 +260,7 @@ fn validate_files(files: &[FileSpec<'_>]) -> Result<u64, DownloadError> {
|
||||
|| f.name.starts_with('.')
|
||||
|| f.name.contains(['/', '\\', ':'])
|
||||
|| f.name.chars().any(char::is_control)
|
||||
|| !seen.insert(f.name)
|
||||
|| !seen.insert(f.name.to_lowercase())
|
||||
{
|
||||
return Err(DownloadError::Invalid("a filename must be a unique, ordinary filename".into()));
|
||||
}
|
||||
|
||||
@@ -425,3 +425,10 @@ fn hostile_file_specs_are_rejected_before_touching_disk() {
|
||||
assert!(!dir.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_differing_only_in_case_are_one_file() {
|
||||
let spec = |name| FileSpec { name, size: Some(1), sha256: None, max: 1 };
|
||||
assert!(super::validate_files(&[spec("Model.bin")]).is_ok());
|
||||
assert!(super::validate_files(&[spec("Model.bin"), spec("model.BIN")]).is_err());
|
||||
}
|
||||
@@ -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 };
|
||||
|
||||
+105
-8
@@ -371,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 {
|
||||
@@ -378,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);
|
||||
@@ -1034,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.
|
||||
@@ -1418,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(),
|
||||
};
|
||||
@@ -1460,7 +1487,7 @@ const MAX_DABS: usize = 4096;
|
||||
|
||||
/// The `shape` kernel's brush data for `dabs`: stroke records (12 words: dab offset, dab count,
|
||||
/// r, hard, flow, density, erase, bbox x0 y0 x1 y1, auto) then each dab's centre and the flow it
|
||||
/// adds (3 words; the stroke's flow before process V8, [`lightcraft_pipeline::masks::BrushDabs::dab`]).
|
||||
/// adds (3 words; the stroke's flow before process V9, [`lightcraft_pipeline::masks::BrushDabs::dab`]).
|
||||
fn brush_aux(dabs: &[&lightcraft_pipeline::masks::BrushDabs], erase: bool) -> Vec<f32> {
|
||||
let mut aux = Vec::new();
|
||||
let mut off = 12 * dabs.len();
|
||||
@@ -1842,6 +1869,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() {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -94,7 +94,7 @@ fn shape(@builtin(global_invocation_id) g: vec3<u32>) {
|
||||
let hard = aux[o + 3u];
|
||||
var keep = 1.0;
|
||||
for (var j = 0u; j < cnt; j++) {
|
||||
// dab record: centre x, y and the flow it adds (the stroke's before process V8)
|
||||
// dab record: centre x, y and the flow it adds (the stroke's before process V9)
|
||||
let dx = px - aux[off + 3u * j];
|
||||
let dy = py - aux[off + 3u * j + 1u];
|
||||
let flow = aux[off + 3u * j + 2u];
|
||||
|
||||
@@ -434,8 +434,8 @@ fn cases() -> Vec<(&'static str, Edit)> {
|
||||
},
|
||||
];
|
||||
}),
|
||||
("masks (brush, process V8: flow per radius travelled)", |s| {
|
||||
s.process = lightcraft_develop::Process::V8.version();
|
||||
("masks (brush, process V9: flow per radius travelled)", |s| {
|
||||
s.process = lightcraft_develop::Process::V9.version();
|
||||
let stroke = BrushStroke {
|
||||
points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.4), Point::new(0.8, 0.35)],
|
||||
size: 0.04,
|
||||
@@ -448,8 +448,8 @@ fn cases() -> Vec<(&'static str, Edit)> {
|
||||
..Default::default()
|
||||
}];
|
||||
}),
|
||||
("masks (brush, process V7: flow per dab)", |s| {
|
||||
s.process = lightcraft_develop::Process::V7.version();
|
||||
("masks (brush, process V8: flow per dab)", |s| {
|
||||
s.process = lightcraft_develop::Process::V8.version();
|
||||
let stroke = BrushStroke {
|
||||
points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.4), Point::new(0.8, 0.35)],
|
||||
size: 0.04,
|
||||
@@ -835,7 +835,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() {
|
||||
@@ -866,7 +866,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
@@ -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) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
/// `a` 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!("{};&", "&".repeat(200_000));
|
||||
assert_eq!(unescape(&hostile), format!("{};&", "&".repeat(200_000)));
|
||||
assert_eq!(unescape("<a>  &unknownreference;"), "<a> \u{10FFFF} &unknownreference;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_padded_numeric_references_decode() {
|
||||
assert_eq!(unescape("Canon A A"), "Canon A A");
|
||||
assert_eq!(unescape("&abc&#xyz;&;"), "&abc&#xyz;&;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entity_rejects_signed_numeric_references() {
|
||||
assert_eq!(entity("#+65"), None);
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
/// `a` 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);
|
||||
|
||||
@@ -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("Canon A A"), "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!("{};&", "&".repeat(200_000));
|
||||
assert_eq!(unescape_attr(&hostile), format!("{};&", "&".repeat(200_000)));
|
||||
assert_eq!(unescape_attr("<a>  &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());
|
||||
}
|
||||
@@ -148,8 +148,8 @@ impl GrainModel {
|
||||
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),
|
||||
Process::V7 | Process::V8 | Process::V9 if draft => crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal),
|
||||
Process::V7 | Process::V8 | Process::V9 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -407,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 | Process::V7 | Process::V8 => match info.camera_tone.as_ref().filter(|_| info.raw) {
|
||||
Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V9 => 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),
|
||||
|
||||
@@ -37,7 +37,7 @@ pub struct Frame {
|
||||
/// `lightcraft_develop::Mask::on_photo`); otherwise they are normalized coordinates of this
|
||||
/// frame's transformed image, like spots and the crop.
|
||||
pub masks_on_photo: bool,
|
||||
/// Brush Flow is coverage per brush radius travelled (process V8, [`crate::masks::flow_per_radius`]),
|
||||
/// Brush Flow is coverage per brush radius travelled (process V9, [`crate::masks::flow_per_radius`]),
|
||||
/// not per dab.
|
||||
pub brush_flow_per_radius: bool,
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -32,6 +32,7 @@ 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]
|
||||
@@ -444,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),
|
||||
}
|
||||
@@ -487,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)
|
||||
{
|
||||
@@ -522,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,
|
||||
@@ -530,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,
|
||||
@@ -548,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,
|
||||
}
|
||||
}
|
||||
@@ -585,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
|
||||
};
|
||||
@@ -722,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)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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 | Process::V7 | Process::V8 => camera_look,
|
||||
Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V9 => camera_look,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+121
-10
@@ -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,78 @@ 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 | Process::V7 | Process::V8 => base_detail_radius(px_per_long),
|
||||
Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V9 => {
|
||||
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 +699,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 +744,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 +873,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 +1376,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 +1464,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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::*;
|
||||
@@ -511,20 +517,20 @@ pub struct BrushDabs {
|
||||
pub auto: bool,
|
||||
/// Pen pressure (0..1) of each dab, parallel to `dabs`; empty when the stroke has no pressure data (full pressure).
|
||||
pub pressure: Vec<f32>,
|
||||
/// What each dab adds under process V8 ([`travel_flow`], pressure applied), parallel to `dabs`;
|
||||
/// empty before V8, where every dab adds the stroke's flow.
|
||||
/// What each dab adds under process V9 ([`travel_flow`], pressure applied), parallel to `dabs`;
|
||||
/// empty before V9, where every dab adds the stroke's flow.
|
||||
pub flows: Vec<f32>,
|
||||
}
|
||||
|
||||
impl BrushDabs {
|
||||
/// Radius, hard core and flow of dab `i`, pen pressure applied ([`pressure_radius`], [`pressure_flow`]);
|
||||
/// under process V8 the flow is what the dab adds for the distance it travelled ([`travel_flow`]).
|
||||
/// under process V9 the flow is what the dab adds for the distance it travelled ([`travel_flow`]).
|
||||
pub fn dab(&self, i: usize) -> (f64, f64, f32) {
|
||||
let (r, hard, flow) = self.pressed(i);
|
||||
(r, hard, self.flows.get(i).copied().unwrap_or(flow))
|
||||
}
|
||||
|
||||
/// [`Self::dab`] with the stroke's flow for every dab, as before process V8.
|
||||
/// [`Self::dab`] with the stroke's flow for every dab, as before process V9.
|
||||
fn pressed(&self, i: usize) -> (f64, f64, f32) {
|
||||
match self.pressure.get(i) {
|
||||
Some(&p) => {
|
||||
@@ -535,7 +541,7 @@ impl BrushDabs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Give every dab what it adds for the distance it travelled ([`travel_flow`], process V8).
|
||||
/// Give every dab what it adds for the distance it travelled ([`travel_flow`], process V9).
|
||||
fn flow_by_travel(mut self) -> BrushDabs {
|
||||
let flows = (0..self.dabs.len())
|
||||
.map(|i| {
|
||||
@@ -553,14 +559,14 @@ impl BrushDabs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether brush Flow is the coverage a stroke adds per brush radius it travels (process V8 on), as
|
||||
/// Whether brush Flow is the coverage a stroke adds per brush radius it travels (process V9 on), as
|
||||
/// in Lightroom, rather than what every dab adds whatever the spacing of the dabs.
|
||||
pub fn flow_per_radius(s: &lightcraft_develop::DevelopSettings) -> bool {
|
||||
s.process.process() >= lightcraft_develop::Process::V8
|
||||
s.process.process() >= lightcraft_develop::Process::V9
|
||||
}
|
||||
|
||||
/// What one dab adds to a stroke's coverage when Flow is coverage per brush radius travelled
|
||||
/// (process V8): `1 − (1 − flow)^(dist / r)` for a dab `dist` past the previous one, brush radius
|
||||
/// (process V9): `1 − (1 − flow)^(dist / r)` for a dab `dist` past the previous one, brush radius
|
||||
/// `r`. A stroke then covers a point it passes over for a length `L` by `1 − (1 − flow)^(L / r)`
|
||||
/// however densely its dabs lie: a straight stroke's centre (`L` = 2 r) by 44 % at Flow 25, 75 % at
|
||||
/// Flow 50 and fully at 100, as Lightroom Classic's strokes measure on a grey card (#4045).
|
||||
|
||||
@@ -465,17 +465,17 @@ fn straight_stroke(process: lightcraft_develop::Process, flow: f64, points: Vec<
|
||||
shape_alpha(&MaskShape::Brush { strokes: vec![s] }, &f, w, h, &Rgb32f::new(w, h), &Plane::new(w, h), 0.0, None)
|
||||
}
|
||||
|
||||
/// Process V8: Flow is the coverage a stroke adds per brush radius it travels, as Lightroom
|
||||
/// Process V9: Flow is the coverage a stroke adds per brush radius it travels, as Lightroom
|
||||
/// Classic's strokes measure on a grey card (Feather 0, straight strokes, #4045): a point the brush
|
||||
/// passes over for a length `L` is covered by `1 − (1 − flow)^(L / r)`, so the centre of a stroke
|
||||
/// (L = 2 r) by 41 % at Flow 25, 76 % at 50 and fully at 100 (Lightroom), and a point 0.6 radii off
|
||||
/// the centre line less. Process V7 adds the flow per dab, r/4 apart: 90 % at Flow 25.
|
||||
/// the centre line less. Process V8 adds the flow per dab, r/4 apart: 90 % at Flow 25.
|
||||
#[test]
|
||||
fn flow_is_coverage_per_radius_travelled_as_in_lightroom() {
|
||||
use lightcraft_develop::Process;
|
||||
let line = vec![Point::new(0.1, 0.5), Point::new(0.9, 0.5)];
|
||||
for (flow, lightroom) in [(25.0, 0.41), (50.0, 0.76), (100.0, 1.0)] {
|
||||
let a = straight_stroke(Process::V8, flow, line.clone());
|
||||
let a = straight_stroke(Process::V9, flow, line.clone());
|
||||
let keep = 1.0 - flow as f32 / 100.0;
|
||||
let centre = a.get(200, 50);
|
||||
assert!((centre - (1.0 - keep.powi(2))).abs() < 0.03, "Flow {flow}: centre {centre}");
|
||||
@@ -486,29 +486,29 @@ fn flow_is_coverage_per_radius_travelled_as_in_lightroom() {
|
||||
assert!((off - (1.0 - keep.powf(chord))).abs() < 0.05, "Flow {flow}: 0.6 r off the line {off}");
|
||||
assert!(off <= centre + 1e-6);
|
||||
}
|
||||
let old = straight_stroke(Process::V7, 25.0, line).get(200, 50);
|
||||
assert!(old > 0.85, "V7 keeps the flow per dab: {old}");
|
||||
let old = straight_stroke(Process::V8, 25.0, line).get(200, 50);
|
||||
assert!(old > 0.85, "V8 keeps the flow per dab: {old}");
|
||||
}
|
||||
|
||||
/// Process V8: a stroke covers the same however densely its samples lie (a slow drag samples
|
||||
/// every pixel, a fast one far apart); before V8 a slow stroke laid more dabs and built up more.
|
||||
/// Process V9: a stroke covers the same however densely its samples lie (a slow drag samples
|
||||
/// every pixel, a fast one far apart); before V9 a slow stroke laid more dabs and built up more.
|
||||
#[test]
|
||||
fn flow_does_not_depend_on_how_fast_the_stroke_was_painted() {
|
||||
use lightcraft_develop::Process;
|
||||
let fast = vec![Point::new(0.1, 0.5), Point::new(0.9, 0.5)];
|
||||
// one sample per output pixel
|
||||
let slow: Vec<Point> = (40..=360).map(|x| Point::new(x as f64 / 400.0, 0.5)).collect();
|
||||
let (f, s) = (straight_stroke(Process::V8, 25.0, fast.clone()).get(200, 50), straight_stroke(Process::V8, 25.0, slow.clone()).get(200, 50));
|
||||
let (f, s) = (straight_stroke(Process::V9, 25.0, fast.clone()).get(200, 50), straight_stroke(Process::V9, 25.0, slow.clone()).get(200, 50));
|
||||
assert!((f - s).abs() < 0.02, "fast {f} vs slow {s}");
|
||||
let (f7, s7) = (straight_stroke(Process::V7, 25.0, fast).get(200, 50), straight_stroke(Process::V7, 25.0, slow).get(200, 50));
|
||||
assert!(s7 > f7, "before V8 a slow stroke builds up more: {f7} vs {s7}");
|
||||
let (f8, s8) = (straight_stroke(Process::V8, 25.0, fast).get(200, 50), straight_stroke(Process::V8, 25.0, slow).get(200, 50));
|
||||
assert!(s8 > f8, "before V9 a slow stroke builds up more: {f8} vs {s8}");
|
||||
}
|
||||
|
||||
/// A click (one dab) paints its flow on every process; Flow 100 paints fully.
|
||||
#[test]
|
||||
fn a_click_paints_its_flow() {
|
||||
use lightcraft_develop::Process;
|
||||
for p in [Process::V7, Process::V8] {
|
||||
for p in [Process::V8, Process::V9] {
|
||||
let a = straight_stroke(p, 40.0, vec![Point::new(0.5, 0.5)]);
|
||||
assert!((a.get(200, 50) - 0.4).abs() < 1e-4, "{p:?}: {}", a.get(200, 50));
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -35,7 +35,7 @@ fn processes_before_v7_keep_the_value_noise() {
|
||||
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:?}"),
|
||||
Process::V7 | Process::V8 | Process::V9 => 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");
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -49,8 +49,15 @@ fn box_row<T: Pixel>(row: &mut [T], tmp: &mut Vec<T>, r: usize) {
|
||||
let last = w - 1;
|
||||
let inv = 1.0 / (2 * r + 1) as f32;
|
||||
let mut acc = T::zero();
|
||||
for i in 0..=2 * r {
|
||||
acc = acc.madd(s[i.saturating_sub(r).min(last)], 1.0);
|
||||
// the window [-r, r] with clamped edges: r copies of the first pixel, the pixels 0..=min(r, last), then the
|
||||
// last pixel for each offset past it (O(w), not O(r), however large the radius)
|
||||
acc = acc.madd(s[0], r as f32);
|
||||
for v in &s[..=r.min(last)] {
|
||||
acc = acc.madd(*v, 1.0);
|
||||
}
|
||||
// only when the window reaches past the last pixel: a NaN there must not poison a row it isn't in
|
||||
if r > last {
|
||||
acc = acc.madd(s[last], (r - last) as f32);
|
||||
}
|
||||
for x in 0..w {
|
||||
row[x] = T::zero().madd(acc, inv);
|
||||
@@ -177,6 +184,14 @@ pub fn gaussian_taps<T: Pixel>(img: &Image<T>, taps: &[f32]) -> Image<T> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_non_finite_last_pixel_stays_out_of_windows_that_do_not_reach_it() {
|
||||
let mut row = [1.0f32; 8];
|
||||
row[7] = f32::NAN;
|
||||
box_row(&mut row, &mut Vec::new(), 2);
|
||||
assert!(row[..5].iter().all(|v| v.is_finite()), "{row:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fir_gaussian_has_bounded_finite_taps_for_hostile_sigmas() {
|
||||
for sigma in [f32::NAN, f32::NEG_INFINITY, f32::INFINITY, f32::MAX, -5.0, 0.0, 0.1, 4.0] {
|
||||
@@ -277,4 +292,18 @@ mod tests {
|
||||
let var: f32 = b.data.iter().enumerate().map(|(i, v)| v * ((i as f32 - 100.0).powi(2))).sum();
|
||||
assert!((var.sqrt() - sigma).abs() / sigma < 0.1, "{}", var.sqrt());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn box_row_matches_the_clamped_window_sum_for_radii_past_the_row() {
|
||||
for (w, r) in [(1usize, 1usize), (5, 1), (5, 4), (5, 5), (5, 9), (7, 3)] {
|
||||
let mut row: Vec<f32> = (0..w).map(|i| (i * i + 1) as f32).collect();
|
||||
let want: Vec<f32> = (0..w as isize)
|
||||
.map(|x| (-(r as isize)..=r as isize).map(|j| row[(x + j).clamp(0, w as isize - 1) as usize]).sum::<f32>() / (2 * r + 1) as f32)
|
||||
.collect();
|
||||
box_row(&mut row, &mut Vec::new(), r);
|
||||
for (a, b) in row.iter().zip(&want) {
|
||||
assert!((a - b).abs() < 1e-3, "w {w} r {r}: {a} vs {b}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -605,5 +605,8 @@ mod tests {
|
||||
assert_eq!(hostile, write_dng(&raw, &opts(2048)).expect("the cap itself writes"), "u32::MAX is clamped to the cap");
|
||||
assert_ne!(hostile, write_dng(&raw, &opts(256)).expect("a normal tile writes"), "the clamp is not a no-op");
|
||||
assert_eq!(crate::probe(&hostile), Some(RawFormat::Dng), "the clamped output is still a DNG");
|
||||
// the writer's own padded tile (2048 × 2048 around an 8 × 8 image) reads back
|
||||
let back = crate::decode(&hostile).expect("a tile this writer pads to decodes");
|
||||
assert_eq!((back.width, back.height), (w, h));
|
||||
}
|
||||
}
|
||||
@@ -98,11 +98,17 @@ pub fn embedded_preview_dynamic_range_optimized(bytes: &[u8]) -> Option<bool> {
|
||||
|
||||
/// The first frame (SOF) marker of a JPEG and its position, from the marker segments before the first scan.
|
||||
fn first_frame(b: &[u8]) -> Option<(u8, usize)> {
|
||||
first_frame_within(b, &mut { usize::MAX })
|
||||
}
|
||||
|
||||
/// [`first_frame`] charging `work` one per step (a segment, or a fill byte); `None` too when it runs out.
|
||||
fn first_frame_within(b: &[u8], work: &mut usize) -> Option<(u8, usize)> {
|
||||
if b.len() < 4 || !b.starts_with(&[0xff, 0xd8]) {
|
||||
return None;
|
||||
}
|
||||
let mut i = 2usize;
|
||||
while i.checked_add(4)? <= b.len() {
|
||||
*work = work.checked_sub(1)?;
|
||||
if *b.get(i)? != 0xff {
|
||||
return None;
|
||||
}
|
||||
@@ -314,6 +320,7 @@ fn preview_covering(bytes: &[u8], min_edge: Option<u32>) -> Option<Vec<u8>> {
|
||||
if let Some(p) = crate::vendor::orf::preview(bytes) {
|
||||
found.push(p);
|
||||
}
|
||||
bound_candidates(&mut found, bytes.len());
|
||||
let largest = found.iter().copied().filter(|s| is_dct_jpeg(s) || is_jxl(s)).max_by_key(|s| s.len());
|
||||
let best = min_edge
|
||||
.zip(largest)
|
||||
@@ -326,6 +333,25 @@ fn preview_covering(bytes: &[u8], min_edge: Option<u32>) -> Option<Vec<u8>> {
|
||||
.or_else(|| (format == Some(crate::RawFormat::CfaTiff)).then(|| crate::vendor::hasselblad::rgb_preview(&tiff, bytes)).flatten())
|
||||
}
|
||||
|
||||
/// Drops candidate ranges that repeat an earlier one, that are not a displayable JPEG or JPEG XL, and valid ones
|
||||
/// past a shared budget of [`scan_budget`] bytes: a range is charged only once it validates, so invalid ranges
|
||||
/// covering most of the file cannot use up the budget before a valid preview. The header walks that validate
|
||||
/// (or reject) the ranges share a second budget of the same size, charged for every walk, so many ranges
|
||||
/// that start a JPEG header and run through fill bytes cannot each cost a walk of their length.
|
||||
fn bound_candidates(found: &mut Vec<&[u8]>, file_len: usize) {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut left = scan_budget(file_len);
|
||||
let mut work = scan_budget(file_len);
|
||||
found.retain(|s| {
|
||||
let mut dct = || first_frame_within(s, &mut work).is_some_and(|(m, _)| matches!(m, 0xc0..=0xc2));
|
||||
if !seen.insert((s.as_ptr() as usize, s.len())) || !(dct() || is_jxl(s)) || s.len() > left {
|
||||
return false;
|
||||
}
|
||||
left -= s.len();
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// The end of the DCT JPEG whose SOI is at `soi` (exclusive index after its EOI) and its component count,
|
||||
/// walking the marker segments and the entropy-coded data. `None` when it is not a complete, displayable
|
||||
/// (baseline or progressive) JPEG, so a stray `D8 FF` in other data is rejected. `*reach` is left at
|
||||
@@ -645,3 +671,52 @@ fn trim_eoi(s: &[u8]) -> &[u8] {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod bound_tests {
|
||||
#[test]
|
||||
fn repeated_and_over_budget_candidates_are_dropped() {
|
||||
let mut data = vec![0u8; 4 << 20];
|
||||
// a valid JPEG header every 16 bytes, so each range below validates
|
||||
for i in 0..64 {
|
||||
data[i * 16..i * 16 + 15].copy_from_slice(&[0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 8, 0, 8, 1, 1, 0x11, 0]);
|
||||
}
|
||||
let mut found: Vec<&[u8]> = vec![&data[..], &data[..], &data[..]];
|
||||
super::bound_candidates(&mut found, data.len());
|
||||
assert_eq!(found.len(), 1);
|
||||
// overlapping but unequal ranges stop at the shared budget (8 x the file, at least 1 MiB)
|
||||
let mut found: Vec<&[u8]> = (0..64).map(|i| &data[i * 16..]).collect();
|
||||
super::bound_candidates(&mut found, data.len());
|
||||
assert!(found.len() <= 8 && found.iter().map(|s| s.len()).sum::<usize>() <= 8 * data.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_ranges_do_not_use_up_the_budget_before_a_valid_preview() {
|
||||
let mut data = vec![0u8; 2 << 20];
|
||||
let jpeg = [0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 8, 0, 8, 1, 1, 0x11, 0];
|
||||
data[1 << 20..(1 << 20) + jpeg.len()].copy_from_slice(&jpeg);
|
||||
// 40 distinct invalid ranges of nearly the whole file (far past the 8 x budget), then the valid one
|
||||
let mut found: Vec<&[u8]> = (0..40).map(|i| &data[i..1 << 20]).collect();
|
||||
found.push(&data[1 << 20..]);
|
||||
super::bound_candidates(&mut found, data.len());
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].starts_with(&[0xff, 0xd8]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_walks_of_many_fill_byte_ranges_share_a_budget() {
|
||||
// a JPEG header followed by 100 000 fill bytes and no frame: each walk would run to the end
|
||||
let mut data = vec![0xffu8; 100_100];
|
||||
data[..2].copy_from_slice(&[0xff, 0xd8]);
|
||||
let valid = [0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 8, 0, 8, 1, 1, 0x11, 0];
|
||||
// 50 distinct such ranges (5 M steps against the 1 MiB budget), then a valid header
|
||||
let mut found: Vec<&[u8]> = (0..50).map(|i| &data[..100_000 + i]).collect();
|
||||
found.push(&valid);
|
||||
super::bound_candidates(&mut found, data.len());
|
||||
assert!(found.is_empty(), "the walks stop at the shared budget, so the later header is not reached");
|
||||
// the same header with no hostile ranges before it is kept
|
||||
let mut found: Vec<&[u8]> = vec![&valid];
|
||||
super::bound_candidates(&mut found, data.len());
|
||||
assert_eq!(found.len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -247,7 +247,12 @@ fn decode_chunk(data: &[u8], info: &ImageInfo, c: &Chunk, order: ByteOrder, pack
|
||||
}
|
||||
comp::LOSSY_JPEG => {
|
||||
// lossy DNG: each chunk is a baseline (DCT) JPEG of 8-bit samples
|
||||
let (px, jw, jh, jc) = lossy_jpeg(src, cpp, MAX_JPEG_SAMPLES)?;
|
||||
// a JPEG decoded for a tile may hold no more samples than the tile (a real one is exactly the tile):
|
||||
// many small tiles pointing at one big JPEG would otherwise each decode all of it
|
||||
// (the JPEG codes whole MCUs, at most 32 × 32 pixels each, so its size is the tile's rounded up to them)
|
||||
let mcu = |v: usize| v.div_ceil(32).saturating_mul(32);
|
||||
let tile_budget = mcu(cw).saturating_mul(mcu(ch)).saturating_mul(if cpp == 1 { 1 } else { 3 }).clamp(1, MAX_JPEG_SAMPLES);
|
||||
let (px, jw, jh, jc) = lossy_jpeg(src, cpp, tile_budget)?;
|
||||
// the buffer holds the rows the decoded JPEG covers (the caller zero-fills the tile's
|
||||
// remainder and reads only rows it fills): a tile-many-larger decoded JPEG does not
|
||||
// get the nominal tile's full buffer (issue #1517)
|
||||
@@ -271,6 +276,16 @@ fn decode_chunk(data: &[u8], info: &ImageInfo, c: &Chunk, order: ByteOrder, pack
|
||||
// Deflate compresses at most about 1:1032, so a source this far under half of its
|
||||
// nominal length cannot reconstruct the chunk: refused before the nominal buffer is
|
||||
// inflated and predicted, which padding-only work would make gigabytes.
|
||||
// Nor may the nominal chunk be mostly padding outside the image (a tile far larger than the picture):
|
||||
// its allocation and predictor pass would be spent on samples nobody reads.
|
||||
if n > vw
|
||||
.saturating_mul(vh)
|
||||
.saturating_mul(cpp)
|
||||
.saturating_mul(MAX_PADDING_FACTOR)
|
||||
.saturating_add(MAX_WRITER_TILE_SAMPLES.saturating_mul(cpp))
|
||||
{
|
||||
return Err(RawError::Limit("deflated chunk is mostly padding outside the image"));
|
||||
}
|
||||
if (src.len() as u64).saturating_mul(2048) < inflate_len {
|
||||
return Err(RawError::Corrupt(format!("a deflated chunk of {inflate_len} bytes is packed into only {} bytes", src.len())));
|
||||
}
|
||||
@@ -315,6 +330,13 @@ fn jxl_chunk_check(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp:
|
||||
jxl_chunk(src, cw, ch, vw, vh, cpp, bits, float).map(|_| ())
|
||||
}
|
||||
|
||||
/// How many times its in-image samples a deflated chunk's nominal size may reach (plus a writer tile of slack):
|
||||
/// edge tiles of real files are mostly inside the image.
|
||||
const MAX_PADDING_FACTOR: usize = 32;
|
||||
/// Samples per plane of the largest Deflate tile the DNG writer pads to (2048 × 2048, `dngwrite::MAX_DEFLATE_TILE`),
|
||||
/// which a small image's one tile is nearly all padding of: such files still decode.
|
||||
const MAX_WRITER_TILE_SAMPLES: usize = 2048 * 2048;
|
||||
|
||||
/// The most samples a tiled JPEG chunk or a white-balance preview may decode to: far more than
|
||||
/// any real lossy tile or preview carries, and small enough that a JPEG header alone cannot size
|
||||
/// a multi-gigabyte allocation.
|
||||
@@ -505,6 +527,39 @@ mod lossy_tests {
|
||||
assert!((px(10, 5)[1] as i32 - 150).abs() <= 6, "green ramp: {:?}", px(10, 5));
|
||||
}
|
||||
|
||||
/// A small tile may not decode a JPEG much larger than itself (a table of tiny tiles all pointing at one big
|
||||
/// JPEG would decode it once per tile); a JPEG that fills the tile's whole 32 × 32 MCU block still decodes.
|
||||
#[test]
|
||||
fn a_lossy_tile_may_not_decode_a_much_larger_jpeg() {
|
||||
let encode = |w: usize, h: usize| {
|
||||
let mut out = Vec::new();
|
||||
jpeg_encoder::Encoder::new(&mut out, 90).encode(&vec![128u8; w * h * 3], w as u16, h as u16, jpeg_encoder::ColorType::Rgb).unwrap();
|
||||
out
|
||||
};
|
||||
let image = |jpeg: &[u8]| {
|
||||
let mut file = vec![0u8; 8];
|
||||
file.extend_from_slice(jpeg);
|
||||
let info = ImageInfo {
|
||||
width: 4,
|
||||
height: 4,
|
||||
bits_per_sample: vec![8, 8, 8],
|
||||
samples_per_pixel: 3,
|
||||
compression: comp::LOSSY_JPEG,
|
||||
photometric: 34892,
|
||||
planar: 1,
|
||||
predictor: 1,
|
||||
sample_format: 1,
|
||||
new_subfile_type: 0,
|
||||
layout: Layout::Tiles { tile_width: 16, tile_height: 16 },
|
||||
offsets: vec![8],
|
||||
byte_counts: vec![jpeg.len() as u64],
|
||||
};
|
||||
read_image(&file, &info, ByteOrder::Little, Packing::Msb)
|
||||
};
|
||||
assert!(image(&encode(32, 32)).is_ok());
|
||||
assert!(matches!(image(&encode(256, 256)), Err(RawError::Corrupt(_))));
|
||||
}
|
||||
|
||||
fn strip_info(compression: u16, offsets: Vec<u64>, byte_counts: Vec<u64>) -> ImageInfo {
|
||||
ImageInfo {
|
||||
width: 4,
|
||||
|
||||
Vendored
+3
-1
@@ -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(),
|
||||
|
||||
Vendored
+12
@@ -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);
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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()?;
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "編集パネル",
|
||||
|
||||
@@ -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": "დეტალური ხედი",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -2202,6 +2202,34 @@
|
||||
"Image on Black": "Imagem sobre preto",
|
||||
"Image on White": "Imagem sobre branco",
|
||||
"White on Black": "Branco sobre preto",
|
||||
"Blur Amount": "Intensidade do desfoque",
|
||||
"Boost": "Realce",
|
||||
"In Focus": "Em foco",
|
||||
"Blur what is out of focus, as a wide aperture would": "Desfoca o que está fora de foco, como faria uma abertura ampla",
|
||||
"What stays sharp: the photo's subject, or the selection of one of its masks": "O que fica nítido: o assunto da foto ou a seleção de uma de suas máscaras",
|
||||
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Dica: selecione o assunto com precisão usando uma máscara Objeto (Máscara, M) e escolha essa máscara aqui.",
|
||||
"Brush Refinement": "Refinamento com pincel",
|
||||
"Blur": "Desfoque",
|
||||
"Paint what should stay sharp": "Pinte o que deve ficar nítido",
|
||||
"Paint what should be blurred": "Pinte o que deve ser desfocado",
|
||||
"Remove the strokes of both brushes": "Remover os traços dos dois pincéis",
|
||||
"Find Subject": "Encontrar assunto",
|
||||
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Seleciona o assunto com IA (SAM 3), começando onde a câmera focou quando o arquivo registra isso, e o mantém em foco",
|
||||
"Selecting the subject at the camera's focus point…": "Selecionando o assunto no ponto de foco da câmera…",
|
||||
"Selecting the subject…": "Selecionando o assunto…",
|
||||
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Refine em Máscara (M): + → Objeto acrescenta o que faltou, − → Objeto deixa uma parte de fora.",
|
||||
"Finding the subject… The first time on a photo takes a while.": "Encontrando o assunto… Na primeira vez em uma foto, isso demora um pouco.",
|
||||
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "O assunto não foi selecionado. Tente Encontrar assunto de novo ou clique nele em Máscara (M).",
|
||||
"Transition": "Transição",
|
||||
"Selection": "Seleção",
|
||||
"Outside": "Fora",
|
||||
"Shape": "Formato",
|
||||
"Round": "Redondo",
|
||||
"Auto: the photo's subject, estimated": "Automático: o assunto estimado da foto",
|
||||
"Horizontal oval": "Oval horizontal",
|
||||
"Vertical oval": "Oval vertical",
|
||||
"Move & Resize": "Mover e 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.": "Arraste o formato na foto para movê-lo; arraste a alça lateral ou inferior para esticá-lo. Um botão de formato o devolve ao centro.",
|
||||
"Layout Image": "Imagem de layout",
|
||||
"Detail View": "Exibição de detalhe",
|
||||
"Edit Panel": "Painel Editar",
|
||||
|
||||
@@ -2564,6 +2564,34 @@
|
||||
"CPU": "ЦП",
|
||||
"A face model uses the GPU only when a check shows it gives the same results faster.": "Модель лиц использует ГП, только если проверка показала, что он даёт те же результаты быстрее.",
|
||||
"Checking the GPU for faces": "Проверка ГП для лиц",
|
||||
"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": "Выделить главный объект с помощью ИИ (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": "Панель «Правка»",
|
||||
|
||||
@@ -2437,6 +2437,35 @@
|
||||
"★ Favorites": "★ Favoriter",
|
||||
"日本語": "日本語",
|
||||
"繁體中文(台灣)": "繁體中文(台灣)",
|
||||
"Blur Amount": "Oskärpemängd",
|
||||
"Boost": "Förstärkning",
|
||||
"In Focus": "I fokus",
|
||||
"Blur what is out of focus, as a wide aperture would": "Gör det som är utanför fokus oskarpt, som en stor bländaröppning",
|
||||
"What stays sharp: the photo's subject, or the selection of one of its masks": "Det som förblir skarpt: fotots motiv eller markeringen i en av dess masker",
|
||||
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Tips: markera motivet exakt med en Objekt-mask (Maskering, M) och välj sedan den masken här.",
|
||||
"Brush Refinement": "Penselförfining",
|
||||
"Focus": "Fokus",
|
||||
"Blur": "Oskärpa",
|
||||
"Paint what should stay sharp": "Måla det som ska förbli skarpt",
|
||||
"Paint what should be blurred": "Måla det som ska bli oskarpt",
|
||||
"Remove the strokes of both brushes": "Ta bort penseldragen från båda penslarna",
|
||||
"Find Subject": "Hitta motiv",
|
||||
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Markera motivet med AI (SAM 3) med start där kameran fokuserade, om filen anger det, och håll det i fokus",
|
||||
"Selecting the subject at the camera's focus point…": "Markerar motivet vid kamerans fokuspunkt…",
|
||||
"Selecting the subject…": "Markerar motivet…",
|
||||
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Förfina i Maskering (M): + → Objekt lägger till det som saknas, − → Objekt utesluter en del.",
|
||||
"Finding the subject… The first time on a photo takes a while.": "Söker motivet… Första gången i ett foto tar det en stund.",
|
||||
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Motivet markerades inte. Försök med Hitta motiv igen, eller klicka på det i Maskering (M).",
|
||||
"Transition": "Övergång",
|
||||
"Selection": "Markering",
|
||||
"Outside": "Utanför",
|
||||
"Shape": "Form",
|
||||
"Round": "Rund",
|
||||
"Auto: the photo's subject, estimated": "Auto: fotots uppskattade motiv",
|
||||
"Horizontal oval": "Vågrät oval",
|
||||
"Vertical oval": "Lodrät oval",
|
||||
"Move & Resize": "Flytta och ändra storlek",
|
||||
"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.": "Dra formen i fotot för att flytta den; dra i dess sido- eller nederhandtag för att sträcka den. En formknapp sätter tillbaka den i mitten.",
|
||||
"All Mask Overlays": "Alla masköverlägg",
|
||||
"Before/After Side by Side": "Före/efter sida vid sida",
|
||||
"Clipping": "Klippning",
|
||||
|
||||
@@ -2354,6 +2354,34 @@
|
||||
"CPU": "ЦП",
|
||||
"A face model uses the GPU only when a check shows it gives the same results faster.": "Модель облич використовує ГП, лише якщо перевірка показала, що він дає ті самі результати швидше.",
|
||||
"Checking the GPU for faces": "Перевірка ГП для облич",
|
||||
"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": "Виділити головний об’єкт за допомогою ШІ (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": "Панель «Редагування»",
|
||||
|
||||
@@ -2246,6 +2246,34 @@
|
||||
"⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-kéo để chỉnh thẳng, ⇧G Chỉnh thẳng có hướng dẫn, lưới khi biến đổi.",
|
||||
"日本語": "日本語",
|
||||
"繁體中文(台灣)": "繁體中文(台灣)",
|
||||
"Blur Amount": "Mức làm mờ",
|
||||
"Boost": "Tăng cường",
|
||||
"In Focus": "Vùng nét",
|
||||
"Blur what is out of focus, as a wide aperture would": "Làm mờ phần nằm ngoài vùng lấy nét, như khi mở khẩu độ lớn",
|
||||
"What stays sharp: the photo's subject, or the selection of one of its masks": "Phần giữ nét: chủ thể của ảnh hoặc vùng chọn của một trong các mặt nạ",
|
||||
"Tip: select the subject precisely with an Object mask (Masking, M), then choose that mask here.": "Mẹo: chọn chính xác chủ thể bằng mặt nạ Đối tượng (Mặt nạ, M), rồi chọn mặt nạ đó tại đây.",
|
||||
"Brush Refinement": "Tinh chỉnh bằng cọ",
|
||||
"Blur": "Làm mờ",
|
||||
"Paint what should stay sharp": "Tô vùng cần giữ nét",
|
||||
"Paint what should be blurred": "Tô vùng cần làm mờ",
|
||||
"Remove the strokes of both brushes": "Xóa nét vẽ của cả hai cọ",
|
||||
"Find Subject": "Tìm chủ thể",
|
||||
"Select the subject with AI (SAM 3), starting where the camera focused when the file records it, and keep it in focus": "Chọn chủ thể bằng AI (SAM 3), bắt đầu từ điểm lấy nét của máy ảnh nếu tệp có ghi, và giữ chủ thể nét",
|
||||
"Selecting the subject at the camera's focus point…": "Đang chọn chủ thể tại điểm lấy nét của máy ảnh…",
|
||||
"Selecting the subject…": "Đang chọn chủ thể…",
|
||||
"Refine it in Masking (M): + → Object adds what was missed, − → Object leaves a part out.": "Tinh chỉnh trong Mặt nạ (M): + → Đối tượng thêm phần còn thiếu, − → Đối tượng bỏ một phần.",
|
||||
"Finding the subject… The first time on a photo takes a while.": "Đang tìm chủ thể… Lần đầu trên một ảnh sẽ mất một lúc.",
|
||||
"The subject wasn't selected. Try Find Subject again, or click it in Masking (M).": "Chưa chọn được chủ thể. Thử Tìm chủ thể lần nữa, hoặc nhấp vào chủ thể trong Mặt nạ (M).",
|
||||
"Transition": "Chuyển tiếp",
|
||||
"Selection": "Vùng chọn",
|
||||
"Outside": "Bên ngoài",
|
||||
"Shape": "Hình dạng",
|
||||
"Round": "Tròn",
|
||||
"Auto: the photo's subject, estimated": "Tự động: chủ thể ước tính của ảnh",
|
||||
"Horizontal oval": "Hình bầu dục ngang",
|
||||
"Vertical oval": "Hình bầu dục dọc",
|
||||
"Move & Resize": "Di chuyển & đổi kích thước",
|
||||
"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.": "Kéo hình trên ảnh để di chuyển; kéo tay nắm bên hoặc dưới để kéo giãn. Nút hình dạng đưa nó về giữa.",
|
||||
"All Mask Overlays": "Mọi lớp phủ mặt nạ",
|
||||
"Before/After Side by Side": "Trước/Sau cạnh nhau",
|
||||
"Clipping": "Vùng cắt tông",
|
||||
|
||||
@@ -2194,6 +2194,34 @@
|
||||
"This build cannot run recognition models: they can be added and chosen, not used.": "此版本无法运行识别模型:可以添加和选择,但无法使用。",
|
||||
"Detect Faces (Photo menu) needs it: a small one-time download.": "“检测人脸”(照片菜单)依赖它:一次性小文件下载。",
|
||||
"This build has nowhere to keep face models, so the model list is not available. (The desktop app has.)": "此版本无法存放人脸模型,因此模型列表不可用。(桌面版可以存放。)",
|
||||
"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.": "在照片上拖动形状以移动它;拖动其侧边或底部手柄以拉伸。形状按钮会让它回到中间。",
|
||||
"Before/After Side by Side": "修改前/修改后左右排列",
|
||||
"Clipping": "溢出警告",
|
||||
"Mask Overlay": "蒙版叠加",
|
||||
|
||||
@@ -2158,6 +2158,34 @@
|
||||
"CPU": "CPU",
|
||||
"A face model uses the GPU only when a check shows it gives the same results faster.": "只有在檢查顯示 GPU 能更快得出相同結果時,臉孔模型才會使用 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": "編輯面板",
|
||||
|
||||
@@ -108,6 +108,7 @@ impl LightcraftApp {
|
||||
compare_windows: [None; 2],
|
||||
compare_tiles: Default::default(),
|
||||
compare_hold_until: f64::NEG_INFINITY,
|
||||
survey_motion: Default::default(),
|
||||
merge: merge::MergeState::default(),
|
||||
import: None,
|
||||
scan: None,
|
||||
|
||||
@@ -28,7 +28,7 @@ pub struct LiveParams {
|
||||
/// Flow and density, 0..1.
|
||||
pub flow: f32,
|
||||
pub density: f32,
|
||||
/// Flow is coverage per brush radius travelled (process V8, `masks::flow_per_radius`), as the
|
||||
/// Flow is coverage per brush radius travelled (process V9, `masks::flow_per_radius`), as the
|
||||
/// committed stroke paints it.
|
||||
pub per_radius: bool,
|
||||
/// Overlay colour and its opacity (0..1) at full coverage.
|
||||
@@ -248,9 +248,9 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Issue #517: two samples far apart (a fast stroke) paint a continuous band between them,
|
||||
/// Process V8: the live stroke adds Flow per brush radius travelled, as the committed one does,
|
||||
/// Process V9: the live stroke adds Flow per brush radius travelled, as the committed one does,
|
||||
/// so a slow drag (a sample every point) and a fast one cover a point the same; a stroke's centre
|
||||
/// at Flow 25 is covered by 1 − 0.75² (Feather 0 here). Before V8 the slow drag built up more.
|
||||
/// at Flow 25 is covered by 1 − 0.75² (Feather 0 here). Before V9 the slow drag built up more.
|
||||
#[test]
|
||||
fn flow_per_radius_does_not_depend_on_the_drag_speed() {
|
||||
let p = LiveParams { flow: 0.25, hard: 10.0, ..params() };
|
||||
@@ -265,7 +265,7 @@ mod tests {
|
||||
let (fast, slow) = (paint(true, 360), paint(true, 1));
|
||||
assert!((fast - 0.4375).abs() < 0.03, "{fast}");
|
||||
assert!((fast - slow).abs() < 0.02, "fast {fast} vs slow {slow}");
|
||||
assert!(paint(false, 1) > paint(false, 360), "before V8 a slow drag builds up more");
|
||||
assert!(paint(false, 1) > paint(false, 360), "before V9 a slow drag builds up more");
|
||||
}
|
||||
|
||||
/// not two separate dabs.
|
||||
|
||||
@@ -85,6 +85,9 @@ fn switch_library(app: &mut LightcraftApp, path: &str) -> Result<Value, String>
|
||||
app.ui.dialog = None;
|
||||
}
|
||||
app.renderer.forget_all();
|
||||
// photo ids are local to a catalog: a survey tile of the next library must not glide from a
|
||||
// cell of this one, nor keep its render slot
|
||||
app.survey_motion = Default::default();
|
||||
if let Err(err) = opened {
|
||||
let Some(prev) = previous_dir else { return Err(err) };
|
||||
return match app.session.open_library(&prev, false) {
|
||||
|
||||
@@ -400,6 +400,7 @@ impl Headless {
|
||||
|| self.app.import.is_some()
|
||||
|| self.app.export.is_some()
|
||||
|| self.app.session.denoise_busy()
|
||||
|| self.app.survey_motion.moving(self.time)
|
||||
|| !self.app.tasks.is_empty()
|
||||
|| !self.app.synthetic.is_empty()
|
||||
|| !self.app.pending_gestures.is_empty()
|
||||
|
||||
@@ -320,6 +320,8 @@ pub struct LightcraftApp {
|
||||
pub(crate) compare_tiles: std::collections::HashMap<(u8, u64), region::RegionView>,
|
||||
/// Until when (s) a pinch or scroll in Compare / Reference holds the windows there are.
|
||||
pub(crate) compare_hold_until: f64,
|
||||
/// Survey tiles gliding to new cells, and the render slot each surveyed photo keeps.
|
||||
pub(crate) survey_motion: panels::compare::survey::SurveyMotion,
|
||||
/// Photo Merge dialog previews and background merges.
|
||||
pub merge: merge::MergeState,
|
||||
/// An import in progress (the import review dialog's batches).
|
||||
|
||||
@@ -162,6 +162,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[
|
||||
("section.effects", "Effects", Some("Cmd+3"), "Window>Edit Sections"),
|
||||
("section.detail", "Detail", Some("Cmd+4"), "Window>Edit Sections"),
|
||||
("section.optics", "Optics", Some("Cmd+5"), "Window>Edit Sections"),
|
||||
("section.lensBlur", "Lens Blur", Some("Cmd+6"), "Window>Edit Sections"),
|
||||
("section.calibration", "Calibration", None, ""),
|
||||
// {on?}; no params toggles. Opening one Edit section closes the others.
|
||||
("view.soloSections", "Solo Mode", None, "Window>Edit Sections"),
|
||||
|
||||
@@ -13,6 +13,8 @@ use crate::state::{ViewMode, Zoom};
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::register;
|
||||
|
||||
pub mod survey;
|
||||
|
||||
/// Most photos a survey shows.
|
||||
pub const SURVEY_MAX: usize = 48;
|
||||
|
||||
@@ -203,11 +205,27 @@ fn request_tile_renders(app: &mut LightcraftApp, id: PhotoId, slot: Slot, want:
|
||||
if let Some(job) = app.session.render_job(id, rw.max(8), rh.max(8), false, true) {
|
||||
app.renderer.request(slot, job, 60);
|
||||
}
|
||||
request_thumb(app, id);
|
||||
}
|
||||
|
||||
/// Ask for the thumbnail a tile shows until its render is there.
|
||||
fn request_thumb(app: &mut LightcraftApp, id: PhotoId) {
|
||||
if let Some(job) = app.session.thumb_job(id, 256) {
|
||||
app.renderer.request(Slot::Thumb(id), job, 30);
|
||||
}
|
||||
}
|
||||
|
||||
/// The photo's frame as shown: cropped, rotated and lens-corrected.
|
||||
fn frame_of(photo: &lightcraft_catalog::Photo) -> lightcraft_pipeline::geometry::Frame {
|
||||
lightcraft_pipeline::geometry::Frame::with_lens(
|
||||
photo.width.max(1) as usize,
|
||||
photo.height.max(1) as usize,
|
||||
&photo.develop,
|
||||
true,
|
||||
photo.embedded_lens.as_ref(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Draw one photo fitted into `area` (rendered at its display size into `slot`), with its caption
|
||||
/// strip below. Returns the image rect and the click/drag response.
|
||||
fn photo_tile(
|
||||
@@ -226,13 +244,7 @@ fn photo_tile(
|
||||
let Some(photo) = app.session.catalog.photo(id).cloned() else { return (area, area, resp) };
|
||||
let caption_h = 26.0;
|
||||
let img_area = Rect::from_min_max(area.min, pos2(area.right(), area.bottom() - caption_h));
|
||||
let frame = lightcraft_pipeline::geometry::Frame::with_lens(
|
||||
photo.width.max(1) as usize,
|
||||
photo.height.max(1) as usize,
|
||||
&photo.develop,
|
||||
true,
|
||||
photo.embedded_lens.as_ref(),
|
||||
);
|
||||
let frame = frame_of(&photo);
|
||||
let aspect = frame.aspect() as f32;
|
||||
let native = super::detail::output_px(&frame);
|
||||
let mut img = super::detail::fit_rect(img_area, aspect, zoom, native, ppp, app.ui.pan);
|
||||
@@ -249,7 +261,13 @@ fn photo_tile(
|
||||
let texture_side = super::detail::texture_side(ui.ctx());
|
||||
let want =
|
||||
(img.width().max(img.height()).min(img_area.width().max(img_area.height()) * 4.0) * ppp).min(2560.0_f32.min(texture_side as f32)) as usize;
|
||||
request_tile_renders(app, id, slot, want, aspect);
|
||||
// a gliding survey tile asks for its render once it has landed, not one per size it passes on
|
||||
// the way, and for its thumbnail (one size) meanwhile; tiles that stay put render as usual
|
||||
if app.ui.view == ViewMode::Survey && app.survey_motion.gliding(id, ui.input(|i| i.time)) {
|
||||
request_thumb(app, id);
|
||||
} else {
|
||||
request_tile_renders(app, id, slot, want, aspect);
|
||||
}
|
||||
// zoomed past what that render holds (1:1 to check focus): the part on screen as a window, as
|
||||
// in the loupe. Compare and Reference only; Survey tiles are fit views.
|
||||
let pane = match slot {
|
||||
@@ -546,21 +564,6 @@ pub fn show_compare(app: &mut LightcraftApp, ui: &mut egui::Ui) {
|
||||
ui.painter().line_segment([pos2(mid, area.top()), pos2(mid, area.bottom())], Stroke::new(1.0, Tokens::get(ui.ctx()).divider));
|
||||
}
|
||||
|
||||
/// Columns for `n` tiles of aspect ~3:2 in `area`, maximizing the tile size.
|
||||
pub fn survey_columns(n: usize, area: Rect) -> usize {
|
||||
let mut best = (1, 0.0f32);
|
||||
for cols in 1..=n.max(1) {
|
||||
let rows = n.div_ceil(cols);
|
||||
let w = area.width() / cols as f32;
|
||||
let h = area.height() / rows as f32;
|
||||
let s = w.min(h * 1.5);
|
||||
if s > best.1 {
|
||||
best = (cols, s);
|
||||
}
|
||||
}
|
||||
best.0
|
||||
}
|
||||
|
||||
pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let canvas = area_and_filmstrip(app, ui);
|
||||
@@ -570,14 +573,20 @@ pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) {
|
||||
return;
|
||||
}
|
||||
let area = canvas.shrink(14.0);
|
||||
let cols = survey_columns(photos.len(), area);
|
||||
let rows = photos.len().div_ceil(cols);
|
||||
let (cw, ch) = (area.width() / cols as f32, area.height() / rows as f32);
|
||||
for (i, id) in photos.iter().enumerate() {
|
||||
let (c, r) = (i % cols, i / cols);
|
||||
let cell = Rect::from_min_size(pos2(area.left() + c as f32 * cw, area.top() + r as f32 * ch), vec2(cw, ch)).shrink(6.0);
|
||||
let aspects: Vec<f32> = photos.iter().map(|id| app.session.catalog.photo(*id).map_or(1.5, |p| frame_of(p).aspect() as f32)).collect();
|
||||
let cells = survey::cells(&aspects, area);
|
||||
let now = ui.input(|i| i.time);
|
||||
let placed = app.survey_motion.place(&photos, &cells, area, ui.ctx().cumulative_frame_nr(), now);
|
||||
let (slots, freed) = app.survey_motion.assign_slots(&photos);
|
||||
for s in freed {
|
||||
app.renderer.release(Slot::Compare(s));
|
||||
}
|
||||
if app.survey_motion.moving(now) {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
for ((id, cell), slot) in photos.iter().zip(placed).zip(slots) {
|
||||
// (Survey tiles are fit views with no windows: what counts is the photo as painted)
|
||||
let (_, img, resp) = photo_tile(app, ui, *id, Slot::Compare(i as u8), cell, "", Zoom::Fit);
|
||||
let (_, img, resp) = photo_tile(app, ui, *id, Slot::Compare(slot), cell.shrink(survey::GAP), "", Zoom::Fit);
|
||||
if app.session.selection.active == Some(*id) {
|
||||
app.image_rect = Some(img);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
//! Survey layout: the cells the photos are tiled in, fitted to their shapes, and the glide that
|
||||
//! moves the tiles left to their new cells when a photo leaves or joins the survey, so it is
|
||||
//! plain which photo went where.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use egui::{Rect, pos2, vec2};
|
||||
use lightcraft_catalog::PhotoId;
|
||||
|
||||
/// Space a tile keeps below its photo for the caption (as `photo_tile` draws it).
|
||||
pub const CAPTION_H: f32 = 26.0;
|
||||
/// Margin around each tile inside its cell.
|
||||
pub const GAP: f32 = 6.0;
|
||||
/// Seconds a tile takes to glide to its new cell.
|
||||
pub const GLIDE_SECS: f64 = 0.2;
|
||||
|
||||
/// A width / height ratio that layout arithmetic can use: the photo's own, as it is drawn (a
|
||||
/// 100:1 panorama counts as one), or a square for a size that is none.
|
||||
fn usable_aspect(a: f32) -> f32 {
|
||||
if a.is_finite() && a > 0.0 { a } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Image area photos with `aspects` show in a grid of `cols` equal cells in `area`.
|
||||
fn shown_area(aspects: &[f32], cols: usize, area: Rect) -> f32 {
|
||||
let rows = aspects.len().div_ceil(cols.max(1));
|
||||
let iw = area.width() / cols.max(1) as f32 - 2.0 * GAP;
|
||||
let ih = area.height() / rows.max(1) as f32 - 2.0 * GAP - CAPTION_H;
|
||||
if iw <= 0.0 || ih <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
aspects
|
||||
.iter()
|
||||
.map(|&a| {
|
||||
let a = usable_aspect(a);
|
||||
let w = iw.min(ih * a);
|
||||
w * w / a
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// The cell of each photo (width / height `aspects`, in survey order) in `area`: equal cells in
|
||||
/// rows, with the column count that shows the most of the photos, so the survey fits their shapes
|
||||
/// to the screen as Lightroom Classic's does (four portrait photos side by side on a wide screen,
|
||||
/// not two by two). An incomplete last row is centred.
|
||||
pub fn cells(aspects: &[f32], area: Rect) -> Vec<Rect> {
|
||||
let n = aspects.len();
|
||||
if n == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut best = (1, f32::NEG_INFINITY);
|
||||
for cols in 1..=n {
|
||||
let shown = shown_area(aspects, cols, area);
|
||||
if shown > best.1 {
|
||||
best = (cols, shown);
|
||||
}
|
||||
}
|
||||
let cols = best.0;
|
||||
let rows = n.div_ceil(cols);
|
||||
let (cw, ch) = (area.width() / cols as f32, area.height() / rows as f32);
|
||||
let last_row = n - (rows - 1) * cols;
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let (c, r) = (i % cols, i / cols);
|
||||
let indent = if r == rows - 1 { (cols - last_row) as f32 * cw / 2.0 } else { 0.0 };
|
||||
Rect::from_min_size(pos2(area.left() + indent + c as f32 * cw, area.top() + r as f32 * ch), vec2(cw, ch))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One tile's way from where it was drawn to its cell.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Glide {
|
||||
from: Rect,
|
||||
to: Rect,
|
||||
start: f64,
|
||||
}
|
||||
|
||||
impl Glide {
|
||||
fn at(&self, now: f64) -> Rect {
|
||||
let t = ((now - self.start) / GLIDE_SECS).clamp(0.0, 1.0) as f32;
|
||||
// ease out: quick to leave, gentle to land
|
||||
let e = 1.0 - (1.0 - t).powi(3);
|
||||
self.from.lerp_towards(&self.to, e)
|
||||
}
|
||||
|
||||
fn on_its_way(&self, now: f64) -> bool {
|
||||
!self.done(now) && self.from != self.to
|
||||
}
|
||||
|
||||
fn done(&self, now: f64) -> bool {
|
||||
// (a hair early: the clock's rounding must not keep a landed tile moving)
|
||||
now - self.start >= GLIDE_SECS - 1e-9
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the survey's tiles are drawn while they glide, and which render slot each photo keeps
|
||||
/// (a photo keeps its slot while it is shown, so the tiles that move keep their renders).
|
||||
#[derive(Default)]
|
||||
pub struct SurveyMotion {
|
||||
/// The survey area of the last frame drawn, and its frame number.
|
||||
last: Option<(Rect, u64)>,
|
||||
tiles: HashMap<PhotoId, Glide>,
|
||||
slots: HashMap<PhotoId, u8>,
|
||||
}
|
||||
|
||||
impl SurveyMotion {
|
||||
/// Where to draw `photos` (in survey order) at `now`, given their `cells` in `area` this frame
|
||||
/// (`frame`, egui's cumulative frame number). A tile whose cell changed since the last frame glides
|
||||
/// there from where it was drawn; a photo that joined appears in its cell. A survey just opened
|
||||
/// or a canvas that changed size is laid out at once.
|
||||
pub fn place(&mut self, photos: &[PhotoId], cells: &[Rect], area: Rect, frame: u64, now: f64) -> Vec<Rect> {
|
||||
let continued = self.last.is_some_and(|(a, p)| a == area && frame <= p.saturating_add(1));
|
||||
self.last = Some((area, frame));
|
||||
let mut next = HashMap::with_capacity(photos.len());
|
||||
let placed = photos
|
||||
.iter()
|
||||
.zip(cells)
|
||||
.map(|(id, &to)| {
|
||||
let glide = match self.tiles.get(id) {
|
||||
Some(g) if continued && g.to == to => *g,
|
||||
Some(g) if continued => Glide { from: g.at(now), to, start: now },
|
||||
_ => Glide { from: to, to, start: now },
|
||||
};
|
||||
next.insert(*id, glide);
|
||||
glide.at(now)
|
||||
})
|
||||
.collect();
|
||||
self.tiles = next;
|
||||
placed
|
||||
}
|
||||
|
||||
/// Whether a tile is still on its way.
|
||||
pub fn moving(&self, now: f64) -> bool {
|
||||
self.tiles.values().any(|g| g.on_its_way(now))
|
||||
}
|
||||
|
||||
/// Whether the tile of `id` is still on its way (a tile that stays put, or a photo that just
|
||||
/// joined, is not, while others glide).
|
||||
pub fn gliding(&self, id: PhotoId, now: f64) -> bool {
|
||||
self.tiles.get(&id).is_some_and(|g| g.on_its_way(now))
|
||||
}
|
||||
|
||||
/// The render slot of each of `photos`: the one it had, else the lowest free one. Returns the
|
||||
/// slots that photos no longer shown gave up, whose renders can be freed.
|
||||
pub fn assign_slots(&mut self, photos: &[PhotoId]) -> (Vec<u8>, Vec<u8>) {
|
||||
let freed: Vec<u8> = self.slots.iter().filter(|(id, _)| !photos.contains(id)).map(|(_, s)| *s).collect();
|
||||
self.slots.retain(|id, _| photos.contains(id));
|
||||
let used: Vec<u8> = self.slots.values().copied().collect();
|
||||
let mut free = (0..=u8::MAX).filter(move |s| !used.contains(s));
|
||||
let slots = photos.iter().map(|id| *self.slots.entry(*id).or_insert_with(|| free.next().unwrap_or(u8::MAX))).collect();
|
||||
(slots, freed)
|
||||
}
|
||||
|
||||
/// The render slot `id` keeps, if it has one.
|
||||
#[cfg(test)]
|
||||
pub fn slot(&self, id: PhotoId) -> Option<u8> {
|
||||
self.slots.get(&id).copied()
|
||||
}
|
||||
|
||||
/// Whether `id` has a tile here (its place or its render slot).
|
||||
#[cfg(test)]
|
||||
pub fn tracks(&self, id: PhotoId) -> bool {
|
||||
self.tiles.contains_key(&id) || self.slots.contains_key(&id)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{CAPTION_H, GAP, GLIDE_SECS, SurveyMotion, cells};
|
||||
use egui::{Rect, pos2, vec2};
|
||||
use lightcraft_catalog::PhotoId;
|
||||
|
||||
const WIDE: Rect = Rect { min: pos2(0.0, 0.0), max: pos2(1600.0, 800.0) };
|
||||
|
||||
fn cols(cells: &[Rect]) -> usize {
|
||||
cells.iter().filter(|c| c.top() == cells[0].top()).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn four_portraits_stand_side_by_side_on_a_wide_screen() {
|
||||
let c = cells(&[2.0 / 3.0; 4], WIDE);
|
||||
assert_eq!(cols(&c), 4, "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn four_landscapes_on_a_wide_screen_take_two_rows() {
|
||||
let c = cells(&[1.5; 4], WIDE);
|
||||
assert_eq!(cols(&c), 2, "{c:?}");
|
||||
}
|
||||
|
||||
/// Column choice follows the ratio drawn, also past 20:1: four 100:1 panoramas and four
|
||||
/// portraits show most side by side in four columns, not one tall column.
|
||||
#[test]
|
||||
fn panoramas_count_at_their_own_ratio() {
|
||||
let area = Rect::from_min_size(pos2(0.0, 0.0), vec2(2560.0, 1440.0));
|
||||
let aspects = [100.0, 100.0, 100.0, 100.0, 2.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0];
|
||||
assert_eq!(cols(&cells(&aspects, area)), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_row_is_centred() {
|
||||
let c = cells(&[1.5; 5], WIDE);
|
||||
assert_eq!(cols(&c), 3, "{c:?}");
|
||||
let (row, last) = (&c[..3], &c[3..]);
|
||||
assert_eq!(last.len(), 2);
|
||||
let mid = |r: &[Rect]| (r[0].left() + r[r.len() - 1].right()) / 2.0;
|
||||
assert!((mid(row) - mid(last)).abs() < 0.01, "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cells_stay_inside_the_area_and_survive_hostile_sizes() {
|
||||
for aspects in [vec![f32::NAN, 0.0, -1.0, f32::INFINITY, 1e9, f32::MAX, f32::MIN_POSITIVE], vec![1.5; 48]] {
|
||||
let c = cells(&aspects, WIDE);
|
||||
assert_eq!(c.len(), aspects.len());
|
||||
assert!(c.iter().all(|r| WIDE.expand(0.01).contains_rect(*r)), "{c:?}");
|
||||
}
|
||||
assert!(cells(&[], WIDE).is_empty());
|
||||
// a canvas too small for any tile still lays them out, one column
|
||||
let tiny = Rect::from_min_size(pos2(0.0, 0.0), vec2(2.0 * GAP, CAPTION_H));
|
||||
assert_eq!(cells(&[1.0; 3], tiny).len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tile_glides_to_its_new_cell_and_lands_there() {
|
||||
let (a, b) = (PhotoId(1), PhotoId(2));
|
||||
let mut m = SurveyMotion::default();
|
||||
let first = cells(&[1.5; 2], WIDE);
|
||||
assert_eq!(m.place(&[a, b], &first, WIDE, 1, 0.0), first, "a new survey is laid out at once");
|
||||
assert!(!m.moving(0.0));
|
||||
// a leaves: b moves to the single cell
|
||||
let one = cells(&[1.5], WIDE);
|
||||
let mid = m.place(&[b], &one, WIDE, 2, 1.0);
|
||||
assert_eq!(mid[0], first[1], "it starts where it was drawn");
|
||||
assert!(m.moving(1.0));
|
||||
let half = m.place(&[b], &one, WIDE, 3, 1.0 + GLIDE_SECS / 2.0)[0];
|
||||
assert!(half != first[1] && half != one[0], "on its way: {half:?}");
|
||||
assert_eq!(m.place(&[b], &one, WIDE, 4, 1.0 + GLIDE_SECS)[0], one[0], "it lands in its cell");
|
||||
assert!(!m.moving(1.0 + GLIDE_SECS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reopened_survey_or_a_resized_canvas_does_not_glide() {
|
||||
let (a, b) = (PhotoId(1), PhotoId(2));
|
||||
let mut m = SurveyMotion::default();
|
||||
m.place(&[a, b], &cells(&[1.5; 2], WIDE), WIDE, 1, 0.0);
|
||||
let one = cells(&[1.5], WIDE);
|
||||
assert_eq!(m.place(&[b], &one, WIDE, 9, 1.0), one, "frames skipped: the survey was not shown");
|
||||
let narrow = Rect::from_min_size(pos2(0.0, 0.0), vec2(900.0, 800.0));
|
||||
let c = cells(&[1.5], narrow);
|
||||
assert_eq!(m.place(&[b], &c, narrow, 10, 2.0), c, "a new canvas size");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn photos_keep_their_slots_and_new_ones_take_freed_slots() {
|
||||
let (a, b, c, d) = (PhotoId(1), PhotoId(2), PhotoId(3), PhotoId(4));
|
||||
let mut m = SurveyMotion::default();
|
||||
assert_eq!(m.assign_slots(&[a, b, c]), (vec![0, 1, 2], vec![]));
|
||||
assert_eq!(m.assign_slots(&[a, c]), (vec![0, 2], vec![1]), "c keeps its render");
|
||||
assert_eq!(m.assign_slots(&[a, c, d]), (vec![0, 2, 1], vec![]), "d takes the freed slot");
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ mod crop;
|
||||
mod filmstrip;
|
||||
mod geometry;
|
||||
mod info;
|
||||
mod lens_blur;
|
||||
mod look_ahead;
|
||||
mod masks;
|
||||
mod retouch;
|
||||
@@ -48,6 +49,7 @@ use info::{
|
||||
preview_only_pill, quick_name,
|
||||
};
|
||||
pub(crate) use info::{draw_focus_point, failed_pill, loupe_pill, rendering_overdue};
|
||||
use lens_blur::{lens_blur_brush_overlay, lens_blur_shape_overlay};
|
||||
use look_ahead::BEHIND;
|
||||
pub use look_ahead::LookAhead;
|
||||
pub(crate) use look_ahead::{Prepare, look_ahead};
|
||||
@@ -59,6 +61,12 @@ use window::{WindowCtx, WindowView, draw_window, request_window};
|
||||
/// An in-progress on-canvas gesture.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Gesture {
|
||||
/// Lens Blur's fixed focus shape: moving it (`handle` 0) or stretching it sideways (1) or
|
||||
/// up and down (2), from `original` (where it was when the drag began).
|
||||
LensBlurArea {
|
||||
handle: u8,
|
||||
original: lightcraft_develop::FocusArea,
|
||||
},
|
||||
Brush {
|
||||
points: Vec<Point>,
|
||||
/// Pen pressure (0..1) at each point; empty when no pen pressure was reported (a mouse) or the
|
||||
@@ -758,6 +766,8 @@ fn tool_interaction(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Res
|
||||
RightPanel::Masking => mask_overlay(app, ui, resp, map, d),
|
||||
RightPanel::Remove => remove_overlay(app, ui, resp, map, d),
|
||||
RightPanel::RedEye => eye_overlay(app, ui, resp, map, d),
|
||||
RightPanel::Edit if app.ui.tool == "lensBlurShape" => lens_blur_shape_overlay(app, ui, resp, map, d),
|
||||
RightPanel::Edit if app.ui.tool.starts_with("lensBlur") => lens_blur_brush_overlay(app, ui, resp, map, d),
|
||||
_ => {
|
||||
// side by side / stacked: Before shows the same frame, so a click in its view (white
|
||||
// balance, colour samples, targeted adjustment) means the same point of the photo.
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Lens Blur's tools on the photo: moving and resizing its fixed focus shape, and painting its
|
||||
//! Focus / Blur refinement brushes.
|
||||
|
||||
use super::geometry::CanvasMap;
|
||||
use super::masks::{frame_long_norm, pen_force, pin, record_pressure};
|
||||
use super::{Color32, DevelopSettings, Gesture, LightcraftApp, Point, Pos2, Rect, Stroke, json, register, vec2};
|
||||
|
||||
/// Lens Blur's fixed focus shape on the photo (Edit Shape): its outline, a centre pin that moves
|
||||
/// it (or drag anywhere inside), and handles on its right and bottom edges that stretch it
|
||||
/// sideways or up and down. One drag is one undo step.
|
||||
pub(super) fn lens_blur_shape_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, d: &DevelopSettings) {
|
||||
let Some(area) = d.lens_blur.focus_area(d.crop_center()) else { return };
|
||||
let clip = app.canvas_rect.unwrap_or(map.rect);
|
||||
let p = &ui.painter_at(clip);
|
||||
let l = frame_long_norm(map);
|
||||
let at = |dx: f64, dy: f64| map.screen(Point::new(area.center.x + dx * l.0, area.center.y + dy * l.1));
|
||||
let outline: Vec<Pos2> = (0..72)
|
||||
.map(|i| {
|
||||
let a = i as f64 / 72.0 * std::f64::consts::TAU;
|
||||
at(area.rx * a.cos(), area.ry * a.sin())
|
||||
})
|
||||
.collect();
|
||||
// a dark keyline under a light line: visible over bright and dark photos alike
|
||||
p.add(egui::Shape::closed_line(outline.clone(), Stroke::new(3.0, Color32::from_black_alpha(140))));
|
||||
p.add(egui::Shape::closed_line(outline, Stroke::new(1.5, Color32::from_white_alpha(235))));
|
||||
let (c, hx, hy) = (at(0.0, 0.0), at(area.rx, 0.0), at(0.0, area.ry));
|
||||
pin(p, c, true);
|
||||
for h in [hx, hy] {
|
||||
p.circle_filled(h, 5.5, Color32::WHITE);
|
||||
p.circle_stroke(h, 5.5, Stroke::new(1.5, Color32::from_black_alpha(160)));
|
||||
}
|
||||
for (name, q) in [("center", c), ("width", hx), ("height", hy)] {
|
||||
register(ui, format!("lensBlurArea:{name}"), Rect::from_center_size(q, vec2(14.0, 14.0)));
|
||||
}
|
||||
// which part a point grabs: a handle, else the inside
|
||||
let hit = |q: Pos2| -> Option<u8> {
|
||||
if q.distance(hx) < 10.0 {
|
||||
return Some(1);
|
||||
}
|
||||
if q.distance(hy) < 10.0 {
|
||||
return Some(2);
|
||||
}
|
||||
let n = map.norm(q);
|
||||
let (ex, ey) = ((n.x - area.center.x) / (area.rx * l.0).max(1e-9), (n.y - area.center.y) / (area.ry * l.1).max(1e-9));
|
||||
(q.distance(c) < 10.0 || ex * ex + ey * ey <= 1.0).then_some(0)
|
||||
};
|
||||
if let Some(q) = resp.hover_pos() {
|
||||
let icon = match hit(q) {
|
||||
Some(1) => Some(egui::CursorIcon::ResizeHorizontal),
|
||||
Some(2) => Some(egui::CursorIcon::ResizeVertical),
|
||||
Some(_) => Some(egui::CursorIcon::Move),
|
||||
None => None,
|
||||
};
|
||||
if let Some(icon) = icon {
|
||||
ui.ctx().set_cursor_icon(icon);
|
||||
}
|
||||
}
|
||||
if resp.drag_started()
|
||||
&& let Some(q) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
|
||||
&& let Some(handle) = hit(q)
|
||||
{
|
||||
let _ = app.run("develop.beginInteraction", json!({"label": "Lens Blur Shape"}));
|
||||
app.gesture = Some(Gesture::LensBlurArea { handle, original: area });
|
||||
}
|
||||
if resp.dragged()
|
||||
&& let (Some(Gesture::LensBlurArea { handle, original }), Some(q)) = (app.gesture.clone(), resp.interact_pointer_pos())
|
||||
{
|
||||
let n = map.norm(q);
|
||||
let n0 = map.norm(ui.input(|i| i.pointer.press_origin()).unwrap_or(q));
|
||||
let moved = match handle {
|
||||
0 => lightcraft_develop::FocusArea { center: Point::new(original.center.x + n.x - n0.x, original.center.y + n.y - n0.y), ..original },
|
||||
1 => lightcraft_develop::FocusArea { rx: (n.x - original.center.x).abs() / l.0.max(1e-9), ..original },
|
||||
_ => lightcraft_develop::FocusArea { ry: (n.y - original.center.y).abs() / l.1.max(1e-9), ..original },
|
||||
}
|
||||
.sanitized();
|
||||
let _ = app.run("develop.merge", json!({"settings": {"lens_blur": {"area": moved}}, "label": "Lens Blur Shape"}));
|
||||
}
|
||||
if resp.drag_stopped() && matches!(app.gesture, Some(Gesture::LensBlurArea { .. })) {
|
||||
app.gesture = None;
|
||||
let _ = app.run("develop.endInteraction", json!({}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Lens Blur Brush Refinement on the photo: the brush circle (size and feather), the stroke being
|
||||
/// painted (green: Focus, red: Blur), committed as `lensBlur.brushStroke` when the drag ends.
|
||||
/// ⌥ (Alt) erases what the brush painted.
|
||||
pub(super) fn lens_blur_brush_overlay(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, d: &DevelopSettings) {
|
||||
let long = (map.rect.width().max(map.rect.height())) as f64;
|
||||
let clip = app.canvas_rect.unwrap_or(map.rect);
|
||||
let p = &ui.painter_at(clip);
|
||||
let focus = app.ui.tool == "lensBlurFocus";
|
||||
let r = (app.ui.brush_size as f64 * long) as f32;
|
||||
if let Some(h) = resp.hover_pos() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
|
||||
p.circle_stroke(h, r, Stroke::new(1.0, Color32::WHITE));
|
||||
p.circle_stroke(h, r * (1.0 - app.ui.brush_feather / 100.0).max(0.05), Stroke::new(1.0, Color32::from_white_alpha(120)));
|
||||
}
|
||||
if let Some(q) = resp.interact_pointer_pos()
|
||||
&& (resp.drag_started() || resp.dragged() || resp.clicked())
|
||||
{
|
||||
let n = map.norm(q);
|
||||
let force = if app.ui.brush_pressure { ui.input(pen_force) } else { None };
|
||||
match &mut app.gesture {
|
||||
Some(Gesture::Brush { points, .. }) if points.last() == Some(&n) => {}
|
||||
Some(Gesture::Brush { points, pressure }) => {
|
||||
record_pressure(pressure, points.len(), force);
|
||||
points.push(n);
|
||||
}
|
||||
_ => {
|
||||
let mut pressure = Vec::new();
|
||||
record_pressure(&mut pressure, 0, force);
|
||||
app.gesture = Some(Gesture::Brush { points: vec![n], pressure });
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(Gesture::Brush { points, pressure }) = &app.gesture {
|
||||
let screen: Vec<Pos2> = points.iter().map(|q| map.screen(*q)).collect();
|
||||
let params = crate::brush_live::LiveParams {
|
||||
clip,
|
||||
scale: ui.ctx().pixels_per_point(),
|
||||
r,
|
||||
hard: r * (1.0 - (app.ui.brush_feather / 100.0).clamp(0.0, 1.0)),
|
||||
flow: (app.ui.brush_flow / 100.0).clamp(0.0, 1.0),
|
||||
density: (app.ui.lens_blur_brush_amount / 100.0).clamp(0.0, 1.0),
|
||||
// (its strokes render as a mask brush does, Flow per radius travelled from V9)
|
||||
per_radius: lightcraft_pipeline::masks::flow_per_radius(d),
|
||||
color: if focus { [70, 200, 120] } else { [230, 70, 70] },
|
||||
opacity: 0.45,
|
||||
};
|
||||
crate::brush_live::paint(&mut app.brush_live, ui.ctx(), p, params, &screen, pressure);
|
||||
} else {
|
||||
app.brush_live = None;
|
||||
}
|
||||
if (resp.drag_stopped() || resp.clicked())
|
||||
&& let Some(Gesture::Brush { points, pressure }) = app.gesture.take()
|
||||
{
|
||||
app.brush_live = None;
|
||||
let pts: Vec<[f64; 2]> = points.iter().map(|q| [q.x, q.y]).collect();
|
||||
let erase = resp.ctx.input(|i| i.modifiers.alt);
|
||||
let r = app.run(
|
||||
"lensBlur.brushStroke",
|
||||
json!({"mode": if focus { "focus" } else { "blur" }, "points": pts, "size": app.ui.brush_size, "feather": app.ui.brush_feather,
|
||||
"flow": app.ui.brush_flow, "amount": app.ui.lens_blur_brush_amount, "erase": erase, "autoMask": app.ui.brush_auto_mask,
|
||||
"pressure": pressure}),
|
||||
);
|
||||
if let Err(e) = r {
|
||||
app.toast(ui.ctx(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user