Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/catalog/src/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
//! | 22 | Pixel Shift merges remember how they were made (registered or plain, the hold-out verdict, why plain) | `MergeSources.registration` (`MergeRegistration`) |
//! | 23 | Custom Order in folders (issue #1583): the order set by hand for the photos of one folder of the library | `FolderRecord.photo_order` |
//! | 24 | Raw + JPEG companions: a JPEG beside its raw imports as the raw's companion, not a photo of its own (issue #1692) | `Op::SetCompanion`, `Photo.companion_jpeg` |
//! | 25 | Source colour: the file's bits per channel, colour model and ICC profile name, for the Bits Per Channel, Source Color Mode and Source Color Profile smart-album fields | `Meta.source_colour` |
//!
//! Rules:
//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a
Expand Down Expand Up @@ -103,7 +104,7 @@ pub(crate) const FORMAT: &str = "lcc-catalog";
pub(crate) const V4_FORMAT: &str = "lcc-catalog-db";
/// 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 = 24;
pub const VERSION: u32 = 25;

/// When [`Journal::wants_snapshot`] says it's time to compact the log.
#[derive(Clone, Copy, Debug)]
Expand Down
14 changes: 12 additions & 2 deletions crates/catalog/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,12 @@ pub struct Meta {
/// Catalog format 12.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub focus: Option<lcc_meta::FocusPoint>,
/// What the source file says about its colour (bits per channel, colour model, ICC profile name), read from
/// its header at import and by the background pass for photos from before; `None` = not read yet, a value
/// with empty parts = read and nothing found. Read-only: never written to XMP. Left out of the catalog JSON
/// when unread, so older catalogs read unchanged. Catalog format 25.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_colour: Option<lcc_meta::SourceColour>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
Expand Down Expand Up @@ -902,12 +908,16 @@ impl Photo {
pub fn extension(&self) -> &str {
self.file_name.rsplit_once('.').filter(|(stem, _)| !stem.is_empty()).map_or("", |(_, ext)| ext)
}
/// Width and height in pixels of the whole frame, turned by the photo's orientation and not cut by its crop.
pub fn uncropped_size(&self) -> (f64, f64) {
let (w, h) = (self.width as f64, self.height as f64);
if self.develop.orientation.swaps_axes() { (h, w) } else { (w, h) }
}
/// Width and height in pixels as the photo is shown: turned by its orientation and cut by its
/// crop. Straightening and Constrain Crop shrink the crop without changing its shape, so the
/// aspect is exact and the edges can read a little larger than an export.
pub fn shown_size(&self) -> (f64, f64) {
let (w, h) = (self.width as f64, self.height as f64);
let (w, h) = if self.develop.orientation.swaps_axes() { (h, w) } else { (w, h) };
let (w, h) = self.uncropped_size();
let r = self.develop.crop.geometry.rect;
// a crop read from a file or an agent is hostile: no NaN, nothing outside the frame
let part = |len: f64| if len.is_finite() { len.clamp(0.0, 1.0) } else { 1.0 };
Expand Down
135 changes: 131 additions & 4 deletions crates/catalog/src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,20 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[
("format", "File Format", Kind::Text),
("duration", "Video Duration", Kind::Number),
("fileSize", "File Size (MB)", Kind::Number),
("bitsPerChannel", "Bits Per Channel", Kind::Number),
(
"sourceColorMode",
"Source Color Mode",
Kind::Choice(&[
("rgb", "RGB"),
("gray", "Grayscale"),
("cmyk", "CMYK"),
("lab", "Lab"),
("raw", "Raw (colour filter array)"),
("other", "Other"),
]),
),
("sourceColorProfile", "Source Color Profile", Kind::Text),
("sameContent", "Same Content as Another Photo", Kind::Bool),
// Date
("captureDate", "Capture Date", Kind::Date),
Expand Down Expand Up @@ -232,6 +246,11 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[
("height", "Height (pixels)", Kind::Number),
("aspect", "Aspect Ratio", Kind::Choice(&[("landscape", "Landscape (wide)"), ("portrait", "Portrait (tall)"), ("square", "Square")])),
("megapixels", "Megapixels", Kind::Number),
("longEdgeUncropped", "Long Edge (uncropped)", Kind::Number),
("shortEdgeUncropped", "Short Edge (uncropped)", Kind::Number),
("widthUncropped", "Width (uncropped, pixels)", Kind::Number),
("heightUncropped", "Height (uncropped, pixels)", Kind::Number),
("megapixelsUncropped", "Megapixels (uncropped)", Kind::Number),
// Develop
("edited", "Has Edits", Kind::Bool),
("hasAdjustments", "Has Adjustments", Kind::Bool),
Expand Down Expand Up @@ -275,7 +294,23 @@ pub const TOP_LEVEL_FIELDS: &[&str] = &["rating", "flag", "label", "text"];
/// once or in [`TOP_LEVEL_FIELDS`].
pub const FIELD_GROUPS: &[(&str, &[&str])] = &[
("Source", &["album", "virtualCopy", "copyName", "stacked", "immich", "publishedVia", "publishCollection"]),
("File", &["fileName", "extension", "filePath", "folder", "kind", "format", "duration", "fileSize", "sameContent"]),
(
"File",
&[
"fileName",
"extension",
"filePath",
"folder",
"kind",
"format",
"duration",
"fileSize",
"bitsPerChannel",
"sourceColorMode",
"sourceColorProfile",
"sameContent",
],
),
("Date", &["captureDate", "importDate", "editDate", "lastExported", "captureMonth", "captureDay"]),
("Keywords & People", &["keywords", "keywordCount", "person", "personCount", "faceCount"]),
(
Expand All @@ -296,7 +331,22 @@ pub const FIELD_GROUPS: &[(&str, &[&str])] = &[
),
("Camera Info", &["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso", "flash", "exposureBias", "cameraSerial"]),
("Location", &["location", "sublocation", "city", "state", "country", "countryCode", "hasGps"]),
("Size", &["longEdge", "shortEdge", "width", "height", "aspect", "megapixels"]),
(
"Size",
&[
"longEdge",
"shortEdge",
"width",
"height",
"aspect",
"megapixels",
"longEdgeUncropped",
"shortEdgeUncropped",
"widthUncropped",
"heightUncropped",
"megapixelsUncropped",
],
),
(
"Develop",
&[
Expand Down Expand Up @@ -1289,6 +1339,11 @@ impl Rule {
"copyName" => text(p.copy_name.as_deref().unwrap_or("")),
"stacked" => yes(cat.stack_of(p.id).is_some()),
"sameContent" => yes(cat.has_same_content(p)),
// what the file's header says; a photo not read yet (or a file that says nothing) has no depth, and
// matches no rule on the mode or the profile (Lightroom's own name for no profile is Untagged)
"bitsPerChannel" => num_op(op, p.meta.source_colour.as_ref().filter(|c| c.bits > 0).map(|c| f64::from(c.bits)), value),
"sourceColorMode" => p.meta.source_colour.as_ref().is_some_and(|c| (c.model.id() == want) == (op == "is")),
"sourceColorProfile" => p.meta.source_colour.as_ref().is_some_and(|c| text(if c.profile.is_empty() { "Untagged" } else { &c.profile })),
"immich" => {
let want = if want == "notlinked" { "notLinked" } else { want.as_str() };
crate::query::immich_state_is(cat, p.id, want) == (op == "is")
Expand Down Expand Up @@ -1364,8 +1419,19 @@ impl Rule {
_ => text_op(op, &folder, &want),
}
}
"width" => num_op(op, Some(p.width as f64), value),
"height" => num_op(op, Some(p.height as f64), value),
// the shown frame: turned by the orientation and cut by the crop, as Lightroom's Width and Height
"width" => num_op(op, Some(p.shown_size().0.round()), value),
"height" => num_op(op, Some(p.shown_size().1.round()), value),
"widthUncropped" => num_op(op, Some(p.uncropped_size().0), value),
"heightUncropped" => num_op(op, Some(p.uncropped_size().1), value),
"longEdgeUncropped" | "shortEdgeUncropped" => {
let (w, h) = p.uncropped_size();
num_op(op, Some(if field == "longEdgeUncropped" { w.max(h) } else { w.min(h) }), value)
}
"megapixelsUncropped" => {
let (w, h) = p.uncropped_size();
num_op(op, Some(w * h / 1e6), value)
}
"copyright" => text(&m.copyright),
"copyrightStatus" => {
let want = crate::CopyrightStatus::parse(&want);
Expand Down Expand Up @@ -2383,6 +2449,67 @@ mod tests {
assert!(m(&empty, "megapixels", "is", json!(0)));
}

/// Bits Per Channel, Source Color Mode and Source Color Profile read what the source file's header said; a photo
/// not read yet matches none of them, and a file with no profile is Lightroom's `Untagged`.
#[test]
fn source_colour_fields_follow_what_the_file_said() {
use lcc_meta::{ColourModel, SourceColour};
let cat = Catalog::new();
let mut p = photo(1);
let m = |p: &Photo, field: &str, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat)
};
for (field, op, value) in [
("bitsPerChannel", "is", json!(8)),
("sourceColorMode", "is", json!("rgb")),
("sourceColorMode", "isNot", json!("rgb")),
("sourceColorProfile", "contains", json!("srgb")),
("sourceColorProfile", "is", json!("Untagged")),
] {
assert!(!m(&p, field, op, value), "{field} {op}: a photo not read yet matches no colour rule");
}
p.meta.source_colour = Some(SourceColour { bits: 16, model: ColourModel::Rgb, profile: "Display P3".into(), version: 1 });
assert!(m(&p, "bitsPerChannel", "is", json!(16)) && !m(&p, "bitsPerChannel", "is", json!(8)) && m(&p, "bitsPerChannel", "gte", json!(10)));
assert!(
m(&p, "sourceColorMode", "is", json!("rgb"))
&& m(&p, "sourceColorMode", "isNot", json!("raw"))
&& !m(&p, "sourceColorMode", "is", json!("raw"))
);
assert!(m(&p, "sourceColorProfile", "is", json!("display p3")) && m(&p, "sourceColorProfile", "contains", json!("P3")));
assert!(!m(&p, "sourceColorProfile", "is", json!("Untagged")));
p.meta.source_colour = Some(SourceColour { bits: 14, model: ColourModel::Raw, profile: String::new(), version: 1 });
assert!(m(&p, "sourceColorProfile", "is", json!("Untagged")) && !m(&p, "sourceColorProfile", "isEmpty", json!("")));
assert!(m(&p, "sourceColorMode", "is", json!("raw")) && m(&p, "bitsPerChannel", "is", json!(14)));
p.meta.source_colour = Some(SourceColour::nothing_found());
assert!(!m(&p, "bitsPerChannel", "is", json!(0)), "a file that says nothing has no depth");
assert!(m(&p, "sourceColorMode", "is", json!("other")));
}

/// Width and Height are the shown frame, like the edges; the uncropped fields are the whole frame
/// (turned by the orientation, never cut by the crop).
#[test]
fn width_and_height_follow_the_crop_and_the_uncropped_fields_do_not() {
let cat = Catalog::new();
let mut p = photo(1); // 6000 × 4000
let m = |p: &Photo, field: &str, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat)
};
assert!(m(&p, "width", "is", json!(6000)) && m(&p, "height", "is", json!(4000)));
assert!(m(&p, "widthUncropped", "is", json!(6000)) && m(&p, "heightUncropped", "is", json!(4000)));
let mut s = (*p.develop).clone();
s.orientation = lcc_geom::Orientation::Rotate90;
// a square crop of the rotated frame: 4000 wide, 4000 of its 6000 tall
s.crop.geometry.rect = lcc_geom::Rect::new(0.0, 1.0 / 6.0, 1.0, 5.0 / 6.0);
p.develop = std::sync::Arc::new(s);
assert!(m(&p, "width", "is", json!(4000)) && m(&p, "height", "is", json!(4000)), "the crop, after the turn");
assert!(!m(&p, "height", "is", json!(6000)));
assert!(m(&p, "widthUncropped", "is", json!(4000)) && m(&p, "heightUncropped", "is", json!(6000)), "the turn, not the crop");
assert!(m(&p, "longEdgeUncropped", "is", json!(6000)) && m(&p, "shortEdgeUncropped", "is", json!(4000)));
assert!(m(&p, "longEdge", "is", json!(4000)), "the cropped edge is the crop's");
assert!(m(&p, "megapixelsUncropped", "is", json!(24)) && m(&p, "megapixels", "is", json!(16)));
assert!(m(&p, "megapixelsUncropped", "gte", json!(20)) && !m(&p, "megapixels", "gte", json!(20)));
}

/// Any Searchable Text also finds the state / province, the alt text, a person on a face and
/// a virtual copy's name, as it already finds the city and country.
#[test]
Expand Down
5 changes: 3 additions & 2 deletions crates/catalog/src/tests_format_version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,9 @@ fn op_variants_are_versioned() {
}
/// v20: `Analysis.quality` (the Image Quality Scanner's scores); v21: `QualityScan.rating_written`; v22:
/// `MergeSources.registration`; v23: `FolderRecord.photo_order` (a folder's Custom Order); v24:
/// `Photo.companion_jpeg` (the raw's companion JPEG, issue #1692).
const NEWEST_FIELDS: u32 = 24;
/// `Photo.companion_jpeg` (the raw's companion JPEG, issue #1692); v25: `Meta.source_colour` (the source file's bits
/// per channel, colour model and ICC profile name).
const NEWEST_FIELDS: u32 = 25;
let map = lcc_develop::EmbeddedVignettingMap::from_ev([4, 4], [2, 2], None, Default::default(), &[0.0; 4]).unwrap();
let id = lcc_develop::VignettingMapId::of(&map);
let _vignetting = since(&Op::AddVignettingMap {
Expand Down
44 changes: 44 additions & 0 deletions crates/codecs/src/jxl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,50 @@ fn open(bytes: &[u8], opts: &DecodeOptions) -> Result<JxlImage> {
Ok(img)
}

/// What a JPEG XL file's headers say about its source colour (see [`source_colour`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SourceColourFacts {
/// Bits per sample of the colour channels.
pub bits: u8,
/// A grayscale image.
pub gray: bool,
/// The embedded ICC profile, when the file carries one rather than naming a colour space.
pub icc: Option<Vec<u8>>,
}

/// The bit depth, colour model and embedded ICC profile of a JPEG XL file, from its image header alone: no frame is
/// loaded and the allocation budget is the smallest one. `None` for a file whose header can't be read.
pub fn source_colour(bytes: &[u8]) -> Option<SourceColourFacts> {
std::panic::catch_unwind(|| source_colour_unguarded(bytes)).ok().flatten()
}

fn source_colour_unguarded(bytes: &[u8]) -> Option<SourceColourFacts> {
let tracker = AllocTracker::with_limit(usize::try_from(MIN_TRACKED_BYTES).unwrap_or(usize::MAX));
let mut uninit = JxlImage::builder().alloc_tracker(tracker).build_uninit();
let mut rest = bytes;
let mut window = INPUT_CHUNK;
let img = loop {
let consumed = uninit.feed_bytes(rest.get(..window).unwrap_or(rest)).ok()?;
rest = rest.get(consumed..).unwrap_or_default();
match uninit.try_init().ok()? {
InitializeResult::Initialized(img) => break img,
InitializeResult::NeedMoreData(more) => uninit = more,
}
if consumed == 0 {
if window >= rest.len() {
return None;
}
window = window.saturating_mul(2);
}
};
let header = img.image_header();
Some(SourceColourFacts {
bits: u8::try_from(header.metadata.bit_depth.bits_per_sample()).unwrap_or(u8::MAX),
gray: header.metadata.grayscale(),
icc: img.original_icc().map(<[u8]>::to_vec),
})
}

/// Dimensions from the codestream (orientation already applied by jxl-oxide, so 1, as a decode
/// reports it) without rendering a frame: the frames are parsed within the decode's allocation
/// budget, and a file without a complete first keyframe (truncated) is refused, as a decode would.
Expand Down
15 changes: 15 additions & 0 deletions crates/codecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,22 @@ pub use encode::{
encode_psd, encode_tiff, encode_tiff_associated, encode_webp_lossless, encode_webp_lossy, hlg_signal, webp_max_side,
};
pub use exr_encode::{ACESCG, ExrOptions, encode_exr};
#[cfg(feature = "jxl")]
pub use jxl::{SourceColourFacts as JxlSourceColour, source_colour as jxl_source_colour};
/// What a JPEG XL file's headers say about its source colour (always `None` in a build without JPEG XL).
#[cfg(not(feature = "jxl"))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JxlSourceColour {
pub bits: u8,
pub gray: bool,
pub icc: Option<Vec<u8>>,
}
#[cfg(not(feature = "jxl"))]
pub fn jxl_source_colour(_: &[u8]) -> Option<JxlSourceColour> {
None
}
pub use jxl_encode::{JxlColour, JxlEffort, JxlOptions, encode_jxl, encode_jxl_gain_map};
pub use png_codec::icc_profile as png_icc_profile;
pub use sniff::{Format, sniff};
pub use space::{NamedSpace, SourceSpace, SpaceOrigin, Trc};

Expand Down
13 changes: 13 additions & 0 deletions crates/codecs/src/png_codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,19 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
finish(F, raw, meta, (w, h), opts)
}

/// The embedded ICC profile (`iCCP`) of a PNG, read from the chunks before the image data, which is not touched. Its
/// inflated size is bounded; a malformed file has none.
pub fn icc_profile(bytes: &[u8]) -> Option<Vec<u8>> {
std::panic::catch_unwind(|| {
let mut dec = png::Decoder::new(std::io::Cursor::new(bytes));
dec.set_limits(png::Limits { bytes: 16 << 20 });
let reader = dec.read_info().ok()?;
reader.info().icc_profile.as_ref().map(|c| c.to_vec())
})
.ok()
.flatten()
}

/// Stored dimensions and EXIF orientation (`eXIf`, wherever it is) from the chunk headers, without
/// inflating the image data. Refused, as a decode would refuse it: an invalid IHDR, an indexed
/// image without a palette, no IDAT, or a file that ends before the chunk after the last IDAT
Expand Down
2 changes: 2 additions & 0 deletions crates/engine/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ mod people_recognize;
mod people_roles;
pub mod profile_manager;
pub(crate) mod retouch;
mod source_colour;
pub mod vignetting_calibration;
#[cfg(test)]
pub(crate) use organize::STACK_WORK;
Expand Down Expand Up @@ -375,6 +376,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
#[cfg(not(target_arch = "wasm32"))]
v.extend(update::specs());
v.extend(focus::specs());
v.extend(source_colour::specs());
v.extend(ml::specs());
v.extend(folder_metadata::specs());
v.extend(activity::specs());
Expand Down
Loading