diff --git a/Cargo.lock b/Cargo.lock index 8cac297f0f..f7e437eaea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5125,6 +5125,8 @@ dependencies = [ name = "lcc-meta" version = "26.45.4" dependencies = [ + "brotli", + "brotli-decompressor", "chrono", "lcc-brand", "lcc-geom", diff --git a/crates/actions/src/lib.rs b/crates/actions/src/lib.rs index 32e48d0f5a..c6c917ec73 100644 --- a/crates/actions/src/lib.rs +++ b/crates/actions/src/lib.rs @@ -146,6 +146,8 @@ pub fn is_navigation(id: &str) -> bool { | "library.selectNone" | "library.next" | "library.previous" + | "library.nextUnrated" + | "library.prevUnrated" | "library.first" | "library.last" | "library.source" diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 946955e462..609bc5cd0b 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -198,11 +198,20 @@ pub struct Meta { /// two bodies of one model apart for their own camera profiles ([`Meta::camera_model`] says the model). #[serde(skip_serializing_if = "String::is_empty")] pub camera_serial: String, + /// The lens maker (Exif `LensMake`), written back on export. Left out of the catalog JSON when empty. + #[serde(skip_serializing_if = "String::is_empty")] + pub lens_make: String, pub lens: String, pub focal_mm: Option, pub aperture: Option, pub shutter: String, pub iso: Option, + /// Whether the flash fired (Exif `Flash`); `None` when the file does not say. + #[serde(skip_serializing_if = "Option::is_none")] + pub flash: Option, + /// Exposure compensation in EV (Exif `ExposureBiasValue`). + #[serde(skip_serializing_if = "Option::is_none")] + pub exposure_bias: Option, /// The lens's focal range (mm, shortest and longest), from the file's LensSpecification: the loupe's shot info /// adds it to a lens name that doesn't say it (OneSlips PERF-CULL-7 a5f6da85e). Left out of the catalog JSON when /// unknown, so older catalogs read unchanged. diff --git a/crates/catalog/src/rules.rs b/crates/catalog/src/rules.rs index 16388bed3f..9efeba943b 100644 --- a/crates/catalog/src/rules.rs +++ b/crates/catalog/src/rules.rs @@ -110,6 +110,9 @@ pub const FIELDS: &[(&str, &str, Kind)] = &[ ("aperture", "Aperture", Kind::Number), ("shutterSpeed", "Shutter Speed", Kind::Number), ("iso", "ISO Speed", Kind::Number), + ("flash", "Flash", Kind::Bool), + ("exposureBias", "Exposure Bias", Kind::Number), + ("cameraSerial", "Camera Serial Number", Kind::Text), // Location ("location", "Location", Kind::Text), ("sublocation", "Sublocation", Kind::Text), @@ -149,7 +152,7 @@ pub const FIELD_GROUPS: &[(&str, &[&str])] = &[ ("Date", &["captureDate", "importDate", "editDate"]), ("Keywords & People", &["keywords", "keywordCount", "person", "personCount", "faceCount"]), ("Description", &["title", "caption", "altText", "creator", "copyright", "usageTerms", "copyrightStatus"]), - ("Camera Info", &["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso"]), + ("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"]), ("Develop", &["edited", "cropped", "treatment"]), @@ -1103,6 +1106,9 @@ impl Rule { "editDate" => date_op(op, p.edited.as_deref(), value), "shutterSpeed" => num_op(op, crate::parse_shutter_seconds(&m.shutter), &shutter_value(value)), "iso" => num_op(op, m.iso.map(|v| v as f64), value), + "flash" => yes(m.flash.unwrap_or(false)), + "exposureBias" => num_op32(op, m.exposure_bias, value), + "cameraSerial" => text(&m.camera_serial), "aperture" => num_op32(op, m.aperture, value), "focalLength" => num_op32(op, m.focal_mm, value), "longEdge" | "shortEdge" => { @@ -1387,6 +1393,21 @@ mod tests { yes(json!({"rules": [{"field": "filePath", "op": "isEmpty"}]})); yes(json!({"rules": [{"field": "camera", "op": "contains", "value": "x2"}, {"field": "title", "op": "isEmpty"}]})); yes(json!({"rules": [{"field": "iso", "op": "between", "value": [800, 3200]}, {"field": "aperture", "op": "lte", "value": "f/4"}]})); + // flash, exposure bias and camera serial (ported from upstream #3821): unrecorded is "no flash", no bias, empty + no(json!({"rules": [{"field": "flash", "op": "is", "value": true}]})); + no(json!({"rules": [{"field": "exposureBias", "op": "lt", "value": 0}]})); + no(json!({"rules": [{"field": "cameraSerial", "op": "contains", "value": "x2"}]})); + let mut fl = photo(2); + fl.meta.flash = Some(true); + fl.meta.exposure_bias = Some(-0.67); + fl.meta.camera_serial = "SN-X2".into(); + let flm = |v: serde_json::Value| rs(v).matches(&fl, &cat); + assert!(flm(json!({"rules": [{"field": "flash", "op": "is", "value": true}]}))); + assert!(!flm(json!({"rules": [{"field": "flash", "op": "is", "value": false}]}))); + assert!(flm(json!({"rules": [{"field": "exposureBias", "op": "lt", "value": 0}]}))); + assert!(flm(json!({"rules": [{"field": "exposureBias", "op": "between", "value": [-1.0, -0.3]}]}))); + assert!(flm(json!({"rules": [{"field": "cameraSerial", "op": "contains", "value": "x2"}]}))); + assert_eq!(field_group("exposureBias"), Some("Camera Info")); yes(json!({"rules": [{"field": "megapixels", "op": "gte", "value": 24}]})); yes( json!({"rules": [{"field": "captureDate", "op": "is", "value": "2026-08"}, {"field": "captureDate", "op": "before", "value": "2026-09-01"}]}), diff --git a/crates/codecs/src/jxl.rs b/crates/codecs/src/jxl.rs index 08bd582eb2..ff9862b1e1 100644 --- a/crates/codecs/src/jxl.rs +++ b/crates/codecs/src/jxl.rs @@ -131,7 +131,8 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { meta.icc = icc; } if let Ok(AuxBoxData::Data(ex)) = img.aux_boxes().first_exif() { - meta.exif = Some(ex.payload().to_vec()); + // The box declares where the TIFF header starts inside its payload; skip any prefix before it. + meta.exif = usize::try_from(ex.tiff_header_offset()).ok().and_then(|offset| ex.payload().get(offset..)).map(<[u8]>::to_vec); } if let AuxBoxData::Data(x) = img.aux_boxes().first_xml() { meta.xmp = Some(String::from_utf8_lossy(x).trim_end_matches('\0').to_string()); diff --git a/crates/codecs/tests/it/jxl_streaming.rs b/crates/codecs/tests/it/jxl_streaming.rs index 7785ae4692..b04304e54d 100644 --- a/crates/codecs/tests/it/jxl_streaming.rs +++ b/crates/codecs/tests/it/jxl_streaming.rs @@ -94,3 +94,29 @@ fn progressive_truncation_matches_builder() { } } } + +#[test] +fn exif_payload_starts_at_declared_tiff_header() { + let pixels = Rgba8::from_fn(8, 8, |x, y| [(x * 20) as u8, (y * 20) as u8, 80, 255]); + let encoded = encode_jxl(&EncodeImage::rgba8(&pixels), &JxlOptions { lossless: true, ..Default::default() }, &EncodeMeta::default()).unwrap(); + let raw = codestream(&encoded); + let exif = minimal_exif(1); + for offset in [0u32, 6, 64] { + let mut exif_box = offset.to_be_bytes().to_vec(); + exif_box.resize(4 + offset as usize, 0xab); + exif_box.extend_from_slice(&exif); + let mut bytes = b"\0\0\0\x0cJXL \x0d\x0a\x87\x0a".to_vec(); + box_bytes(&mut bytes, b"ftyp", b"jxl \0\0\0\0jxl "); + box_bytes(&mut bytes, b"jxlc", &raw); + box_bytes(&mut bytes, b"Exif", &exif_box); + let decoded = decode(&bytes, DecodeOptions::default()).unwrap(); + assert_eq!(decoded.exif.as_deref(), Some(exif.as_slice()), "offset {offset}"); + } + // an offset past the payload must not panic and yields no Exif + let mut bytes = b"\0\0\0\x0cJXL \x0d\x0a\x87\x0a".to_vec(); + box_bytes(&mut bytes, b"ftyp", b"jxl \0\0\0\0jxl "); + box_bytes(&mut bytes, b"jxlc", &raw); + box_bytes(&mut bytes, b"Exif", &[0xff, 0xff, 0xff, 0xff, 1, 2]); + let decoded = decode(&bytes, DecodeOptions::default()).unwrap(); + assert!(decoded.exif.is_none()); +} diff --git a/crates/codecs/tests/it/main.rs b/crates/codecs/tests/it/main.rs index 6c18a1c014..9f6519c673 100644 --- a/crates/codecs/tests/it/main.rs +++ b/crates/codecs/tests/it/main.rs @@ -11,3 +11,4 @@ mod heif; #[cfg(all(feature = "jxl", not(target_arch = "wasm32")))] mod jxl_streaming; mod roundtrip; +mod tiff_zip; diff --git a/crates/codecs/tests/it/tiff_zip.rs b/crates/codecs/tests/it/tiff_zip.rs new file mode 100644 index 0000000000..4c968a51ff --- /dev/null +++ b/crates/codecs/tests/it/tiff_zip.rs @@ -0,0 +1,83 @@ +//! Noisy 8/16-bit ZIP TIFFs stay within their uncompressed size (issue #2882), using the Deflate backend the +//! application dependency graph selects (no test-only backend is forced), so a dependency switching it shows up. + +use lcc_codecs::*; + +/// A deterministic value in -0.5..0.5 per position and channel. +fn hash(x: u32, y: u32, c: u32) -> f64 { + let mut z = (x as u64) << 32 ^ (y as u64) << 2 ^ c as u64 ^ 0x2882; + z = (z ^ (z >> 33)).wrapping_mul(0xff51_afd7_ed55_8ccd); + z = (z ^ (z >> 33)).wrapping_mul(0xc4ce_b9fe_1a85_ec53); + (z ^ (z >> 33)) as f64 / u64::MAX as f64 - 0.5 +} + +/// 16-bit RGB: smooth gradients plus noise of `noise` codes peak to peak (a clean to a high-ISO photo's low bits). +fn noisy16(w: u32, h: u32, noise: f64) -> Vec { + let mut v = Vec::with_capacity((w * h * 3) as usize); + for y in 0..h { + for x in 0..w { + let (u, t) = (x as f64 / w as f64, y as f64 / h as f64); + let base = [0.10 + 0.5 * u, 0.15 + 0.4 * t, 0.3 + 0.3 * u * t]; + for c in 0..3 { + v.push((base[c as usize] * 65535.0 + noise * hash(x, y, c)).clamp(0.0, 65535.0) as u16); + } + } + } + v +} + +/// Both depths must actually use Deflate and decode at the original dimensions. +fn checked_zip_size(img: &EncodeImage<'_>) -> usize { + let bytes = encode_tiff(img, TiffCompression::Deflate, &EncodeMeta::default()).unwrap(); + let mut decoder = tiff::decoder::Decoder::new(std::io::Cursor::new(&bytes)).unwrap(); + let compression = decoder.get_tag_u32(tiff::tags::Tag::Compression).unwrap(); + assert!(matches!(compression, 8 | 32946), "Compression tag {compression} is not Deflate"); + let decoded = decode(&bytes, DecodeOptions::default()).unwrap(); + assert_eq!((decoded.image.width, decoded.image.height), (img.width as usize, img.height as usize)); + bytes.len() +} + +/// The shipped backend keeps noisy 16-bit ZIP exports smaller than uncompressed TIFFs. +#[test] +fn sixteen_bit_zip_tiff_is_never_larger_than_uncompressed() { + let (w, h) = (512, 384); + for noise in [0.0, 200.0, 1300.0, 4000.0, 13000.0] { + let px = noisy16(w, h, noise); + let img = EncodeImage::new(w, h, 3, Samples::U16(&px)); + let none = encode_tiff(&img, TiffCompression::None, &EncodeMeta::default()).unwrap().len(); + let zip = checked_zip_size(&img); + eprintln!("noise {noise} codes: none {none} B, ZIP {zip} B ({:+.1} %)", 100.0 * (zip as f64 / none as f64 - 1.0)); + assert!(zip <= none, "noise {noise}: 16-bit ZIP {zip} B is larger than uncompressed {none} B"); + } +} + +/// The same size guarantee holds for 8-bit ZIP exports across several noise levels. +#[test] +fn eight_bit_zip_tiff_is_never_larger_than_uncompressed() { + let (w, h) = (512, 384); + for noise in [0.0, 4.0, 20.0, 60.0] { + let px: Vec = noisy16(w, h, noise * 257.0).iter().map(|v| (v >> 8) as u8).collect(); + let img = EncodeImage::new(w, h, 3, Samples::U8(&px)); + let none = encode_tiff(&img, TiffCompression::None, &EncodeMeta::default()).unwrap().len(); + let zip = checked_zip_size(&img); + eprintln!("8-bit noise {noise}: none {none} B, ZIP {zip} B ({:+.1} %)", 100.0 * (zip as f64 / none as f64 - 1.0)); + assert!(zip <= none, "8-bit noise {noise}: ZIP {zip} B is larger than uncompressed {none} B"); + } +} + +/// What ZIP costs at 24 MP, 16 bit (ignored by default): +/// `cargo test --release -p lcc-codecs --test it tiff_zip::bench -- --ignored --nocapture` +#[test] +#[ignore] +fn bench_24mp_16_bit_zip() { + let (w, h) = (6000, 4000); + for noise in [200.0, 1300.0, 4000.0] { + let px = noisy16(w, h, noise); + let img = EncodeImage::new(w, h, 3, Samples::U16(&px)); + for c in [TiffCompression::None, TiffCompression::Deflate, TiffCompression::Lzw] { + let t = std::time::Instant::now(); + let n = encode_tiff(&img, c, &EncodeMeta::default()).unwrap().len(); + println!("noise {noise:>6} {c:?}: {:>7.1} MB in {:>6.0} ms", n as f64 / 1e6, t.elapsed().as_secs_f64() * 1e3); + } + } +} diff --git a/crates/engine/src/availability.rs b/crates/engine/src/availability.rs index c664b595b7..0ab208e8ab 100644 --- a/crates/engine/src/availability.rs +++ b/crates/engine/src/availability.rs @@ -17,6 +17,12 @@ //! reads of an import or a scan on the same share. So the worker starts no sweep check while the //! caller says files are busy ([`Availability::sweep_yields_to`]); what is asked still gets //! answered (within [`YIELD_POLL`]), and the sweep goes on where it stopped when the work ends. +//! +//! What is kept for the files that are there does not grow with the library, which the grid and a +//! sweep go through whole: [`MAX_THERE`] of them are kept, and the oldest found is forgotten first +//! unless it was asked about meanwhile (a file that is not kept is unknown, which counts as there). A +//! file found gone is kept for as long as it is gone (the offline badges and the Missing Photos count +//! are made of those), and a sweep adds to what is kept only the files it finds gone. use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; @@ -37,15 +43,40 @@ const YIELD_POLL: Duration = Duration::from_millis(250); /// How long a cached answer is used before it is checked again (it is still returned meanwhile). pub const RECHECK: Duration = Duration::from_secs(15); +/// How many files found there are kept: far more than the grid and the filmstrip show at once, and +/// enough for the originals of all but a very large library (next to nothing is forgotten there; +/// the smart previews that were looked at take places too). Each takes a few hundred bytes with its +/// path: about 20 MB for paths of 50 characters, a few tens of MB at most. (The files found gone +/// are kept besides, for as long as they are gone.) +const MAX_THERE: usize = 65_536; + fn fs_exists(path: &str) -> bool { // the browser build has no file system: its originals are always "there" cfg!(target_arch = "wasm32") || std::path::Path::new(path).exists() } +/// What the last check of a file found, and how the file stands in [`State::there`]. +#[derive(Clone, Copy)] +struct Kept { + /// Whether the file was there. + there: bool, + /// When it was checked. + at: std::time::Instant, + /// Whether [`State::there`] has an entry for the file (one at most): from when it was found there + /// until its turn to be forgotten comes, even if it was found gone meanwhile. + listed: bool, + /// Whether the file was asked about since it was listed or last spared ([`State::make_room`]), or + /// found there again while its old entry was still listed. + used: bool, +} + #[derive(Default)] struct State { - /// path → (exists, when checked) - known: HashMap, + /// path → what the last check of it found + known: HashMap, + /// The files found there, oldest first, each once ([`Kept::listed`]): [`MAX_THERE`] at most. One + /// found gone since stays listed until its turn, which only unlists it: it is kept as gone. + there: VecDeque, queue: VecDeque, queued: HashSet, /// What a sweep has left to check: after the queue, whatever it holds. @@ -65,6 +96,53 @@ fn lock(m: &Mutex) -> MutexGuard<'_, State> { m.lock().unwrap_or_else(PoisonError::into_inner) } +impl State { + /// Keep what a check found for `path`, and say whether that differs from what was kept (nothing + /// kept differs). All the files found gone are kept, and [`MAX_THERE`] of the files found there: + /// room for one more is made by forgetting the oldest ([`State::make_room`]), and a forgotten file + /// is unknown, which counts as there. + fn remember(&mut self, path: String, ok: bool) -> bool { + let old = self.known.get(&path).copied(); + let (listed, used) = old.map_or((false, false), |k| (k.listed, k.used)); + let mut kept = Kept { there: ok, at: std::time::Instant::now(), listed, used }; + if ok && !listed { + self.make_room(); + self.there.push_back(path.clone()); + kept.listed = true; + kept.used = false; + } else if ok && old.is_some_and(|k| !k.there) { + // found there again while its entry from before is still listed: that entry's turn only spares it + kept.used = true; + } + self.known.insert(path, kept); + old.map(|k| k.there) != Some(ok) + } + + /// Make room in `there` for one more file: the oldest listed is forgotten, unless it was asked about + /// since it was listed (or last spared), which spares it once: it goes to the back, and the next + /// oldest is looked at. A file found gone since is only unlisted: its answer stays. + fn make_room(&mut self) { + while self.there.len() >= MAX_THERE { + let Some(oldest) = self.there.pop_front() else { break }; + let Some(kept) = self.known.get_mut(&oldest) else { continue }; + if !kept.there { + kept.listed = false; + } else if kept.used { + kept.used = false; + self.there.push_back(oldest); + } else { + self.known.remove(&oldest); + } + } + } + + /// The sweep's list goes, and the room it took (a path for every photo of the library) with it: its last + /// path is taken, it is over, or it is dropped. + fn end_sweep(&mut self) { + self.sweep = VecDeque::new(); + } +} + /// File availability, synchronous or cached + background-checked. Cloning shares the cache. #[derive(Clone)] pub struct Availability { @@ -91,6 +169,7 @@ impl Availability { self.probe = probe; let mut st = lock(&self.state); st.known.clear(); + st.there.clear(); st.gone.clear(); st.gone_generation += 1; } @@ -121,21 +200,26 @@ impl Availability { self.background.is_some() } - /// Does `path` exist? Synchronous mode: checked now. Background mode: the cached answer - /// (`None` while unknown); unknown or stale answers are queued for the worker. + /// Does `path` exist? Synchronous mode: checked now. Background mode: the cached answer (`None` + /// while unknown, and for a file found there that was forgotten: see [`MAX_THERE`]); unknown or + /// stale answers are queued for the worker. Asking about a kept answer spares it once when its + /// turn to be forgotten comes. pub fn exists(&self, path: &str) -> Option { let Some(wake) = &self.background else { return Some((self.probe)(path)); }; let mut st = lock(&self.state); let now = std::time::Instant::now(); - let cached = st.known.get(path).copied(); - if cached.is_none_or(|(_, at)| now.saturating_duration_since(at) >= RECHECK) && !st.queued.contains(path) { + let cached = st.known.get_mut(path).map(|kept| { + kept.used = true; + *kept + }); + if cached.is_none_or(|kept| now.saturating_duration_since(kept.at) >= RECHECK) && !st.queued.contains(path) { st.queued.insert(path.to_string()); st.queue.push_back(path.to_string()); self.start(st, wake); } - cached.map(|c| c.0) + cached.map(|kept| kept.there) } /// Known to be missing (unknown counts as present). @@ -155,9 +239,11 @@ impl Availability { } /// Check `paths` too, in the background and after whatever is asked meanwhile, skipping those - /// checked less than [`RECHECK`] ago. One sweep at a time: `false` (and nothing queued) while - /// one is under way, or in synchronous mode. A sweep's answers wake only when a file is found - /// gone or back. + /// with a kept answer less than [`RECHECK`] old. One sweep at a time: `false` (and nothing + /// queued) while one is under way, or in synchronous mode. A sweep's answers wake only when a + /// file is found gone or back. It keeps an answer only for a file found gone, or one it already + /// keeps an answer for: the files found there are not kept (see [`MAX_THERE`]), so a sweep of a + /// library leaves what is gone behind, not the library. pub fn sweep(&self, paths: Vec) -> bool { self.sweep_checked(None, paths) } @@ -178,7 +264,7 @@ impl Availability { /// list of files being made for the old one is then refused. pub fn restart_sweeps(&self) -> u64 { let mut st = lock(&self.state); - st.sweep.clear(); + st.end_sweep(); st.sweep_epoch += 1; st.sweep_epoch } @@ -237,10 +323,16 @@ impl Availability { Some(p) => (p, true), None => loop { let Some(p) = st.sweep.pop_front() else { + st.end_sweep(); st.worker = false; return; }; - let fresh = st.known.get(&p).is_some_and(|(_, at)| at.elapsed() < RECHECK); + if st.sweep.is_empty() { + // (the last path: the list gives back its room now, not when the worker next finds nothing asked, + // which a share that answers slowly can put off for long) + st.end_sweep(); + } + let fresh = st.known.get(&p).is_some_and(|kept| kept.at.elapsed() < RECHECK); if !fresh && !st.queued.contains(&p) { break (p, false); } @@ -254,11 +346,12 @@ impl Availability { st.queued.remove(&path); } let gone_changed = if ok { st.gone.remove(&path) } else { st.gone.insert(path.clone()) }; - let prev = st.known.insert(path, (ok, std::time::Instant::now())); - let changed = prev.map(|p| p.0) != Some(ok); if gone_changed { st.gone_generation += 1; } + // what a sweep finds there is kept only where an answer is kept already: a library's + // worth of paths is not what this cache is for + let changed = (asked || !ok || st.known.contains_key(&path)) && st.remember(path, ok); (asked && changed) || gone_changed }; if wakes { @@ -270,7 +363,7 @@ impl Availability { // try again on the next question; a sweep nobody works on would refuse every new one let mut st = lock(&self.state); st.worker = false; - st.sweep.clear(); + st.end_sweep(); } } } @@ -349,6 +442,28 @@ mod tests { m.lock().unwrap_or_else(PoisonError::into_inner) } + /// The worker has answered all it was given and stopped. + fn wait_idle(a: &Availability) { + wait_until("the worker to finish", || !lock(&a.state).worker); + } + + /// How many answers are kept. + fn remembered(a: &Availability) -> usize { + lock(&a.state).known.len() + } + + /// What is kept for `path`: whether the file was there. + fn kept_there(st: &State, path: &str) -> Option { + st.known.get(path).map(|kept| kept.there) + } + + /// Make the answer kept for `path` `by` older (a sweep skips what was checked a moment ago). + fn age(a: &Availability, path: &str, by: Duration) { + let mut st = lock(&a.state); + let kept = st.known.get_mut(path).expect("an answer is kept for the path"); + kept.at = kept.at.checked_sub(by).expect("the clock has run for longer than that"); + } + /// A background `Availability` whose probe logs what it checks; files named `gone…` are not there. fn logged() -> (Availability, Arc>>, Arc) { let mut a = Availability::default(); @@ -380,7 +495,7 @@ mod tests { let (a, _, woke) = logged(); let before = a.gone_generation(); a.sweep(vec!["a".into(), "b".into(), "c".into()]); - wait_until("the answers", || ["a", "b", "c"].iter().all(|p| lock(&a.state).known.contains_key(*p))); + wait_idle(&a); assert_eq!(a.gone_generation(), before, "nothing went missing"); assert_eq!(woke.load(Ordering::SeqCst), 0, "a sweep finding files there wakes nobody"); a.sweep(vec!["gone".into()]); @@ -539,4 +654,231 @@ mod tests { wait_until("the sweep", || a.sweeping() == 0); assert_eq!(held(&log).iter().filter(|p| *p == "a").count(), 1, "`a` was checked a moment ago"); } + + #[test] + fn a_sweep_keeps_only_the_files_it_finds_gone() { + let (a, _, _) = logged(); + // a library's worth of files, a few of them gone + let paths: Vec = (0..2_000).map(|i| if i % 500 == 0 { format!("gone {i}") } else { format!("here {i}") }).collect(); + assert!(a.sweep(paths)); + wait_idle(&a); + assert_eq!(a.gone_len(), 4); + assert_eq!(remembered(&a), 4, "the files found there are not kept"); + assert_eq!(a.exists("gone 500"), Some(false)); + assert_eq!(a.exists("here 7"), None, "not kept: unknown, which counts as there"); + assert!(!a.is_offline("here 7")); + } + + #[test] + fn a_sweep_still_updates_the_answer_kept_for_a_file() { + let mut a = Availability::default(); + let there = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let t = there.clone(); + a.set_probe(Arc::new(move |_| t.load(Ordering::SeqCst))); + a.run_in_background(Arc::new(|| {})); + assert_eq!(a.exists("moved"), None); + wait_until("the answer", || a.is_offline("moved")); + // the drive comes back, and the answer is old enough for the sweep to check the file again + there.store(true, Ordering::SeqCst); + age(&a, "moved", RECHECK + Duration::from_secs(1)); + assert!(a.sweep(vec!["moved".into()])); + wait_idle(&a); + assert!(!a.is_gone("moved")); + assert_eq!(a.exists("moved"), Some(true), "the kept answer follows the sweep, not what was found before"); + } + + #[test] + fn the_files_found_there_are_kept_up_to_a_limit_and_the_files_found_gone_are_not_forgotten() { + let (a, _, _) = logged(); + let gone: Vec = (0..3).map(|i| format!("gone {i}")).collect(); + for p in &gone { + assert_eq!(a.exists(p), None); + } + wait_until("the gone files", || gone.iter().all(|p| a.is_gone(p))); + // far more files than are kept are asked about, as the grid scrolls through a large library + let n = MAX_THERE + 1_000; + for i in 0..n { + a.exists(&format!("here {i}")); + } + wait_idle(&a); + assert_eq!(remembered(&a), MAX_THERE + 3, "the last {MAX_THERE} found there and every one found gone"); + assert!(gone.iter().all(|p| a.is_offline(p)), "a file found gone stays so, however much is asked after it"); + assert_eq!(a.exists(&format!("here {}", n - 1)), Some(true), "the newest is kept"); + assert_eq!(a.exists(&format!("here {}", n - MAX_THERE)), Some(true), "the oldest of the kept"); + // (last: asking about a forgotten file makes room for its new answer) + assert_eq!(a.exists(&format!("here {}", n - MAX_THERE - 1)), None, "the first one forgotten: unknown counts as there"); + assert_eq!(a.exists("here 0"), None); + assert!(!a.is_offline("here 0")); + } + + #[test] + fn a_sweep_that_is_over_gives_back_the_room_its_list_took() { + let (a, _, _) = logged(); + assert!(a.sweep((0..1_000).map(|i| format!("sweep {i}")).collect())); + wait_idle(&a); + assert_eq!(lock(&a.state).sweep.capacity(), 0); + } + + #[test] + fn a_sweep_dropped_for_another_library_gives_back_the_room_its_list_took() { + let (a, _, _) = logged(); + let busy = busy_flag(&a); + assert!(a.sweep((0..1_000).map(|i| format!("sweep {i}")).collect())); + assert!(lock(&a.state).sweep.capacity() >= 1_000); + a.restart_sweeps(); + assert_eq!(lock(&a.state).sweep.capacity(), 0); + busy.store(false, Ordering::SeqCst); + wait_idle(&a); + } + + #[test] + fn a_sweep_gives_back_the_room_its_list_took_as_soon_as_its_last_path_is_taken() { + let mut a = Availability::default(); + let log = Arc::new(Mutex::new(Vec::::new())); + // the last path is taken from the list, and then the worker waits on it (a share that does not answer) + let hold = Arc::new(std::sync::atomic::AtomicBool::new(true)); + let (l, h) = (log.clone(), hold.clone()); + a.set_probe(Arc::new(move |p| { + held(&l).push(p.to_string()); + while p == "sweep 999" && h.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + true + })); + a.run_in_background(Arc::new(|| {})); + assert!(a.sweep((0..1_000).map(|i| format!("sweep {i}")).collect())); + wait_until("the last path is being checked", || held(&log).iter().any(|p| p == "sweep 999")); + assert_eq!(a.sweeping(), 0, "nothing of the sweep is left to check"); + assert_eq!(lock(&a.state).sweep.capacity(), 0, "the list goes with its last path, not once the worker has nothing else to do"); + hold.store(false, Ordering::SeqCst); + wait_idle(&a); + } + + #[test] + fn an_answer_found_again_keeps_its_place_in_the_list() { + let mut st = State::default(); + assert!(st.remember("same".into(), true), "the first answer is a change"); + for _ in 0..2 * MAX_THERE { + assert!(!st.remember("same".into(), true), "the same answer again is none"); + } + assert_eq!(st.there.len(), 1, "listed once, however often it is found again"); + assert_eq!(kept_there(&st, "same"), Some(true), "and still kept"); + } + + #[test] + fn a_file_found_there_again_after_being_gone_is_not_forgotten_by_its_old_entry() { + let mut st = State::default(); + st.remember("back".into(), true); + st.remember("back".into(), false); + st.remember("back".into(), true); + assert_eq!(st.there.len(), 1, "listed once, however often it comes and goes"); + for i in 0..MAX_THERE - 1 { + st.remember(format!("here {i}"), true); + } + assert_eq!(kept_there(&st, "back"), Some(true), "found there among the last {MAX_THERE}"); + // one more: the oldest entry is `back`'s from before it was gone, and it was found there again since + st.remember("one more".into(), true); + assert_eq!(kept_there(&st, "back"), Some(true), "not forgotten by the entry it had before"); + assert_eq!(kept_there(&st, "here 0"), None, "the oldest found there goes instead"); + } + + #[test] + fn a_file_found_there_again_once_its_old_entry_is_dropped_is_listed_again() { + let mut st = State::default(); + st.remember("moved".into(), true); + st.remember("moved".into(), false); + // its turn comes with the files found there after it: it is unlisted, and still kept as gone + for i in 0..MAX_THERE { + st.remember(format!("here {i}"), true); + } + assert_eq!(kept_there(&st, "moved"), Some(false)); + assert_eq!(st.there.len(), MAX_THERE); + assert!(st.remember("moved".into(), true), "found back"); + assert_eq!(kept_there(&st, "moved"), Some(true)); + assert_eq!(st.there.back().map(String::as_str), Some("moved"), "listed as the newest"); + assert_eq!(st.there.len(), MAX_THERE, "the oldest made room for it"); + assert_eq!(kept_there(&st, "here 0"), None); + } + + #[test] + fn an_answer_asked_about_is_spared_once_when_its_turn_to_be_forgotten_comes() { + let mut a = Availability::default(); + a.run_in_background(Arc::new(|| {})); + { + let mut st = lock(&a.state); + st.remember("shown".into(), true); + for i in 0..MAX_THERE - 1 { + st.remember(format!("here {i}"), true); + } + } + // (the Info panel asks about the selected photo's smart preview on every frame) + assert_eq!(a.exists("shown"), Some(true)); + let mut st = lock(&a.state); + st.remember("new 1".into(), true); + st.remember("new 2".into(), true); + assert_eq!(kept_there(&st, "shown"), Some(true), "the oldest, but asked about: spared"); + assert_eq!(kept_there(&st, "here 0"), None, "the files found there after it go first"); + assert_eq!(kept_there(&st, "here 1"), None); + assert_eq!(kept_there(&st, "here 2"), Some(true)); + // not asked about since: at its next turn it goes + for i in 0..MAX_THERE { + st.remember(format!("later {i}"), true); + } + assert_eq!(kept_there(&st, "shown"), None); + } + + #[test] + fn a_check_that_finds_a_file_there_again_does_not_spare_it() { + let mut st = State::default(); + st.remember("old".into(), true); + for i in 0..MAX_THERE - 1 { + st.remember(format!("here {i}"), true); + } + // checked again, as a sweep does: nobody asked about it + assert!(!st.remember("old".into(), true), "the same answer again is none"); + st.remember("one more".into(), true); + assert_eq!(kept_there(&st, "old"), None, "the oldest goes: a check again is no reason to keep it"); + } + + #[test] + fn a_file_listed_again_is_not_spared_for_having_been_asked_about_before_it_was_gone() { + let mut a = Availability::default(); + a.run_in_background(Arc::new(|| {})); + lock(&a.state).remember("moved".into(), true); + assert_eq!(a.exists("moved"), Some(true), "asked about"); + let mut st = lock(&a.state); + st.remember("moved".into(), false); + // enough files found there after it for its old entry to come up: it is unlisted + for i in 0..MAX_THERE { + st.remember(format!("here {i}"), true); + } + st.remember("moved".into(), true); + // and as many again for its new entry to come up + for i in 0..MAX_THERE { + st.remember(format!("later {i}"), true); + } + assert_eq!(kept_there(&st, "moved"), None, "the ask from before does not spare the new entry"); + } + + #[test] + fn a_file_found_gone_after_being_found_there_is_not_forgotten_with_the_files_found_there() { + let mut a = Availability::default(); + let there = Arc::new(std::sync::atomic::AtomicBool::new(true)); + let t = there.clone(); + a.set_probe(Arc::new(move |p| p != "moved" || t.load(Ordering::SeqCst))); + a.run_in_background(Arc::new(|| {})); + assert_eq!(a.exists("moved"), None); + wait_until("found there", || a.exists("moved") == Some(true)); + // the drive goes away, and the answer is old enough for the file to be checked again + there.store(false, Ordering::SeqCst); + age(&a, "moved", RECHECK + Duration::from_secs(1)); + assert_eq!(a.exists("moved"), Some(true), "the old answer is used while the file is checked again"); + wait_until("found gone", || a.is_offline("moved")); + // a long scroll pushes out the files found there, the first of them `moved`'s old answer + for i in 0..MAX_THERE + 5 { + a.exists(&format!("here {i}")); + } + wait_idle(&a); + assert!(a.is_offline("moved"), "found gone: not forgotten with the answers found there"); + } } diff --git a/crates/engine/src/capture_one_catalog.rs b/crates/engine/src/capture_one_catalog.rs index 98b9d13a05..296837f71b 100644 --- a/crates/engine/src/capture_one_catalog.rs +++ b/crates/engine/src/capture_one_catalog.rs @@ -418,6 +418,7 @@ pub fn read_with_progress(path: &Path, cancel: &AtomicBool, total: &AtomicUsize, history: Vec::new(), snapshots: Vec::new(), original: original.clone(), + as_shot_white: None, }); if master == 0 { master = variant_pk; diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index f7eda754cd..717d9ab0a7 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -278,12 +278,17 @@ fn fill_missing_meta(id: lcc_catalog::PhotoId, ph: &lcc_catalog::Photo, info: &c if m.lens.is_empty() { m.lens = src.lens.clone(); } + if m.lens_make.is_empty() { + m.lens_make = src.lens_make.clone(); + } if m.shutter.is_empty() { m.shutter = src.shutter.clone(); } m.focal_mm = m.focal_mm.or(src.focal_mm); m.aperture = m.aperture.or(src.aperture); m.iso = m.iso.or(src.iso); + m.flash = m.flash.or(src.flash); + m.exposure_bias = m.exposure_bias.or(src.exposure_bias); m.gps = m.gps.or(src.gps); // the camera's focus point: photos imported before it was read get it here if m.focus.is_none() { diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 3a44e804bb..fa243fb396 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -13,6 +13,18 @@ fn active(s: &Session, c: &str) -> Result { } /// Modify the active photo's settings with `f` and commit (or preview during an interaction). +/// Auto's tone and colour numbers onto a photo's settings. +fn set_auto_tone(d: &mut DevelopSettings, a: &lcc_pipeline::auto::AutoTone) { + d.light.exposure = a.exposure; + d.light.contrast = a.contrast; + d.light.highlights = a.highlights; + d.light.shadows = a.shadows; + d.light.whites = a.whites; + d.light.blacks = a.blacks; + d.color.vibrance = a.vibrance; + d.color.saturation = a.saturation; +} + fn edit(s: &mut Session, c: &str, label: &str, f: impl FnOnce(&mut DevelopSettings) -> Result<()>) -> Result { let id = active(s, c)?; let mut d = (*s.develop_of(id).unwrap_or_default()).clone(); @@ -727,20 +739,47 @@ pub fn specs() -> Vec { // Source plug-in filters (e.g. a negative conversion) change what the photo is let src = lcc_pipeline::plugin_filters::filtered_source(&src, &info, &d, 1024); let a = lcc_pipeline::auto::auto_tone(&src, &info, &d); - edit(s, "develop.auto", "Auto", |d| { - d.light.exposure = a.exposure; - d.light.contrast = a.contrast; - d.light.highlights = a.highlights; - d.light.shadows = a.shadows; - d.light.whites = a.whites; - d.light.blacks = a.blacks; - d.color.vibrance = a.vibrance; - d.color.saturation = a.saturation; - Ok(()) - })?; - if let Some(d) = s.develop_of(id) { - let values = Session::auto_values(&d); - s.auto_applied.insert(id, values); + // With Auto Sync on, every other selected photo gets its own Auto (worked out on its own pixels), not + // the active photo's numbers (upstream #3808, in our own form); one undo step. A photo that can't + // be read keeps its settings. + if s.auto_sync_applies(id, "Auto") { + let others: Vec = s.selection.ids.iter().copied().filter(|x| *x != id).collect(); + let mut picks = vec![(id, a)]; + for x in others { + let Ok(xsrc) = s.source_now(x, SourceLevel::Thumb) else { continue }; + let (xinfo, xd) = (s.source_info(x), s.develop_of(x).unwrap_or_default()); + let xsrc = lcc_pipeline::plugin_filters::filtered_source(&xsrc, &xinfo, &xd, 1024); + picks.push((x, lcc_pipeline::auto::auto_tone(&xsrc, &xinfo, &xd))); + } + let mut ops: Vec = Vec::new(); + let mut done: Vec = Vec::new(); + for (x, ax) in picks { + let mut nd = (*s.develop_of(x).unwrap_or_default()).clone(); + set_auto_tone(&mut nd, &ax); + if let Some(op) = s.develop_op(x, nd, "Auto") { + ops.push(op); + done.push(x); + } + } + s.end_interaction()?; + if !ops.is_empty() { + s.commit("Auto", Op::Batch { ops })?; + } + for x in done { + if let Some(d) = s.develop_of(x) { + let values = Session::auto_values(&d); + s.auto_applied.insert(x, values); + } + } + } else { + edit(s, "develop.auto", "Auto", |d| { + set_auto_tone(d, &a); + Ok(()) + })?; + if let Some(d) = s.develop_of(id) { + let values = Session::auto_values(&d); + s.auto_applied.insert(id, values); + } } let mut r = serde_json::to_value(a).unwrap_or_default(); if let Some(o) = r.as_object_mut() { @@ -1809,22 +1848,91 @@ pub fn specs() -> Vec { } Ok(json!({"group": new_group})) }), - cmd!("preset.deleteGroup", "Delete Preset Folder", [], None, "{group}", always, |s, p| { - let c = "preset.deleteGroup"; - let group = str_param(p, "group").map(str::trim).filter(|g| !g.is_empty()).ok_or_else(|| bad(c, "missing group"))?; - if s.presets.iter().any(|q| q.builtin && in_group(q, group)) { - return Err(bad(c, "the group holds built-in presets, which can't be deleted: hide the group instead")); - } - let prefix = format!("{group}/"); - s.preset_folders.retain(|f| f != group && !f.starts_with(&prefix)); - let gone: Vec = s.presets.iter().filter(|q| in_group(q, group)).map(|q| q.id.clone()).collect(); - let removed = gone.len(); - s.presets.retain(|q| !gone.contains(&q.id)); - s.preset_at_import.retain(|x| !gone.contains(x)); - s.preset_hidden.retain(|x| !gone.contains(x)); - s.presets.bump(); - Ok(json!({"deleted": removed})) - }), + cmd!( + "preset.copy", + "Copy Presets to Folder", + [], + None, + "{ids: [presetId], group} → {ids: [new presetId], skipped} — user presets with the same settings under a new id, built-in presets included, unstarred; a preset identical to one already in the folder is skipped", + always, + |s, p| { + let c = "preset.copy"; + let group = str_param(p, "group").map(str::trim).filter(|g| !g.is_empty()).ok_or_else(|| bad(c, "missing group"))?; + let group = existing_preset_group(s, group); + let ids = super::metadata_files::strings(p, "ids").filter(|v| !v.is_empty()).ok_or_else(|| bad(c, "missing ids"))?; + let copies: Vec = s + .presets + .iter() + .filter(|x| ids.contains(&x.id)) + .map(|x| Preset { + id: String::new(), + name: x.name.clone(), + group: group.clone(), + settings: x.settings.clone(), + favorite: false, + builtin: false, + }) + .collect(); + if copies.is_empty() { + return Err(bad(c, "none of these presets exist")); + } + let asked = copies.len(); + let added = s.add_presets(copies); + let skipped = asked.saturating_sub(added.len()); + s.presets.bump(); + Ok(json!({"ids": added, "skipped": skipped})) + } + ), + cmd!( + "preset.deleteMany", + "Delete Presets", + [], + None, + "{ids: [presetId]} → {deleted, skipped} — user presets; built-in and unknown ids are skipped", + always, + |s, p| { + let c = "preset.deleteMany"; + let ids = super::metadata_files::strings(p, "ids").filter(|v| !v.is_empty()).ok_or_else(|| bad(c, "missing ids"))?; + let gone: std::collections::HashSet<&String> = + s.presets.iter().filter(|q| !q.builtin && ids.contains(&q.id)).map(|q| &q.id).collect(); + let gone: Vec = gone.into_iter().cloned().collect(); + s.presets.retain(|q| !gone.contains(&q.id)); + s.preset_at_import.retain(|x| !gone.contains(x)); + s.preset_hidden.retain(|x| !gone.contains(x)); + s.presets.bump(); + Ok(json!({"deleted": gone.len(), "skipped": ids.len().saturating_sub(gone.len())})) + } + ), + cmd!( + "preset.deleteGroup", + "Delete Preset Folder", + [], + None, + "{group, expect?: how many presets it should hold} — refused when `expect` is given and wrong", + always, + |s, p| { + let c = "preset.deleteGroup"; + let group = str_param(p, "group").map(str::trim).filter(|g| !g.is_empty()).ok_or_else(|| bad(c, "missing group"))?; + if s.presets.iter().any(|q| q.builtin && in_group(q, group)) { + return Err(bad(c, "the group holds built-in presets, which can't be deleted: hide the group instead")); + } + if let Some(expect) = p.get("expect").and_then(Value::as_u64) { + let held = s.presets.iter().filter(|q| in_group(q, group)).count() as u64; + if held != expect { + return Err(bad(c, format!("the folder holds {held} presets, not {expect}: nothing deleted"))); + } + } + let prefix = format!("{group}/"); + s.preset_folders.retain(|f| f != group && !f.starts_with(&prefix)); + let gone: Vec = s.presets.iter().filter(|q| in_group(q, group)).map(|q| q.id.clone()).collect(); + let removed = gone.len(); + s.presets.retain(|q| !gone.contains(&q.id)); + s.preset_at_import.retain(|x| !gone.contains(x)); + s.preset_hidden.retain(|x| !gone.contains(x)); + s.presets.bump(); + Ok(json!({"deleted": removed})) + } + ), cmd!( "preset.update", "Update Preset with Current Settings", diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 2c40e62489..bb32779f13 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -431,6 +431,52 @@ fn step_in(s: &mut Session, d: isize, within: bool) -> Result { Ok(json!({"active": vis[next].0})) } +/// `library.nextUnrated` / `library.prevUnrated` (ported from upstream #3904 in our own form): jump to the next +/// (`d > 0`) or previous photo of the view with no rating, wrapping round. With several photos selected the target is +/// added to the selection, which is kept. `{"allRated": true}` when nothing in the view is unrated. +fn step_unrated(s: &mut Session, d: isize) -> Result { + let vis = s.visible_cloned(); + if vis.is_empty() { + return ok(); + } + let unrated: Vec = vis.iter().map(|id| s.catalog.photo(*id).is_some_and(|p| p.rating == 0)).collect(); + if !unrated.iter().any(|u| *u) { + return Ok(json!({"allRated": true})); + } + let n = vis.len(); + let cur = s.selection.active.and_then(|a| vis.iter().position(|x| *x == a)); + // Walk away from the current photo (from the near end when there is none), wrapping once round; the current + // photo is the last candidate, so the only unrated photo stays where it is. + let target = (1..=n).find_map(|k| { + let i = match (cur, d >= 0) { + (Some(c), true) => c.checked_add(k)? % n, + (Some(c), false) => c.checked_add(n.checked_sub(k % n)?)? % n, + (None, true) => k.checked_sub(1)?, + (None, false) => n.checked_sub(k)?, + }; + unrated.get(i).copied().unwrap_or(false).then_some(i) + }); + let Some(id) = target.and_then(|i| vis.get(i)).copied() else { + return Ok(json!({"allRated": true})); + }; + if s.selection.active == Some(id) { + return Ok(json!({"active": id.0})); + } + s.end_interaction()?; + let (was, was_mask) = (s.selection.active, s.active_mask); + if s.selection.ids.len() > 1 { + if !s.selection.contains(id) { + s.selection.ids.push(id); + } + s.selection.active = Some(id); + } else { + s.selection = Selection::single(id); + } + s.active_mask = s.carried_mask(was, was_mask, s.selection.active); + s.active_spot = None; + Ok(json!({"active": id.0})) +} + /// `library.up` / `library.down`: how many photos to move (at least 1, capped so hostile input /// can't overflow). fn row_step(p: &Value) -> isize { @@ -1072,6 +1118,24 @@ pub fn specs() -> Vec { always, |s, _| step_in(s, -1, true) ), + cmd!( + "library.nextUnrated", + "Next Unrated Photo", + [], + Some("Cmd+Alt+Right"), + "{} — the next photo of the view with no rating, wrapping round; {allRated: true} when there is none", + always, + |s, _| step_unrated(s, 1) + ), + cmd!( + "library.prevUnrated", + "Previous Unrated Photo", + [], + Some("Cmd+Alt+Left"), + "{} — the previous photo of the view with no rating, wrapping round; {allRated: true} when there is none", + always, + |s, _| step_unrated(s, -1) + ), cmd!( "library.down", "Photo Below", @@ -2767,6 +2831,10 @@ mod rated_out_tests; #[path = "library/tests_step_selection.rs"] mod step_selection_tests; +#[cfg(test)] +#[path = "library/tests_next_unrated.rs"] +mod next_unrated_tests; + #[cfg(test)] #[path = "library/tests_clear_label.rs"] mod clear_label_tests; diff --git a/crates/engine/src/cmd/library/tests_next_unrated.rs b/crates/engine/src/cmd/library/tests_next_unrated.rs new file mode 100644 index 0000000000..ae7791af56 --- /dev/null +++ b/crates/engine/src/cmd/library/tests_next_unrated.rs @@ -0,0 +1,75 @@ +//! Next / Previous Unrated Photo (ported from upstream #3904): jump over rated photos, wrap, keep a multi-selection. +use lcc_catalog::{Op, Photo, PhotoId, Source}; +use serde_json::json; + +use crate::{Result, Session}; + +fn session() -> Result { + let mut s = Session::new(); + for (id, rating) in [(1, 5), (2, 1), (3, 0), (4, 0)] { + let mut photo = + Photo::new(PhotoId(id), Source::File { path: format!("/next-unrated/{id}.jpg") }, &format!("{id}.jpg"), "JPEG", 40, 30, "2026-10-09"); + photo.rating = rating; + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) })?; + } + s.execute("library.sort", &json!({"key": "fileName", "ascending": true}))?; + s.execute("library.select", &json!({"ids": [1]}))?; + Ok(s) +} + +#[test] +fn next_skips_rated_photos_and_wraps() { + let mut s = session().unwrap(); + s.execute("library.nextUnrated", &json!({})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(3))); + s.execute("library.nextUnrated", &json!({})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(4))); + s.execute("library.nextUnrated", &json!({})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(3)), "wraps past the rated photos at the start"); +} + +#[test] +fn previous_skips_rated_photos_and_wraps() { + let mut s = session().unwrap(); + assert_eq!(s.execute("library.prevUnrated", &json!({})).unwrap(), json!({"active": 4})); + s.execute("library.prevUnrated", &json!({})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(3))); +} + +#[test] +fn everything_rated_says_so_and_stays() { + let mut s = session().unwrap(); + s.execute("photo.rate", &json!({"ids": [3, 4], "rating": 5})).unwrap(); + for c in ["library.nextUnrated", "library.prevUnrated"] { + assert_eq!(s.execute(c, &json!({})).unwrap(), json!({"allRated": true})); + assert_eq!(s.active(), Some(PhotoId(1))); + } +} + +#[test] +fn a_multi_selection_is_kept_and_the_target_added() { + let mut s = session().unwrap(); + s.execute("library.select", &json!({"ids": [1, 2, 4], "active": 1})).unwrap(); + s.execute("library.nextUnrated", &json!({})).unwrap(); + assert_eq!(s.active(), Some(PhotoId(3))); + assert_eq!(s.selection.ids, vec![PhotoId(1), PhotoId(2), PhotoId(4), PhotoId(3)]); +} + +#[test] +fn the_only_unrated_photo_keeps_selection_and_mask() { + let mut s = session().unwrap(); + s.execute("photo.rate", &json!({"ids": [4], "rating": 5})).unwrap(); + s.execute("library.select", &json!({"ids": [1, 2, 3], "active": 3})).unwrap(); + s.active_mask = Some(7); + let r = s.execute("library.nextUnrated", &json!({})).unwrap(); + assert_eq!(r, json!({"active": 3})); + assert_eq!(s.selection.ids, vec![PhotoId(1), PhotoId(2), PhotoId(3)]); + assert_eq!(s.active_mask, Some(7)); +} + +#[test] +fn an_empty_view_is_not_an_error() { + let mut s = Session::new(); + assert!(s.execute("library.nextUnrated", &json!({})).is_ok()); + assert!(s.execute("library.prevUnrated", &json!({})).is_ok()); +} diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index f3ccf07eb1..443ec3c5ec 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -2086,6 +2086,7 @@ pub fn export_metadata(photo: &lcc_catalog::Photo, catalog: &lcc_catalog::Catalo }; out.make = make; out.model = model; + out.lens_make = text(&m.lens_make); out.lens_model = text(&m.lens); out.focal_length = m.focal_mm.map(f64::from); out.f_number = m.aperture.map(f64::from); @@ -4052,6 +4053,22 @@ mod tests { assert_eq!((m.make.as_deref(), m.model.as_deref()), (None, Some("Canon Canon IXUS 185"))); } + /// The lens maker (Exif LensMake, upstream #3828) is exported with metadata "All" and reads back from the JPEG. + #[test] + fn export_writes_lens_make() { + use lcc_catalog::{Catalog, Photo, PhotoId, Source}; + let mut p = Photo::new(PhotoId(1), Source::Demo { scene: 0 }, "a.jpg", "jpeg", 10, 10, "2026-10-06T00:00:00"); + p.meta.lens = "RF 24-105mm f/4L IS USM".into(); + p.meta.lens_make = "Canon".into(); + let m = export_metadata(&p, &Catalog::new(), &ExportOptions::default()).unwrap(); + assert_eq!(m.lens_make.as_deref(), Some("Canon")); + let jpg = encode_with_metadata(&test_image(), &ExportOptions::default(), Some(&m)).unwrap(); + assert_eq!(lcc_meta::extract(&jpg).lens_make.as_deref(), Some("Canon")); + p.meta.lens_make.clear(); + let m = export_metadata(&p, &Catalog::new(), &ExportOptions::default()).unwrap(); + assert_eq!(m.lens_make, None); + } + #[test] fn watermark_draws_in_the_anchored_corner_only() { let mut img = Rgba8::new(400, 300); diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index bff2892c4d..3d3f88b128 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -24,12 +24,15 @@ fn meta_of(m: &lcc_meta::Metadata) -> (Meta, Option) { camera_make, camera_model, camera_serial: m.serial_number.as_deref().map(str::trim).unwrap_or_default().chars().take(64).collect(), + lens_make: m.lens_make.clone().unwrap_or_default(), // (a camera that writes no lens name, like Nikon's DSLRs, still says what range the lens covers) lens: m.lens_model.clone().or_else(|| m.lens_spec.and_then(lcc_meta::lens_spec_name)).unwrap_or_default(), focal_mm: m.focal_length.map(|f| f as f32), aperture: m.f_number.map(|f| f as f32), shutter, iso: m.iso, + flash: m.flash.as_ref().map(|f| f.fired), + exposure_bias: m.exposure_bias.map(|v| v as f32).filter(|v| v.is_finite()), lens_range: m.lens_spec.map(|s| (s[0] as f32, s[1] as f32)).filter(|(a, b)| a.is_finite() && b.is_finite() && *a > 0.0 && *b >= *a), location: m.sublocation.clone().unwrap_or_default(), city: m.city.clone().unwrap_or_default(), diff --git a/crates/engine/src/lightroom_archive.rs b/crates/engine/src/lightroom_archive.rs index 283fef4a90..dbf58ea672 100644 --- a/crates/engine/src/lightroom_archive.rs +++ b/crates/engine/src/lightroom_archive.rs @@ -602,6 +602,7 @@ mod tests { history: vec![BTreeMap::from([("text".into(), serde_json::json!("step")), ("curve".into(), serde_json::json!([0, 128, 255]))])], snapshots: vec![BTreeMap::from([("name".into(), serde_json::json!("before"))])], original: crate::lightroom_catalog::Original::Local, + as_shot_white: None, }; CatalogImport { source: "source.lrcat".into(), @@ -692,6 +693,7 @@ mod tests { ])], snapshots: vec![BTreeMap::from([("name".into(), serde_json::json!("Before")), ("text".into(), serde_json::json!("s = {}"))])], original: crate::lightroom_catalog::Original::Local, + as_shot_white: None, } }) .collect(); diff --git a/crates/engine/src/lightroom_catalog.rs b/crates/engine/src/lightroom_catalog.rs index 989815c61f..07284646dc 100644 --- a/crates/engine/src/lightroom_catalog.rs +++ b/crates/engine/src/lightroom_catalog.rs @@ -223,6 +223,25 @@ impl Reader { Ok(out) } + /// Fill `out` with the as-shot white of each image in `wanted`, from the last of its history steps that has one. + /// Streamed, a row at a time and none kept: only a wanted image's step is decoded, and each is bounded on its own. + fn as_shot_whites(&self, wanted: &HashSet, cancel: &AtomicBool, out: &mut HashMap) -> Result<(), String> { + self.each_row("Adobe_libraryImageDevelopHistoryStep", false, false, cancel, |r, blobs| { + let image = number(&r, "image"); + if !wanted.contains(&image) { + return Ok(()); + } + let white = match blobs.into_iter().find(|(column, _)| *column == "text") { + Some((_, bytes)) => decode_compressed(&bytes, "settings").ok().as_deref().and_then(step_as_shot_white), + None => step_as_shot_white(text(&r, "text")), + }; + if let Some(white) = white { + out.insert(image, white); + } + Ok(()) + }) + } + /// `Adobe_imageDevelopSettings`, streamed into image id -> settings text. The photos' edits come from here, so a /// failure to read it fails the import rather than quietly bringing every photo in unedited. fn develop_settings(&self, cancel: &AtomicBool) -> Result, String> { @@ -308,6 +327,10 @@ pub struct CatalogPhoto { /// Whether `path` may be looked at (derived when the catalog is read; not archived). #[serde(skip)] pub original: Original, + /// Lightroom's as-shot `(Temperature, Tint)` for a Custom white balance, from its history: what the Kelvin in + /// `settings` is measured from (upstream #3906; [`custom_as_shot`]). Not archived. + #[serde(skip)] + pub as_shot_white: Option<(f64, f64)>, } /// Whether the original a catalog lists may be looked at. Its path is resolved with the catalog @@ -837,6 +860,8 @@ fn read_lightroom(path: &Path, reader: Reader, source_guard: SourceGuard, cancel ensure_read_active(cancel)?; let mut snapshots = reader.grouped("Adobe_libraryImageDevelopSnapshot", &mut warnings, cancel)?; done.fetch_add(1, Ordering::Relaxed); + let as_shot_whites = custom_as_shot(&reader, &develops, cancel, &mut warnings); + ensure_read_active(cancel)?; let mut out = CatalogImport { source: path.to_string_lossy().into(), photos: Vec::new(), @@ -917,6 +942,7 @@ fn read_lightroom(path: &Path, reader: Reader, source_guard: SourceGuard, cancel history: history.remove(&id).unwrap_or_default(), snapshots: snapshots.remove(&id).unwrap_or_default(), original, + as_shot_white: as_shot_whites.get(&id).copied(), }); } if left_out > LEFT_OUT_NAMED { @@ -1074,11 +1100,27 @@ fn mapped_settings( aspect: f64, orientation: Orientation, stored_aspect: f64, +) -> Result<(Value, Vec), String> { + mapped_settings_from(text, None, target, aspect, orientation, stored_aspect) +} + +/// [`mapped_settings`] with `as_shot`, the white a Custom Kelvin is measured from, when the catalog's history gave one. +fn mapped_settings_from( + text: &str, + as_shot: Option<(f64, f64)>, + target: crate::crs::Target, + aspect: f64, + orientation: Orientation, + stored_aspect: f64, ) -> Result<(Value, Vec), String> { let mut root = crate::preset_import::parse_lua(text)?; let deferred = strip_lua_sentinels(&mut root); // A catalog's develop settings carry no `HasCrop`: `crs::to_partial` takes any crop field as a crop. - let (props, values) = crate::preset_import::lua_settings_props(&root)?; + let (mut props, values) = crate::preset_import::lua_settings_props(&root)?; + if let Some((temperature, tint)) = as_shot { + props.entry("crs:AsShotTemperature".into()).or_insert_with(|| vec![temperature.to_string()]); + props.entry("crs:AsShotTint".into()).or_insert_with(|| vec![tint.to_string()]); + } let (mut partial, mut unknown) = crate::crs::to_partial_report(&props, Some(&values), target, aspect); catalog_crop(&mut partial, orientation, stored_aspect); if deferred > 0 { @@ -1087,6 +1129,40 @@ fn mapped_settings( Ok((partial, unknown)) } +/// The `(Temperature, Tint)` of a history step whose white balance is As Shot. Lightroom writes them there as it read +/// them from the file, and keeps them nowhere else once the photo has a Custom white balance. `None` for any other +/// step, and for a photo's first steps, which say As Shot without the values. +fn step_as_shot_white(text: &str) -> Option<(f64, f64)> { + let props = settings_with_white_balance(text, "As Shot")?; + let number = |k: &str| props.get(k)?.first()?.parse::().ok().filter(|v| v.is_finite()); + Some((number("crs:Temperature").filter(|t| *t > 0.0)?, number("crs:Tint")?)) +} + +/// The parsed develop settings in `text` when their white balance is `mode`; `None` for another mode or text that +/// does not parse. The substring test only skips parsing text that cannot match. +fn settings_with_white_balance(text: &str, mode: &str) -> Option { + if !text.contains(mode) { + return None; + } + let root = crate::preset_import::parse_lua(text).ok()?; + let (props, _) = crate::preset_import::lua_settings_props(&root).ok()?; + (props.get("crs:WhiteBalance")?.first()?.as_str() == mode).then_some(props) +} + +/// The as-shot white of each photo with a Custom white balance (issue #510: without it a raw developed relative to +/// its as-shot look can't take the Kelvin). Optional: what was read before a failure is kept, with a warning. +fn custom_as_shot(reader: &Reader, develops: &HashMap, cancel: &AtomicBool, warnings: &mut Vec) -> HashMap { + let wanted: HashSet = develops.iter().filter(|(_, t)| settings_with_white_balance(t, "Custom").is_some()).map(|(id, _)| *id).collect(); + let mut found = HashMap::new(); + if !wanted.is_empty() + && let Err(error) = reader.as_shot_whites(&wanted, cancel, &mut found) + && !cancel.load(Ordering::Relaxed) + { + warnings.push(format!("as-shot white balance from Lightroom history: {error}")); + } + found +} + /// Lightroom's `Adobe_images.orientation`: where the stored image's top-left and top-right corners /// land in the displayed photo, naming the displayed corners A, B, C, D clockwise from the top left /// (`AB` upright, `BC` a quarter turn clockwise, `DA` a quarter turn counter-clockwise, `BA` mirrored). @@ -1437,7 +1513,7 @@ pub(crate) fn apply_prepared(s: &mut crate::Session, mut data: CatalogImport, co let target = crate::crs::Target::for_photo(&p); let aspect = p.width.max(1) as f64 / p.height.max(1) as f64; let base = p.develop.clone(); - match mapped_settings(&src.settings, target, aspect, orientation, stored_aspect) { + match mapped_settings_from(&src.settings, src.as_shot_white, target, aspect, orientation, stored_aspect) { Ok((partial, unknown)) => { let mut develop = lcc_develop::apply_partial(&base, &partial, 1.0); crate::crs::keep_chosen_dcp(&base, &mut develop); @@ -1911,6 +1987,7 @@ pub(crate) mod tests { history: vec![row(json!({"text":"s = { Exposure2012 = 0.5 }"}))], snapshots: Vec::new(), original: Original::Local, + as_shot_white: None, }; let mut copy = photo.clone(); copy.source_id = 2; @@ -2649,6 +2726,56 @@ pub(crate) mod tests { assert!(!unknown.iter().any(|k| k.starts_with("Temperature")), "{unknown:?}"); } + /// Upstream #3906: a Custom white balance is shifted from the as-shot white the photo's history still holds, as + /// its text or compressed step; steps without the values, damaged steps and other photos' steps give none. + #[test] + fn a_custom_white_balance_is_shifted_from_the_as_shot_white_in_its_history() { + use crate::lightroom_fixture::{self as fixture, Table}; + let custom = "s = { WhiteBalance = \"Custom\", Temperature = 3578, Tint = -5, Exposure2012 = 0.5 }"; + let as_shot = "s = { WhiteBalance = \"As Shot\", Temperature = 3650, Tint = -2 }"; + let bare = "s = { WhiteBalance = \"As Shot\" }"; + let damaged = "s = { WhiteBalance = \"As Shot\", Temperature = 0, Tint = 1"; + type Case = (&'static str, Vec>, Option<(f64, f64)>); + let cases: Vec = vec![ + ( + "text", + vec![fixture::history_step(1, 1, 1.0, "Import", fixture::text(bare)), fixture::history_step(2, 1, 2.0, "WB", fixture::text(as_shot))], + Some((3650.0, -2.0)), + ), + ("blob", vec![fixture::history_step(1, 1, 1.0, "WB", fixture::Field::Blob(fixture::compressed(as_shot)))], Some((3650.0, -2.0))), + ("bare", vec![fixture::history_step(1, 1, 1.0, "Import", fixture::text(bare))], None), + ( + "damaged", + vec![ + fixture::history_step(1, 1, 1.0, "WB", fixture::Field::Blob(vec![0xff; 9])), + fixture::history_step(2, 1, 2.0, "WB", fixture::text(damaged)), + fixture::history_step(3, 2, 3.0, "Other photo", fixture::text(as_shot)), + ], + None, + ), + ]; + for (tag, steps, expected) in cases { + let dir = fixture::dir(&format!("as-shot-white-{tag}")); + let mut tables = fixture::one_photo(&dir.join("originals"), custom); + tables.push(Table { name: "Adobe_libraryImageDevelopHistoryStep", columns: fixture::HISTORY_COLUMNS, rows: steps }); + let catalog = dir.join("test.lrcat"); + fixture::write(&catalog, &tables); + let imported = read(&catalog).unwrap(); + assert_eq!(imported.photos[0].as_shot_white, expected, "{tag}: {:?}", imported.warnings); + let (partial, unknown) = + mapped_settings_from(custom, imported.photos[0].as_shot_white, crate::crs::Target::RawRelative, 1.5, Orientation::Normal, 1.5) + .unwrap(); + if expected.is_some() { + assert_eq!(partial["wb"]["mode"], "custom", "{partial}"); + assert!(partial["wb"]["temp"].as_f64().is_some_and(|t| t.is_finite()), "{partial}"); + assert!(!unknown.iter().any(|k| k.starts_with("Temperature")), "{unknown:?}"); + } else { + assert_eq!(partial["wb"], json!({"mode": "asShot"}), "{partial}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + } + #[test] fn catalog_crops_without_has_crop_are_imported() { // Lightroom Classic catalogs store crop edges and angle but never `HasCrop` @@ -4609,6 +4736,7 @@ pub(crate) mod tests { ], snapshots: Vec::new(), original: Original::Local, + as_shot_white: None, }; let data = CatalogImport { source: "test.lrcat".into(), @@ -4667,6 +4795,7 @@ pub(crate) mod tests { history: Vec::new(), snapshots: Vec::new(), original: Original::Local, + as_shot_white: None, }], collections: Vec::new(), members: Vec::new(), @@ -4787,6 +4916,7 @@ pub(crate) mod tests { history: Vec::new(), snapshots: Vec::new(), original: Original::Local, + as_shot_white: None, } } /// `sample()` (a virtual copy, then its master) with a Copy Name on the master, Lightroom's edit times, a photo diff --git a/crates/engine/src/lightroom_job.rs b/crates/engine/src/lightroom_job.rs index 3f352d8869..31851b0c14 100644 --- a/crates/engine/src/lightroom_job.rs +++ b/crates/engine/src/lightroom_job.rs @@ -456,6 +456,7 @@ mod tests { history: Vec::new(), snapshots: Vec::new(), original: lightroom_catalog::Original::Local, + as_shot_white: None, }], collections: Vec::new(), members: Vec::new(), @@ -605,6 +606,7 @@ mod tests { )])], snapshots: Vec::new(), original: lightroom_catalog::Original::Local, + as_shot_white: None, } }) .collect(); @@ -657,6 +659,7 @@ mod tests { history: Vec::new(), snapshots: Vec::new(), original: lightroom_catalog::Original::NotHere, + as_shot_white: None, }) .collect(); let mut session = crate::Session::new(); diff --git a/crates/engine/src/tests_autosync.rs b/crates/engine/src/tests_autosync.rs index 12fcb41629..67630a3c09 100644 --- a/crates/engine/src/tests_autosync.rs +++ b/crates/engine/src/tests_autosync.rs @@ -128,3 +128,27 @@ fn pasted_object_masks_leave_their_clicks_behind() { let MaskShape::Object { hint, exclude, seg, .. } = &got[0].components[0].shape else { panic!("an Object: {got:?}") }; assert!(hint.is_empty() && exclude.is_empty() && seg.is_none(), "no clicks or pixels from a"); } + +/// Auto with Auto Sync on gives every selected photo its own Auto (upstream #3808), not the active photo's numbers, +/// as one undo step. +#[test] +fn auto_with_auto_sync_runs_each_photos_own_auto() { + let ids: Vec = demo().visible_cloned().iter().take(3).map(|p| p.0).collect(); + // what Auto gives each photo alone + let mut alone = Vec::new(); + for id in &ids { + let mut s = demo(); + s.execute("library.select", &json!({"ids": [id]})).unwrap(); + s.execute("develop.auto", &json!({})).unwrap(); + alone.push(Session::auto_values(&s.develop_of(lcc_catalog::PhotoId(*id)).unwrap())); + } + let mut s = demo(); + s.execute("library.select", &json!({"ids": ids, "active": ids[0]})).unwrap(); + s.execute("develop.autoSync", &json!({"on": true})).unwrap(); + let before = s.commits(); + s.execute("develop.auto", &json!({})).unwrap(); + for (id, want) in ids.iter().zip(&alone) { + assert_eq!(&Session::auto_values(&s.develop_of(lcc_catalog::PhotoId(*id)).unwrap()), want, "photo {id} got its own Auto"); + } + assert_eq!(s.commits(), before + 1, "one undo step"); +} diff --git a/crates/engine/src/tests_preset_marks.rs b/crates/engine/src/tests_preset_marks.rs index 67a842bd13..1d5ea4d868 100644 --- a/crates/engine/src/tests_preset_marks.rs +++ b/crates/engine/src/tests_preset_marks.rs @@ -71,3 +71,27 @@ fn manager_commands_refuse_bad_parameters() { assert!(s.execute(c, &p).is_err(), "{c} {p}"); } } + +/// LR-PRE-MANAGE: presets are copied (built-ins too) and deleted several at once; a folder delete can be guarded by +/// the count the user was shown. +#[test] +fn copy_delete_many_and_guarded_folder_delete() { + let mut s = Session::with_demo(); + let b = s.presets.iter().find(|p| p.builtin).unwrap().clone(); + let r = s.execute("preset.copy", &json!({"ids": [b.id, "no.such"], "group": "Mine"})).unwrap(); + let new_ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect(); + assert_eq!(new_ids.len(), 1); + let copy = s.presets.iter().find(|p| p.id == new_ids[0]).unwrap().clone(); + assert!(!copy.builtin && !copy.favorite && copy.group == "Mine" && copy.settings == b.settings); + // again: the same preset is already in the folder + let r = s.execute("preset.copy", &json!({"ids": [b.id], "group": "mine"})).unwrap(); + assert_eq!((r["ids"].as_array().unwrap().len(), r["skipped"].clone()), (0, json!(1))); + assert!(s.execute("preset.copy", &json!({"ids": ["no.such"], "group": "Mine"})).is_err()); + assert!(s.execute("preset.copy", &json!({"ids": [b.id]})).is_err()); + assert!(s.execute("preset.deleteGroup", &json!({"group": "Mine", "expect": 5})).is_err()); + assert!(s.presets.iter().any(|p| p.id == copy.id), "a wrong count deletes nothing"); + let r = s.execute("preset.deleteMany", &json!({"ids": [copy.id, b.id, "no.such"]})).unwrap(); + assert_eq!((r["deleted"].clone(), r["skipped"].clone()), (json!(1), json!(2))); + assert!(s.presets.iter().any(|p| p.id == b.id), "built-ins stay"); + assert!(s.execute("preset.deleteMany", &json!({})).is_err()); +} diff --git a/crates/lensdb/src/lib.rs b/crates/lensdb/src/lib.rs index 2e584568b4..9e3e5a05ab 100644 --- a/crates/lensdb/src/lib.rs +++ b/crates/lensdb/src/lib.rs @@ -232,7 +232,7 @@ impl LensDb { { score *= 0.8; } - if score >= 0.6 && best.is_none_or(|(s, _)| score > s) { + if score >= 0.6 && best.is_none_or(|(s, b)| score > s || (score == s && b.crop_factor.is_none() && lens.crop_factor.is_some())) { best = Some((score, lens)); } } @@ -271,7 +271,7 @@ impl LensDb { continue; } let score = focals.iter().filter(|f| (lo..=hi).contains(*f)).count() as f64 / focals.len() as f64; - if score > 0.0 && best.is_none_or(|(s, _)| score > s) { + if score > 0.0 && best.is_none_or(|(s, b)| score > s || (score == s && b.crop_factor.is_none() && p.crop_factor.is_some())) { best = Some((score, p)); } } diff --git a/crates/lensdb/src/tests.rs b/crates/lensdb/src/tests.rs index 902ca5ce26..360eaab6c3 100644 --- a/crates/lensdb/src/tests.rs +++ b/crates/lensdb/src/tests.rs @@ -552,3 +552,28 @@ fn load_dir_refuses_a_non_regular_xml_entry() { assert!(db.is_empty()); assert_eq!(errs.len(), 1, "{errs:?}"); } + +/// Of two equally good lens matches, the one whose calibration crop is known wins: the other +/// cannot be converted to the shot's frame at all, so file order must not decide. +#[test] +fn tied_lens_matches_prefer_a_known_calibration_crop() { + let name = spec_name([50.0, 50.0, 1.8, 1.8]); + let known = r#"cropfactor="1""#; + let unknown = r#"cropfactor="bad""#; + for (first, second) in [(unknown, known), (known, unknown)] { + let calibration = |attributes: &str| format!(r#""#); + let xml = format!( + "Test{name}{}{}", + calibration(first), + calibration(second) + ); + let db = LensDb::parse(&xml).unwrap(); + assert_eq!(db.lenses.len(), 2); + assert_eq!(db.lenses.iter().filter(|p| p.crop_factor.is_none()).count(), 1); + for profile in [db.find_lens(None, &name, None), db.find_lens_named(None, &name, None)] { + let profile = profile.unwrap(); + assert_eq!(profile.crop_factor, Some(1.0), "{first}, {second}"); + assert!(profile.correction(&shot(50.0)).is_some()); + } + } +} diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 3d3c472860..b5c4b8b979 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -560,6 +560,22 @@ impl Backend for Recorder { } } +/// A malformed `paths` entry refuses the whole import before any file is discovered or dispatched. +#[test] +fn import_rejects_non_string_paths_before_dispatch() { + for mode in ["add", "copy", "move"] { + for invalid in [json!(null), json!(false), json!(7), json!(1.5), json!({"path": "photo.png"}), json!(["photo.png"])] { + for paths in [json!(["photo.png", invalid]), json!([invalid, "photo.png"])] { + let mut b = Recorder(vec![]); + let r = call_tool(&mut b, "import", &json!({"paths": paths, "mode": mode})); + assert!(r.is_error, "{mode} {paths}: {r:?}"); + assert!(r.content[0]["text"].as_str().unwrap().contains("paths["), "{r:?}"); + assert!(b.0.is_empty(), "{mode} {paths} dispatched a partial batch: {:?}", b.0); + } + } + } +} + /// With the app attached, agents cut, copy and paste in its text fields (`clipboard`). #[test] fn the_clipboard_tool_cuts_copies_and_pastes_in_the_app() { diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 375a6e17f8..714c875209 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -729,11 +729,21 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult { None => ToolResult::error("missing `command`"), }, "import" => { - let paths: Vec = match args.get("paths") { - Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(), - Some(Value::String(p)) => vec![p.clone()], + // Validate the whole request before discovering files or importing a partial batch, + // especially in move mode, which removes the sources of what it imported. + let paths: Result, String> = match args.get("paths") { + Some(Value::Array(a)) => a + .iter() + .enumerate() + .map(|(i, v)| v.as_str().map(str::to_string).ok_or_else(|| format!("`paths[{i}]` must be a string"))) + .collect(), + Some(Value::String(p)) => Ok(vec![p.clone()]), _ => return ToolResult::error("missing `paths`"), }; + let paths = match paths { + Ok(paths) => paths, + Err(e) => return ToolResult::error(e), + }; let files = expand_paths(&paths); if files.is_empty() { return ToolResult::error(format!("no photos found in {paths:?}")); diff --git a/crates/meta/Cargo.toml b/crates/meta/Cargo.toml index 25c9dbb3cc..035abc1e2e 100644 --- a/crates/meta/Cargo.toml +++ b/crates/meta/Cargo.toml @@ -15,6 +15,8 @@ lcc-geom = { workspace = true } serde = { workspace = true } quick-xml = { workspace = true } chrono = { workspace = true } +# `brob` (Brotli-wrapped) JPEG XL metadata boxes +brotli-decompressor = { version = "5", default-features = false, features = ["std"] } [dev-dependencies] proptest = { workspace = true } @@ -23,3 +25,5 @@ lcc-testkit = { workspace = true } serde_json = { workspace = true } # Lossless synthetic HEIF files for the container reader's tests. lcc-heif = { workspace = true, features = ["testdata"] } +# Brotli-wrapped (`brob`) JPEG XL metadata boxes in test fixtures +brotli = { version = "8", default-features = false, features = ["std"] } diff --git a/crates/meta/src/container.rs b/crates/meta/src/container.rs index 655434d663..7d58dc6eb5 100644 --- a/crates/meta/src/container.rs +++ b/crates/meta/src/container.rs @@ -1,628 +1,633 @@ -//! Locating metadata blocks inside image containers. -//! -//! - JPEG (ITU-T T.81 marker structure): APP1 `Exif\0\0`, APP1 `http://ns.adobe.com/xap/1.0/\0` (XMP), -//! APP1 `http://ns.adobe.com/xmp/extension/\0` (extended XMP, reassembled), APP2 `ICC_PROFILE\0` -//! (multi-chunk, reassembled in sequence order), APP13 `Photoshop 3.0\0` 8BIM resource 0x0404 (IPTC-IIM). -//! - PNG (PNG spec 3rd ed.): `eXIf`, `iTXt` with keyword `XML:com.adobe.xmp` (uncompressed). -//! - WebP (RIFF container spec): `EXIF`, `XMP `, `ICCP` chunks. -//! - TIFF-based files (TIFF, DNG and most raws): the whole file is the Exif block; XMP (700), ICC (34675) and -//! IPTC (33723) from IFD0. -//! - Photoshop PSD/PSB: EXIF (image resource 1058) and XMP (image resource 1060) from the bounded image-resource section. -//! - Minolta MRW (see [`crate::mrw`]): the `TTW` block is the Exif block. -//! - Canon CR3 (ISO base media file, see [`crate::cr3`]): `CMT1`/`CMT2`/`CMT4` merged into one Exif block; the -//! XMP `uuid` box. -//! - HEIF, HEIC and AVIF (ISO base media file, see `crate::heif`): the primary image's `Exif` item and XMP -//! (`mime`) item, found through `meta` / `iinf` / `iloc` / `iref`; no picture is decoded. - -use lcc_tiff::{Tiff, tags}; - -/// Metadata blocks found in a file. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct Embedded { - /// TIFF-structured Exif block (without the `Exif\0\0` prefix). - pub exif: Option>, - /// XMP packet (the main one; extended XMP is appended by [`Embedded::xmp_extended`]). - pub xmp: Option, - /// Extended XMP (JPEG only), reassembled. - pub xmp_extended: Option, - pub icc: Option>, - /// IPTC-IIM stream. - pub iptc: Option>, -} - -/// Sniff the container and collect its metadata blocks. Unknown containers yield an empty result. -pub fn embedded(bytes: &[u8]) -> Embedded { - if bytes.starts_with(b"8BPS") { - return crate::psd::embedded(bytes); - } - if bytes.starts_with(b"FUJIFILMCCD-RAW") { - // Fujifilm RAF: metadata lives in the embedded JPEG whose (offset, length) are big-endian u32s at byte 84 - let be = |i: usize| bytes.get(i..i + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize); - return match (be(84), be(88)) { - (Some(o), Some(l)) if o > 0 => bytes.get(o..o.saturating_add(l).min(bytes.len())).map(jpeg_segments).unwrap_or_default(), - _ => Embedded::default(), - }; - } - if let Some(m) = crate::mrw::parse(bytes) { - // Minolta MRW: the `TTW` block is a complete TIFF with the Exif data - return m - .block(b"TTW") - .filter(|t| Tiff::parse(t).is_ok()) - .map(|t| Embedded { exif: Some(t.to_vec()), ..Default::default() }) - .unwrap_or_default(); - } - if let Some(c) = crate::cr3::parse_cr3(bytes) { - return Embedded { exif: crate::cr3::merged_exif(&c), xmp: c.xmp.map(|b| String::from_utf8_lossy(b).into_owned()), ..Default::default() }; - } - if let Some(e) = crate::heif::embedded(bytes) { - return e; - } - if bytes.starts_with(&[0xff, 0xd8]) { - jpeg_segments(bytes) - } else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { - png_chunks(bytes) - } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { - webp_chunks(bytes) - } else if let Ok(t) = Tiff::parse(bytes) { - let ifd0 = &t.ifds[0]; - Embedded { - exif: Some(bytes.to_vec()), - xmp: ifd0.bytes(tags::XMP).map(|b| String::from_utf8_lossy(b).into_owned()), - xmp_extended: None, - icc: ifd0.bytes(tags::ICC_PROFILE).map(|b| b.to_vec()), - iptc: ifd0.value(tags::IPTC_NAA).map(|v| match v { - lcc_tiff::Value::Byte(b) | lcc_tiff::Value::Undefined(b) => b.clone(), - other => lcc_tiff::writer::encode(t.order, other), - }), - } - } else { - Embedded::default() - } -} - -/// Locate metadata blocks while preserving PSD/PSB resource-structure errors for callers that -/// must establish whether embedded GPS is absent. Other containers keep their best-effort walk. -pub(crate) fn try_embedded(bytes: &[u8]) -> Result { - if bytes.starts_with(b"8BPS") { crate::psd::parse(bytes).ok_or(crate::ExtractError::MalformedPsd) } else { Ok(embedded(bytes)) } -} - -const XMP_SIG: &[u8] = b"http://ns.adobe.com/xap/1.0/\0"; -const XMP_EXT_SIG: &[u8] = b"http://ns.adobe.com/xmp/extension/\0"; - -/// Walk JPEG markers up to SOS and collect APP1 Exif / XMP, APP2 ICC and APP13 IPTC. -pub fn jpeg_segments(b: &[u8]) -> Embedded { - let mut out = Embedded::default(); - if !b.starts_with(&[0xff, 0xd8]) { - return out; - } - let mut icc_parts: [Option<&[u8]>; 255] = [None; 255]; - let mut icc_total = None; - let mut icc_invalid = false; - // extended XMP chunks: (GUID, full length, offset, data) - let mut ext: Vec<([u8; 32], u32, u32, &[u8])> = Vec::new(); - let mut i = 2usize; - while i + 4 <= b.len() { - if b[i] != 0xff { - break; - } - let marker = b[i + 1]; - if marker == 0xff { - i += 1; // fill byte - continue; - } - if marker == 0xd8 || (0xd0..=0xd7).contains(&marker) || marker == 0x01 { - i += 2; - continue; - } - if marker == 0xd9 || marker == 0xda { - break; - } - let len = u16::from_be_bytes([b[i + 2], b[i + 3]]) as usize; - if len < 2 { - break; - } - let Some(start) = i.checked_add(4) else { break }; - let Some(declared_end) = i.checked_add(2).and_then(|at| at.checked_add(len)) else { break }; - let complete = declared_end <= b.len(); - let end = declared_end.min(b.len()); - let Some(payload) = b.get(start..end) else { break }; - match marker { - 0xe1 if payload.starts_with(b"Exif\0") && out.exif.is_none() => out.exif = Some(payload.get(6..).unwrap_or(&[]).to_vec()), - 0xe1 if payload.starts_with(XMP_SIG) && out.xmp.is_none() => { - out.xmp = Some(String::from_utf8_lossy(&payload[XMP_SIG.len()..]).into_owned()); - } - 0xe1 if payload.starts_with(XMP_EXT_SIG) => { - // GUID (32) + full length (4) + offset (4) + data - if complete - && let Some(p) = payload.get(XMP_EXT_SIG.len()..) - && let (Some(guid), Some(full), Some(off), Some(data)) = (p.get(..32), p.get(32..36), p.get(36..40), p.get(40..)) - && let (Ok(guid), Ok(full), Ok(off)) = (<[u8; 32]>::try_from(guid), <[u8; 4]>::try_from(full), <[u8; 4]>::try_from(off)) - { - ext.push((guid, u32::from_be_bytes(full), u32::from_be_bytes(off), data)); - } - } - 0xe2 if payload.starts_with(b"ICC_PROFILE\0") => { - if !complete || payload.len() < 14 { - icc_invalid = true; - } else if let Some(header) = payload.get(12..14) { - let (Some(&sequence), Some(&total)) = (header.first(), header.get(1)) else { - icc_invalid = true; - i = end; - continue; - }; - if sequence == 0 || total == 0 || sequence > total || icc_total.is_some_and(|expected| expected != total) { - icc_invalid = true; - } else { - icc_total = Some(total); - if let Some(slot) = icc_parts.get_mut(usize::from(sequence - 1)) { - if slot.is_some() { - icc_invalid = true; - } else if let Some(data) = payload.get(14..) { - *slot = Some(data); - } else { - icc_invalid = true; - } - } else { - icc_invalid = true; - } - } - } else { - icc_invalid = true; - } - } - 0xed if payload.starts_with(b"Photoshop 3.0\0") && out.iptc.is_none() => out.iptc = photoshop_iptc(&payload[14..]), - _ => {} - } - i = end; - } - if let Some(total) = icc_total { - let mut profile_len = 0usize; - for chunk in icc_parts.iter().take(usize::from(total)) { - let Some(bytes) = chunk else { - icc_invalid = true; - break; - }; - let Some(next_len) = profile_len.checked_add(bytes.len()) else { - icc_invalid = true; - break; - }; - profile_len = next_len; - } - let maximum_len = usize::from(total).checked_mul(65_519); - if maximum_len.is_none_or(|maximum| profile_len > maximum) { - icc_invalid = true; - } - if !icc_invalid { - let mut profile = Vec::with_capacity(profile_len); - for bytes in icc_parts.iter().take(usize::from(total)).flatten() { - profile.extend_from_slice(bytes); - } - out.icc = Some(profile); - } - } - out.xmp_extended = out.xmp.as_deref().and_then(extended_guid).and_then(|guid| reassemble_extended(&guid, ext)); - out -} - -/// The most bytes an extended XMP packet may claim: far more than any real one carries. -const MAX_EXTENDED_XMP: u32 = 64 << 20; - -/// The GUID the main XMP packet names in `xmpNote:HasExtendedXMP` (32 upper-case hex digits, the -/// MD5 of the extended packet), as an attribute or an element. `None` when it names none. -fn extended_guid(xmp: &str) -> Option<[u8; 32]> { - let at = xmp.find("HasExtendedXMP")?; - let rest = xmp.get(at..)?.get("HasExtendedXMP".len()..)?; - let rest = rest.trim_start_matches(|c: char| c.is_whitespace() || matches!(c, '=' | '"' | '\'' | '>')); - let guid = <[u8; 32]>::try_from(rest.as_bytes().get(..32)?).ok()?; - guid.iter().all(u8::is_ascii_hexdigit).then_some(guid) -} - -/// The extended XMP packet the main packet refers to (XMP Specification Part 3, 1.1.3.1): only the -/// chunks carrying its GUID, all agreeing on the full length, which together cover that length -/// exactly once. Anything else (chunks of another packet, a gap, an overlap, a length past the -/// cap) is not that packet, and nothing of it is read. -fn reassemble_extended(guid: &[u8; 32], chunks: Vec<([u8; 32], u32, u32, &[u8])>) -> Option { - let mut mine: Vec<(u32, u32, &[u8])> = chunks.into_iter().filter(|c| c.0.eq_ignore_ascii_case(guid)).map(|c| (c.1, c.2, c.3)).collect(); - let full = mine.first()?.0; - if full == 0 || full > MAX_EXTENDED_XMP || mine.iter().any(|c| c.0 != full) { - return None; - } - mine.sort_by_key(|c| c.1); - let mut packet = Vec::with_capacity(full as usize); - for (_, off, data) in mine { - if off as usize != packet.len() { - return None; - } - packet.extend_from_slice(data); - if packet.len() > full as usize { - return None; - } - } - (packet.len() == full as usize).then(|| String::from_utf8_lossy(&packet).into_owned()) -} - -/// IPTC-IIM block (resource 0x0404) from a Photoshop image-resource stream (`8BIM` records). -fn photoshop_iptc(mut b: &[u8]) -> Option> { - while b.len() >= 12 && &b[..4] == b"8BIM" { - let id = u16::from_be_bytes([b[4], b[5]]); - let name_len = b[6] as usize; - let name_total = (1 + name_len).next_multiple_of(2); - let size_at = 6 + name_total; - let size = u32::from_be_bytes(b.get(size_at..size_at + 4)?.try_into().ok()?) as usize; - let data_at = size_at + 4; - let data = b.get(data_at..data_at.checked_add(size)?)?; - if id == 0x0404 { - return Some(data.to_vec()); - } - b = b.get(data_at + size.next_multiple_of(2)..)?; - } - None -} - -/// PNG chunks: `eXIf`, uncompressed `iTXt` XMP. -pub fn png_chunks(b: &[u8]) -> Embedded { - let mut out = Embedded::default(); - let mut i = 8usize; - while i + 12 <= b.len() { - let len = u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) as usize; - let typ = &b[i + 4..i + 8]; - let Some(data) = b.get(i + 8..(i + 8).saturating_add(len)) else { break }; - match typ { - b"eXIf" => out.exif = Some(crate::strip_exif_header(data).to_vec()), - b"iTXt" if data.starts_with(b"XML:com.adobe.xmp\0") => { - // keyword\0 compression-flag compression-method language\0 translated\0 text - let rest = &data[18..]; - if rest.len() >= 2 && rest[0] == 0 { - let rest = &rest[2..]; - let mut parts = rest.splitn(3, |&c| c == 0); - let (_, _, text) = (parts.next(), parts.next(), parts.next()); - if let Some(t) = text { - out.xmp = Some(String::from_utf8_lossy(t).into_owned()); - } - } - } - b"IEND" => break, - _ => {} - } - i += 12 + len; - } - out -} - -/// WebP RIFF chunks `EXIF`, `XMP `, `ICCP`. -pub fn webp_chunks(b: &[u8]) -> Embedded { - let mut out = Embedded::default(); - let mut i = 12usize; - while i + 8 <= b.len() { - let id = &b[i..i + 4]; - let len = u32::from_le_bytes([b[i + 4], b[i + 5], b[i + 6], b[i + 7]]) as usize; - let Some(data) = b.get(i + 8..(i + 8).saturating_add(len)) else { break }; - match id { - b"EXIF" => out.exif = Some(crate::strip_exif_header(data).to_vec()), - b"XMP " => out.xmp = Some(String::from_utf8_lossy(data).into_owned()), - b"ICCP" => out.icc = Some(data.to_vec()), - _ => {} - } - i += 8 + len + (len & 1); - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::exif::tests::sample_exif; - use lcc_tiff::ByteOrder; - - fn seg(marker: u8, payload: &[u8]) -> Vec { - let mut v = vec![0xff, marker]; - v.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes()); - v.extend_from_slice(payload); - v - } - - fn icc_seg(sequence: u8, total: u8, data: &[u8]) -> Vec { - let mut payload = b"ICC_PROFILE\0".to_vec(); - payload.extend_from_slice(&[sequence, total]); - payload.extend_from_slice(data); - seg(0xe2, &payload) - } - - fn jpeg_with_icc(parts: &[Vec]) -> Vec { - let mut jpeg = vec![0xff, 0xd8]; - let packet = crate::write_xmp(&crate::Metadata { title: Some("retained".into()), ..Default::default() }, None); - let mut xmp = XMP_SIG.to_vec(); - xmp.extend_from_slice(packet.as_bytes()); - jpeg.extend_from_slice(&seg(0xe1, &xmp)); - for part in parts { - jpeg.extend_from_slice(part); - } - jpeg.extend_from_slice(&[0xff, 0xda, 0, 2]); - jpeg - } - - pub(crate) fn sample_jpeg() -> Vec { - let mut j = vec![0xff, 0xd8]; - j.extend(seg(0xe0, b"JFIF\0\x01\x02\0\0\x01\0\x01\0\0")); - let mut exif = b"Exif\0\0".to_vec(); - exif.extend(sample_exif(ByteOrder::Big)); - j.extend(seg(0xe1, &exif)); - let meta = crate::Metadata { title: Some("Sunset".into()), rating: Some(4), ..Default::default() }; - let mut xmp = XMP_SIG.to_vec(); - xmp.extend(crate::write_xmp(&meta, Some("{\"exposure\":1.5}")).into_bytes()); - j.extend(seg(0xe1, &xmp)); - // ICC in two chunks, out of order - j.extend(seg(0xe2, b"ICC_PROFILE\0\x02\x02WORLD")); - j.extend(seg(0xe2, b"ICC_PROFILE\0\x01\x02HELLO")); - // IPTC - let iim = crate::iptc::tests::sample_iim(); - let mut ps = b"Photoshop 3.0\0".to_vec(); - ps.extend_from_slice(b"8BIM\x04\x0c\0\0"); - ps.extend_from_slice(&2u32.to_be_bytes()); - ps.extend_from_slice(&[1, 2]); - ps.extend_from_slice(b"8BIM\x04\x04\0\0"); - ps.extend_from_slice(&(iim.len() as u32).to_be_bytes()); - ps.extend_from_slice(&iim); - j.extend(seg(0xed, &ps)); - j.extend_from_slice(&[0xff, 0xda, 0, 2, 1, 2, 3, 0xff, 0xd9]); - j - } - - #[test] - fn jpeg_blocks() { - let j = sample_jpeg(); - let e = jpeg_segments(&j); - assert_eq!(e.icc.as_deref(), Some(&b"HELLOWORLD"[..])); - assert!(e.xmp.as_deref().unwrap().contains("Sunset")); - assert!(e.iptc.is_some()); - let m = crate::extract(&j); - assert_eq!(m.iso, Some(400)); - assert_eq!(m.title.as_deref(), Some("Sunset")); - assert_eq!(m.rating, Some(4)); // XMP overrides EXIF rating 3 - assert_eq!(m.keywords, vec!["alpha".to_string(), "beta".to_string()]); // from IPTC - assert_eq!(m.caption.as_deref(), Some("A caption")); - } - - const GUID: &[u8; 32] = b"0123456789ABCDEF0123456789ABCDEF"; - - /// A JPEG whose main packet names `named` and whose extended chunks are `(guid, full, offset, data)`. - fn jpeg_with_extended(named: Option<&[u8; 32]>, chunks: &[(&[u8; 32], u32, u32, &[u8])]) -> Vec { - let mut j = vec![0xff, 0xd8]; - let main = match named { - Some(g) => format!( - "", - std::str::from_utf8(g).unwrap() - ), - None => "".to_string(), - }; - let mut p = XMP_SIG.to_vec(); - p.extend_from_slice(main.as_bytes()); - j.extend(seg(0xe1, &p)); - for (guid, full, off, part) in chunks { - let mut p = XMP_EXT_SIG.to_vec(); - p.extend_from_slice(&guid[..]); - p.extend_from_slice(&full.to_be_bytes()); - p.extend_from_slice(&off.to_be_bytes()); - p.extend_from_slice(part); - j.extend(seg(0xe1, &p)); - } - j - } - - fn jpeg_with_orientation(exif_orientation: Option, xmp_orientation: &str) -> Vec { - let mut jpeg = vec![0xff, 0xd8]; - if let Some(orientation) = exif_orientation { - let mut exif = b"Exif\0\0".to_vec(); - exif.extend(crate::exif::write_exif(&crate::Metadata { orientation: Some(orientation), ..Default::default() })); - jpeg.extend(seg(0xe1, &exif)); - } - let packet = format!( - r#""# - ); - let mut xmp = XMP_SIG.to_vec(); - xmp.extend_from_slice(packet.as_bytes()); - jpeg.extend(seg(0xe1, &xmp)); - jpeg.extend_from_slice(&[0xff, 0xd9]); - jpeg - } - - #[test] - fn embedded_xmp_orientation_requires_integral_value_and_respects_exif() { - let malformed = crate::extract(&jpeg_with_orientation(None, "6.9")); - assert_eq!(malformed.orientation, None); - - let valid_xmp = crate::extract(&jpeg_with_orientation(None, "6")); - assert_eq!(valid_xmp.orientation.map(|orientation| orientation.to_exif()), Some(6)); - - let valid_exif = crate::extract(&jpeg_with_orientation(Some(crate::Orientation::Rotate180), "6")); - assert_eq!(valid_exif.orientation.map(|orientation| orientation.to_exif()), Some(3)); - } - - #[test] - fn jpeg_invalid_iptc_time_created_allows_xmp_fallback() { - let mut data = Vec::new(); - for (dataset, value) in [(55, &b"20260101"[..]), (60, b"121314+01"), (5, b"retained title")] { - data.extend_from_slice(&[0x1c, 2, dataset]); - data.extend_from_slice(&(value.len() as u16).to_be_bytes()); - data.extend_from_slice(value); - } - let xmp = crate::write_xmp( - &crate::Metadata { - capture_time: Some(crate::DateTime { year: 2026, month: 1, day: 2, hour: 10, offset_minutes: Some(0), ..Default::default() }), - ..Default::default() - }, - None, - ); - let mut jpeg = vec![0xff, 0xd8]; - let mut payload = XMP_SIG.to_vec(); - payload.extend_from_slice(xmp.as_bytes()); - jpeg.extend_from_slice(&seg(0xe1, &payload)); - let mut resource = b"Photoshop 3.0".to_vec(); - resource.extend_from_slice(b"8BIM"); - resource.extend_from_slice(&(data.len() as u32).to_be_bytes()); - resource.extend_from_slice(&data); - if data.len() % 2 == 1 { - resource.push(0); - } - jpeg.extend_from_slice(&seg(0xed, &resource)); - jpeg.extend_from_slice(&[0xff, 0xda, 0, 2]); - assert!(embedded(&jpeg).iptc.is_some(), "raw IIM remains available"); - let m = crate::extract(&jpeg); - assert_eq!(m.capture_time.map(|time| time.to_iso()).as_deref(), Some("2026-01-02T10:00:00+00:00")); - assert_eq!(m.title.as_deref(), Some("retained title")); - } - - #[test] - fn jpeg_extended_xmp() { - let j = jpeg_with_extended(Some(GUID), &[(GUID, 10, 5, b"world"), (GUID, 10, 0, b"hello")]); - assert_eq!(jpeg_segments(&j).xmp_extended.as_deref(), Some("helloworld")); - // chunks of another packet are left out - let other = b"FEDCBA9876543210FEDCBA9876543210"; - let j = jpeg_with_extended(Some(GUID), &[(GUID, 10, 5, b"world"), (other, 3, 0, b"bad"), (GUID, 10, 0, b"hello")]); - assert_eq!(jpeg_segments(&j).xmp_extended.as_deref(), Some("helloworld")); - } - - /// What a writer moved to the extended packet (here a GPS position and a caption) is read with - /// the main packet's fields, so export's location check sees it too. - #[test] - fn extract_reads_the_referenced_extended_packet() { - let ext = r#"Long caption"#; - let (a, b) = ext.as_bytes().split_at(40); - let full = ext.len() as u32; - let j = jpeg_with_extended(Some(GUID), &[(GUID, full, 40, b), (GUID, full, 0, a)]); - let m = crate::extract(&j); - assert_eq!(m.caption.as_deref(), Some("Long caption")); - assert!(m.gps.is_some(), "{m:?}"); - // not referenced: not read - let j = jpeg_with_extended(None, &[(GUID, full, 0, ext.as_bytes())]); - assert!(crate::extract(&j).gps.is_none()); - } - - #[test] - fn jpeg_extended_xmp_is_read_only_whole_and_referenced() { - let other = b"FEDCBA9876543210FEDCBA9876543210"; - for (name, named, chunks) in [ - ("not referenced", None, vec![(GUID, 10, 0, &b"helloworld"[..])]), - ("another GUID", Some(GUID), vec![(other, 10, 0, &b"helloworld"[..])]), - ("a gap", Some(GUID), vec![(GUID, 10, 0, &b"hell"[..]), (GUID, 10, 5, b"world")]), - ("an overlap", Some(GUID), vec![(GUID, 10, 0, &b"hello"[..]), (GUID, 10, 4, b"oworld")]), - ("short", Some(GUID), vec![(GUID, 10, 0, &b"hello"[..])]), - ("past its length", Some(GUID), vec![(GUID, 4, 0, &b"hello"[..])]), - ("lengths disagree", Some(GUID), vec![(GUID, 10, 0, &b"hello"[..]), (GUID, 11, 5, b"world")]), - ("a huge length", Some(GUID), vec![(GUID, u32::MAX, 0, &b"hello"[..])]), - ] { - let j = jpeg_with_extended(named, &chunks); - assert_eq!(jpeg_segments(&j).xmp_extended, None, "{name}"); - } - } - - #[test] - fn jpeg_icc_accepts_reordered_chunks() { - let parts = [icc_seg(2, 2, b"world"), icc_seg(1, 2, b"hello")]; - let embedded = jpeg_segments(&jpeg_with_icc(&parts)); - assert_eq!(embedded.icc.as_deref(), Some(&b"helloworld"[..])); - } - - #[test] - fn jpeg_icc_rejects_incomplete_or_incoherent_chunks() { - let cases = [ - ("missing", vec![icc_seg(1, 2, b"helloworld")]), - ("duplicate", vec![icc_seg(1, 2, b"hello"), icc_seg(1, 2, b"world")]), - ("zero sequence", vec![icc_seg(0, 1, b"helloworld")]), - ("zero total", vec![icc_seg(1, 0, b"helloworld")]), - ("out of range", vec![icc_seg(2, 1, b"helloworld")]), - ("gap", vec![icc_seg(1, 3, b"hello"), icc_seg(3, 3, b"world")]), - ("inconsistent totals", vec![icc_seg(1, 2, b"hello"), icc_seg(2, 3, b"world")]), - ("short header", vec![seg(0xe2, b"ICC_PROFILE\0\x01")]), - ]; - for (name, parts) in cases { - let embedded = jpeg_segments(&jpeg_with_icc(&parts)); - assert!(embedded.icc.is_none(), "{name} ICC chunks must be rejected"); - assert!(embedded.xmp.as_deref().is_some_and(|x| x.contains("retained")), "{name}: unrelated XMP must remain readable"); - } - } - - #[test] - fn jpeg_icc_rejects_truncated_segment_and_keeps_other_metadata() { - let mut truncated = icc_seg(1, 1, b"profile"); - let declared = u16::from_be_bytes([truncated[2], truncated[3]]).saturating_add(1); - truncated[2..4].copy_from_slice(&declared.to_be_bytes()); - let mut jpeg = vec![0xff, 0xd8]; - let xmp = crate::write_xmp(&crate::Metadata { title: Some("kept".into()), ..Default::default() }, None); - let mut packet = XMP_SIG.to_vec(); - packet.extend_from_slice(xmp.as_bytes()); - jpeg.extend_from_slice(&seg(0xe1, &packet)); - jpeg.extend_from_slice(&truncated); - - let embedded = jpeg_segments(&jpeg); - assert!(embedded.icc.is_none()); - assert!(embedded.xmp.as_deref().is_some_and(|x| x.contains("kept"))); - } - - #[test] - fn png_and_webp() { - let exif = sample_exif(ByteOrder::Little); - let mut p = b"\x89PNG\r\n\x1a\n".to_vec(); - let mut chunk = |typ: &[u8], data: &[u8]| { - p.extend_from_slice(&(data.len() as u32).to_be_bytes()); - p.extend_from_slice(typ); - p.extend_from_slice(data); - p.extend_from_slice(&[0; 4]); - }; - chunk(b"eXIf", &exif); - let mut itxt = b"XML:com.adobe.xmp\0\0\0\0\0".to_vec(); - itxt.extend(crate::write_xmp(&crate::Metadata { label: Some("Red".into()), ..Default::default() }, None).into_bytes()); - chunk(b"iTXt", &itxt); - chunk(b"IEND", &[]); - let m = crate::extract(&p); - assert_eq!(m.iso, Some(400)); - assert_eq!(m.label.as_deref(), Some("Red")); - - let mut w = b"RIFF\0\0\0\0WEBP".to_vec(); - let mut body = |id: &[u8], data: &[u8]| { - w.extend_from_slice(id); - w.extend_from_slice(&(data.len() as u32).to_le_bytes()); - w.extend_from_slice(data); - if data.len() % 2 == 1 { - w.push(0); - } - }; - body(b"VP8X", &[0; 10]); - body(b"ICCP", b"abc"); - let mut ex = b"Exif\0\0".to_vec(); - ex.extend_from_slice(&exif); - body(b"EXIF", &ex); - let e = webp_chunks(&w); - assert_eq!(e.icc.as_deref(), Some(&b"abc"[..])); - assert_eq!(crate::extract(&w).f_number, Some(2.8)); - } - - #[test] - fn tiff_file_is_its_own_exif() { - let t = sample_exif(ByteOrder::Big); - assert_eq!(crate::extract(&t).model.as_deref(), Some("Model X")); - assert_eq!(embedded(b"not an image"), Embedded::default()); - } - - #[test] - fn raf_reads_its_embedded_jpeg() { - let j = sample_jpeg(); - let mut raf = b"FUJIFILMCCD-RAW 0201FF000000TEST".to_vec(); - raf.resize(120, 0); - raf[84..88].copy_from_slice(&120u32.to_be_bytes()); - raf[88..92].copy_from_slice(&(j.len() as u32).to_be_bytes()); - raf.extend_from_slice(&j); - assert_eq!(crate::extract(&raf).iso, Some(400)); - for n in 0..raf.len() { - let _ = crate::extract(&raf[..n]); - } - } - - #[test] - fn truncated_containers_do_not_panic() { - let j = sample_jpeg(); - for n in 0..j.len() { - let _ = crate::extract(&j[..n]); - } - } -} +//! Locating metadata blocks inside image containers. +//! +//! - JPEG (ITU-T T.81 marker structure): APP1 `Exif\0\0`, APP1 `http://ns.adobe.com/xap/1.0/\0` (XMP), +//! APP1 `http://ns.adobe.com/xmp/extension/\0` (extended XMP, reassembled), APP2 `ICC_PROFILE\0` +//! (multi-chunk, reassembled in sequence order), APP13 `Photoshop 3.0\0` 8BIM resource 0x0404 (IPTC-IIM). +//! - PNG (PNG spec 3rd ed.): `eXIf`, `iTXt` with keyword `XML:com.adobe.xmp` (uncompressed). +//! - WebP (RIFF container spec): `EXIF`, `XMP `, `ICCP` chunks. +//! - TIFF-based files (TIFF, DNG and most raws): the whole file is the Exif block; XMP (700), ICC (34675) and +//! IPTC (33723) from IFD0. +//! - Photoshop PSD/PSB: EXIF (image resource 1058) and XMP (image resource 1060) from the bounded image-resource section. +//! - Minolta MRW (see [`crate::mrw`]): the `TTW` block is the Exif block. +//! - Canon CR3 (ISO base media file, see [`crate::cr3`]): `CMT1`/`CMT2`/`CMT4` merged into one Exif block; the +//! XMP `uuid` box. +//! - HEIF, HEIC and AVIF (ISO base media file, see `crate::heif`): the primary image's `Exif` item and XMP +//! (`mime`) item, found through `meta` / `iinf` / `iloc` / `iref`; no picture is decoded. +//! - JPEG XL (ISO base media file, see [`crate::jxl`]): the `Exif` and `xml ` boxes, plain or Brotli-wrapped in +//! `brob`; a bare codestream has no metadata. + +use lcc_tiff::{Tiff, tags}; + +/// Metadata blocks found in a file. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Embedded { + /// TIFF-structured Exif block (without the `Exif\0\0` prefix). + pub exif: Option>, + /// XMP packet (the main one; extended XMP is appended by [`Embedded::xmp_extended`]). + pub xmp: Option, + /// Extended XMP (JPEG only), reassembled. + pub xmp_extended: Option, + pub icc: Option>, + /// IPTC-IIM stream. + pub iptc: Option>, +} + +/// Sniff the container and collect its metadata blocks. Unknown containers yield an empty result. +pub fn embedded(bytes: &[u8]) -> Embedded { + if bytes.starts_with(b"8BPS") { + return crate::psd::embedded(bytes); + } + if bytes.starts_with(b"FUJIFILMCCD-RAW") { + // Fujifilm RAF: metadata lives in the embedded JPEG whose (offset, length) are big-endian u32s at byte 84 + let be = |i: usize| bytes.get(i..i + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize); + return match (be(84), be(88)) { + (Some(o), Some(l)) if o > 0 => bytes.get(o..o.saturating_add(l).min(bytes.len())).map(jpeg_segments).unwrap_or_default(), + _ => Embedded::default(), + }; + } + if let Some(m) = crate::mrw::parse(bytes) { + // Minolta MRW: the `TTW` block is a complete TIFF with the Exif data + return m + .block(b"TTW") + .filter(|t| Tiff::parse(t).is_ok()) + .map(|t| Embedded { exif: Some(t.to_vec()), ..Default::default() }) + .unwrap_or_default(); + } + if let Some(c) = crate::cr3::parse_cr3(bytes) { + return Embedded { exif: crate::cr3::merged_exif(&c), xmp: c.xmp.map(|b| String::from_utf8_lossy(b).into_owned()), ..Default::default() }; + } + if let Some(e) = crate::heif::embedded(bytes) { + return e; + } + if crate::jxl::is_jxl_container(bytes) { + return crate::jxl::metadata(bytes); + } + if bytes.starts_with(&[0xff, 0xd8]) { + jpeg_segments(bytes) + } else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + png_chunks(bytes) + } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + webp_chunks(bytes) + } else if let Ok(t) = Tiff::parse(bytes) { + let ifd0 = &t.ifds[0]; + Embedded { + exif: Some(bytes.to_vec()), + xmp: ifd0.bytes(tags::XMP).map(|b| String::from_utf8_lossy(b).into_owned()), + xmp_extended: None, + icc: ifd0.bytes(tags::ICC_PROFILE).map(|b| b.to_vec()), + iptc: ifd0.value(tags::IPTC_NAA).map(|v| match v { + lcc_tiff::Value::Byte(b) | lcc_tiff::Value::Undefined(b) => b.clone(), + other => lcc_tiff::writer::encode(t.order, other), + }), + } + } else { + Embedded::default() + } +} + +/// Locate metadata blocks while preserving PSD/PSB resource-structure errors for callers that +/// must establish whether embedded GPS is absent. Other containers keep their best-effort walk. +pub(crate) fn try_embedded(bytes: &[u8]) -> Result { + if bytes.starts_with(b"8BPS") { crate::psd::parse(bytes).ok_or(crate::ExtractError::MalformedPsd) } else { Ok(embedded(bytes)) } +} + +const XMP_SIG: &[u8] = b"http://ns.adobe.com/xap/1.0/\0"; +const XMP_EXT_SIG: &[u8] = b"http://ns.adobe.com/xmp/extension/\0"; + +/// Walk JPEG markers up to SOS and collect APP1 Exif / XMP, APP2 ICC and APP13 IPTC. +pub fn jpeg_segments(b: &[u8]) -> Embedded { + let mut out = Embedded::default(); + if !b.starts_with(&[0xff, 0xd8]) { + return out; + } + let mut icc_parts: [Option<&[u8]>; 255] = [None; 255]; + let mut icc_total = None; + let mut icc_invalid = false; + // extended XMP chunks: (GUID, full length, offset, data) + let mut ext: Vec<([u8; 32], u32, u32, &[u8])> = Vec::new(); + let mut i = 2usize; + while i + 4 <= b.len() { + if b[i] != 0xff { + break; + } + let marker = b[i + 1]; + if marker == 0xff { + i += 1; // fill byte + continue; + } + if marker == 0xd8 || (0xd0..=0xd7).contains(&marker) || marker == 0x01 { + i += 2; + continue; + } + if marker == 0xd9 || marker == 0xda { + break; + } + let len = u16::from_be_bytes([b[i + 2], b[i + 3]]) as usize; + if len < 2 { + break; + } + let Some(start) = i.checked_add(4) else { break }; + let Some(declared_end) = i.checked_add(2).and_then(|at| at.checked_add(len)) else { break }; + let complete = declared_end <= b.len(); + let end = declared_end.min(b.len()); + let Some(payload) = b.get(start..end) else { break }; + match marker { + 0xe1 if payload.starts_with(b"Exif\0") && out.exif.is_none() => out.exif = Some(payload.get(6..).unwrap_or(&[]).to_vec()), + 0xe1 if payload.starts_with(XMP_SIG) && out.xmp.is_none() => { + out.xmp = Some(String::from_utf8_lossy(&payload[XMP_SIG.len()..]).into_owned()); + } + 0xe1 if payload.starts_with(XMP_EXT_SIG) => { + // GUID (32) + full length (4) + offset (4) + data + if complete + && let Some(p) = payload.get(XMP_EXT_SIG.len()..) + && let (Some(guid), Some(full), Some(off), Some(data)) = (p.get(..32), p.get(32..36), p.get(36..40), p.get(40..)) + && let (Ok(guid), Ok(full), Ok(off)) = (<[u8; 32]>::try_from(guid), <[u8; 4]>::try_from(full), <[u8; 4]>::try_from(off)) + { + ext.push((guid, u32::from_be_bytes(full), u32::from_be_bytes(off), data)); + } + } + 0xe2 if payload.starts_with(b"ICC_PROFILE\0") => { + if !complete || payload.len() < 14 { + icc_invalid = true; + } else if let Some(header) = payload.get(12..14) { + let (Some(&sequence), Some(&total)) = (header.first(), header.get(1)) else { + icc_invalid = true; + i = end; + continue; + }; + if sequence == 0 || total == 0 || sequence > total || icc_total.is_some_and(|expected| expected != total) { + icc_invalid = true; + } else { + icc_total = Some(total); + if let Some(slot) = icc_parts.get_mut(usize::from(sequence - 1)) { + if slot.is_some() { + icc_invalid = true; + } else if let Some(data) = payload.get(14..) { + *slot = Some(data); + } else { + icc_invalid = true; + } + } else { + icc_invalid = true; + } + } + } else { + icc_invalid = true; + } + } + 0xed if payload.starts_with(b"Photoshop 3.0\0") && out.iptc.is_none() => out.iptc = photoshop_iptc(&payload[14..]), + _ => {} + } + i = end; + } + if let Some(total) = icc_total { + let mut profile_len = 0usize; + for chunk in icc_parts.iter().take(usize::from(total)) { + let Some(bytes) = chunk else { + icc_invalid = true; + break; + }; + let Some(next_len) = profile_len.checked_add(bytes.len()) else { + icc_invalid = true; + break; + }; + profile_len = next_len; + } + let maximum_len = usize::from(total).checked_mul(65_519); + if maximum_len.is_none_or(|maximum| profile_len > maximum) { + icc_invalid = true; + } + if !icc_invalid { + let mut profile = Vec::with_capacity(profile_len); + for bytes in icc_parts.iter().take(usize::from(total)).flatten() { + profile.extend_from_slice(bytes); + } + out.icc = Some(profile); + } + } + out.xmp_extended = out.xmp.as_deref().and_then(extended_guid).and_then(|guid| reassemble_extended(&guid, ext)); + out +} + +/// The most bytes an extended XMP packet may claim: far more than any real one carries. +const MAX_EXTENDED_XMP: u32 = 64 << 20; + +/// The GUID the main XMP packet names in `xmpNote:HasExtendedXMP` (32 upper-case hex digits, the +/// MD5 of the extended packet), as an attribute or an element. `None` when it names none. +fn extended_guid(xmp: &str) -> Option<[u8; 32]> { + let at = xmp.find("HasExtendedXMP")?; + let rest = xmp.get(at..)?.get("HasExtendedXMP".len()..)?; + let rest = rest.trim_start_matches(|c: char| c.is_whitespace() || matches!(c, '=' | '"' | '\'' | '>')); + let guid = <[u8; 32]>::try_from(rest.as_bytes().get(..32)?).ok()?; + guid.iter().all(u8::is_ascii_hexdigit).then_some(guid) +} + +/// The extended XMP packet the main packet refers to (XMP Specification Part 3, 1.1.3.1): only the +/// chunks carrying its GUID, all agreeing on the full length, which together cover that length +/// exactly once. Anything else (chunks of another packet, a gap, an overlap, a length past the +/// cap) is not that packet, and nothing of it is read. +fn reassemble_extended(guid: &[u8; 32], chunks: Vec<([u8; 32], u32, u32, &[u8])>) -> Option { + let mut mine: Vec<(u32, u32, &[u8])> = chunks.into_iter().filter(|c| c.0.eq_ignore_ascii_case(guid)).map(|c| (c.1, c.2, c.3)).collect(); + let full = mine.first()?.0; + if full == 0 || full > MAX_EXTENDED_XMP || mine.iter().any(|c| c.0 != full) { + return None; + } + mine.sort_by_key(|c| c.1); + let mut packet = Vec::with_capacity(full as usize); + for (_, off, data) in mine { + if off as usize != packet.len() { + return None; + } + packet.extend_from_slice(data); + if packet.len() > full as usize { + return None; + } + } + (packet.len() == full as usize).then(|| String::from_utf8_lossy(&packet).into_owned()) +} + +/// IPTC-IIM block (resource 0x0404) from a Photoshop image-resource stream (`8BIM` records). +fn photoshop_iptc(mut b: &[u8]) -> Option> { + while b.len() >= 12 && &b[..4] == b"8BIM" { + let id = u16::from_be_bytes([b[4], b[5]]); + let name_len = b[6] as usize; + let name_total = (1 + name_len).next_multiple_of(2); + let size_at = 6 + name_total; + let size = u32::from_be_bytes(b.get(size_at..size_at + 4)?.try_into().ok()?) as usize; + let data_at = size_at + 4; + let data = b.get(data_at..data_at.checked_add(size)?)?; + if id == 0x0404 { + return Some(data.to_vec()); + } + b = b.get(data_at + size.next_multiple_of(2)..)?; + } + None +} + +/// PNG chunks: `eXIf`, uncompressed `iTXt` XMP. +pub fn png_chunks(b: &[u8]) -> Embedded { + let mut out = Embedded::default(); + let mut i = 8usize; + while i + 12 <= b.len() { + let len = u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) as usize; + let typ = &b[i + 4..i + 8]; + let Some(data) = b.get(i + 8..(i + 8).saturating_add(len)) else { break }; + match typ { + b"eXIf" => out.exif = Some(crate::strip_exif_header(data).to_vec()), + b"iTXt" if data.starts_with(b"XML:com.adobe.xmp\0") => { + // keyword\0 compression-flag compression-method language\0 translated\0 text + let rest = &data[18..]; + if rest.len() >= 2 && rest[0] == 0 { + let rest = &rest[2..]; + let mut parts = rest.splitn(3, |&c| c == 0); + let (_, _, text) = (parts.next(), parts.next(), parts.next()); + if let Some(t) = text { + out.xmp = Some(String::from_utf8_lossy(t).into_owned()); + } + } + } + b"IEND" => break, + _ => {} + } + i += 12 + len; + } + out +} + +/// WebP RIFF chunks `EXIF`, `XMP `, `ICCP`. +pub fn webp_chunks(b: &[u8]) -> Embedded { + let mut out = Embedded::default(); + let mut i = 12usize; + while i + 8 <= b.len() { + let id = &b[i..i + 4]; + let len = u32::from_le_bytes([b[i + 4], b[i + 5], b[i + 6], b[i + 7]]) as usize; + let Some(data) = b.get(i + 8..(i + 8).saturating_add(len)) else { break }; + match id { + b"EXIF" => out.exif = Some(crate::strip_exif_header(data).to_vec()), + b"XMP " => out.xmp = Some(String::from_utf8_lossy(data).into_owned()), + b"ICCP" => out.icc = Some(data.to_vec()), + _ => {} + } + i += 8 + len + (len & 1); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::exif::tests::sample_exif; + use lcc_tiff::ByteOrder; + + fn seg(marker: u8, payload: &[u8]) -> Vec { + let mut v = vec![0xff, marker]; + v.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes()); + v.extend_from_slice(payload); + v + } + + fn icc_seg(sequence: u8, total: u8, data: &[u8]) -> Vec { + let mut payload = b"ICC_PROFILE\0".to_vec(); + payload.extend_from_slice(&[sequence, total]); + payload.extend_from_slice(data); + seg(0xe2, &payload) + } + + fn jpeg_with_icc(parts: &[Vec]) -> Vec { + let mut jpeg = vec![0xff, 0xd8]; + let packet = crate::write_xmp(&crate::Metadata { title: Some("retained".into()), ..Default::default() }, None); + let mut xmp = XMP_SIG.to_vec(); + xmp.extend_from_slice(packet.as_bytes()); + jpeg.extend_from_slice(&seg(0xe1, &xmp)); + for part in parts { + jpeg.extend_from_slice(part); + } + jpeg.extend_from_slice(&[0xff, 0xda, 0, 2]); + jpeg + } + + pub(crate) fn sample_jpeg() -> Vec { + let mut j = vec![0xff, 0xd8]; + j.extend(seg(0xe0, b"JFIF\0\x01\x02\0\0\x01\0\x01\0\0")); + let mut exif = b"Exif\0\0".to_vec(); + exif.extend(sample_exif(ByteOrder::Big)); + j.extend(seg(0xe1, &exif)); + let meta = crate::Metadata { title: Some("Sunset".into()), rating: Some(4), ..Default::default() }; + let mut xmp = XMP_SIG.to_vec(); + xmp.extend(crate::write_xmp(&meta, Some("{\"exposure\":1.5}")).into_bytes()); + j.extend(seg(0xe1, &xmp)); + // ICC in two chunks, out of order + j.extend(seg(0xe2, b"ICC_PROFILE\0\x02\x02WORLD")); + j.extend(seg(0xe2, b"ICC_PROFILE\0\x01\x02HELLO")); + // IPTC + let iim = crate::iptc::tests::sample_iim(); + let mut ps = b"Photoshop 3.0\0".to_vec(); + ps.extend_from_slice(b"8BIM\x04\x0c\0\0"); + ps.extend_from_slice(&2u32.to_be_bytes()); + ps.extend_from_slice(&[1, 2]); + ps.extend_from_slice(b"8BIM\x04\x04\0\0"); + ps.extend_from_slice(&(iim.len() as u32).to_be_bytes()); + ps.extend_from_slice(&iim); + j.extend(seg(0xed, &ps)); + j.extend_from_slice(&[0xff, 0xda, 0, 2, 1, 2, 3, 0xff, 0xd9]); + j + } + + #[test] + fn jpeg_blocks() { + let j = sample_jpeg(); + let e = jpeg_segments(&j); + assert_eq!(e.icc.as_deref(), Some(&b"HELLOWORLD"[..])); + assert!(e.xmp.as_deref().unwrap().contains("Sunset")); + assert!(e.iptc.is_some()); + let m = crate::extract(&j); + assert_eq!(m.iso, Some(400)); + assert_eq!(m.title.as_deref(), Some("Sunset")); + assert_eq!(m.rating, Some(4)); // XMP overrides EXIF rating 3 + assert_eq!(m.keywords, vec!["alpha".to_string(), "beta".to_string()]); // from IPTC + assert_eq!(m.caption.as_deref(), Some("A caption")); + } + + const GUID: &[u8; 32] = b"0123456789ABCDEF0123456789ABCDEF"; + + /// A JPEG whose main packet names `named` and whose extended chunks are `(guid, full, offset, data)`. + fn jpeg_with_extended(named: Option<&[u8; 32]>, chunks: &[(&[u8; 32], u32, u32, &[u8])]) -> Vec { + let mut j = vec![0xff, 0xd8]; + let main = match named { + Some(g) => format!( + "", + std::str::from_utf8(g).unwrap() + ), + None => "".to_string(), + }; + let mut p = XMP_SIG.to_vec(); + p.extend_from_slice(main.as_bytes()); + j.extend(seg(0xe1, &p)); + for (guid, full, off, part) in chunks { + let mut p = XMP_EXT_SIG.to_vec(); + p.extend_from_slice(&guid[..]); + p.extend_from_slice(&full.to_be_bytes()); + p.extend_from_slice(&off.to_be_bytes()); + p.extend_from_slice(part); + j.extend(seg(0xe1, &p)); + } + j + } + + fn jpeg_with_orientation(exif_orientation: Option, xmp_orientation: &str) -> Vec { + let mut jpeg = vec![0xff, 0xd8]; + if let Some(orientation) = exif_orientation { + let mut exif = b"Exif\0\0".to_vec(); + exif.extend(crate::exif::write_exif(&crate::Metadata { orientation: Some(orientation), ..Default::default() })); + jpeg.extend(seg(0xe1, &exif)); + } + let packet = format!( + r#""# + ); + let mut xmp = XMP_SIG.to_vec(); + xmp.extend_from_slice(packet.as_bytes()); + jpeg.extend(seg(0xe1, &xmp)); + jpeg.extend_from_slice(&[0xff, 0xd9]); + jpeg + } + + #[test] + fn embedded_xmp_orientation_requires_integral_value_and_respects_exif() { + let malformed = crate::extract(&jpeg_with_orientation(None, "6.9")); + assert_eq!(malformed.orientation, None); + + let valid_xmp = crate::extract(&jpeg_with_orientation(None, "6")); + assert_eq!(valid_xmp.orientation.map(|orientation| orientation.to_exif()), Some(6)); + + let valid_exif = crate::extract(&jpeg_with_orientation(Some(crate::Orientation::Rotate180), "6")); + assert_eq!(valid_exif.orientation.map(|orientation| orientation.to_exif()), Some(3)); + } + + #[test] + fn jpeg_invalid_iptc_time_created_allows_xmp_fallback() { + let mut data = Vec::new(); + for (dataset, value) in [(55, &b"20260101"[..]), (60, b"121314+01"), (5, b"retained title")] { + data.extend_from_slice(&[0x1c, 2, dataset]); + data.extend_from_slice(&(value.len() as u16).to_be_bytes()); + data.extend_from_slice(value); + } + let xmp = crate::write_xmp( + &crate::Metadata { + capture_time: Some(crate::DateTime { year: 2026, month: 1, day: 2, hour: 10, offset_minutes: Some(0), ..Default::default() }), + ..Default::default() + }, + None, + ); + let mut jpeg = vec![0xff, 0xd8]; + let mut payload = XMP_SIG.to_vec(); + payload.extend_from_slice(xmp.as_bytes()); + jpeg.extend_from_slice(&seg(0xe1, &payload)); + let mut resource = b"Photoshop 3.0".to_vec(); + resource.extend_from_slice(b"8BIM"); + resource.extend_from_slice(&(data.len() as u32).to_be_bytes()); + resource.extend_from_slice(&data); + if data.len() % 2 == 1 { + resource.push(0); + } + jpeg.extend_from_slice(&seg(0xed, &resource)); + jpeg.extend_from_slice(&[0xff, 0xda, 0, 2]); + assert!(embedded(&jpeg).iptc.is_some(), "raw IIM remains available"); + let m = crate::extract(&jpeg); + assert_eq!(m.capture_time.map(|time| time.to_iso()).as_deref(), Some("2026-01-02T10:00:00+00:00")); + assert_eq!(m.title.as_deref(), Some("retained title")); + } + + #[test] + fn jpeg_extended_xmp() { + let j = jpeg_with_extended(Some(GUID), &[(GUID, 10, 5, b"world"), (GUID, 10, 0, b"hello")]); + assert_eq!(jpeg_segments(&j).xmp_extended.as_deref(), Some("helloworld")); + // chunks of another packet are left out + let other = b"FEDCBA9876543210FEDCBA9876543210"; + let j = jpeg_with_extended(Some(GUID), &[(GUID, 10, 5, b"world"), (other, 3, 0, b"bad"), (GUID, 10, 0, b"hello")]); + assert_eq!(jpeg_segments(&j).xmp_extended.as_deref(), Some("helloworld")); + } + + /// What a writer moved to the extended packet (here a GPS position and a caption) is read with + /// the main packet's fields, so export's location check sees it too. + #[test] + fn extract_reads_the_referenced_extended_packet() { + let ext = r#"Long caption"#; + let (a, b) = ext.as_bytes().split_at(40); + let full = ext.len() as u32; + let j = jpeg_with_extended(Some(GUID), &[(GUID, full, 40, b), (GUID, full, 0, a)]); + let m = crate::extract(&j); + assert_eq!(m.caption.as_deref(), Some("Long caption")); + assert!(m.gps.is_some(), "{m:?}"); + // not referenced: not read + let j = jpeg_with_extended(None, &[(GUID, full, 0, ext.as_bytes())]); + assert!(crate::extract(&j).gps.is_none()); + } + + #[test] + fn jpeg_extended_xmp_is_read_only_whole_and_referenced() { + let other = b"FEDCBA9876543210FEDCBA9876543210"; + for (name, named, chunks) in [ + ("not referenced", None, vec![(GUID, 10, 0, &b"helloworld"[..])]), + ("another GUID", Some(GUID), vec![(other, 10, 0, &b"helloworld"[..])]), + ("a gap", Some(GUID), vec![(GUID, 10, 0, &b"hell"[..]), (GUID, 10, 5, b"world")]), + ("an overlap", Some(GUID), vec![(GUID, 10, 0, &b"hello"[..]), (GUID, 10, 4, b"oworld")]), + ("short", Some(GUID), vec![(GUID, 10, 0, &b"hello"[..])]), + ("past its length", Some(GUID), vec![(GUID, 4, 0, &b"hello"[..])]), + ("lengths disagree", Some(GUID), vec![(GUID, 10, 0, &b"hello"[..]), (GUID, 11, 5, b"world")]), + ("a huge length", Some(GUID), vec![(GUID, u32::MAX, 0, &b"hello"[..])]), + ] { + let j = jpeg_with_extended(named, &chunks); + assert_eq!(jpeg_segments(&j).xmp_extended, None, "{name}"); + } + } + + #[test] + fn jpeg_icc_accepts_reordered_chunks() { + let parts = [icc_seg(2, 2, b"world"), icc_seg(1, 2, b"hello")]; + let embedded = jpeg_segments(&jpeg_with_icc(&parts)); + assert_eq!(embedded.icc.as_deref(), Some(&b"helloworld"[..])); + } + + #[test] + fn jpeg_icc_rejects_incomplete_or_incoherent_chunks() { + let cases = [ + ("missing", vec![icc_seg(1, 2, b"helloworld")]), + ("duplicate", vec![icc_seg(1, 2, b"hello"), icc_seg(1, 2, b"world")]), + ("zero sequence", vec![icc_seg(0, 1, b"helloworld")]), + ("zero total", vec![icc_seg(1, 0, b"helloworld")]), + ("out of range", vec![icc_seg(2, 1, b"helloworld")]), + ("gap", vec![icc_seg(1, 3, b"hello"), icc_seg(3, 3, b"world")]), + ("inconsistent totals", vec![icc_seg(1, 2, b"hello"), icc_seg(2, 3, b"world")]), + ("short header", vec![seg(0xe2, b"ICC_PROFILE\0\x01")]), + ]; + for (name, parts) in cases { + let embedded = jpeg_segments(&jpeg_with_icc(&parts)); + assert!(embedded.icc.is_none(), "{name} ICC chunks must be rejected"); + assert!(embedded.xmp.as_deref().is_some_and(|x| x.contains("retained")), "{name}: unrelated XMP must remain readable"); + } + } + + #[test] + fn jpeg_icc_rejects_truncated_segment_and_keeps_other_metadata() { + let mut truncated = icc_seg(1, 1, b"profile"); + let declared = u16::from_be_bytes([truncated[2], truncated[3]]).saturating_add(1); + truncated[2..4].copy_from_slice(&declared.to_be_bytes()); + let mut jpeg = vec![0xff, 0xd8]; + let xmp = crate::write_xmp(&crate::Metadata { title: Some("kept".into()), ..Default::default() }, None); + let mut packet = XMP_SIG.to_vec(); + packet.extend_from_slice(xmp.as_bytes()); + jpeg.extend_from_slice(&seg(0xe1, &packet)); + jpeg.extend_from_slice(&truncated); + + let embedded = jpeg_segments(&jpeg); + assert!(embedded.icc.is_none()); + assert!(embedded.xmp.as_deref().is_some_and(|x| x.contains("kept"))); + } + + #[test] + fn png_and_webp() { + let exif = sample_exif(ByteOrder::Little); + let mut p = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut chunk = |typ: &[u8], data: &[u8]| { + p.extend_from_slice(&(data.len() as u32).to_be_bytes()); + p.extend_from_slice(typ); + p.extend_from_slice(data); + p.extend_from_slice(&[0; 4]); + }; + chunk(b"eXIf", &exif); + let mut itxt = b"XML:com.adobe.xmp\0\0\0\0\0".to_vec(); + itxt.extend(crate::write_xmp(&crate::Metadata { label: Some("Red".into()), ..Default::default() }, None).into_bytes()); + chunk(b"iTXt", &itxt); + chunk(b"IEND", &[]); + let m = crate::extract(&p); + assert_eq!(m.iso, Some(400)); + assert_eq!(m.label.as_deref(), Some("Red")); + + let mut w = b"RIFF\0\0\0\0WEBP".to_vec(); + let mut body = |id: &[u8], data: &[u8]| { + w.extend_from_slice(id); + w.extend_from_slice(&(data.len() as u32).to_le_bytes()); + w.extend_from_slice(data); + if data.len() % 2 == 1 { + w.push(0); + } + }; + body(b"VP8X", &[0; 10]); + body(b"ICCP", b"abc"); + let mut ex = b"Exif\0\0".to_vec(); + ex.extend_from_slice(&exif); + body(b"EXIF", &ex); + let e = webp_chunks(&w); + assert_eq!(e.icc.as_deref(), Some(&b"abc"[..])); + assert_eq!(crate::extract(&w).f_number, Some(2.8)); + } + + #[test] + fn tiff_file_is_its_own_exif() { + let t = sample_exif(ByteOrder::Big); + assert_eq!(crate::extract(&t).model.as_deref(), Some("Model X")); + assert_eq!(embedded(b"not an image"), Embedded::default()); + } + + #[test] + fn raf_reads_its_embedded_jpeg() { + let j = sample_jpeg(); + let mut raf = b"FUJIFILMCCD-RAW 0201FF000000TEST".to_vec(); + raf.resize(120, 0); + raf[84..88].copy_from_slice(&120u32.to_be_bytes()); + raf[88..92].copy_from_slice(&(j.len() as u32).to_be_bytes()); + raf.extend_from_slice(&j); + assert_eq!(crate::extract(&raf).iso, Some(400)); + for n in 0..raf.len() { + let _ = crate::extract(&raf[..n]); + } + } + + #[test] + fn truncated_containers_do_not_panic() { + let j = sample_jpeg(); + for n in 0..j.len() { + let _ = crate::extract(&j[..n]); + } + } +} diff --git a/crates/meta/src/jxl.rs b/crates/meta/src/jxl.rs new file mode 100644 index 0000000000..c6777b8750 --- /dev/null +++ b/crates/meta/src/jxl.rs @@ -0,0 +1,202 @@ +//! JPEG XL container metadata (ISO/IEC 18181-2): the `Exif` and `xml ` boxes, which our export +//! writes and which import used to leave unread. +//! +//! A JPEG XL file is either a bare codestream (`FF 0A`, no metadata) or an ISO base media file +//! that starts with the 12-byte `JXL ` signature box. Its metadata boxes may be stored as they +//! are, or wrapped in a `brob` box: the real box type followed by a Brotli stream of the payload. +//! An `Exif` payload starts with a four-byte big-endian `tiff_header_offset`: the TIFF header +//! begins that many bytes after the prefix. + +use crate::container::Embedded; +use crate::cr3::{be32, boxes}; + +/// Boxes read in one file (a JPEG XL container has a handful). +const MAX_BOXES: usize = 4096; + +/// The signature box every JPEG XL container starts with. +const SIGNATURE: &[u8; 12] = b"\0\0\0\x0cJXL \r\n\x87\n"; + +/// A decompressed `brob` payload larger than this is left out, like HEIF's item cap. +const MAX_BROB: usize = 32 << 20; + +/// Whether `bytes` are a JPEG XL container (a bare codestream is not: it carries no metadata). +pub fn is_jxl_container(bytes: &[u8]) -> bool { + bytes.starts_with(SIGNATURE) +} + +/// The Exif and XMP blocks of a JPEG XL container: the first `Exif` and the first `xml ` box, +/// plain or inside `brob`. Anything malformed is left out rather than reported. +pub fn metadata(bytes: &[u8]) -> Embedded { + let mut out = Embedded::default(); + if !is_jxl_container(bytes) { + return out; + } + let mut budget = MAX_BOXES; + for b in boxes(bytes, SIGNATURE.len(), bytes.len(), &mut budget) { + if out.exif.is_some() && out.xmp.is_some() { + break; + } + let Some(payload) = bytes.get(b.body..b.end) else { break }; + let (kind, payload) = match &b.kind { + b"brob" => { + let (Some(kind), Some(stream)) = (payload.get(..4), payload.get(4..)) else { continue }; + let mut k = [0u8; 4]; + k.copy_from_slice(kind); + if (&k == b"Exif" && out.exif.is_none()) || (&k == b"xml " && out.xmp.is_none()) { + let Some(data) = unbrotli(stream) else { continue }; + (k, std::borrow::Cow::Owned(data)) + } else { + continue; + } + } + k => (*k, std::borrow::Cow::Borrowed(payload)), + }; + match &kind { + b"Exif" if out.exif.is_none() => out.exif = exif_tiff(&payload).map(<[u8]>::to_vec), + b"xml " if out.xmp.is_none() => out.xmp = Some(String::from_utf8_lossy(&payload).trim_end_matches('\0').to_string()), + _ => {} + } + } + out +} + +/// The TIFF stream of an `Exif` box payload: after the four-byte prefix and the offset it holds. +/// `None` when the offset points past the payload, or at nothing. +pub(crate) fn exif_tiff(payload: &[u8]) -> Option<&[u8]> { + let skip = usize::try_from(be32(payload, 0)?).ok()?.checked_add(4)?; + payload.get(skip..).filter(|b| !b.is_empty()) +} + +/// Decompress a `brob` stream, giving up on a malformed stream or one past [`MAX_BROB`]. +fn unbrotli(stream: &[u8]) -> Option> { + use std::io::Read; + let mut out = Vec::new(); + let limit = u64::try_from(MAX_BROB).ok()?.checked_add(1)?; + brotli_decompressor::Decompressor::new(stream, 4096).take(limit).read_to_end(&mut out).ok()?; + (out.len() <= MAX_BROB).then_some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::embedded; + + fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec { + let mut v = Vec::new(); + v.extend_from_slice(&u32::try_from(payload.len() + 8).unwrap().to_be_bytes()); + v.extend_from_slice(kind); + v.extend_from_slice(payload); + v + } + + fn brob(kind: &[u8; 4], payload: &[u8]) -> Vec { + use std::io::Write; + let mut body = kind.to_vec(); + let mut w = brotli::CompressorWriter::new(&mut body, 4096, 5, 22); + w.write_all(payload).unwrap(); + drop(w); + bx(b"brob", &body) + } + + /// A container whose codestream is a stand-in: the metadata reader never parses it. + fn container(boxes: &[Vec]) -> Vec { + let mut v = SIGNATURE.to_vec(); + v.extend(bx(b"ftyp", b"jxl \0\0\0\0jxl ")); + v.extend(bx(b"jxlc", &[0xff, 0x0a, 1, 2, 3])); + for b in boxes { + v.extend_from_slice(b); + } + v + } + + /// A little-endian TIFF with one IFD0 entry: `Make` = `m`. + fn tiff(make: &str) -> Vec { + let m = format!("{make}\0"); + let mut v = b"II*\0\x08\0\0\0\x01\0\x0f\x01\x02\0".to_vec(); + v.extend_from_slice(&(m.len() as u32).to_le_bytes()); + v.extend_from_slice(&26u32.to_le_bytes()); + v.extend_from_slice(&[0; 4]); + v.extend_from_slice(m.as_bytes()); + v + } + + fn exif_box(tiff: &[u8], offset: u32) -> Vec { + let mut p = offset.to_be_bytes().to_vec(); + p.extend(std::iter::repeat_n(0u8, offset as usize)); + p.extend_from_slice(tiff); + p + } + + const XMP: &str = "Golden horizon"; + + #[test] + fn plain_exif_and_xml_boxes_are_read() { + let t = tiff("NIKON CORPORATION"); + let f = container(&[bx(b"Exif", &exif_box(&t, 0)), bx(b"xml ", XMP.as_bytes())]); + let e = embedded(&f); + assert_eq!(e.exif.as_deref(), Some(t.as_slice())); + assert_eq!(e.xmp.as_deref(), Some(XMP)); + let m = crate::extract(&f); + assert_eq!(m.make.as_deref(), Some("NIKON CORPORATION")); + assert_eq!(m.title.as_deref(), Some("Golden horizon")); + } + + #[test] + fn brotli_wrapped_boxes_are_read() { + let t = tiff("SONY"); + let f = container(&[brob(b"Exif", &exif_box(&t, 0)), brob(b"xml ", XMP.as_bytes())]); + let e = embedded(&f); + assert_eq!(e.exif.as_deref(), Some(t.as_slice())); + assert_eq!(e.xmp.as_deref(), Some(XMP)); + } + + /// The `Exif` prefix is an offset to the TIFF header, not always 0 . + #[test] + fn the_tiff_header_offset_is_honoured() { + let t = tiff("Canon"); + let f = container(&[bx(b"Exif", &exif_box(&t, 6))]); + assert_eq!(embedded(&f).exif.as_deref(), Some(t.as_slice())); + assert_eq!(crate::extract(&f).make.as_deref(), Some("Canon")); + // an offset past the payload yields nothing + let f = container(&[bx(b"Exif", &[0, 0, 0, 100, 1, 2, 3, 4])]); + assert_eq!(embedded(&f).exif, None); + assert_eq!(exif_tiff(&[0, 0, 1, 0, 1, 2, 3]), None); + assert_eq!(exif_tiff(&[0, 0]), None); + } + + #[test] + fn the_first_of_each_box_wins_and_the_bare_codestream_has_none() { + let (a, b) = (tiff("A"), tiff("B")); + let f = container(&[bx(b"Exif", &exif_box(&a, 0)), bx(b"Exif", &exif_box(&b, 0)), bx(b"xml ", b""), bx(b"xml ", b"")]); + let e = embedded(&f); + assert_eq!(e.exif.as_deref(), Some(a.as_slice())); + assert_eq!(e.xmp.as_deref(), Some("")); + assert_eq!(embedded(&[0xff, 0x0a, 1, 2, 3, 4]), Embedded::default()); + assert!(!is_jxl_container(b"\0\0\0\x0cJXL \r\n\x87")); + } + + #[test] + fn broken_files_yield_nothing_without_panicking() { + let t = tiff("X"); + let good = container(&[brob(b"Exif", &exif_box(&t, 0)), bx(b"xml ", XMP.as_bytes())]); + for n in 0..good.len() { + let _ = embedded(&good[..n]); + } + // a box that claims more than the file holds, a zero size, a 64-bit size and junk Brotli + let mut huge = bx(b"Exif", &exif_box(&t, 0)); + huge[..4].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(embedded(&container(&[huge])), Embedded::default()); + let mut zero = bx(b"xml ", b""); + zero[..4].copy_from_slice(&[0; 4]); + assert_eq!(embedded(&container(&[zero])).xmp.as_deref(), Some("")); + let mut large = vec![0, 0, 0, 1]; + large.extend_from_slice(b"xml "); + large.extend_from_slice(&(8u64 + 8 + 4).to_be_bytes()); + large.extend_from_slice(b""); + assert_eq!(embedded(&container(&[large])).xmp.as_deref(), Some("")); + assert_eq!(embedded(&container(&[bx(b"brob", b"Exif\x01\x02\x03\x04\x05"), bx(b"brob", b"xm")])), Embedded::default()); + // a brob that inflates past the cap is left out + let big = vec![0u8; MAX_BROB + 1]; + assert_eq!(embedded(&container(&[brob(b"xml ", &big)])), Embedded::default()); + } +} diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 6b5c0c8bdd..24754ab1f2 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -23,6 +23,7 @@ mod fuji; mod gpx; mod heif; mod iptc; +pub mod jxl; mod legacy; pub mod mrw; mod psd; diff --git a/crates/ui-egui/src/panels/rules_editor.rs b/crates/ui-egui/src/panels/rules_editor.rs index b37c0a9da4..82acf7c12f 100644 --- a/crates/ui-egui/src/panels/rules_editor.rs +++ b/crates/ui-egui/src/panels/rules_editor.rs @@ -77,6 +77,7 @@ fn number_value(ui: &mut egui::Ui, v: &mut Value, field: &str) { "rating" => (0.0, 5.0, 0.05), "iso" => (0.0, 409_600.0, 10.0), "aperture" => (0.0, 64.0, 0.05), + "exposureBias" => (-20.0, 20.0, 0.05), "keywordCount" | "personCount" => (0.0, 1000.0, 0.05), "longEdge" | "shortEdge" => (0.0, 100_000.0, 10.0), _ => (0.0, 100_000.0, 0.5), diff --git a/docs/lightroom-catalog-import.md b/docs/lightroom-catalog-import.md index 89758c8623..6bed3c5db9 100644 --- a/docs/lightroom-catalog-import.md +++ b/docs/lightroom-catalog-import.md @@ -184,9 +184,13 @@ public XMP documentation, 105 map (test `develop_field_coverage_over_public_crs_ eight have no equivalent and are reported: `AutoWhiteVersion`, `LensProfileSetup`, `UprightPreview`, `UprightCenterMode`, `UprightFocalLength35mm`, the pre-2012 `Defringe`, `HDRMaxValue` and `SDRBlend`. A Custom white balance on a raw the app develops relative to its as-shot look (ARW, NEF, RW2, -RAF, CR3, CR2, PEF, SRW; Lightroom names them all `RAW`) can't be taken as Kelvin: the catalog keeps no -as-shot white for Custom photos, so the photo stays As Shot and `Temperature, Tint` are reported -(issue #510; a DNG keeps the Kelvin value, and an XMP packet with `crs:AsShotTemperature` is +RAF, CR3, CR2, PEF, SRW; Lightroom names them all `RAW`) can't be taken as Kelvin on its own. A Custom +photo's develop settings keep no as-shot white, but its history does: the last +`Adobe_libraryImageDevelopHistoryStep` that says As Shot with a `Temperature` and `Tint` gives the white +the edit is the same mired shift from (read row by row, none kept, so a history table of any size gives it; a +read that fails warns and keeps the whites found so far). With no such step the photo stays As Shot and +`Temperature, Tint` are reported +(issue #510, upstream #3906; a DNG keeps the Kelvin value, and an XMP packet with `crs:AsShotTemperature` is shifted by the same mired difference, see [xmp-interop.md](xmp-interop.md)). A raw whose camera has measured colour matrices (`lcc_raw::spectral`: ILCE-7M3, D850, EOS 5D Mark III…), or whose white-balance presets give a Kelvin scale (`lcc_raw::kelvin_presets`: ILCA-99M2, ILCA-77M2…), edits in Kelvin diff --git a/docs/mcp.md b/docs/mcp.md index 3d880cd5e3..4e40f92bb4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -188,6 +188,10 @@ per-request `_meta` receive `resultType: complete` and list/read cache hints; re | `render_photo {id?, size?, format?, path?}` | Render with current settings → **image content** (PNG, or JPEG with `format: "jpeg"`), long edge `size` (default 1024); the image travels in the reply, so it also works over `--connect` to an app on another machine (`path` saves a copy on this one) | | `export {path \| dir, id? \| ids?, format?, longEdge? \| shortEdge? \| width?/height? \| megapixels? \| percent?, dontEnlarge?, ppi?, quality?, colorSpace?, bitDepth?, …}` | Full-quality render to `.png` / `.jpg` / `.tif` / `.webp` / `.avif` / `.jxl` (`jxlLossless`, `jxlEffort`, `jxlProgressive`); `format: "original"` copies the file + an XMP sidecar with the edits, `format: "dng"` writes raw photos as DNG with the edits embedded. No size param = 3000 px long edge; `longEdge: 0` = full size (cropped, native resolution); `width` + `height` fit either orientation (Lightroom's Dimensions); with `fit: "widthHeight"` they limit the width and the height as the photo stands (Width & Height); `dontEnlarge` defaults to true | +`import` validates every `paths` array entry before discovering files or importing any of them. +A non-string entry is a tool error naming its zero-based index (for example, `paths[1]`); +the whole request is refused, including in Copy and Move modes. A single path string is also accepted. + `get_develop {id}` and `render_photo {id}` use that photo without changing the selection. `set_develop`, `crop` and `export` with a supplied photo `id` end the current edit interaction, replace the selection with that one photo and make it active. Without `id`, diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index e905603768..3b4eb707dc 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -414,7 +414,7 @@ under the UI command that wraps it (a no-op error); the UI command now wins. |---|---|---|---|---|---| | LR-PRE-PANEL | Presets panel | P0 | ✅ | `cmd:panel.presets`, `cmd:preset.apply`, `crates/ui-egui/src/panels/presets.rs`, `crates/engine/src/presets_smart.rs` | grouped list with amount; starred presets also listed first in a Favorites group (in panel order; shown only when there are any; upstream #1999); folders and nested subfolders with drag-and-drop, renaming and deletion (fork #468); the panel carries the same Classic header as the panels below it and folds from it, so folded it is that bar alone and the panels below get the room (fork #75; a fold state of its own, so folding it in the column cannot leave the presets column open and empty); resting on a preset previews it in the loupe (no history entry); optional live thumbnails (⋯ → Show Thumbnails); groups start folded except the one holding the current preset, and folding is remembered in ui.json (2026-10-13); a preset's masks are added as Lightroom Classic does: the same preset again replaces the masks it just added, another preset or an edit makes them the photographer's; Object / Describe selections are made again per photo (`masks.recompute`) | | LR-PRE-CREATE | Create preset | P0 | ✅ | `cmd:dialog.createPreset`, `cmd:preset.create` (`groups`, `settings`), `cmd:develop.settingItems`, `cmd:preset.update`, `cmd:preset.undoUpdate`, `cmd:dialog.remember`, `cmd:dialog.recall` | name, group and a per-setting tree (each group ticks whole or opens to its single settings: Exposure in Light, Sharpening in Detail…, with a partial state), shared by New Preset, Copy, Paste Selected, Sync and Update Preset; White Balance, crop, masks, remove and red eye off by default; the ticks and the group are remembered (app store); a group typed like an existing one joins it; Update with Current Settings… opens pre-ticked with what the preset holds and can be undone from the toast's Undo button or the preset's menu; New Preset's group is a list of the user's groups with New Group… (from OneSlips) | -| LR-PRE-MANAGE | Manage presets | P1 | ✅ | `cmd:preset.delete`, `cmd:preset.favorite`, `cmd:preset.import`, `cmd:preset.export`, `cmd:preset.rename`, `cmd:preset.update`, `cmd:preset.move`, `cmd:preset.createGroup`, `cmd:preset.renameGroup`, `cmd:preset.moveGroup`, `cmd:preset.deleteGroup`, `cmd:preset.hide`, `cmd:preset.hideGroup`, `cmd:preset.restoreBuiltins`, `cmd:dialog.presetsManager`, `cmd:preset.exportXmp` | rename, update with current settings, move to a group (existing or new); folders and nested subfolders with drag-and-drop, renaming, moving and deletion (fork #468); starred presets are listed in a Favorites section on top, as in the Profile browser (issue #1999, `crates/ui-egui/src/tests_preset_favorites.rs`); Lightroom-style XMP export with AI masks, gradients, luminance ranges, mask sliders, Curve and Point Color, plus the full preset in `lc:PresetSettings` read back on import; built-in Smart Masks group (OneSlips port); Presets Manager (Photo ▸ Develop Settings ▸ Manage Presets…, a preset's menu): every preset by group, built-in ones too, with search, Favorite, At Import, Show (hidden presets leave the panel and pickers), Rename in place (built-in ones too) and Delete (asked in its row); per group Rename, Hide All / Show All and Delete (asked in its row); the user's groups first; drag a preset onto a group, or a group into another; Import…, Export User Presets…, New Group… and Restore Built-ins (names, groups and hidden built-ins as shipped); preset pickers fold their groups, star in place and show a hovered preset on the active photo beside the list (a background variant render) (from OneSlips; `crates/ui-egui/src/panels/presets_manager.rs`) | +| LR-PRE-MANAGE | Manage presets | P1 | ✅ | `cmd:preset.delete`, `cmd:preset.favorite`, `cmd:preset.import`, `cmd:preset.export`, `cmd:preset.rename`, `cmd:preset.update`, `cmd:preset.move`, `cmd:preset.createGroup`, `cmd:preset.renameGroup`, `cmd:preset.moveGroup`, `cmd:preset.deleteGroup`, `cmd:preset.copy`, `cmd:preset.deleteMany`, `cmd:preset.hide`, `cmd:preset.hideGroup`, `cmd:preset.restoreBuiltins`, `cmd:dialog.presetsManager`, `cmd:preset.exportXmp` | rename, update with current settings, move to a group (existing or new); folders and nested subfolders with drag-and-drop, renaming, moving and deletion (fork #468); starred presets are listed in a Favorites section on top, as in the Profile browser (issue #1999, `crates/ui-egui/src/tests_preset_favorites.rs`); Lightroom-style XMP export with AI masks, gradients, luminance ranges, mask sliders, Curve and Point Color, plus the full preset in `lc:PresetSettings` read back on import; built-in Smart Masks group (OneSlips port); Presets Manager (Photo ▸ Develop Settings ▸ Manage Presets…, a preset's menu): every preset by group, built-in ones too, with search, Favorite, At Import, Show (hidden presets leave the panel and pickers), Rename in place (built-in ones too) and Delete (asked in its row); per group Rename, Hide All / Show All and Delete (asked in its row); the user's groups first; drag a preset onto a group, or a group into another; Import…, Export User Presets…, New Group… and Restore Built-ins (names, groups and hidden built-ins as shipped); preset pickers fold their groups, star in place and show a hovered preset on the active photo beside the list (a background variant render) (from OneSlips; `crates/ui-egui/src/panels/presets_manager.rs`) | | LR-PRE-AMOUNT | Preset amount | P1 | ✅ | `cmd:preset.apply` (`amount` 0–200) | scales slider deltas from the pre-preset settings; curves blend per point; discrete values (profile, treatment, switches) take the preset's above 0 % (2026-10-14, #37) | | LR-PRE-ADAPTIVE | Adaptive presets | P2 | ⬜ | | | | LR-PRE-PREMIUM | Built-in presets (own) | P2 | ✅ | `crates/engine/src/presets.rs` | 41 own-authored presets in 10 groups (Color, Film, B&W incl. toners, Portrait, Landscape, Urban, Food, Seasons, Vintage, Style) | @@ -757,7 +757,7 @@ From `06-shortcuts.md` part 1. Evidence is our binding; conflicts are explained | KEY-ERASE | Erase while held — ⌥ | P0 | ✅ | `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/panels/masking.rs` | ⌥ while painting flips Add ↔ Erase for that stroke; Add/Erase buttons too | | KEY-RATEADVANCE | Rate and advance — ⇧0…5 | P1 | ✅ | `crates/ui-egui/src/shortcuts.rs` → `cmd:photo.rate` (`advance`) | | | KEY-FLAGADVANCE | Flag and advance — ⇧Z / ⇧X / ⇧U | P1 | ✅ | `cmd:photo.flag` (`advance`), `crates/ui-egui/src/shortcuts.rs` | Shift+P / Shift+Z pick, Shift+X reject, Shift+U clear in every photo view (grids, Detail and its filmstrip, Compare, Survey); exactly one step with Auto Advance enabled; the last photo stays put | -| KEY-NEXTPREV | Next / previous — → / ←; above / below — ↑ / ↓ | P0 | ✅ | `cmd:library.next`, `cmd:library.previous`, `cmd:library.up`, `cmd:library.down` | ↑ / ↓ go to the cell above / below in the grids (nearest by position in justified rows; the top / bottom row stays put), one photo in the filmstrip (issue #1171); no vim keys by default (H, J, K, L are taken), but they can be assigned in the keyboard shortcuts editor | +| KEY-NEXTPREV | Next / previous — → / ←; above / below — ↑ / ↓ | P0 | ✅ | `cmd:library.next`, `cmd:library.previous`, `cmd:library.up`, `cmd:library.down`, `cmd:library.nextUnrated`, `cmd:library.prevUnrated` | ⌘⌥→ / ⌘⌥← jump to the next / previous unrated photo, wrapping round, the selection kept (upstream #3904); ↑ / ↓ go to the cell above / below in the grids (nearest by position in justified rows; the top / bottom row stays put), one photo in the filmstrip (issue #1171); no vim keys by default (H, J, K, L are taken), but they can be assigned in the keyboard shortcuts editor | | KEY-BA-CYCLE | Before/after — Y | P0 | ✅ | `cmd:view.beforeAfter` | toggles side by side (no cycling) | | KEY-BA-TOPBOTTOM | Before/after top/bottom — ⌥Y | P1 | ✅ | `cmd:view.beforeAfterTopBottom`, `cmd:view.beforeAfterSplitTopBottom` | ⌥Y, ⇧⌥Y | | KEY-BA-SPLIT | Split before/after — ⇧Y | P0 | ✅ | `cmd:view.beforeAfterSplit` | | @@ -797,7 +797,7 @@ PLAN.md §2 carry the status of that survey ("unverified" where it said so) unti | LRC-LIB-SURVEY | Survey view | P2 | ✅ | `cmd:view.survey` | N | | LRC-LIB-REFVIEW | Reference view | P2 | ✅ | `cmd:view.reference`, `cmd:photo.setReference`, `crates/ui-egui/src/panels/compare.rs` (`show_reference`) | View ▸ Before/After ▸ Reference View (⇧R): the reference photo beside the active one (edited with the Edit panel); photo menu ▸ Set as Reference Photo | | LRC-LIB-CATALOG-PANEL | Catalog sets | P1 | 🟡 | `cmd:library.source` (`missing`, `previousImport`, `previousExport`, `quickCollection`), `cmd:library.showQuickCollection`, `cmd:album.clearQuick`, `cmd:album.saveQuick` | all, Quick Collection (with count; ⌘B shows it, ⌥⌘B clears it, ⌘⇧B saves it as an album and clears it, one undo step), previous import (the latest import batch), recently added, picks, recently deleted, missing photos (when any), previous export (`previousExport`: the photos of the last export) | -| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/engine/src/capture_one_catalog.rs`, `crates/ui-egui/src/lightroom_destination.rs`, `crates/ui-egui/src/tests_lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; MAIN pages are read from the file on demand with no whole-file size cap or allocation, so catalogs over 1 GiB import (upstream #798/#1819); the committed WAL is streamed into a compact page index (1 GiB, 4,000,000 frames); MAIN is bounded to 16,777,216 pages, each B-tree walk to 4,000,000 pages, records to 64 MiB, XMP packets to 16 MiB; close Lightroom and all catalog writers first (metadata/header/companion checks are best-effort, not a transactional snapshot, and a source that fails or changes mid-read fails the import); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, smart collections as smart albums when every rule has an equivalent (rating, pick, label, edited, ISO/focal length/aperture, keyword/filename/camera/lens/title/caption/location text rules, capture / edit date rules (incl. today, yesterday, this week / month / year), collection-name rules resolved to the imported albums, nested all/any/none groups; otherwise current membership with the reason reported), folder stacks (order and collapsed state), virtual copies, mapped develop settings, develop history replayed as History (named steps, oldest first, unreadable steps warned), snapshots as Versions (named, unreadable ones warned), 105 of the 113 flat `crs:` fields of Adobe's public XMP docs mapped (`develop_field_coverage_over_public_crs_fields`); stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); the large develop, history, snapshot and metadata tables are streamed row by row with no row or payload cap (issue #1234), tables kept whole are capped at 1,000,000 rows and 256 MiB; develop settings that can't be read fail the import with a clear error rather than importing every photo unedited; archive limits/write failures and unreadable optional tables (history, snapshots, metadata) warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped, except the compressed history-step and snapshot settings of Lightroom Classic 13 and later, which are decoded (they import as History and Versions and are kept in the archive; an archive too big with them is kept without them). Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). Adobe rendering, AI data and metadata-status smart rules remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891); an image record without its file, folder or root record is left out with a warning instead of failing the import; records Lightroom marks `VIDEO` import as videos (and a re-import repairs an earlier one as one undo step). The same command reads a Capture One catalog (`.cocatalogdb`, C1-IMPORT; checked on Capture One 16.9.0): photos, variants as virtual copies, star ratings, colour tags (orange and pink without a label, warned), IPTC fields, hierarchical keywords, albums inside their projects and groups (Recent Imports, All Images and the trash left out), and for offline originals the catalog's capture time, camera and lens; the menu item, file dialog (a filter per catalog kind), windows, messages and undo step name the program; not yet: Capture One's develop settings and smart albums (warned) | +| LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/engine/src/capture_one_catalog.rs`, `crates/ui-egui/src/lightroom_destination.rs`, `crates/ui-egui/src/tests_lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; MAIN pages are read from the file on demand with no whole-file size cap or allocation, so catalogs over 1 GiB import (upstream #798/#1819); the committed WAL is streamed into a compact page index (1 GiB, 4,000,000 frames); MAIN is bounded to 16,777,216 pages, each B-tree walk to 4,000,000 pages, records to 64 MiB, XMP packets to 16 MiB; close Lightroom and all catalog writers first (metadata/header/companion checks are best-effort, not a transactional snapshot, and a source that fails or changes mid-read fails the import); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, smart collections as smart albums when every rule has an equivalent (rating, pick, label, edited, ISO/focal length/aperture, keyword/filename/camera/lens/title/caption/location text rules, capture / edit date rules (incl. today, yesterday, this week / month / year), collection-name rules resolved to the imported albums, nested all/any/none groups; otherwise current membership with the reason reported), folder stacks (order and collapsed state), virtual copies, mapped develop settings, develop history replayed as History (named steps, oldest first, unreadable steps warned), snapshots as Versions (named, unreadable ones warned), 105 of the 113 flat `crs:` fields of Adobe's public XMP docs mapped (`develop_field_coverage_over_public_crs_fields`); stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); the large develop, history, snapshot and metadata tables are streamed row by row with no row or payload cap (issue #1234), tables kept whole are capped at 1,000,000 rows and 256 MiB; develop settings that can't be read fail the import with a clear error rather than importing every photo unedited; archive limits/write failures and unreadable optional tables (history, snapshots, metadata) warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped, except the compressed history-step and snapshot settings of Lightroom Classic 13 and later, which are decoded (they import as History and Versions and are kept in the archive; an archive too big with them is kept without them). Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) is shifted from the as-shot white in the photo's history (read row by row; upstream #3906), and stays As Shot and is reported when the history has none (issue #510). Adobe rendering, AI data and metadata-status smart rules remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891); an image record without its file, folder or root record is left out with a warning instead of failing the import; records Lightroom marks `VIDEO` import as videos (and a re-import repairs an earlier one as one undo step). The same command reads a Capture One catalog (`.cocatalogdb`, C1-IMPORT; checked on Capture One 16.9.0): photos, variants as virtual copies, star ratings, colour tags (orange and pink without a label, warned), IPTC fields, hierarchical keywords, albums inside their projects and groups (Recent Imports, All Images and the trash left out), and for offline originals the catalog's capture time, camera and lens; the menu item, file dialog (a filter per catalog kind), windows, messages and undo step name the program; not yet: Capture One's develop settings and smart albums (warned) | | LRC-LIB-CATALOG-UPGRADE | Older catalogs upgraded with a kept copy | P1 | ✅ | `crates/catalog/src/upgrade_backup.rs`, `crates/catalog/src/tests_upgrade_backup.rs`, `crates/engine/src/tests_library.rs`, `cmd:library.info` | before a catalog format upgrade the library is copied to `backups/before-v