mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-28 09:19:25 +01:00
Merge main (fc10a3faa6) into settings-filter-find-main
Conflicts: crates/ui-egui/locales/fi.json crates/ui-egui/locales/id.json crates/ui-egui/locales/ka.json crates/ui-egui/locales/sv.json crates/ui-egui/locales/vi.json Re-merged main after today's merges. Conflicts: crates/ui-egui/locales/fi.json crates/ui-egui/locales/id.json crates/ui-egui/locales/ka.json crates/ui-egui/locales/sv.json crates/ui-egui/locales/vi.json Docs/locale conflicts are resolved by keeping both sides. Also folds in two fixes for main so the gate passes: crates/engine/src/import/job.rs gets rustfmt (the #1995 merge left it unformatted, so every gate failed at fmt), and the Windows-only folders test joins each path component.
This commit is contained in:
commit
cfa16cd1f7
132 files changed
+7291
-638
No files matched your search
@@ -298,8 +298,11 @@ fn calibrate(args: &[String]) -> Result<(), String> {
|
||||
let result = std::fs::read(path).map_err(|e| e.to_string()).and_then(|bytes| pool.add(&bytes));
|
||||
let n = done.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||
match result {
|
||||
Ok(Some(model)) => eprintln!("[{n}/{}] {} ({model})", files.len(), path.display()),
|
||||
Ok(None) => eprintln!("[{n}/{}] {}: skipped (no usable camera JPEG or colour)", files.len(), path.display()),
|
||||
Ok(Some(added)) if added.colour => eprintln!("[{n}/{}] {} ({})", files.len(), path.display(), added.model),
|
||||
Ok(Some(added)) => {
|
||||
eprintln!("[{n}/{}] {} ({}, tone only: too dark or colourless)", files.len(), path.display(), added.model)
|
||||
}
|
||||
Ok(None) => eprintln!("[{n}/{}] {}: skipped (no usable or a black-and-white camera JPEG)", files.len(), path.display()),
|
||||
Err(e) => eprintln!("[{n}/{}] {}: {e}", files.len(), path.display()),
|
||||
}
|
||||
}
|
||||
@@ -319,11 +322,12 @@ fn calibrate(args: &[String]) -> Result<(), String> {
|
||||
Ok(profile) => {
|
||||
let path = lightcraft_engine::camera_profiles::save(&profile, &dir)?;
|
||||
println!(
|
||||
"{}: {} photos, {} colour pairs, hue/saturation table {} → {}",
|
||||
"{}: {} photos, {} colour pairs, hue/saturation table {}, tone curve {} → {}",
|
||||
profile.model,
|
||||
profile.files,
|
||||
profile.samples,
|
||||
profile.hue_sat.is_some(),
|
||||
profile.tone.is_some(),
|
||||
path.display()
|
||||
);
|
||||
written += 1;
|
||||
|
||||
@@ -132,6 +132,7 @@ impl WireJob {
|
||||
proof: None,
|
||||
window: self.window.map(|[x, y, w, h]| lightcraft_engine::pipeline::PixelWindow { x, y, w, h }),
|
||||
display: None,
|
||||
downscale: lightcraft_engine::pipeline::Downscale::Smooth,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+192
-1
@@ -1,7 +1,8 @@
|
||||
//! Lookups derived from the catalog's own data, so questions asked once per photo of a big library
|
||||
//! don't scan a list each time: which stack a photo is in, whether a regular album holds it, which
|
||||
//! photos have their file in a folder, which have a file of a given name, which photos have the same
|
||||
//! content.
|
||||
//! content, the lower-cased text the free-text search reads, and the text a smart album's Text rule
|
||||
//! reads (each made for every photo the first time it is needed for every photo).
|
||||
//!
|
||||
//! They are never saved (the on-disk format is unchanged). Each is built on first use from what
|
||||
//! the catalog holds, so a catalog read from a snapshot, replayed from the journal or cloned starts
|
||||
@@ -13,6 +14,7 @@
|
||||
//! is kept up to date, and the photos with a photo's content touched, by the ops that change a
|
||||
//! photo's content as the library sees it, once a rule has built it or while a smart album asks
|
||||
//! about contents ([`Catalog::follows_contents`], [`Catalog::content_moved`]).
|
||||
//! The two texts follow every op that changes a photo's fields, and the photo moving to another place in memory.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::OnceLock;
|
||||
@@ -37,6 +39,10 @@ pub(crate) struct Indexes {
|
||||
/// File name, lower-cased ([`file_name_index_key`]) → the photos whose file has it (same
|
||||
/// states as `folders`).
|
||||
names: OnceLock<HashMap<String, HashSet<PhotoId>>>,
|
||||
/// Photo → its lower-cased searchable text ([`PhotoText`]), for the free-text search.
|
||||
search: OnceLock<ByPhoto<PhotoText>>,
|
||||
/// Photo → the lower-cased text a smart album's Text rule looks through ([`crate::rules::rule_text`]).
|
||||
rule_text: OnceLock<ByPhoto<RuleText>>,
|
||||
}
|
||||
|
||||
/// A copy builds its own when asked (copies are made to be saved, not queried).
|
||||
@@ -93,6 +99,34 @@ impl Indexes {
|
||||
}
|
||||
}
|
||||
|
||||
/// Photo `id` is `p` now (`None`: it is gone): the text kept for it is made again.
|
||||
pub(crate) fn text_changed(&mut self, id: PhotoId, p: Option<&Photo>) {
|
||||
if let Some(m) = self.search.get_mut() {
|
||||
match p {
|
||||
Some(p) => m.insert(id, PhotoText::of(p)),
|
||||
None => m.remove(&id),
|
||||
};
|
||||
}
|
||||
if let Some(m) = self.rule_text.get_mut() {
|
||||
match p {
|
||||
Some(p) => m.insert(id, RuleText::of(p)),
|
||||
None => m.remove(&id),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Photo `id` is about to be changed in place, at `p`: an edit of a photo that others hold
|
||||
/// (`Arc::make_mut`) puts it at another address, which its text follows.
|
||||
pub(crate) fn text_moved(&mut self, id: PhotoId, p: &Photo) {
|
||||
let at = addr(p);
|
||||
if let Some(t) = self.search.get_mut().and_then(|m| m.get_mut(&id)) {
|
||||
t.at = at;
|
||||
}
|
||||
if let Some(t) = self.rule_text.get_mut().and_then(|m| m.get_mut(&id)) {
|
||||
t.at = at;
|
||||
}
|
||||
}
|
||||
|
||||
/// Photo `id` had content `old` and has `new` now (`None`: none the library counts).
|
||||
fn content_changed(&mut self, id: PhotoId, old: Option<&str>, new: Option<String>) {
|
||||
let Some(m) = self.contents.get_mut() else { return };
|
||||
@@ -129,6 +163,135 @@ impl Indexes {
|
||||
}
|
||||
}
|
||||
|
||||
/// A map from photos, for a pass over the library that asks about each one in id order.
|
||||
type ByPhoto<T> = HashMap<PhotoId, T, std::hash::BuildHasherDefault<IdHasher>>;
|
||||
|
||||
/// Hashes a photo id as itself in the table's low bits, which is where the table looks first, so
|
||||
/// ids that follow each other sit next to each other and a pass in id order walks it in order
|
||||
/// rather than jumping about (a pass over 300 000 photos spent most of its time on that). The top
|
||||
/// bits, which tag an entry in the table, are mixed so entries still tell each other apart.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct IdHasher(u64);
|
||||
|
||||
impl std::hash::Hasher for IdHasher {
|
||||
fn finish(&self) -> u64 {
|
||||
self.0 ^ (self.0.wrapping_mul(0x9E37_79B9_7F4A_7C15) & 0xFE00_0000_0000_0000)
|
||||
}
|
||||
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
self.0 = self.0.rotate_left(8) ^ u64::from(*b);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_u64(&mut self, n: u64) {
|
||||
self.0 = n;
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `p` is in memory. The contract of the kept texts: a text is used only for the photo at the
|
||||
/// address it was made for. The catalog's own photos (`Arc<Photo>` contents) stay where they are
|
||||
/// until `Arc::make_mut` copies one that others hold, which `photo_mut` reports ([`Indexes::text_moved`]; `repair`
|
||||
/// copies them in bulk and drops every lookup instead);
|
||||
/// every op that changes a searched field makes the text again ([`Indexes::text_changed`]). A copy
|
||||
/// of a photo (a candidate tried with other values) is at another address, so it is read from its
|
||||
/// own fields, never from a text kept for the photo with its id. Only ids and addresses are
|
||||
/// compared; the address is never turned back into a reference. A catalog read from a snapshot
|
||||
/// (and then repaired) or cloned starts with no texts at all: they are made when asked.
|
||||
fn addr(p: &Photo) -> usize {
|
||||
std::ptr::from_ref(p).addr()
|
||||
}
|
||||
|
||||
/// What the free-text search looks through for one photo, lower-cased as `str::to_lowercase` does
|
||||
/// for each field alone: file name, title, caption, camera, lens, location, format, then each
|
||||
/// keyword, then the name of each person (a named face), separated by NUL. A search word may hold
|
||||
/// white space (a quoted phrase); one that holds NUL is read from the fields one by one
|
||||
/// ([`PhotoText::field_contains`]), so no word runs over a field.
|
||||
pub(crate) struct PhotoText {
|
||||
/// The address of the photo this was made from ([`addr`]).
|
||||
at: usize,
|
||||
text: Box<str>,
|
||||
}
|
||||
|
||||
impl PhotoText {
|
||||
/// The fields of `p` that the text joins before its keywords and people.
|
||||
fn fields(p: &Photo) -> [&String; 7] {
|
||||
[&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format]
|
||||
}
|
||||
|
||||
pub(crate) fn of(p: &Photo) -> PhotoText {
|
||||
let fields = Self::fields(p);
|
||||
let people = p.people();
|
||||
// (exact for ASCII, which most text is: the box takes the buffer without copying it)
|
||||
let len = fields
|
||||
.iter()
|
||||
.map(|f| f.len() + 1)
|
||||
.chain(p.meta.keywords.iter().map(|k| k.len() + 1))
|
||||
.chain(people.iter().map(|n| n.len() + 1))
|
||||
.sum::<usize>()
|
||||
.saturating_sub(1);
|
||||
let mut text = String::with_capacity(len);
|
||||
for (i, field) in fields.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
text.push('\0');
|
||||
}
|
||||
push_lowercase(&mut text, field);
|
||||
}
|
||||
for k in p.meta.keywords.iter().map(String::as_str).chain(people) {
|
||||
text.push('\0');
|
||||
push_lowercase(&mut text, k);
|
||||
}
|
||||
PhotoText { at: addr(p), text: text.into_boxed_str() }
|
||||
}
|
||||
|
||||
/// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens,
|
||||
/// location, format, a keyword or the name of a person.
|
||||
pub(crate) fn contains(&self, t: &str) -> bool {
|
||||
self.text.contains(t)
|
||||
}
|
||||
|
||||
/// [`PhotoText::contains`] read from `p`'s fields one by one, for a word that holds NUL: the joined text can't tell
|
||||
/// the NUL that separates two fields from one inside a field, and a word never runs over two fields.
|
||||
pub(crate) fn field_contains(p: &Photo, t: &str) -> bool {
|
||||
Self::fields(p)
|
||||
.into_iter()
|
||||
.map(String::as_str)
|
||||
.chain(p.meta.keywords.iter().map(String::as_str))
|
||||
.chain(p.people())
|
||||
.any(|f| f.to_lowercase().contains(t))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn text(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
}
|
||||
|
||||
/// Push `s` lower-cased as `str::to_lowercase` gives it, without a temporary string for ASCII.
|
||||
fn push_lowercase(out: &mut String, s: &str) {
|
||||
if s.is_ascii() {
|
||||
let from = out.len();
|
||||
out.push_str(s);
|
||||
if let Some(added) = out.get_mut(from..) {
|
||||
added.make_ascii_lowercase();
|
||||
}
|
||||
} else {
|
||||
out.push_str(&s.to_lowercase());
|
||||
}
|
||||
}
|
||||
|
||||
/// A photo's text for a smart album's Text rule: [`crate::rules::rule_text`].
|
||||
struct RuleText {
|
||||
at: usize,
|
||||
text: Box<str>,
|
||||
}
|
||||
|
||||
impl RuleText {
|
||||
fn of(p: &Photo) -> RuleText {
|
||||
RuleText { at: addr(p), text: crate::rules::rule_text(p).into_boxed_str() }
|
||||
}
|
||||
}
|
||||
|
||||
fn rekey(m: &mut HashMap<String, HashSet<PhotoId>>, id: PhotoId, old: Option<String>, new: Option<String>) {
|
||||
if let Some(k) = old
|
||||
&& let Some(set) = m.get_mut(&k)
|
||||
@@ -232,6 +395,34 @@ impl Catalog {
|
||||
m.get(&album).is_some_and(|s| s.contains(&photo))
|
||||
}
|
||||
|
||||
/// `p`'s lower-cased text for the free-text search, when `p` is this catalog's own photo and the
|
||||
/// text was made. `build`: make it for every photo first when it wasn't (a pass over the whole
|
||||
/// library does; testing one photo shouldn't build it for 300 000).
|
||||
pub(crate) fn search_text(&self, p: &Photo, build: bool) -> Option<&PhotoText> {
|
||||
let m = if build {
|
||||
self.index.search.get_or_init(|| self.photos.values().map(|p| (p.id, PhotoText::of(p))).collect())
|
||||
} else {
|
||||
self.index.search.get()?
|
||||
};
|
||||
m.get(&p.id).filter(|t| t.at == addr(p))
|
||||
}
|
||||
|
||||
/// [`Catalog::search_text`] for a smart album's Text rule: the lower-cased, trimmed text of
|
||||
/// [`crate::rules::rule_text`], made for every photo on first use (a smart album's count or
|
||||
/// view asks for it photo by photo).
|
||||
pub(crate) fn rule_text_of(&self, p: &Photo) -> Option<&str> {
|
||||
let m = self.index.rule_text.get_or_init(|| self.photos.values().map(|p| (p.id, RuleText::of(p))).collect());
|
||||
let t = m.get(&p.id)?;
|
||||
(t.at == addr(p)).then_some(&*t.text)
|
||||
}
|
||||
|
||||
/// Whether the Text rules' text has been made (asking for it makes it, so a test cannot look with
|
||||
/// [`Catalog::rule_text_of`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn rule_text_made(&self) -> bool {
|
||||
self.index.rule_text.get().is_some()
|
||||
}
|
||||
|
||||
/// Content → its photos, by the index (built on first use).
|
||||
fn contents(&self) -> &HashMap<String, Vec<PhotoId>> {
|
||||
self.index.contents.get_or_init(|| {
|
||||
|
||||
@@ -688,7 +688,10 @@ impl Catalog {
|
||||
|
||||
fn photo_mut(&mut self, id: PhotoId) -> Result<&mut Photo> {
|
||||
self.touch(id);
|
||||
self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id))
|
||||
let p = self.photos.get_mut(&id).map(Arc::make_mut).ok_or(CatalogError::NoPhoto(id))?;
|
||||
// (`Arc::make_mut` copies a photo others hold: the text kept for it goes with the copy)
|
||||
self.index.text_moved(id, p);
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// The op being applied changes photo `id` (or adds or removes it).
|
||||
@@ -917,11 +920,13 @@ impl Catalog {
|
||||
self.next_photo = self.next_photo.max(id.0.saturating_add(1));
|
||||
self.index.file_changed(id, None, file_path(&photo.source));
|
||||
self.photos.insert(id, Arc::new(*photo));
|
||||
self.index.text_changed(id, self.photos.get(&id).map(|p| &**p));
|
||||
Op::RemovePhoto { id }
|
||||
}
|
||||
Op::RemovePhoto { id } => {
|
||||
let p = self.photos.remove(&id).ok_or(CatalogError::NoPhoto(id))?;
|
||||
self.index.file_changed(id, file_path(&p.source), None);
|
||||
self.index.text_changed(id, None);
|
||||
// album membership is restored by the batch the engine builds (see `delete_permanently`)
|
||||
Op::AddPhoto { photo: Box::new((*p).clone()) }
|
||||
}
|
||||
@@ -949,7 +954,9 @@ impl Catalog {
|
||||
}
|
||||
Op::SetMeta { id, meta } => {
|
||||
let p = self.photo_mut(id)?;
|
||||
Op::SetMeta { id, meta: Box::new(std::mem::replace(&mut p.meta, *meta)) }
|
||||
let old = std::mem::replace(&mut p.meta, *meta);
|
||||
self.index.text_changed(id, self.photos.get(&id).map(|p| &**p));
|
||||
Op::SetMeta { id, meta: Box::new(old) }
|
||||
}
|
||||
Op::SetDeleted { id, deleted } => {
|
||||
let p = self.photo_mut(id)?;
|
||||
@@ -1137,7 +1144,9 @@ impl Catalog {
|
||||
let p = self.photo_mut(id)?;
|
||||
let old_name = std::mem::replace(&mut p.file_name, file_name);
|
||||
let old_format = format.map(|f| std::mem::replace(&mut p.format, f));
|
||||
Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format }
|
||||
let old = Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format };
|
||||
self.index.text_changed(id, self.photos.get(&id).map(|p| &**p));
|
||||
old
|
||||
}
|
||||
Op::SetContent { id, width, height, file_size, content_hash, preview_only, preview_checked } => {
|
||||
let p = self.photo_mut(id)?;
|
||||
@@ -1171,7 +1180,9 @@ impl Catalog {
|
||||
}
|
||||
let p = self.photo_mut(id)?;
|
||||
let old_name = std::mem::replace(&mut p.file_name, file_name);
|
||||
Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) }
|
||||
let old = Op::SetFile { id, file_name: old_name, source: std::mem::replace(&mut p.source, source) };
|
||||
self.index.text_changed(id, self.photos.get(&id).map(|p| &**p));
|
||||
old
|
||||
}
|
||||
Op::SetLabelName { label, name } => {
|
||||
let name = name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty());
|
||||
@@ -1287,6 +1298,10 @@ impl Catalog {
|
||||
/// wrote).
|
||||
pub fn repair(&mut self) -> Vec<String> {
|
||||
let mut changed = Vec::new();
|
||||
// Photos others hold are copied below (`Arc::make_mut`), which moves them in memory and strands the text kept
|
||||
// for their address ([`index::Indexes`]), and stacks and albums change outside `apply`: nothing derived is
|
||||
// kept across a repair, and the lookups are built again when asked.
|
||||
self.index = index::Indexes::default();
|
||||
// Segmentation grids shared by the snapshot this was read from (issue #2154): each
|
||||
// reference takes its grid's data, and the table is not kept — a live catalog always
|
||||
// stores the data inline, so masks render and serialize without the snapshot's table.
|
||||
@@ -1397,9 +1412,8 @@ impl Catalog {
|
||||
self.next_stack = self.next_stack.max(stack);
|
||||
}
|
||||
if !changed.is_empty() {
|
||||
// stacks and albums changed outside `apply`: the lookups are built again when asked
|
||||
self.index = index::Indexes::default();
|
||||
// (and what was worked out from the albums, the guard of [`Self::keeps_written_order`] too)
|
||||
// stacks and albums changed outside `apply`: what was worked out from the albums is made again (the guard of
|
||||
// [`Self::keeps_written_order`] too)
|
||||
self.plans = PlansMemo::default();
|
||||
}
|
||||
changed
|
||||
@@ -1622,6 +1636,8 @@ mod tests_rule_order;
|
||||
#[cfg(test)]
|
||||
mod tests_scale;
|
||||
#[cfg(test)]
|
||||
mod tests_search_text;
|
||||
#[cfg(test)]
|
||||
mod tests_tally;
|
||||
#[cfg(test)]
|
||||
mod tests_torn_append;
|
||||
+48
-17
@@ -152,6 +152,10 @@ fn shuffle_rank(seed: u64, id: PhotoId) -> u64 {
|
||||
pub(crate) struct Prepared {
|
||||
root: Option<String>,
|
||||
only: Option<std::collections::HashSet<PhotoId>>,
|
||||
/// The search words ([`Filter::tokens`]).
|
||||
tokens: Vec<String>,
|
||||
/// A pass over the library, which makes the text kept for each photo when it isn't ([`Catalog::search_text`]).
|
||||
whole: bool,
|
||||
/// [`Filter::rule_set`] with its rules in the order to test them ([`crate::RuleSet::by_cost`]);
|
||||
/// `None` tests them as written.
|
||||
rules: Option<crate::RuleSet>,
|
||||
@@ -186,8 +190,8 @@ fn unquote(s: &str) -> &str {
|
||||
s.strip_prefix('"').map_or(s, |inner| inner.strip_suffix('"').unwrap_or(inner))
|
||||
}
|
||||
|
||||
fn token_matches(p: &Photo, tok: &str) -> bool {
|
||||
let t = tok.to_lowercase();
|
||||
/// Whether the word `t` (lower-cased) is in `p`, as a field of it or as plain text.
|
||||
fn token_matches(p: &Photo, t: &str, hay: &Hay) -> bool {
|
||||
// a token that starts with a quote is a phrase, even with a colon in it
|
||||
if let Some((field, quoted)) = t.split_once(':').filter(|_| !t.starts_with('"')) {
|
||||
let val = unquote(quoted);
|
||||
@@ -231,20 +235,36 @@ fn token_matches(p: &Photo, tok: &str) -> bool {
|
||||
"name" | "file" => p.file_name.to_lowercase().contains(val),
|
||||
// Not a known field: the colon is part of a plain word ("10:30", "Re:"), its value unquoted
|
||||
// (`re:"a b"` is the text `re:a b`).
|
||||
_ if val.len() != quoted.len() => text_matches(p, &format!("{field}:{val}")),
|
||||
_ => text_matches(p, &t),
|
||||
_ if val.len() != quoted.len() => hay.contains(&format!("{field}:{val}")),
|
||||
_ => hay.contains(t),
|
||||
};
|
||||
}
|
||||
text_matches(p, unquote(&t))
|
||||
hay.contains(unquote(t))
|
||||
}
|
||||
|
||||
/// Whether the lower-cased word `t` is in the file name, title, caption, camera, lens, location,
|
||||
/// format, a keyword or the name of a person (a named face) of `p`.
|
||||
fn text_matches(p: &Photo, t: &str) -> bool {
|
||||
let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format];
|
||||
hay.iter().any(|h| h.to_lowercase().contains(t))
|
||||
|| p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t))
|
||||
|| p.people().iter().any(|n| n.to_lowercase().contains(t))
|
||||
/// A photo's lower-cased text for the free-text search: the one the catalog keeps when `p` is its
|
||||
/// own photo and a pass over the library made them ([`Prepared::whole`]), else made when first asked.
|
||||
struct Hay<'a> {
|
||||
p: &'a Photo,
|
||||
cat: &'a Catalog,
|
||||
whole: bool,
|
||||
kept: std::cell::OnceCell<Option<&'a crate::index::PhotoText>>,
|
||||
own: std::cell::OnceCell<crate::index::PhotoText>,
|
||||
}
|
||||
|
||||
impl Hay<'_> {
|
||||
fn text(&self) -> &crate::index::PhotoText {
|
||||
match self.kept.get_or_init(|| self.cat.search_text(self.p, self.whole)) {
|
||||
Some(t) => t,
|
||||
None => self.own.get_or_init(|| crate::index::PhotoText::of(self.p)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `t` (lower-cased) is in one field of the photo ([`crate::index::PhotoText::contains`]): a word with NUL
|
||||
/// is read from the fields themselves, for the joined text separates them with NUL.
|
||||
fn contains(&self, t: &str) -> bool {
|
||||
if t.contains('\0') { crate::index::PhotoText::field_contains(self.p, t) } else { self.text().contains(t) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `p` has a named face region called `name` (case-insensitive).
|
||||
@@ -356,13 +376,13 @@ impl Filter {
|
||||
|
||||
pub fn matches(&self, p: &Photo, cat: &Catalog) -> bool {
|
||||
// one photo: its rules are tested as written (ordering them would cost more than it saves)
|
||||
self.matches_in(p, cat, &Prepared { root: self.library_root(), only: None, rules: None })
|
||||
self.matches_in(p, cat, &Prepared { root: self.library_root(), only: None, tokens: self.tokens(), whole: false, rules: None })
|
||||
}
|
||||
|
||||
/// [`Filter::prepare`] for testing one photo at a time, with what each needs worked out once
|
||||
/// (the `only` ids are looked through, not hashed).
|
||||
pub(crate) fn prepare_one(&self, cat: &Catalog) -> Prepared {
|
||||
Prepared { root: self.library_root(), only: None, rules: self.ordered_rules(cat) }
|
||||
Prepared { root: self.library_root(), only: None, tokens: self.tokens(), whole: false, rules: self.ordered_rules(cat) }
|
||||
}
|
||||
|
||||
/// The rule set to test, cheapest rule first: once per prepared filter, not per photo. `None`
|
||||
@@ -376,16 +396,23 @@ impl Filter {
|
||||
}
|
||||
|
||||
/// What [`Filter::matches_in`] needs worked out once for a pass over many photos rather than
|
||||
/// once per photo: the library folder's identity, the `only` ids as a set and the rules in the
|
||||
/// order to test them.
|
||||
/// once per photo: the library folder's identity, the `only` ids as a set, the search words and the
|
||||
/// rules in the order to test them.
|
||||
pub(crate) fn prepare(&self, cat: &Catalog) -> Prepared {
|
||||
Prepared {
|
||||
root: self.library_root(),
|
||||
only: (!self.only.is_empty()).then(|| self.only.iter().copied().collect()),
|
||||
tokens: self.tokens(),
|
||||
whole: true,
|
||||
rules: self.ordered_rules(cat),
|
||||
}
|
||||
}
|
||||
|
||||
/// The search words ([`search_tokens`]), lower-cased (as `str::to_lowercase` does, once per query, not once per photo).
|
||||
fn tokens(&self) -> Vec<String> {
|
||||
search_tokens(&self.text).map(str::to_lowercase).collect()
|
||||
}
|
||||
|
||||
/// [`Filter::library_folder`] as a folder identity ([`folder_key`]); `None` without a choice.
|
||||
fn library_root(&self) -> Option<String> {
|
||||
// as given: a folder may be named with spaces at its edge, and trimming would make it
|
||||
@@ -510,7 +537,11 @@ impl Filter {
|
||||
{
|
||||
return false;
|
||||
}
|
||||
search_tokens(&self.text).all(|tok| token_matches(p, tok))
|
||||
if prepared.tokens.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let hay = Hay { p, cat, whole: prepared.whole, kept: std::cell::OnceCell::new(), own: std::cell::OnceCell::new() };
|
||||
prepared.tokens.iter().all(|t| token_matches(p, t, &hay))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+34
-21
@@ -714,8 +714,37 @@ fn lower(v: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a Text rule looks through for `p`: its file name, title, caption, camera, lens, location, city,
|
||||
/// state, country, alt text, format, keywords, people and copy name, trimmed and lower-cased.
|
||||
pub(crate) fn rule_text(p: &Photo) -> String {
|
||||
let m = &p.meta;
|
||||
let all = [
|
||||
p.file_name.as_str(),
|
||||
&m.title,
|
||||
&m.caption,
|
||||
&m.camera,
|
||||
&m.lens,
|
||||
&m.location,
|
||||
&m.city,
|
||||
&m.state,
|
||||
&m.country,
|
||||
&m.alt_text,
|
||||
&p.format,
|
||||
&m.keywords.join(" "),
|
||||
&p.people().join(" "),
|
||||
p.copy_name.as_deref().unwrap_or(""),
|
||||
]
|
||||
.join(" ");
|
||||
let all = all.trim();
|
||||
if all.is_ascii() { all.to_ascii_lowercase() } else { all.to_lowercase() }
|
||||
}
|
||||
|
||||
fn text_op(op: &str, have: &str, want: &str) -> bool {
|
||||
let have = have.trim().to_lowercase();
|
||||
text_op_lowered(op, &have.trim().to_lowercase(), want)
|
||||
}
|
||||
|
||||
/// [`text_op`] for a `have` that is trimmed and lower-cased already.
|
||||
fn text_op_lowered(op: &str, have: &str, want: &str) -> bool {
|
||||
match op {
|
||||
"contains" => want.split_whitespace().all(|w| have.contains(w)),
|
||||
"notContains" => !want.split_whitespace().any(|w| have.contains(w)),
|
||||
@@ -1060,26 +1089,10 @@ impl Rule {
|
||||
"keywordCount" => num_op(op, Some(p.keyword_count() as f64), value),
|
||||
"person" => names_op(op, &p.people(), &want),
|
||||
"personCount" => num_op(op, Some(p.people().len() as f64), value),
|
||||
"text" => {
|
||||
let all = [
|
||||
p.file_name.as_str(),
|
||||
&m.title,
|
||||
&m.caption,
|
||||
&m.camera,
|
||||
&m.lens,
|
||||
&m.location,
|
||||
&m.city,
|
||||
&m.state,
|
||||
&m.country,
|
||||
&m.alt_text,
|
||||
&p.format,
|
||||
&m.keywords.join(" "),
|
||||
&p.people().join(" "),
|
||||
p.copy_name.as_deref().unwrap_or(""),
|
||||
]
|
||||
.join(" ");
|
||||
text(&all)
|
||||
}
|
||||
"text" => match cat.rule_text_of(p) {
|
||||
Some(have) => text_op_lowered(op, have, &want),
|
||||
None => text_op_lowered(op, &rule_text(p), &want),
|
||||
},
|
||||
"fileName" => text(&p.file_name),
|
||||
"extension" => text_op(op, p.extension(), want.trim_start_matches('.')),
|
||||
"duration" => num_op(op, p.duration.filter(|d| d.is_finite()), value),
|
||||
|
||||
@@ -0,0 +1,474 @@
|
||||
//! The free-text search and smart albums' Text rules read a photo's lower-cased text from a cache
|
||||
//! ([`crate::index`]) rather than lower-casing every field of every photo on every keystroke. The
|
||||
//! cache must give the matches the fields give, and follow every edit of a field it holds.
|
||||
|
||||
use lightcraft_meta::{Rect, Region, RegionKind};
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
use crate::index::PhotoText;
|
||||
|
||||
fn photo(id: u64, file: &str) -> Photo {
|
||||
Photo::new(PhotoId(id), Source::Demo { scene: 1 }, file, "JPEG", 60, 40, "2026-01-01T00:00:00")
|
||||
}
|
||||
|
||||
fn face(name: &str) -> Region {
|
||||
Region { rect: Rect { x0: 0.4, y0: 0.4, x1: 0.6, y1: 0.6 }, kind: RegionKind::Face, name: Some(name.into()), description: None }
|
||||
}
|
||||
|
||||
/// Photos whose text is hard on a lower-casing shortcut: Unicode that changes length or depends on
|
||||
/// its neighbours, a word that is only there across two fields, a colon in a plain word.
|
||||
fn library() -> Catalog {
|
||||
let mut photos = Vec::new();
|
||||
let mut p = photo(1, "IMG_0001.JPG");
|
||||
p.rating = 3;
|
||||
p.meta.camera = "Canon EOS R5".into();
|
||||
p.meta.lens = "RF24-70mm F2.8 L".into();
|
||||
p.meta.title = "Trip to Ōsaka".into();
|
||||
p.meta.caption = "Straße am Fluss".into();
|
||||
p.meta.location = "Kyōto".into();
|
||||
p.meta.keywords = vec!["Travel|Italy".into(), "Ὀδυσσεύς".into(), "Kyōto Japan".into()];
|
||||
photos.push(p);
|
||||
let mut p = photo(2, "İstanbul.jpg");
|
||||
p.meta.title = "ΣΊΣΥΦΟΣ".into();
|
||||
p.meta.caption = "Re: 10:30 meeting".into();
|
||||
p.meta.city = "Zürich".into();
|
||||
p.meta.regions = vec![face("Ana Lima")];
|
||||
photos.push(p);
|
||||
let mut p = photo(3, "plain.png");
|
||||
p.format = "PNG".into();
|
||||
photos.push(p);
|
||||
let mut p = photo(4, "abc");
|
||||
p.meta.camera = "def".into();
|
||||
p.meta.title = "Dž dž".into();
|
||||
photos.push(p);
|
||||
let mut p = photo(5, "name:colon.jpg");
|
||||
p.meta.lens = "title:trip".into();
|
||||
p.copy_name = Some("Black and White".into());
|
||||
photos.push(p);
|
||||
let mut c = Catalog::new();
|
||||
for p in photos {
|
||||
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// How the search read a word before the cache: each field lower-cased alone, for every photo.
|
||||
fn before_text_matches(p: &Photo, t: &str) -> bool {
|
||||
let hay = [&p.file_name, &p.meta.title, &p.meta.caption, &p.meta.camera, &p.meta.lens, &p.meta.location, &p.format];
|
||||
hay.iter().any(|h| h.to_lowercase().contains(t))
|
||||
|| p.meta.keywords.iter().any(|k| k.to_lowercase().contains(t))
|
||||
|| p.people().iter().any(|n| n.to_lowercase().contains(t))
|
||||
}
|
||||
|
||||
/// [`before_text_matches`] for the words the tests use: plain ones and the fields the cache serves.
|
||||
fn before_matches(p: &Photo, text: &str) -> bool {
|
||||
text.split_whitespace().all(|tok| {
|
||||
let t = tok.to_lowercase();
|
||||
match t.split_once(':') {
|
||||
Some(("camera", val)) => p.meta.camera.to_lowercase().contains(val),
|
||||
Some(("lens", val)) => p.meta.lens.to_lowercase().contains(val),
|
||||
Some(("name" | "file", val)) => p.file_name.to_lowercase().contains(val),
|
||||
Some(("rating", val)) => p.rating.to_string() == val,
|
||||
Some(("kw" | "keyword", val)) => p.meta.keywords.iter().any(|k| crate::keywords::is_under(k, val)),
|
||||
_ => before_text_matches(p, &t),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const QUERIES: &[&str] = &[
|
||||
"img",
|
||||
"IMG_0001",
|
||||
"IMG_0001.JPG",
|
||||
"canon r5",
|
||||
"CANON eos",
|
||||
"ōsaka",
|
||||
"ŌSAKA",
|
||||
"osaka",
|
||||
"straße",
|
||||
"STRASSE",
|
||||
"i̇stanbul",
|
||||
"İSTANBUL",
|
||||
"istanbul",
|
||||
"σίσυφος",
|
||||
"ΣΊΣΥΦΟΣ",
|
||||
"ς",
|
||||
"σ",
|
||||
"ὀδυσσεύς",
|
||||
"travel",
|
||||
"italy",
|
||||
"travel|italy",
|
||||
"kyōto japan",
|
||||
"kyōto",
|
||||
"10:30",
|
||||
"re:",
|
||||
"name:img",
|
||||
"NAME:IMG_0001",
|
||||
"file:plain",
|
||||
"name:",
|
||||
"camera:canon",
|
||||
"camera:r5",
|
||||
"lens:rf24",
|
||||
"lens:",
|
||||
"title:trip",
|
||||
"abcdef",
|
||||
"abc def",
|
||||
"dž",
|
||||
"rating:3 trip",
|
||||
"kw:travel ōsaka",
|
||||
"kw:travel osaka",
|
||||
"png jpeg",
|
||||
"",
|
||||
" ",
|
||||
"zzz",
|
||||
];
|
||||
|
||||
fn shown(c: &Catalog, text: &str) -> Vec<u64> {
|
||||
let f = Filter { text: text.into(), ..Default::default() };
|
||||
let mut ids: Vec<u64> = c.query(&f, &Sort::default()).into_iter().map(|id| id.0).collect();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
}
|
||||
|
||||
fn expected(c: &Catalog, text: &str) -> Vec<u64> {
|
||||
c.photos().filter(|p| !p.deleted && before_matches(p, text)).map(|p| p.id.0).collect()
|
||||
}
|
||||
|
||||
/// A search finds what the fields hold, whether it asks for one photo at a time, as a pass over the
|
||||
/// library that makes the cache, or one photo after that.
|
||||
#[test]
|
||||
fn search_matches_as_the_fields_do() {
|
||||
let c = library();
|
||||
let mut one_by_one = Vec::new();
|
||||
for q in QUERIES.iter().copied() {
|
||||
let f = Filter { text: q.into(), ..Default::default() };
|
||||
one_by_one.push(c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect::<Vec<_>>());
|
||||
}
|
||||
assert!(c.photos().all(|p| c.search_text(p, false).is_none()), "testing one photo makes no cache for the library");
|
||||
for (q, got) in QUERIES.iter().zip(&one_by_one) {
|
||||
assert_eq!(*got, expected(&c, q), "{q:?}, one photo at a time");
|
||||
}
|
||||
for q in QUERIES.iter().copied() {
|
||||
assert_eq!(shown(&c, q), expected(&c, q), "{q:?}, a pass over the library");
|
||||
}
|
||||
assert!(c.photos().all(|p| c.search_text(p, false).is_some()), "a pass made the cache");
|
||||
for q in QUERIES.iter().copied() {
|
||||
let f = Filter { text: q.into(), ..Default::default() };
|
||||
let got: Vec<u64> = c.photos().filter(|p| f.matches(p, &c)).map(|p| p.id.0).collect();
|
||||
assert_eq!(got, expected(&c, q), "{q:?}, one photo at a time, with the cache");
|
||||
}
|
||||
}
|
||||
|
||||
/// A photo that isn't the catalog's own (an edit not made yet, a candidate being tried) is read
|
||||
/// from its own fields, not from what the catalog kept for the photo with its id.
|
||||
#[test]
|
||||
fn a_copy_of_a_photo_is_read_as_it_is() {
|
||||
let c = library();
|
||||
let f = Filter { text: "ōsaka".into(), ..Default::default() };
|
||||
assert_eq!(c.count(&f), 1);
|
||||
let mut p = (**c.photo(PhotoId(1)).unwrap()).clone();
|
||||
p.meta.title = "Trip to Nara".into();
|
||||
p.meta.keywords.clear();
|
||||
p.meta.location.clear();
|
||||
assert!(!f.matches(&p, &c), "the catalog's own text says Ōsaka, this copy doesn't");
|
||||
let nara = Filter { text: "nara".into(), ..Default::default() };
|
||||
assert!(nara.matches(&p, &c));
|
||||
assert!(!nara.matches(c.photo(PhotoId(1)).unwrap(), &c));
|
||||
let rule = Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": "contains", "value": "nara"}]}))), ..Default::default() };
|
||||
assert_eq!(c.count(&rule), 0);
|
||||
assert!(rule.matches(&p, &c));
|
||||
}
|
||||
|
||||
fn rules(v: serde_json::Value) -> RuleSet {
|
||||
serde_json::from_value(v).unwrap()
|
||||
}
|
||||
|
||||
fn text_rule(op: &str, value: &str) -> Filter {
|
||||
Filter { rule_set: Some(rules(json!({"rules": [{"field": "text", "op": op, "value": value}]}))), ..Default::default() }
|
||||
}
|
||||
|
||||
/// What the cache holds is what a scan of the photos would give it, and every photo's is used.
|
||||
fn assert_current(c: &Catalog) {
|
||||
for p in c.photos() {
|
||||
let kept = c.search_text(p, false).unwrap_or_else(|| panic!("photo {}: no text kept, or kept for another place", p.id.0));
|
||||
let now = PhotoText::of(p);
|
||||
assert_eq!(kept.text(), now.text(), "photo {}", p.id.0);
|
||||
assert_eq!(c.rule_text_of(p), Some(crate::rules::rule_text(p).as_str()), "photo {}: the Text rule's text", p.id.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the caches, as the first search and the first smart album with a Text rule do.
|
||||
fn warm(c: &Catalog) {
|
||||
c.count(&Filter { text: "x".into(), ..Default::default() });
|
||||
c.count(&text_rule("contains", "x"));
|
||||
assert_current(c);
|
||||
}
|
||||
|
||||
fn found(c: &Catalog, text: &str) -> usize {
|
||||
c.count(&Filter { text: text.into(), ..Default::default() })
|
||||
}
|
||||
|
||||
fn found_by_rule(c: &Catalog, text: &str) -> usize {
|
||||
c.count(&text_rule("contains", text))
|
||||
}
|
||||
|
||||
/// An edit of each field that is searched puts the new text in the cache and takes the old one out,
|
||||
/// through the op, its inverse and a batch that fails and is taken back.
|
||||
#[test]
|
||||
fn the_cache_follows_every_field_that_is_searched() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let id = PhotoId(3);
|
||||
let edit = |c: &mut Catalog, set: &dyn Fn(&mut Meta)| {
|
||||
let mut meta = c.photo(id).unwrap().meta.clone();
|
||||
set(&mut meta);
|
||||
c.apply(Op::SetMeta { id, meta: Box::new(meta) }).unwrap()
|
||||
};
|
||||
type Set = fn(&mut Meta, &str);
|
||||
let fields: [(&str, Set); 6] = [
|
||||
("title", |m, v| m.title = v.into()),
|
||||
("caption", |m, v| m.caption = v.into()),
|
||||
("camera", |m, v| m.camera = v.into()),
|
||||
("lens", |m, v| m.lens = v.into()),
|
||||
("location", |m, v| m.location = v.into()),
|
||||
("keywords", |m, v| m.keywords = vec![v.into()]),
|
||||
];
|
||||
for (n, (field, set)) in fields.into_iter().enumerate() {
|
||||
let word = format!("Zq{n}x");
|
||||
let before = found(&c, &word);
|
||||
let undo = edit(&mut c, &|m| set(m, &word));
|
||||
assert_eq!((before, found(&c, &word)), (0, 1), "{field}: found after the edit");
|
||||
assert_eq!(found_by_rule(&c, &word.to_lowercase()), 1, "{field}: the Text rule");
|
||||
assert_current(&c);
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!(found(&c, &word), 0, "{field}: gone after the undo");
|
||||
assert_current(&c);
|
||||
}
|
||||
// the fields only Text rules read
|
||||
let rule_fields: [(&str, Set); 3] =
|
||||
[("city", |m, v| m.city = v.into()), ("state", |m, v| m.state = v.into()), ("country", |m, v| m.country = v.into())];
|
||||
for (n, (field, set)) in rule_fields.into_iter().enumerate() {
|
||||
let word = format!("zr{n}y");
|
||||
let undo = edit(&mut c, &|m| set(m, &word));
|
||||
assert_eq!((found_by_rule(&c, &word), found(&c, &word)), (1, 0), "{field}");
|
||||
assert_current(&c);
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!(found_by_rule(&c, &word), 0, "{field}: gone after the undo");
|
||||
}
|
||||
let undo = edit(&mut c, &|m| m.alt_text = "zalt".into());
|
||||
assert_eq!(found_by_rule(&c, "zalt"), 1);
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!(found_by_rule(&c, "zalt"), 0);
|
||||
let undo = edit(&mut c, &|m| m.regions = vec![face("Zed Person")]);
|
||||
assert_eq!(found_by_rule(&c, "zed person"), 1, "a person named on a face");
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!(found_by_rule(&c, "zed person"), 0);
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_follows_a_file_name_and_a_format() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let id = PhotoId(3);
|
||||
let source = Source::Demo { scene: 1 };
|
||||
let undo = c.apply(Op::SetFile { id, file_name: "Renamed_0042.PNG".into(), source: source.clone() }).unwrap();
|
||||
assert_eq!((found(&c, "renamed_0042"), found(&c, "plain"), found(&c, "name:renamed")), (1, 0, 1));
|
||||
assert_eq!((found_by_rule(&c, "renamed_0042"), found_by_rule(&c, "plain")), (1, 0));
|
||||
assert_current(&c);
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!((found(&c, "renamed_0042"), found(&c, "plain")), (0, 1));
|
||||
assert_current(&c);
|
||||
|
||||
let undo = c.apply(Op::Relink { id, file_name: "Moved.TIF".into(), source: source.clone(), format: Some("TIFF".into()) }).unwrap();
|
||||
assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (1, 1, 0));
|
||||
assert_eq!((found_by_rule(&c, "moved"), found_by_rule(&c, "tiff"), found_by_rule(&c, "png")), (1, 1, 0));
|
||||
assert_current(&c);
|
||||
c.apply(undo).unwrap();
|
||||
assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (0, 0, 1));
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
/// A photo that comes or goes (an import, a virtual copy, a permanent delete and its undo) does
|
||||
/// too, and a virtual copy's name is read by a Text rule.
|
||||
#[test]
|
||||
fn the_cache_follows_photos_that_come_and_go() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let mut copy = (**c.photo(PhotoId(1)).unwrap()).clone();
|
||||
copy.id = PhotoId(9);
|
||||
copy.copy_of = Some(PhotoId(1));
|
||||
copy.meta = Default::default();
|
||||
copy.copy_name = Some("Zcopy Name".into());
|
||||
copy.file_name = "Zfresh.jpg".into();
|
||||
let undo = c.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap();
|
||||
assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy"), found(&c, "zcopy")), (1, 1, 0));
|
||||
assert_current(&c);
|
||||
let redo = c.apply(undo).unwrap();
|
||||
assert_eq!((found(&c, "zfresh"), found_by_rule(&c, "zcopy")), (0, 0));
|
||||
assert_current(&c);
|
||||
c.apply(redo).unwrap();
|
||||
assert_eq!(found(&c, "zfresh"), 1);
|
||||
assert_current(&c);
|
||||
let removed = c.apply(Op::RemovePhoto { id: PhotoId(1) }).unwrap();
|
||||
assert_eq!(found(&c, "ōsaka"), 0);
|
||||
assert_current(&c);
|
||||
c.apply(removed).unwrap();
|
||||
assert_eq!(found(&c, "ōsaka"), 1);
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
/// A batch that fails half way is taken back, and the cache with it.
|
||||
#[test]
|
||||
fn the_cache_follows_a_batch_that_fails() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone();
|
||||
meta.title = "Zbatch title".into();
|
||||
let batch = Op::Batch {
|
||||
ops: vec![
|
||||
Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) },
|
||||
Op::SetFile { id: PhotoId(3), file_name: "Zbatch.png".into(), source: Source::Demo { scene: 1 } },
|
||||
Op::SetFile { id: PhotoId(404), file_name: "gone.png".into(), source: Source::Demo { scene: 1 } },
|
||||
],
|
||||
};
|
||||
assert!(c.apply(batch).is_err());
|
||||
assert_eq!((found(&c, "zbatch"), found_by_rule(&c, "zbatch")), (0, 0));
|
||||
assert_eq!(found(&c, "plain"), 1);
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
/// An edit of a photo that something else holds (a thumbnail list, an undo step) puts it at another
|
||||
/// place in memory. The cache follows it, so a search isn't left reading every such photo from its fields.
|
||||
#[test]
|
||||
fn the_cache_follows_a_photo_that_others_hold() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let held: Vec<_> = c.photos().cloned().collect();
|
||||
for p in &held {
|
||||
c.apply(Op::SetRating { id: p.id, rating: 5 }).unwrap();
|
||||
}
|
||||
assert!(held.iter().all(|old| !std::ptr::eq(&**old, &**c.photo(old.id).unwrap())), "the edits copied the photos");
|
||||
assert_current(&c);
|
||||
assert_eq!(found(&c, "ōsaka"), 1);
|
||||
c.apply(Op::SetFile { id: PhotoId(2), file_name: "after.jpg".into(), source: Source::Demo { scene: 1 } }).unwrap();
|
||||
assert_current(&c);
|
||||
assert_eq!((found(&c, "after"), found(&c, "istanbul")), (1, 0));
|
||||
}
|
||||
|
||||
/// A catalog read from a snapshot or cloned starts with no cache and builds its own.
|
||||
#[test]
|
||||
fn a_clone_builds_its_own() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let mut copy = c.clone();
|
||||
assert!(copy.photos().all(|p| copy.search_text(p, false).is_none()));
|
||||
assert_eq!(found(©, "ōsaka"), 1);
|
||||
warm(©);
|
||||
let mut meta = copy.photo(PhotoId(1)).unwrap().meta.clone();
|
||||
meta.title = "Elsewhere".into();
|
||||
copy.apply(Op::SetMeta { id: PhotoId(1), meta: Box::new(meta) }).unwrap();
|
||||
assert_eq!((found(©, "elsewhere"), found(&c, "elsewhere")), (1, 0));
|
||||
c.apply(Op::SetRating { id: PhotoId(1), rating: 1 }).unwrap();
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
/// `repair` copies the photos others hold (`Arc::make_mut`) without reporting a change, so the cache would
|
||||
/// still keep a text for the address the retained photo has. The retained photo, changed on its own, is
|
||||
/// read from its fields, never from the text kept for the photo with its id.
|
||||
#[test]
|
||||
fn repair_keeps_no_text_for_a_photo_it_copied() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
let mut held = c.photo(PhotoId(1)).unwrap().clone();
|
||||
assert!(c.repair().is_empty(), "a sound catalog");
|
||||
assert!(!std::ptr::eq(&*held, &**c.photo(PhotoId(1)).unwrap()), "repair copied the photo");
|
||||
std::sync::Arc::make_mut(&mut held).meta.title = "Trip to Nara".into();
|
||||
let nara = Filter { text: "nara".into(), ..Default::default() };
|
||||
let osaka = Filter { text: "ōsaka".into(), ..Default::default() };
|
||||
assert!(nara.matches(&held, &c), "the retained photo's own title");
|
||||
assert!(!osaka.matches(&held, &c), "not the title it had");
|
||||
assert!(text_rule("contains", "nara").matches(&held, &c), "the Text rule reads the retained photo's own title");
|
||||
assert!(!text_rule("contains", "ōsaka").matches(&held, &c));
|
||||
warm(&c);
|
||||
assert_eq!((found(&c, "ōsaka"), found(&c, "nara")), (1, 0));
|
||||
}
|
||||
|
||||
/// The words of Text rules (not the search) read the same with the cache as without: what the fields give when each
|
||||
/// photo is read alone (a copy of a photo is not the catalog's own, so the text kept for its id is not used), and what the
|
||||
/// kept text gives.
|
||||
#[test]
|
||||
fn text_rules_match_as_the_fields_do() {
|
||||
let c = library();
|
||||
let every_op = ["contains", "notContains", "is", "isNot", "startsWith", "endsWith", "isEmpty", "isNotEmpty"];
|
||||
let values =
|
||||
["", "ōsaka", "TRIP TO", "kyōto japan", "ana lima", "zürich", "img_0001.jpg", "black and white", "ς", "i̇stanbul", "png", "re: 10:30 meeting"];
|
||||
assert!(!c.rule_text_made(), "nothing made the text yet");
|
||||
let after: Vec<Vec<usize>> = every_op.iter().map(|op| values.iter().map(|v| c.count(&text_rule(op, v))).collect()).collect();
|
||||
assert!(c.rule_text_made(), "the first rule asked made the text");
|
||||
let from_the_fields: Vec<Vec<usize>> = every_op
|
||||
.iter()
|
||||
.map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(&Photo::clone(p), &c)).count()).collect())
|
||||
.collect();
|
||||
assert_eq!(from_the_fields, after);
|
||||
assert!(after.iter().flatten().any(|&n| n > 0), "the rules found something");
|
||||
let again: Vec<Vec<usize>> =
|
||||
every_op.iter().map(|op| values.iter().map(|v| c.photos().filter(|p| text_rule(op, v).matches(p, &c)).count()).collect()).collect();
|
||||
assert_eq!(after, again);
|
||||
}
|
||||
|
||||
/// A smart album's count through the tally path (`album_contains`, one photo at a time) reads the
|
||||
/// kept text: it is made there, and an edit shows in the next count.
|
||||
#[test]
|
||||
fn a_smart_album_count_reads_the_kept_text() {
|
||||
let mut c = library();
|
||||
let mut album = Album::new(AlbumId(1), "Osaka");
|
||||
album.smart = Some(Box::new(text_rule("contains", "ōsaka")));
|
||||
c.apply(Op::AddAlbum { album }).unwrap();
|
||||
let one_by_one = |c: &Catalog| c.photos().filter(|p| c.album_contains(AlbumId(1), p)).count();
|
||||
assert!(!c.rule_text_made(), "nothing made the text yet");
|
||||
assert_eq!(one_by_one(&c), 1);
|
||||
assert!(c.rule_text_made(), "counting made the text");
|
||||
let mut meta = c.photo(PhotoId(3)).unwrap().meta.clone();
|
||||
meta.title = "Ōsaka again".into();
|
||||
c.apply(Op::SetMeta { id: PhotoId(3), meta: Box::new(meta) }).unwrap();
|
||||
assert_eq!(one_by_one(&c), 2);
|
||||
}
|
||||
|
||||
/// The kept text holds the names of the people on a photo's faces, and a quoted phrase is read as
|
||||
/// one word that never runs from one field into the next.
|
||||
#[test]
|
||||
fn the_kept_text_holds_the_people_and_a_phrase_stays_in_one_field() {
|
||||
let mut c = library();
|
||||
warm(&c);
|
||||
assert_eq!(found(&c, "ana"), 1, "a person's name is searched");
|
||||
assert_eq!(found(&c, "\"ana lima\""), 1, "a quoted name is one phrase");
|
||||
assert_eq!(found(&c, "\"lima ana\""), 0);
|
||||
assert_eq!(found(&c, "\"ōsaka straße\""), 0, "a phrase doesn't run from the title into the caption");
|
||||
assert_eq!(found(&c, "\"trip to ōsaka\""), 1, "…but fits inside one field");
|
||||
assert_eq!(found(&c, "\"Kyōto Japan\""), 1, "…or one keyword");
|
||||
// (the photo that has Ana Lima's face)
|
||||
let mut meta = c.photo(PhotoId(2)).unwrap().meta.clone();
|
||||
meta.regions = vec![face("Zed Person")];
|
||||
c.apply(Op::SetMeta { id: PhotoId(2), meta: Box::new(meta) }).unwrap();
|
||||
assert_eq!(found(&c, "\"zed person\""), 1, "a renamed person is found at once");
|
||||
assert_eq!(found(&c, "ana"), 0, "and the old name is gone");
|
||||
assert_current(&c);
|
||||
}
|
||||
|
||||
/// A word that holds NUL (a filter's text can) is looked for inside one field, as before the cache: it never matches across
|
||||
/// the NUL the cache puts between two fields, and still matches a field that holds NUL itself.
|
||||
#[test]
|
||||
fn a_word_holding_nul_never_runs_over_two_fields() {
|
||||
let mut c = Catalog::new();
|
||||
let mut p = photo(1, "a");
|
||||
p.meta.title = "b".into();
|
||||
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
let mut p = photo(2, "c\0d");
|
||||
p.meta.title = "e".into();
|
||||
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
for text in ["a\0b", "\"a\0b\"", "b\0", "\0e"] {
|
||||
assert_eq!(shown(&c, text), Vec::<u64>::new(), "{text:?}");
|
||||
}
|
||||
assert_eq!(shown(&c, "c\0d"), vec![2], "a field's own NUL is still found");
|
||||
}
|
||||
@@ -247,7 +247,7 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R
|
||||
let opts = *opts;
|
||||
// The reason a format can't be decoded lives in one place, `Format::not_decodable`.
|
||||
let unsupported = || Err(Error::Unsupported(format, format.not_decodable().unwrap_or("not decodable in this build")));
|
||||
match format {
|
||||
let d = match format {
|
||||
Format::Jpeg => jpeg::decode(bytes, &opts),
|
||||
Format::Png => png_codec::decode(bytes, &opts),
|
||||
Format::Tiff => tiff_codec::decode(bytes, &opts),
|
||||
@@ -261,7 +261,20 @@ pub fn decode_unguarded(bytes: &[u8], format: Format, opts: &DecodeOptions) -> R
|
||||
Format::Heif => heif::decode(bytes, &opts),
|
||||
Format::Avif => avif_decode::decode(bytes, &opts),
|
||||
Format::RawTiffLike | Format::RawOther => unsupported(),
|
||||
}?;
|
||||
check_has_pixels(format, &d.image)?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// An image with no pixels (a malformed header claiming zero width or height, a `w × h` that
|
||||
/// overflows, or a buffer shorter than its size) is refused, so nothing downstream sees an empty
|
||||
/// image.
|
||||
fn check_has_pixels(format: Format, image: &Rgb32f) -> Result<()> {
|
||||
let (w, h) = (image.width, image.height);
|
||||
if w == 0 || h == 0 || w.checked_mul(h).is_none_or(|n| image.data.len() < n) {
|
||||
return Err(Error::Malformed(format, "image has no pixels".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convert a decode result to linear Rec.2020 D65 (Bradford-adapted), the develop working space.
|
||||
@@ -381,4 +394,29 @@ mod checked_arithmetic_tests {
|
||||
// 300 Mpx RGBA is within the default pixel limit, so it must not be refused by sample count.
|
||||
assert_eq!(checked_sample_buf_len(20_000, 15_000, 4), Some(1_200_000_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checked_sample_buf_len_does_not_wrap_like_32_bit_usize() {
|
||||
// 65535 × 21846 × 3 = 4_295_032_830, which a 32-bit `usize` product wraps to 65_534
|
||||
assert_eq!(checked_sample_buf_len(65_535, 21_846, 3), Some(4_295_032_830));
|
||||
assert!(checked_sample_buf_len(65_535, 21_846, 3).is_some_and(|n| n > 65_534));
|
||||
}
|
||||
|
||||
fn image(width: usize, height: usize, len: usize) -> Rgb32f {
|
||||
Rgb32f { width, height, data: vec![[0.0; 3]; len] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_image_without_pixels_is_refused() {
|
||||
for (w, h, len) in [(0, 4, 0), (4, 0, 0), (usize::MAX, 2, 1), (4, 4, 15)] {
|
||||
let r = check_has_pixels(Format::Png, &image(w, h, len));
|
||||
assert!(matches!(r, Err(Error::Malformed(Format::Png, _))), "{w}x{h} with {len} pixels");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_image_with_all_pixels_is_accepted() {
|
||||
assert!(check_has_pixels(Format::Png, &image(4, 4, 16)).is_ok());
|
||||
assert!(check_has_pixels(Format::Png, &image(1, 1, 1)).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -291,6 +291,43 @@ fn thumbnail_respects_configured_source_pixel_limit() {
|
||||
assert_eq!(decode_thumbnail_with(&bytes, &opts).unwrap().image.width, 1);
|
||||
}
|
||||
|
||||
/// A header claiming zero width or height is an error, never a decoded image with no pixels
|
||||
/// (downstream filters index into it).
|
||||
#[test]
|
||||
// End-to-end no-panic check: headers claiming a zero dimension are errors. The JPEG and PNG
|
||||
// readers already refuse these; `decode_unguarded`'s own final-output guard is tested directly in
|
||||
// the crate's unit tests.
|
||||
fn zero_size_headers_are_refused() {
|
||||
let jpeg = seeds()[0].clone();
|
||||
let sof = jpeg.windows(2).position(|m| m == [0xFF, 0xC0]).unwrap();
|
||||
for at in [sof + 5, sof + 7] {
|
||||
let mut j = jpeg.clone();
|
||||
j[at..at + 2].copy_from_slice(&[0, 0]);
|
||||
assert!(decode_unguarded(&j, Format::Jpeg, &small_opts()).is_err());
|
||||
}
|
||||
let png = seeds()[1].clone();
|
||||
for at in [16, 20] {
|
||||
let mut p = png.clone();
|
||||
p[at..at + 4].copy_from_slice(&[0; 4]);
|
||||
// repair the IHDR CRC so the dimension, not the checksum, is what gets refused
|
||||
let crc = crc32(&p[12..29]);
|
||||
p[29..33].copy_from_slice(&crc.to_be_bytes());
|
||||
assert!(decode_unguarded(&p, Format::Png, &small_opts()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// CRC-32 (IEEE), as PNG chunks use.
|
||||
fn crc32(bytes: &[u8]) -> u32 {
|
||||
let mut c = !0u32;
|
||||
for &b in bytes {
|
||||
c ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
|
||||
}
|
||||
}
|
||||
!c
|
||||
}
|
||||
|
||||
fn seeds() -> &'static Vec<Vec<u8>> {
|
||||
static S: OnceLock<Vec<Vec<u8>>> = OnceLock::new();
|
||||
S.get_or_init(|| {
|
||||
|
||||
@@ -35,6 +35,7 @@ fn sources(op: &Op) -> (usize, Option<usize>) {
|
||||
match op {
|
||||
Op::Conv(c) => (c.src, c.src2),
|
||||
Op::ConvT2(c) => (c.src, None),
|
||||
Op::Add { src, src2 } => (*src, Some(*src2)),
|
||||
Op::MaxPool2 { src } | Op::DepthToSpace2 { src } => (*src, None),
|
||||
}
|
||||
}
|
||||
@@ -108,6 +109,7 @@ impl NetRunner {
|
||||
(a.channels, a.side / 2)
|
||||
}
|
||||
Op::DepthToSpace2 { .. } => (a.channels / 4, a.side.checked_mul(2).ok_or_else(|| bad("size overflow"))?),
|
||||
Op::Add { .. } => (a.channels, a.side),
|
||||
};
|
||||
let n = count(channels, side)?;
|
||||
let slot = busy
|
||||
@@ -215,6 +217,7 @@ impl NetRunner {
|
||||
&mut w.lower,
|
||||
&mut w.product,
|
||||
)?,
|
||||
Op::Add { .. } => add(a, b.ok_or_else(|| bad("Add needs two inputs"))?, shape.side, dest)?,
|
||||
Op::MaxPool2 { .. } => pool(a, shape.side, dest)?,
|
||||
Op::DepthToSpace2 { .. } => shuffle(a, shape.side, dest)?,
|
||||
}
|
||||
@@ -381,6 +384,46 @@ fn shuffle(a: &[f32], side: usize, dest: &mut [f32]) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn add(a: &[f32], b: &[f32], side: usize, dest: &mut [f32]) -> Result<()> {
|
||||
let pixels = side * side;
|
||||
let channels = a.len() / pixels;
|
||||
let need = channels.checked_mul(pixels).ok_or_else(|| bad("Add size overflows"))?;
|
||||
if a.len() < need || b.len() < need || dest.len() < need {
|
||||
return Err(bad("Add inputs and output are not the same size"));
|
||||
}
|
||||
for c in 0..channels {
|
||||
let a_plane = &a[c * pixels..(c + 1) * pixels];
|
||||
let b_plane = &b[c * pixels..(c + 1) * pixels];
|
||||
let d_plane = &mut dest[c * pixels..(c + 1) * pixels];
|
||||
for (d, (&av, &bv)) in d_plane.iter_mut().zip(a_plane.iter().zip(b_plane)) {
|
||||
*d = av + bv;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn add_op_produces_elementwise_sum() {
|
||||
use crate::net::{Conv, Net, Op, TensorId};
|
||||
|
||||
fn conv(src: TensorId, cin: usize, cout: usize) -> Op {
|
||||
Op::Conv(Conv { src, src2: None, cin, cout, k: 1, weight: vec![0.1; cout * cin], bias: vec![0.0; cout], leaky: None })
|
||||
}
|
||||
|
||||
let tile = 8usize;
|
||||
let ops = vec![conv(0, 4, 12), Op::Add { src: 1, src2: 1 }, Op::DepthToSpace2 { src: 2 }];
|
||||
let net = Net::new(4, ops).unwrap();
|
||||
let runner = NetRunner::new(&net, tile).unwrap();
|
||||
|
||||
let pixels = tile * tile;
|
||||
let input: Vec<f32> = vec![1.0; 4 * pixels];
|
||||
let output = runner.run(&input).unwrap();
|
||||
assert_eq!(output.len(), 3 * (2 * tile) * (2 * tile));
|
||||
for &v in &output {
|
||||
assert!((v - 0.8).abs() < 1e-4, "expected 0.8, got {v}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -63,6 +63,11 @@ pub struct ConvT2 {
|
||||
pub enum Op {
|
||||
Conv(Conv),
|
||||
ConvT2(ConvT2),
|
||||
/// Elementwise addition of two same-shape tensors.
|
||||
Add {
|
||||
src: TensorId,
|
||||
src2: TensorId,
|
||||
},
|
||||
/// 2 × 2 maximum, stride 2.
|
||||
MaxPool2 {
|
||||
src: TensorId,
|
||||
@@ -146,6 +151,20 @@ impl Net {
|
||||
check_weights(i, &c.weight, c.cin.checked_mul(c.cout).and_then(|n| n.checked_mul(4)), &c.bias, c.cout, c.leaky, &mut weights)?;
|
||||
Shape { channels: c.cout, level: a.level - 1 }
|
||||
}
|
||||
Op::Add { src, src2 } => {
|
||||
let a = shape_of(*src)?;
|
||||
let b = shape_of(*src2)?;
|
||||
if a.channels != b.channels || a.level != b.level {
|
||||
return invalid(format!("layer {i}: add of tensors of different shapes"));
|
||||
}
|
||||
if a.channels == 0 {
|
||||
return invalid(format!("layer {i}: add with zero channels"));
|
||||
}
|
||||
if a.channels > MAX_CHANNELS {
|
||||
return invalid(format!("layer {i}: add with more than {} channels", MAX_CHANNELS));
|
||||
}
|
||||
Shape { channels: a.channels, level: a.level }
|
||||
}
|
||||
Op::MaxPool2 { src } => {
|
||||
let a = shape_of(*src)?;
|
||||
Shape { channels: a.channels, level: a.level + 1 }
|
||||
|
||||
+469
-23
@@ -2,16 +2,18 @@
|
||||
//!
|
||||
//! Only what the denoise U-Nets are made of is understood: `Conv` (3 × 3 "same" or 1 × 1, stride 1, no groups, no
|
||||
//! dilation) optionally followed by `LeakyRelu`, `ConvTranspose` (2 × 2, stride 2) likewise, `MaxPool` (2 × 2, stride 2),
|
||||
//! a two-input `Concat` on the channels that feeds a convolution, and a final `DepthToSpace` (2, `CRD`). Any other
|
||||
//! a two-input `Concat` on the channels that feeds a convolution, an `Add` of two same-shape tensors (elementwise addition),
|
||||
//! a standalone `LeakyRelu` (as a 1 × 1 identity convolution with the
|
||||
//! activation, when its source has more than one reader), and a final `DepthToSpace` (2, `CRD`). Any other
|
||||
//! operator or attribute is [`NetError::Unsupported`], which is reported to the user by both runners.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
use crate::onnx_proto::{self, AttributeProto, NodeProto, TensorProto, ValueInfoProto};
|
||||
use std::io::Read;
|
||||
|
||||
use crate::net::{Conv, ConvT2, MAX_WEIGHTS, Net, NetError, Op, TensorId};
|
||||
use crate::net::{Conv, ConvT2, MAX_CHANNELS, MAX_OPS, MAX_WEIGHTS, Net, NetError, Op, TensorId};
|
||||
|
||||
fn unsupported<T>(why: impl Into<String>) -> Result<T, NetError> {
|
||||
Err(NetError::Unsupported(why.into()))
|
||||
@@ -62,11 +64,23 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
|
||||
// a Concat is not a layer of its own: the convolution that reads it takes both sources
|
||||
let mut joins: HashMap<String, (TensorId, TensorId)> = HashMap::new();
|
||||
let mut ops: Vec<Op> = Vec::new();
|
||||
let mut shapes: Vec<(usize, i32)> = vec![(in_channels, 0)];
|
||||
let mut weights_total = 0usize;
|
||||
|
||||
let nodes = &graph.node;
|
||||
let mut i = 0;
|
||||
let mut fused_indices = HashSet::new();
|
||||
while i < nodes.len() {
|
||||
// Skip nodes that were fused as LeakyRelu activations
|
||||
while i < nodes.len() && fused_indices.contains(&i) {
|
||||
i += 1;
|
||||
}
|
||||
if i >= nodes.len() {
|
||||
break;
|
||||
}
|
||||
if ops.len() >= MAX_OPS {
|
||||
return invalid("the network has too many layers");
|
||||
}
|
||||
let Some(node) = nodes.get(i) else { break };
|
||||
i += 1;
|
||||
if node.output.len() != 1 || node.output.first().is_none_or(|n| n.is_empty() || ids.contains_key(n) || joins.contains_key(n)) {
|
||||
@@ -77,6 +91,8 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
|
||||
"ConvTranspose" => &["kernel_shape", "pads", "strides", "dilations", "group", "output_padding", "auto_pad"],
|
||||
"MaxPool" => &["kernel_shape", "pads", "strides", "dilations", "ceil_mode", "storage_order", "auto_pad"],
|
||||
"Concat" => &["axis"],
|
||||
"Add" => &[],
|
||||
"LeakyRelu" => &["alpha"],
|
||||
"DepthToSpace" => &["blocksize", "mode"],
|
||||
_ => &[],
|
||||
};
|
||||
@@ -87,25 +103,37 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
|
||||
let lookup = |name: &str| -> Result<TensorId, NetError> {
|
||||
ids.get(name).copied().ok_or_else(|| NetError::Invalid(format!("`{}` reads `{name}`, which nothing makes", node.op_type)))
|
||||
};
|
||||
// a LeakyRelu straight after this layer, which nothing else reads, is part of it
|
||||
let mut fuse_leaky = |out: &str| -> Result<(Option<f32>, String), NetError> {
|
||||
if let Some(next) = nodes.get(i)
|
||||
&& next.op_type == "LeakyRelu"
|
||||
&& next.input.first().map(String::as_str) == Some(out)
|
||||
&& readers.get(out).copied() == Some(1)
|
||||
{
|
||||
if next.input.len() != 1 || next.output.len() != 1 || next.attribute.iter().any(|a| a.name != "alpha") {
|
||||
return invalid("malformed LeakyRelu");
|
||||
// a LeakyRelu consuming this output, which nothing else reads, is part of it
|
||||
let mut fuse_leaky = |out: &str, joins: &HashMap<String, (TensorId, TensorId)>| -> Result<(Option<f32>, String), NetError> {
|
||||
// Search forward for a LeakyRelu consuming this output
|
||||
for j in i..nodes.len() {
|
||||
if fused_indices.contains(&j) {
|
||||
continue;
|
||||
}
|
||||
let next = &nodes[j];
|
||||
if next.op_type == "LeakyRelu" && next.input.first().map(String::as_str) == Some(out) && readers.get(out).copied() == Some(1) {
|
||||
if next.input.len() != 1 || next.output.len() != 1 || next.attribute.iter().any(|a| a.name != "alpha") {
|
||||
return invalid("malformed LeakyRelu");
|
||||
}
|
||||
// only an omitted alpha gets the ONNX default; one that is not a single float must not read as 0
|
||||
let alpha = match next.attribute.as_slice() {
|
||||
[] => 0.01,
|
||||
[AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f,
|
||||
_ => return invalid("LeakyRelu alpha is not a single float"),
|
||||
};
|
||||
let name = next.output.first().cloned().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?;
|
||||
if name.is_empty() || ids.contains_key(&name) || joins.contains_key(&name) {
|
||||
continue;
|
||||
}
|
||||
// Fusing gives the LeakyRelu's output the id of this op. If that output is the graph
|
||||
// output it must stay the last tensor, so decline the fusion when another node after
|
||||
// this one emits an operation: it would push the graph output before a later tensor.
|
||||
if name == output.name.as_str() && nodes[i..].iter().enumerate().any(|(k, n)| i + k != j && emits_op(n.op_type.as_str())) {
|
||||
continue;
|
||||
}
|
||||
fused_indices.insert(j);
|
||||
return Ok((Some(alpha), name));
|
||||
}
|
||||
// only an omitted alpha gets the ONNX default; one that is not a single float must not read as 0
|
||||
let alpha = match next.attribute.as_slice() {
|
||||
[] => 0.01,
|
||||
[AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f,
|
||||
_ => return invalid("LeakyRelu alpha is not a single float"),
|
||||
};
|
||||
i += 1;
|
||||
let name = next.output.first().cloned().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?;
|
||||
return Ok((Some(alpha), name));
|
||||
}
|
||||
Ok((None, out.to_string()))
|
||||
};
|
||||
@@ -147,8 +175,9 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
|
||||
None => (lookup(src_name)?, None),
|
||||
};
|
||||
let out = node.output.first().ok_or_else(|| NetError::Invalid("Conv without an output".into()))?;
|
||||
let (leaky, out_name) = fuse_leaky(out)?;
|
||||
let (leaky, out_name) = fuse_leaky(out, &joins)?;
|
||||
ids.insert(out_name, this);
|
||||
shapes.push((cout, shapes.get(src).copied().map_or(0, |s| s.1)));
|
||||
ops.push(Op::Conv(Conv { src, src2, cin, cout, k: kh, weight: w.1, bias: b, leaky }));
|
||||
}
|
||||
"ConvTranspose" => {
|
||||
@@ -172,8 +201,9 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
|
||||
}
|
||||
let src = lookup(node.input.first().map_or("", String::as_str))?;
|
||||
let out = node.output.first().ok_or_else(|| NetError::Invalid("ConvTranspose without an output".into()))?;
|
||||
let (leaky, out_name) = fuse_leaky(out)?;
|
||||
let (leaky, out_name) = fuse_leaky(out, &joins)?;
|
||||
ids.insert(out_name, this);
|
||||
shapes.push((cout, shapes.get(src).copied().map_or(0, |s| s.1) - 1));
|
||||
ops.push(Op::ConvT2(ConvT2 { src, cin, cout, weight: w.1, bias: b, leaky }));
|
||||
}
|
||||
"MaxPool" => {
|
||||
@@ -190,8 +220,72 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
|
||||
let src = lookup(node.input.first().map_or("", String::as_str))?;
|
||||
let out = node.output.first().ok_or_else(|| NetError::Invalid("MaxPool without an output".into()))?;
|
||||
ids.insert(out.clone(), this);
|
||||
shapes.push(shapes.get(src).copied().map_or((in_channels, 1), |(c, l)| (c, l + 1)));
|
||||
ops.push(Op::MaxPool2 { src });
|
||||
}
|
||||
"Add" => {
|
||||
let [a, b] = node.input.as_slice() else { return unsupported("Add of other than two tensors") };
|
||||
if joins.contains_key(a) || joins.contains_key(b) {
|
||||
return unsupported("Add reading a Concat output");
|
||||
}
|
||||
if initialisers.contains_key(a.as_str()) || initialisers.contains_key(b.as_str()) {
|
||||
return unsupported("Add with an initializer operand");
|
||||
}
|
||||
let src = lookup(a)?;
|
||||
let src2 = lookup(b)?;
|
||||
let out = node.output.first().ok_or_else(|| NetError::Invalid("Add without an output".into()))?;
|
||||
let (ca, la) = shapes.get(src).copied().ok_or_else(|| NetError::Invalid("Add reads a tensor with no shape".into()))?;
|
||||
let (cb, lb) = shapes.get(src2).copied().ok_or_else(|| NetError::Invalid("Add reads a tensor with no shape".into()))?;
|
||||
if ca != cb || la != lb {
|
||||
return unsupported("Add of tensors of different shapes");
|
||||
}
|
||||
if ca == 0 {
|
||||
return invalid("Add with zero channels");
|
||||
}
|
||||
if ca > MAX_CHANNELS {
|
||||
return unsupported("Add with more than 4096 channels");
|
||||
}
|
||||
ids.insert(out.clone(), this);
|
||||
shapes.push((ca, la));
|
||||
ops.push(Op::Add { src, src2 });
|
||||
}
|
||||
"LeakyRelu" => {
|
||||
let [a] = node.input.as_slice() else { return invalid("malformed LeakyRelu") };
|
||||
if joins.contains_key(a) {
|
||||
return unsupported("LeakyRelu reading a Concat output");
|
||||
}
|
||||
if initialisers.contains_key(a.as_str()) {
|
||||
return unsupported("LeakyRelu with an initializer operand");
|
||||
}
|
||||
let src = lookup(a)?;
|
||||
let out = node.output.first().ok_or_else(|| NetError::Invalid("LeakyRelu without an output".into()))?;
|
||||
let (ca, la) = shapes.get(src).copied().ok_or_else(|| NetError::Invalid("LeakyRelu reads a tensor with no shape".into()))?;
|
||||
if ca == 0 {
|
||||
return invalid("LeakyRelu with zero channels");
|
||||
}
|
||||
if ca > MAX_CHANNELS {
|
||||
return unsupported("LeakyRelu with more than 4096 channels");
|
||||
}
|
||||
let alpha = match node.attribute.as_slice() {
|
||||
[] => 0.01,
|
||||
[AttributeProto { f: Some(f), kind: 0 | 1, .. }] => *f,
|
||||
_ => return invalid("LeakyRelu alpha is not a single float"),
|
||||
};
|
||||
let nn = ca.checked_mul(ca).ok_or_else(|| NetError::Invalid("LeakyRelu channel count overflows".into()))?;
|
||||
weights_total = weights_total.saturating_add(nn).saturating_add(ca);
|
||||
if weights_total > MAX_WEIGHTS {
|
||||
return invalid("the network has too many weights");
|
||||
}
|
||||
let mut weight = vec![0.0f32; nn];
|
||||
for c in 0..ca {
|
||||
if let Some(w) = weight.get_mut(c * ca + c) {
|
||||
*w = 1.0;
|
||||
}
|
||||
}
|
||||
ids.insert(out.clone(), this);
|
||||
shapes.push((ca, la));
|
||||
ops.push(Op::Conv(Conv { src, src2: None, cin: ca, cout: ca, k: 1, weight, bias: vec![0.0; ca], leaky: Some(alpha) }));
|
||||
}
|
||||
"DepthToSpace" => {
|
||||
if attr(node, "blocksize").map(|a| a.i) != Some(2) || attr(node, "mode").map(|a| a.s.as_slice()) != Some(&b"CRD"[..]) {
|
||||
return unsupported("depth-to-space other than block size 2 in CRD order");
|
||||
@@ -199,6 +293,7 @@ fn read_bytes(bytes: &[u8]) -> Result<Net, NetError> {
|
||||
let src = lookup(node.input.first().map_or("", String::as_str))?;
|
||||
let out = node.output.first().ok_or_else(|| NetError::Invalid("DepthToSpace without an output".into()))?;
|
||||
ids.insert(out.clone(), this);
|
||||
shapes.push(shapes.get(src).copied().map_or((in_channels / 4, -1), |(c, l)| (c / 4, l - 1)));
|
||||
ops.push(Op::DepthToSpace2 { src });
|
||||
}
|
||||
other => return unsupported(format!("the `{other}` operator")),
|
||||
@@ -222,6 +317,12 @@ fn ints_or(n: &NodeProto, name: &str, default: &[i64]) -> Vec<i64> {
|
||||
attr(n, name).map_or_else(|| default.to_vec(), |a| a.ints.clone())
|
||||
}
|
||||
|
||||
/// Whether an ONNX operator node emits a denoise-layer operation. `Concat` does not: it only
|
||||
/// records a join for the convolution that follows it.
|
||||
fn emits_op(op_type: &str) -> bool {
|
||||
matches!(op_type, "Conv" | "ConvTranspose" | "MaxPool" | "Add" | "LeakyRelu" | "DepthToSpace")
|
||||
}
|
||||
|
||||
fn four(dims: &[i64]) -> Result<(usize, usize, usize, usize), NetError> {
|
||||
match dims {
|
||||
[a, b, c, d] if dims.iter().all(|&v| v > 0 && v <= 1 << 20) => Ok((*a as usize, *b as usize, *c as usize, *d as usize)),
|
||||
@@ -297,6 +398,7 @@ fn channel_dim(v: &ValueInfoProto) -> Option<usize> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::synthetic::unet_onnx;
|
||||
use crate::synthetic_proto::{len_field, value_info_bytes, varint_field};
|
||||
|
||||
fn temp_model(name: &str, bytes: &[u8]) -> std::path::PathBuf {
|
||||
let p = std::env::temp_dir().join(format!("lc-denoise-onnx-{name}-{}.onnx", std::process::id()));
|
||||
@@ -304,6 +406,109 @@ mod tests {
|
||||
p
|
||||
}
|
||||
|
||||
fn node(op: &str, inputs: &[&str], output: &str, ints: &[(&str, i64)]) -> Vec<u8> {
|
||||
let mut n = Vec::new();
|
||||
for i in inputs {
|
||||
len_field(1, i.as_bytes(), &mut n);
|
||||
}
|
||||
len_field(2, output.as_bytes(), &mut n);
|
||||
len_field(4, op.as_bytes(), &mut n);
|
||||
for (name, value) in ints {
|
||||
let mut a = Vec::new();
|
||||
len_field(1, name.as_bytes(), &mut a);
|
||||
varint_field(3, *value as u64, &mut a);
|
||||
varint_field(20, 2, &mut a);
|
||||
len_field(5, &a, &mut n);
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn tensor(name: &str, dims: &[u64], values: &[f32]) -> Vec<u8> {
|
||||
let mut t = Vec::new();
|
||||
for d in dims {
|
||||
varint_field(1, *d, &mut t);
|
||||
}
|
||||
varint_field(2, 1, &mut t);
|
||||
len_field(8, name.as_bytes(), &mut t);
|
||||
let raw: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
len_field(9, &raw, &mut t);
|
||||
t
|
||||
}
|
||||
|
||||
fn model(nodes: &[Vec<u8>], in_channels: u64, out: &str) -> Vec<u8> {
|
||||
let mut graph = Vec::new();
|
||||
for n in nodes {
|
||||
len_field(1, n, &mut graph);
|
||||
}
|
||||
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(in_channels), Ok(8), Ok(8)]), &mut graph);
|
||||
len_field(12, &value_info_bytes(out, 1, &[Ok(1), Ok(3), Ok(8), Ok(8)]), &mut graph);
|
||||
let mut ops = Vec::new();
|
||||
len_field(1, b"", &mut ops);
|
||||
varint_field(2, 13, &mut ops);
|
||||
let mut model = Vec::new();
|
||||
varint_field(1, 8, &mut model);
|
||||
len_field(7, &graph, &mut model);
|
||||
len_field(8, &ops, &mut model);
|
||||
model
|
||||
}
|
||||
|
||||
fn varint(mut v: u64, out: &mut Vec<u8>) {
|
||||
loop {
|
||||
let b = (v & 0x7f) as u8;
|
||||
v >>= 7;
|
||||
if v == 0 {
|
||||
out.push(b);
|
||||
return;
|
||||
}
|
||||
out.push(b | 0x80);
|
||||
}
|
||||
}
|
||||
|
||||
fn node_with_ints(op: &str, inputs: &[&str], output: &str, ints: &[(&str, &[i64])]) -> Vec<u8> {
|
||||
let mut n = Vec::new();
|
||||
for i in inputs {
|
||||
len_field(1, i.as_bytes(), &mut n);
|
||||
}
|
||||
len_field(2, output.as_bytes(), &mut n);
|
||||
len_field(4, op.as_bytes(), &mut n);
|
||||
for &(name, values) in ints {
|
||||
let mut a = Vec::new();
|
||||
len_field(1, name.as_bytes(), &mut a);
|
||||
// field 8: INTS (wire type 2) - varint-encoded list
|
||||
varint(8 << 3 | 2, &mut a);
|
||||
// length of the list in bytes (we'll compute after writing values)
|
||||
let mut vals = Vec::new();
|
||||
for &v in values {
|
||||
varint(v as u64, &mut vals);
|
||||
}
|
||||
varint(vals.len() as u64, &mut a);
|
||||
a.extend_from_slice(&vals);
|
||||
// field 20: type = 7 (INTS)
|
||||
varint_field(20, 7, &mut a);
|
||||
len_field(5, &a, &mut n);
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn leaky_relu_node(inputs: &[&str], output: &str, alpha: f32) -> Vec<u8> {
|
||||
let mut n = Vec::new();
|
||||
for i in inputs {
|
||||
len_field(1, i.as_bytes(), &mut n);
|
||||
}
|
||||
len_field(2, output.as_bytes(), &mut n);
|
||||
len_field(4, b"LeakyRelu", &mut n);
|
||||
// alpha attribute: field 1=name, field 2=float value (wire type 5), field 20=type=1 (FLOAT)
|
||||
let mut a = Vec::new();
|
||||
len_field(1, b"alpha", &mut a);
|
||||
// field 2 with wire type 5 (fixed 4-byte float)
|
||||
varint(2 << 3 | 5, &mut a);
|
||||
a.extend_from_slice(&alpha.to_le_bytes());
|
||||
// field 20: type = 1 (FLOAT)
|
||||
varint_field(20, 1, &mut a);
|
||||
len_field(5, &a, &mut n);
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_u_net_is_read_with_its_layers_fused() {
|
||||
let (tile, depth) = (32usize, 2usize);
|
||||
@@ -324,6 +529,38 @@ mod tests {
|
||||
let _ = std::fs::remove_file(p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_operator_model_is_accepted() {
|
||||
// the convolution output added back to the input, as a residual block does
|
||||
let mut graph = Vec::new();
|
||||
len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph);
|
||||
len_field(1, &node("Add", &["c1", "data"], "a1", &[]), &mut graph);
|
||||
len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph);
|
||||
let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]);
|
||||
let mut mode = Vec::new();
|
||||
len_field(1, b"mode", &mut mode);
|
||||
len_field(4, b"CRD", &mut mode);
|
||||
varint_field(20, 3, &mut mode);
|
||||
len_field(5, &mode, &mut depth_to_space);
|
||||
len_field(1, &depth_to_space, &mut graph);
|
||||
len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph);
|
||||
len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph);
|
||||
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
|
||||
len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph);
|
||||
let mut ops = Vec::new();
|
||||
len_field(1, b"", &mut ops);
|
||||
varint_field(2, 13, &mut ops);
|
||||
let mut model = Vec::new();
|
||||
varint_field(1, 8, &mut model);
|
||||
len_field(7, &graph, &mut model);
|
||||
len_field(8, &ops, &mut model);
|
||||
|
||||
let net = read_bytes(&model);
|
||||
assert!(net.is_ok(), "a model with an Add residual was rejected: {:?}", net.err());
|
||||
let net = net.unwrap();
|
||||
assert_eq!((net.in_channels, net.out_channels()), (4, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leaky_relu_alpha_that_is_not_a_float_is_rejected() {
|
||||
let good = unet_onnx(4, 3, 1, 7);
|
||||
@@ -390,4 +627,213 @@ mod tests {
|
||||
// a missing file
|
||||
assert!(read(Path::new("/does/not/exist.onnx")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_reading_concat_and_oversized_channels_are_unsupported() {
|
||||
let concat_model =
|
||||
model(&[node("Concat", &["data", "data"], "joined", &[("axis", 1)]), node("Add", &["joined", "data"], "a1", &[])], 4, "a1");
|
||||
assert!(matches!(read_bytes(&concat_model), Err(NetError::Unsupported(_))));
|
||||
|
||||
let oversized_model = model(&[node("Add", &["data", "data"], "a1", &[])], 4097, "a1");
|
||||
assert!(matches!(read_bytes(&oversized_model), Err(NetError::Unsupported(_))));
|
||||
|
||||
let mut depth = node("DepthToSpace", &["data"], "d", &[("blocksize", 2)]);
|
||||
let mut mode = Vec::new();
|
||||
len_field(1, b"mode", &mut mode);
|
||||
len_field(4, b"CRD", &mut mode);
|
||||
varint_field(20, 3, &mut mode);
|
||||
len_field(5, &mode, &mut depth);
|
||||
let zero_model = model(&[depth, node("Add", &["d", "d"], "a1", &[])], 3, "a1");
|
||||
assert!(matches!(read_bytes(&zero_model), Err(NetError::Invalid(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_adds_on_a_wide_input_are_accepted_up_to_max_ops() {
|
||||
// 32 Add nodes on 4096 channels should be accepted (32 < MAX_OPS=512, no weight allocation)
|
||||
let mut nodes = Vec::new();
|
||||
let mut prev = "data".to_string();
|
||||
for i in 0..32 {
|
||||
let out = format!("a{i}");
|
||||
nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[]));
|
||||
prev = out;
|
||||
}
|
||||
let wide_model = model(&nodes, 4096, &prev);
|
||||
assert!(read_bytes(&wide_model).is_ok(), "many Add nodes on wide input should be accepted");
|
||||
|
||||
// But exceeding MAX_OPS should still be rejected
|
||||
let mut nodes = Vec::new();
|
||||
let mut prev = "data".to_string();
|
||||
for i in 0..=MAX_OPS {
|
||||
let out = format!("a{i}");
|
||||
nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[]));
|
||||
prev = out;
|
||||
}
|
||||
let too_many_model = model(&nodes, 1, &prev);
|
||||
assert!(matches!(read_bytes(&too_many_model), Err(NetError::Invalid(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaky_relu_with_an_add_residual_branch_is_accepted() {
|
||||
// the convolution output is read by both the LeakyRelu and the Add residual branch
|
||||
let mut graph = Vec::new();
|
||||
len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph);
|
||||
len_field(1, &node("LeakyRelu", &["c1"], "l1", &[]), &mut graph);
|
||||
len_field(1, &node("Add", &["c1", "l1"], "a1", &[]), &mut graph);
|
||||
len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph);
|
||||
let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]);
|
||||
let mut mode = Vec::new();
|
||||
len_field(1, b"mode", &mut mode);
|
||||
len_field(4, b"CRD", &mut mode);
|
||||
varint_field(20, 3, &mut mode);
|
||||
len_field(5, &mode, &mut depth_to_space);
|
||||
len_field(1, &depth_to_space, &mut graph);
|
||||
len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph);
|
||||
len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph);
|
||||
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
|
||||
len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph);
|
||||
let mut ops = Vec::new();
|
||||
len_field(1, b"", &mut ops);
|
||||
varint_field(2, 13, &mut ops);
|
||||
let mut model = Vec::new();
|
||||
varint_field(1, 8, &mut model);
|
||||
len_field(7, &graph, &mut model);
|
||||
len_field(8, &ops, &mut model);
|
||||
|
||||
let net = read_bytes(&model);
|
||||
assert!(net.is_ok(), "a LeakyRelu residual model was rejected: {:?}", net.err());
|
||||
let net = net.unwrap();
|
||||
assert_eq!((net.in_channels, net.out_channels()), (4, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaky_relu_fuses_across_interleaved_nodes() {
|
||||
// Conv produces "c1", then an unrelated MaxPool (reading "data") comes between,
|
||||
// then a LeakyRelu consumes "c1". The fusion should still happen.
|
||||
let mut graph = Vec::new();
|
||||
len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph);
|
||||
// Valid MaxPool: 2x2 kernel, stride 2, no padding, no dilation
|
||||
len_field(
|
||||
1,
|
||||
&node_with_ints(
|
||||
"MaxPool",
|
||||
&["data"],
|
||||
"mp1",
|
||||
&[("kernel_shape", &[2, 2]), ("strides", &[2, 2]), ("pads", &[0, 0, 0, 0]), ("dilations", &[1, 1])],
|
||||
),
|
||||
&mut graph,
|
||||
);
|
||||
len_field(1, &leaky_relu_node(&["c1"], "l1", 0.2), &mut graph); // alpha=0.2
|
||||
let mut depth_to_space = node("DepthToSpace", &["l1"], "rgb", &[("blocksize", 2)]);
|
||||
let mut mode = Vec::new();
|
||||
len_field(1, b"mode", &mut mode);
|
||||
len_field(4, b"CRD", &mut mode);
|
||||
varint_field(20, 3, &mut mode);
|
||||
len_field(5, &mode, &mut depth_to_space);
|
||||
len_field(1, &depth_to_space, &mut graph);
|
||||
len_field(5, &tensor("w1", &[12, 4, 1, 1], &[0.1; 48]), &mut graph);
|
||||
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
|
||||
len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph);
|
||||
let mut ops = Vec::new();
|
||||
len_field(1, b"", &mut ops);
|
||||
varint_field(2, 13, &mut ops);
|
||||
let mut model = Vec::new();
|
||||
varint_field(1, 8, &mut model);
|
||||
len_field(7, &graph, &mut model);
|
||||
len_field(8, &ops, &mut model);
|
||||
|
||||
let net = read_bytes(&model);
|
||||
assert!(net.is_ok(), "LeakyRelu across interleaved nodes was rejected: {:?}", net.err());
|
||||
let net = net.unwrap();
|
||||
assert_eq!((net.in_channels, net.out_channels()), (4, 3));
|
||||
// The Conv should have the leaky ReLU fused with alpha=0.2
|
||||
let ops = net.ops();
|
||||
assert_eq!(ops.len(), 3); // Conv (fused), MaxPool, DepthToSpace
|
||||
match &ops[0] {
|
||||
crate::net::Op::Conv(c) => {
|
||||
assert_eq!(c.leaky, Some(0.2), "LeakyRelu alpha should be fused into Conv");
|
||||
}
|
||||
_ => panic!("first op should be fused Conv"),
|
||||
}
|
||||
assert!(matches!(ops[1], crate::net::Op::MaxPool2 { .. }));
|
||||
assert!(matches!(ops[2], crate::net::Op::DepthToSpace2 { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_with_initializer_operand_is_unsupported() {
|
||||
let mut graph = Vec::new();
|
||||
len_field(1, &node("Add", &["data", "w1"], "a1", &[]), &mut graph);
|
||||
len_field(5, &tensor("w1", &[4], &[0.1; 4]), &mut graph);
|
||||
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
|
||||
len_field(12, &value_info_bytes("a1", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
|
||||
let mut ops = Vec::new();
|
||||
len_field(1, b"", &mut ops);
|
||||
varint_field(2, 13, &mut ops);
|
||||
let mut model = Vec::new();
|
||||
varint_field(1, 8, &mut model);
|
||||
len_field(7, &graph, &mut model);
|
||||
len_field(8, &ops, &mut model);
|
||||
|
||||
assert!(matches!(read_bytes(&model), Err(NetError::Unsupported(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaky_relu_with_initializer_operand_is_unsupported() {
|
||||
let mut graph = Vec::new();
|
||||
len_field(1, &node("LeakyRelu", &["w1"], "l1", &[]), &mut graph);
|
||||
len_field(5, &tensor("w1", &[4], &[0.1; 4]), &mut graph);
|
||||
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
|
||||
len_field(12, &value_info_bytes("l1", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
|
||||
let mut ops = Vec::new();
|
||||
len_field(1, b"", &mut ops);
|
||||
varint_field(2, 13, &mut ops);
|
||||
let mut model = Vec::new();
|
||||
varint_field(1, 8, &mut model);
|
||||
len_field(7, &graph, &mut model);
|
||||
len_field(8, &ops, &mut model);
|
||||
|
||||
assert!(matches!(read_bytes(&model), Err(NetError::Unsupported(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_than_max_ops_small_adds_are_rejected_as_too_many_layers() {
|
||||
let mut nodes = Vec::new();
|
||||
let mut prev = "data".to_string();
|
||||
for i in 0..=MAX_OPS {
|
||||
let out = format!("a{i}");
|
||||
nodes.push(node("Add", &[prev.as_str(), prev.as_str()], &out, &[]));
|
||||
prev = out;
|
||||
}
|
||||
let many_model = model(&nodes, 1, &prev);
|
||||
assert!(matches!(read_bytes(&many_model), Err(NetError::Invalid(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_operator_model_is_accepted_review_regression_1() {
|
||||
// An Add residual block: the convolution output is added back to the input.
|
||||
let mut graph = Vec::new();
|
||||
len_field(1, &node("Conv", &["data", "w1"], "c1", &[("group", 1)]), &mut graph);
|
||||
len_field(1, &node("Add", &["c1", "data"], "a1", &[]), &mut graph);
|
||||
len_field(1, &node("Conv", &["a1", "w2"], "c2", &[("group", 1)]), &mut graph);
|
||||
let mut depth_to_space = node("DepthToSpace", &["c2"], "rgb", &[("blocksize", 2)]);
|
||||
let mut mode = Vec::new();
|
||||
len_field(1, b"mode", &mut mode);
|
||||
len_field(4, b"CRD", &mut mode);
|
||||
varint_field(20, 3, &mut mode);
|
||||
len_field(5, &mode, &mut depth_to_space);
|
||||
len_field(1, &depth_to_space, &mut graph);
|
||||
len_field(5, &tensor("w1", &[4, 4, 1, 1], &[0.1; 16]), &mut graph);
|
||||
len_field(5, &tensor("w2", &[12, 4, 1, 1], &[0.1; 48]), &mut graph);
|
||||
len_field(11, &value_info_bytes("data", 1, &[Ok(1), Ok(4), Ok(8), Ok(8)]), &mut graph);
|
||||
len_field(12, &value_info_bytes("rgb", 1, &[Ok(1), Ok(3), Ok(16), Ok(16)]), &mut graph);
|
||||
let mut ops = Vec::new();
|
||||
len_field(1, b"", &mut ops);
|
||||
varint_field(2, 13, &mut ops);
|
||||
let mut model = Vec::new();
|
||||
varint_field(1, 8, &mut model);
|
||||
len_field(7, &graph, &mut model);
|
||||
len_field(8, &ops, &mut model);
|
||||
|
||||
let net = read_bytes(&model);
|
||||
assert!(net.is_ok(), "a model with an Add residual was rejected: {:?}", net.err());
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,16 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError>
|
||||
}
|
||||
T { channels: c.cout, side: out_side, data }
|
||||
}
|
||||
Op::Add { src, src2 } => {
|
||||
let a = get(&tensors, *src)?;
|
||||
let b = get(&tensors, *src2)?;
|
||||
let (channels, side) = (tensors[a].channels, tensors[a].side);
|
||||
let mut data = tensor(channels, side, &mut total)?;
|
||||
for (d, (&av, &bv)) in data.iter_mut().zip(tensors[a].data.iter().zip(&tensors[b].data)) {
|
||||
*d = av + bv;
|
||||
}
|
||||
T { channels, side, data }
|
||||
}
|
||||
Op::MaxPool2 { src } => {
|
||||
let a = get(&tensors, *src)?;
|
||||
let (channels, side) = (tensors[a].channels, tensors[a].side / 2);
|
||||
|
||||
+373
-45
@@ -5,8 +5,12 @@
|
||||
//! computed from the photo's *original* state (its import settings, when known) and the preset's
|
||||
//! value, and replaces the photo's value; every other setting keeps the photo's value (issue
|
||||
//! #2159). `amount` (0..200 %) moves each named number between the original and the preset's
|
||||
//! value. Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the
|
||||
//! current settings as before.
|
||||
//! value; a point curve (a tone curve) moves between the two curves as rendered. Switches and choices
|
||||
//! (a profile or LUT id, a style, a flag) take the original's value below half amount and the
|
||||
//! preset's from half amount up, and the strength of a choice the preset changes fades in from 0
|
||||
//! there; white balance on another scale is taken whole (see [`interpolate_object`]).
|
||||
//! Copy/paste/sync use the same group selection ([`SettingsGroup`]) and merge into the current
|
||||
//! settings as before.
|
||||
//!
|
||||
//! The rendering process ([`crate::ProcessVersion`]) is in no group: copy, paste, sync and presets
|
||||
//! made from a photo never carry it, so the photos they change keep their own. A partial that names
|
||||
@@ -159,42 +163,34 @@ pub fn deep_merge(base: &mut Value, patch: &Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpolate numbers in `patch` towards/away from `base` by `t` (1 = patch as-is); non-numeric
|
||||
/// values are taken from the patch when `t >= 0.5`.
|
||||
fn scale_patch(base: &Value, patch: &Value, t: f64) -> Value {
|
||||
match (base, patch) {
|
||||
(Value::Object(b), Value::Object(p)) => {
|
||||
let mut out = Map::new();
|
||||
for (k, pv) in p {
|
||||
let bv = b.get(k).unwrap_or(&Value::Null);
|
||||
out.insert(k.clone(), scale_patch(bv, pv, t));
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
// Integer fields (the grain seed, ids) are discrete like strings: an interpolated seed would
|
||||
// not deserialize as an integer, and the whole preset would silently not apply.
|
||||
(Value::Number(b), Value::Number(p)) if b.is_f64() || p.is_f64() => {
|
||||
let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0));
|
||||
serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number).unwrap_or(Value::Null)
|
||||
}
|
||||
(b, p) => {
|
||||
if t >= 0.5 {
|
||||
p.clone()
|
||||
} else {
|
||||
b.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a partial settings object with an amount (1.0 = 100 %). Out-of-range values are clamped
|
||||
/// through the control specs, as every merge does ([`DevelopSettings::merged`]).
|
||||
/// Apply a partial settings object with an amount (1.0 = 100 %): each setting it names is blended
|
||||
/// from `s`'s value by the same rules as a preset ([`interpolate_object`]). Out-of-range values are
|
||||
/// clamped through the control specs, as every merge does ([`DevelopSettings::merged`]). At 0 %
|
||||
/// (or less) nothing changes; at 100 % the partial is merged as it is.
|
||||
pub fn apply_partial(s: &DevelopSettings, partial: &Value, amount: f64) -> DevelopSettings {
|
||||
let patch = if (amount - 1.0).abs() < 1e-9 { Cow::Borrowed(partial) } else { Cow::Owned(scale_patch(&s.to_json_for_merge(), partial, amount)) };
|
||||
if amount.is_nan() || amount <= 0.0 {
|
||||
return s.clone();
|
||||
}
|
||||
let patch = if (amount - 1.0).abs() < 1e-9 {
|
||||
Cow::Borrowed(partial)
|
||||
} else {
|
||||
let base = blend_base(s);
|
||||
Cow::Owned(Value::Object(partial.as_object().map(|p| interpolate_object(base.as_object(), p, amount)).unwrap_or_default()))
|
||||
};
|
||||
// (a white balance without a scale keeps its old meaning: `DevelopSettings::merged`)
|
||||
s.merged(&patch).unwrap_or_else(|_| s.clone())
|
||||
}
|
||||
|
||||
/// `s` as the base an amount blends from: every group written out, also the ones serialization
|
||||
/// leaves out while at their defaults (HDR), so their numbers blend from `s`'s values too.
|
||||
fn blend_base(s: &DevelopSettings) -> Value {
|
||||
let mut v = s.to_json_for_merge();
|
||||
if let (Some(o), Ok(hdr)) = (v.as_object_mut(), serde_json::to_value(s.hdr)) {
|
||||
o.entry("hdr").or_insert(hdr);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Top-level settings keys that hold per-photo pixel repairs: a preset's named repairs compose on
|
||||
/// the photo's own values instead of the original's (masks are added by [`Preset::apply_on`]), and
|
||||
/// a preset without them leaves the photo's alone.
|
||||
@@ -212,7 +208,7 @@ fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings
|
||||
return current.merged(settings).unwrap_or_else(|_| current.clone());
|
||||
}
|
||||
let cur = current.to_json();
|
||||
let mut base = original.to_json();
|
||||
let mut base = blend_base(original);
|
||||
if let (Some(b), Some(c)) = (base.as_object_mut(), cur.as_object()) {
|
||||
for k in REPAIR_KEYS {
|
||||
if let Some(v) = c.get(k) {
|
||||
@@ -229,12 +225,38 @@ fn compose_named(current: &DevelopSettings, original: &DevelopSettings, settings
|
||||
}
|
||||
|
||||
/// The leaves of `patch` that apply at `t` (below 100 %), each computed from the same place in
|
||||
/// `base`. A leaf the amount does not reach is left out, so the photo keeps its own value there.
|
||||
/// `base` ([`interpolate_leaf`]). A leaf the amount does not reach is left out, so the photo keeps
|
||||
/// its own value there. Two rules look at an object as a whole (issue #2669):
|
||||
///
|
||||
/// - **The `amount` beside a choice.** When the preset changes a choice here (a string such as the
|
||||
/// profile or LUT id or a style, or the object's `enabled` switch), its `amount` is the strength of
|
||||
/// that choice, not of the base's: from half amount up, where the preset's choice applies, the
|
||||
/// amount fades in from 0 (a new profile at 50 % has half the preset's strength, and a profile at
|
||||
/// 0 % is no look at all); below half amount the base's choice keeps its own amount.
|
||||
/// - **White balance on another scale.** `temp` / `tint` on a different [`crate::WbScale`] than the
|
||||
/// base's (Kelvin against the older relative scale; a partial that names no scale is on the
|
||||
/// relative one, as [`DevelopSettings::merged`] reads it) are in other units and are never
|
||||
/// blended: below half amount the base's numbers and scale apply, from half amount up the
|
||||
/// preset's, as for any other choice.
|
||||
fn interpolate_object(base: Option<&Map<String, Value>>, patch: &Map<String, Value>, t: f64) -> Map<String, Value> {
|
||||
let get = |k: &str| base.and_then(|b| b.get(k));
|
||||
let choice_changed = patch.iter().any(|(k, pv)| (pv.is_string() || (k == "enabled" && pv.is_boolean())) && get(k) != Some(pv));
|
||||
let scale_of = |o: Option<&Map<String, Value>>| o.and_then(|o| o.get("scale")).and_then(Value::as_str).unwrap_or("legacy").to_string();
|
||||
let other_scale = (patch.contains_key("temp") || patch.contains_key("tint")) && scale_of(Some(patch)) != scale_of(base);
|
||||
let mut out = Map::new();
|
||||
for (k, pv) in patch {
|
||||
let bv = base.and_then(|b| b.get(k));
|
||||
if other_scale && matches!(k.as_str(), "temp" | "tint" | "scale") {
|
||||
continue;
|
||||
}
|
||||
let bv = get(k);
|
||||
let v = match pv {
|
||||
Value::Number(_) if choice_changed && k == "amount" => {
|
||||
if t >= 0.5 {
|
||||
interpolate_leaf(Some(&Value::from(0.0)), pv, t)
|
||||
} else {
|
||||
bv.cloned()
|
||||
}
|
||||
}
|
||||
Value::Object(p) => Some(Value::Object(interpolate_object(bv.and_then(Value::as_object), p, t))),
|
||||
_ => interpolate_leaf(bv, pv, t),
|
||||
};
|
||||
@@ -242,18 +264,38 @@ fn interpolate_object(base: Option<&Map<String, Value>>, patch: &Map<String, Val
|
||||
out.insert(k.clone(), v);
|
||||
}
|
||||
}
|
||||
if other_scale {
|
||||
// the numbers and their scale come together from one side, never a mix of the two
|
||||
let side = if t >= 0.5 { Some(patch) } else { base };
|
||||
for k in ["temp", "tint"] {
|
||||
if let Some(v) = patch.get(k).and(side.and_then(|o| o.get(k))) {
|
||||
out.insert(k.to_string(), v.clone());
|
||||
}
|
||||
}
|
||||
out.insert("scale".to_string(), Value::from(scale_of(side)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One leaf at `t`. Numbers move from `base` towards `patch`. Other values switch to the preset's
|
||||
/// at half amount and up, and below it take the base's value. A null in the base is the baseline
|
||||
/// value the import state recorded (a cleared option, such as a free crop aspect): below half
|
||||
/// amount it applies and clears the photo's value, as the amount contract promises. A null the
|
||||
/// preset writes is a value like any other, so it applies at half amount and up (a preset can
|
||||
/// clear an option field such as a crop aspect).
|
||||
/// One leaf at `t`. Numbers move from `base` towards `patch`. Point curves (lists of `{x, y}`
|
||||
/// points, the tone curves; empty is the identity) move as curves: both are evaluated as the
|
||||
/// renderer does (monotone cubic) at every control point of either, and the points blend like
|
||||
/// numbers, `y` kept in `0..1`. Other values switch to the preset's at half amount and up, and
|
||||
/// below it take the base's value. A null in the base is the baseline value the import state
|
||||
/// recorded (a cleared option, such as a free crop aspect): below half amount it applies and
|
||||
/// clears the photo's value, as the amount contract promises. A null the preset writes is a value
|
||||
/// like any other, so it applies at half amount and up (a preset can clear an option field such as
|
||||
/// a crop aspect).
|
||||
fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option<Value> {
|
||||
if t > 0.0
|
||||
&& let (Some(bc), Some(pc)) = (base.and_then(point_curve), point_curve(patch))
|
||||
&& !(bc.is_empty() && pc.is_empty())
|
||||
{
|
||||
return Some(blend_curves(&bc, &pc, t));
|
||||
}
|
||||
match (base, patch) {
|
||||
// integer fields (the grain seed, ids) are discrete like strings: see `scale_patch`
|
||||
// integer fields (the grain seed, ids) are discrete like strings: an interpolated seed would
|
||||
// not deserialize as an integer, and the whole preset would silently not apply
|
||||
(Some(Value::Number(b)), Value::Number(p)) if b.is_f64() || p.is_f64() => {
|
||||
let (b, p) = (b.as_f64().unwrap_or(0.0), p.as_f64().unwrap_or(0.0));
|
||||
serde_json::Number::from_f64(b + (p - b) * t).map(Value::Number)
|
||||
@@ -263,6 +305,34 @@ fn interpolate_leaf(base: Option<&Value>, patch: &Value, t: f64) -> Option<Value
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as a point curve: a list whose items all are `{x, y}` numbers (empty: the identity).
|
||||
fn point_curve(v: &Value) -> Option<Vec<(f64, f64)>> {
|
||||
v.as_array()?
|
||||
.iter()
|
||||
.map(|q| {
|
||||
let o = q.as_object().filter(|o| o.len() == 2)?;
|
||||
Some((o.get("x")?.as_f64()?, o.get("y")?.as_f64()?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Two point curves blended by `t` at the control points of both (see [`interpolate_leaf`]).
|
||||
fn blend_curves(base: &[(f64, f64)], patch: &[(f64, f64)], t: f64) -> Value {
|
||||
use lightcraft_color::spline::MonotoneCurve;
|
||||
let (bc, pc) = (MonotoneCurve::new(base), MonotoneCurve::new(patch));
|
||||
let mut xs: Vec<f64> = bc.points().into_iter().chain(pc.points()).map(|(x, _)| x.clamp(0.0, 1.0)).collect();
|
||||
xs.sort_by(f64::total_cmp);
|
||||
xs.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
|
||||
let points = xs
|
||||
.into_iter()
|
||||
.map(|x| {
|
||||
let (yb, yp) = (bc.eval(x), pc.eval(x));
|
||||
serde_json::json!({"x": x, "y": (yb + (yp - yb) * t).clamp(0.0, 1.0)})
|
||||
})
|
||||
.collect();
|
||||
Value::Array(points)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Preset {
|
||||
pub id: String,
|
||||
@@ -285,6 +355,11 @@ impl Preset {
|
||||
/// settings (see [`Preset::apply_on`]): right for the import default preset and for scratch
|
||||
/// bases. Masks in the preset are added to the photo's own (ones it already has are skipped),
|
||||
/// their effect scaled by the amount.
|
||||
///
|
||||
/// This knows nothing about the photo's source. A preset that names only one white balance
|
||||
/// number needs the photo prepared against its as-shot white first, and the result put back on
|
||||
/// the scale the photo is edited on: callers on a real photo go through the engine's
|
||||
/// `apply_preset_to_photo`, which does that.
|
||||
pub fn apply(&self, s: &DevelopSettings, amount: f64) -> DevelopSettings {
|
||||
self.apply_on(s, s, amount)
|
||||
}
|
||||
@@ -295,8 +370,15 @@ impl Preset {
|
||||
/// the photo's pixel repairs (masks, spots, red eye), which the preset patches; masks in the
|
||||
/// preset are added to the photo's own (ones it already has are skipped), their effect scaled
|
||||
/// by the amount. A second preset therefore restores what the first one changed in the
|
||||
/// settings it names (issue #2159), and nothing it leaves out.
|
||||
/// settings it names (issue #2159), and nothing it leaves out. At 0 % (or less) the settings it
|
||||
/// names take `original`'s values, so with `current` as the original nothing changes, and its
|
||||
/// masks are not added (a mask at no strength would only block applying the preset later); a
|
||||
/// NaN `amount` changes nothing.
|
||||
pub fn apply_on(&self, current: &DevelopSettings, original: &DevelopSettings, amount: f64) -> DevelopSettings {
|
||||
if amount.is_nan() {
|
||||
return current.clone();
|
||||
}
|
||||
let amount = amount.max(0.0);
|
||||
let Some(masks) = self.settings.get("masks").and_then(Value::as_array).filter(|m| !m.is_empty()) else {
|
||||
return compose_named(current, original, &self.settings, amount);
|
||||
};
|
||||
@@ -305,7 +387,9 @@ impl Preset {
|
||||
o.remove("masks");
|
||||
}
|
||||
let mut out = compose_named(current, original, &rest, amount);
|
||||
add_masks(&mut out, masks, amount);
|
||||
if amount > 0.0 {
|
||||
add_masks(&mut out, masks, amount);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -391,6 +475,250 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn pts(v: &[(f64, f64)]) -> Vec<lightcraft_geom::Point> {
|
||||
v.iter().map(|&(x, y)| lightcraft_geom::Point::new(x, y)).collect()
|
||||
}
|
||||
|
||||
fn eval(c: &[lightcraft_geom::Point], x: f64) -> f64 {
|
||||
lightcraft_color::spline::MonotoneCurve::new(&c.iter().map(|p| (p.x, p.y)).collect::<Vec<_>>()).eval(x)
|
||||
}
|
||||
|
||||
fn preset(settings: Value) -> Preset {
|
||||
Preset { id: "p".into(), name: "P".into(), group: "G".into(), settings, favorite: false, builtin: false }
|
||||
}
|
||||
|
||||
/// Issue #2669: a preset's tone curve did nothing below 50 % and all of it from 50 % up.
|
||||
#[test]
|
||||
fn amount_blends_point_curves() {
|
||||
let curve = [(0.0, 0.0), (0.25, 0.15), (0.75, 0.85), (1.0, 1.0)];
|
||||
let partial = json!({"curve": {"master": pts(&curve)}});
|
||||
let base = DevelopSettings::default();
|
||||
let mut last = 0.25;
|
||||
for i in 1..=10 {
|
||||
let t = f64::from(i) / 10.0;
|
||||
let out = apply_partial(&base, &partial, t);
|
||||
let y = eval(&out.curve.master, 0.25);
|
||||
assert!((y - (0.25 - 0.10 * t)).abs() < 1e-9, "{t}: y(0.25) = {y}");
|
||||
assert!(y < last + 1e-12, "{t}: the curve moves steadily towards the preset's");
|
||||
last = y;
|
||||
}
|
||||
assert!(apply_partial(&base, &partial, 0.0).curve.master.is_empty(), "0 % keeps the photo's curve");
|
||||
// 200 % goes twice as far, kept in 0..1
|
||||
let more = apply_partial(&base, &partial, 2.0);
|
||||
assert!((eval(&more.curve.master, 0.25) - 0.05).abs() < 1e-9);
|
||||
assert!(more.curve.master.iter().all(|p| (0.0..=1.0).contains(&p.y)));
|
||||
|
||||
// a photo whose original has its own curves (other points): at every control point of either
|
||||
// curve the result is the blend of the original's curve and the preset's as rendered, whatever
|
||||
// the photo's current curve is
|
||||
let mut original = DevelopSettings::default();
|
||||
original.curve.master = pts(&[(0.0, 0.05), (0.5, 0.6), (1.0, 0.95)]);
|
||||
original.curve.red = pts(&[(0.0, 0.0), (0.4, 0.5), (1.0, 1.0)]);
|
||||
let mut current = DevelopSettings::default();
|
||||
current.curve.master = pts(&[(0.0, 0.2), (1.0, 0.8)]);
|
||||
let p = preset(json!({"curve": {"master": pts(&curve), "red": []}}));
|
||||
let out = p.apply_on(¤t, &original, 0.4);
|
||||
for x in [0.0, 0.25, 0.5, 0.75, 1.0] {
|
||||
let want = eval(&original.curve.master, x) * 0.6 + eval(&pts(&curve), x) * 0.4;
|
||||
assert!((eval(&out.curve.master, x) - want).abs() < 1e-9, "x {x}");
|
||||
}
|
||||
// towards the identity (an empty curve) too
|
||||
assert!((eval(&out.curve.red, 0.4) - (0.5 * 0.6 + 0.4 * 0.4)).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// The profile (and LUT) choice steps to the preset's at half amount, as every choice does
|
||||
/// (#2207); from there its strength fades in from 0 %, so the look shows in proportion to the
|
||||
/// amount. The same profile blends its amount from the original's, not the photo's current one.
|
||||
#[test]
|
||||
fn amount_fades_in_a_new_profile() {
|
||||
let p = preset(json!({"profile": {"id": "lc.vivid", "amount": 150.0}}));
|
||||
let base = DevelopSettings::default();
|
||||
for (t, id, amount) in [(0.3, "lc.color", 100.0), (0.5, "lc.vivid", 75.0), (0.8, "lc.vivid", 120.0), (1.0, "lc.vivid", 150.0)] {
|
||||
let out = p.apply_on(&base, &base, t);
|
||||
assert_eq!(out.profile.id, id, "{t}");
|
||||
assert!((out.profile.amount - amount).abs() < 1e-9, "{t}: amount {}", out.profile.amount);
|
||||
}
|
||||
assert_eq!(p.apply_on(&base, &base, 0.0), base, "0 % changes nothing");
|
||||
// the same profile: its amount blends from the original's (60 → 150 at 50 % is 105), not
|
||||
// from the photo's current 20
|
||||
let mut original = DevelopSettings::default();
|
||||
original.profile.id = "lc.vivid".into();
|
||||
original.profile.amount = 60.0;
|
||||
let mut current = original.clone();
|
||||
current.profile.amount = 20.0;
|
||||
for t in [0.3, 0.5] {
|
||||
let out = p.apply_on(¤t, &original, t);
|
||||
assert_eq!(out.profile.id, "lc.vivid");
|
||||
assert!((out.profile.amount - (60.0 + 90.0 * t)).abs() < 1e-9, "{t}: {}", out.profile.amount);
|
||||
}
|
||||
}
|
||||
|
||||
/// Switches and choices keep the original's value below half amount and take the preset's from
|
||||
/// half amount up; an `enabled` switch or a style the preset changes brings its amount in from 0
|
||||
/// there, and below half amount leaves the original's amount as it is.
|
||||
#[test]
|
||||
fn amount_steps_switches_and_choices_at_half_and_fades_in_their_amount() {
|
||||
let mut original = DevelopSettings::default();
|
||||
original.lens_blur.amount = 50.0;
|
||||
original.optics.lens_profile = true;
|
||||
let style = serde_json::to_value(crate::VignetteStyle::ColorPriority).unwrap();
|
||||
let p = preset(json!({
|
||||
"lens_blur": {"enabled": true, "amount": 80.0},
|
||||
"treatment": "bw",
|
||||
"optics": {"lens_profile": false},
|
||||
"vignette": {"style": style, "amount": -40.0},
|
||||
}));
|
||||
let mut current = original.clone();
|
||||
current.light.exposure = 1.0;
|
||||
let low = p.apply_on(¤t, &original, 0.25);
|
||||
assert!(!low.lens_blur.enabled);
|
||||
assert_eq!(low.lens_blur.amount, 50.0, "below half the original's own amount");
|
||||
assert_eq!(low.treatment, original.treatment);
|
||||
assert!(low.optics.lens_profile);
|
||||
assert_eq!((low.vignette.style, low.vignette.amount), (original.vignette.style, original.vignette.amount));
|
||||
assert_eq!(low.light.exposure, 1.0, "a setting the preset doesn't name keeps the photo's value");
|
||||
let half = p.apply_on(¤t, &original, 0.5);
|
||||
assert!(half.lens_blur.enabled);
|
||||
assert!((half.lens_blur.amount - 40.0).abs() < 1e-9, "{}", half.lens_blur.amount);
|
||||
assert_eq!(half.treatment, crate::Treatment::Bw);
|
||||
assert!(!half.optics.lens_profile);
|
||||
assert_eq!(half.vignette.style, crate::VignetteStyle::ColorPriority);
|
||||
assert!((half.vignette.amount + 20.0).abs() < 1e-9, "{}", half.vignette.amount);
|
||||
assert_eq!(p.apply_on(¤t, &original, 0.0), current, "0 % changes nothing");
|
||||
}
|
||||
|
||||
/// HDR is left out of the JSON while at its defaults; its numbers still blend from the original's.
|
||||
#[test]
|
||||
fn amount_blends_groups_left_out_at_their_defaults() {
|
||||
let p = preset(json!({"hdr": {"enabled": true, "sdr_contrast": 40.0}}));
|
||||
let base = DevelopSettings::default();
|
||||
let out = p.apply_on(&base, &base, 0.5);
|
||||
assert!(out.hdr.enabled);
|
||||
assert!((out.hdr.sdr_contrast - 20.0).abs() < 1e-9, "{}", out.hdr.sdr_contrast);
|
||||
let out = apply_partial(&base, &p.settings, 0.3);
|
||||
assert!(!out.hdr.enabled);
|
||||
assert!((out.hdr.sdr_contrast - 12.0).abs() < 1e-9, "{}", out.hdr.sdr_contrast);
|
||||
}
|
||||
|
||||
/// White balance on another scale (Kelvin against the older relative one) is in other units:
|
||||
/// the original's below half amount and the preset's from half amount up, each whole with its
|
||||
/// scale, never a blend of the two.
|
||||
#[test]
|
||||
fn amount_takes_white_balance_on_another_scale_whole() {
|
||||
let kelvin = preset(json!({"wb": {"mode": "custom", "temp": 4200.0, "tint": 8.0, "scale": "kelvin"}}));
|
||||
let photo = DevelopSettings::default(); // relative scale, 6500 / 0 = as shot
|
||||
for t in [0.01, 0.3, 0.49] {
|
||||
assert_eq!(kelvin.apply_on(&photo, &photo, t).wb, photo.wb, "{t}");
|
||||
}
|
||||
for t in [0.5, 0.7, 1.5] {
|
||||
let out = kelvin.apply_on(&photo, &photo, t);
|
||||
assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Kelvin, 4200.0, 8.0), "{t}");
|
||||
}
|
||||
let wb = crate::WhiteBalance { mode: crate::WbMode::Custom, temp: 5000.0, tint: 0.0, scale: crate::WbScale::Kelvin };
|
||||
let photo = DevelopSettings { wb, ..DevelopSettings::default() };
|
||||
// a partial without a scale is on the relative scale
|
||||
let relative = preset(json!({"wb": {"temp": 7000.0, "tint": 10.0}}));
|
||||
assert_eq!(relative.apply_on(&photo, &photo, 0.3).wb, photo.wb);
|
||||
let out = relative.apply_on(&photo, &photo, 0.6);
|
||||
assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Legacy, 7000.0, 10.0));
|
||||
// the same scale blends
|
||||
let out = kelvin.apply_on(&photo, &photo, 0.5);
|
||||
assert_eq!((out.wb.scale, out.wb.temp, out.wb.tint), (crate::WbScale::Kelvin, 4600.0, 4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_amount_mask_preset_leaves_settings_unchanged_and_can_be_applied_later() {
|
||||
let photo = DevelopSettings { masks: vec![crate::Mask { id: 9, name: "Existing".into(), ..Default::default() }], ..Default::default() };
|
||||
let p = preset(json!({"light": {"exposure": 1.0}, "masks": [{"name": "New", "adjust": {"amount": 80.0}}]}));
|
||||
for amount in [0.0, -0.5, f64::NAN] {
|
||||
let unchanged = p.apply_on(&photo, &photo, amount);
|
||||
assert_eq!(unchanged, photo);
|
||||
let out = p.apply(&unchanged, 1.0);
|
||||
assert_eq!(out.light.exposure, 1.0);
|
||||
assert_eq!(out.masks.len(), 2);
|
||||
assert_eq!(out.masks[0], photo.masks[0]);
|
||||
assert_eq!(out.masks[1].name, "New");
|
||||
assert_eq!(out.masks[1].adjust.amount, 80.0);
|
||||
}
|
||||
// with an import state, 0 % is that state for the settings the preset names (#2207), and still
|
||||
// adds no mask
|
||||
let mut current = photo.clone();
|
||||
current.light.exposure = 2.0;
|
||||
current.curve.master = pts(&[(0.0, 0.1), (1.0, 0.9)]);
|
||||
let original = DevelopSettings { light: crate::Light { exposure: -0.5, ..Default::default() }, ..Default::default() };
|
||||
let q =
|
||||
preset(json!({"light": {"exposure": 1.0}, "curve": {"master": pts(&[(0.0, 0.0), (0.5, 0.7), (1.0, 1.0)])}, "masks": [{"name": "New"}]}));
|
||||
let out = q.apply_on(¤t, &original, 0.0);
|
||||
assert_eq!(out.light.exposure, -0.5);
|
||||
assert!(out.curve.master.is_empty(), "the original's curve, point for point");
|
||||
assert_eq!(out.masks, current.masks);
|
||||
}
|
||||
|
||||
/// Every leaf of `v` that is not a number (and every list's length), by path.
|
||||
fn non_numbers(v: &Value, path: &str, out: &mut Vec<(String, Value)>) {
|
||||
match v {
|
||||
Value::Object(o) => o.iter().for_each(|(k, v)| non_numbers(v, &format!("{path}/{k}"), out)),
|
||||
Value::Array(a) => {
|
||||
out.push((format!("{path}#len"), Value::from(a.len())));
|
||||
a.iter().enumerate().for_each(|(i, v)| non_numbers(v, &format!("{path}/{i}"), out));
|
||||
}
|
||||
Value::Number(_) => {}
|
||||
v => out.push((path.to_string(), v.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Across the whole Amount range a preset has one step, at half amount (#2207): below it the
|
||||
/// switches, choices and lists stay as at 1 %, from it as at 50 %; the numbers and tone curves
|
||||
/// move in proportion to the amount throughout, and the strength of a changed choice fades in
|
||||
/// from 0 once the choice is the preset's.
|
||||
#[test]
|
||||
fn amount_has_one_step_at_half_and_blends_the_rest() {
|
||||
let mut a = DevelopSettings::default();
|
||||
a.profile.id = "lc.vivid".into();
|
||||
a.profile.amount = 140.0;
|
||||
a.treatment = crate::Treatment::Bw;
|
||||
a.light.exposure = 0.8;
|
||||
a.curve.master = pts(&[(0.0, 0.0), (0.3, 0.2), (0.7, 0.8), (1.0, 1.0)]);
|
||||
a.curve.green = pts(&[(0.0, 0.05), (1.0, 0.9)]);
|
||||
a.grain.amount = 30.0;
|
||||
a.grain.seed = 777;
|
||||
a.vignette.style = crate::VignetteStyle::ColorPriority;
|
||||
a.vignette.amount = -25.0;
|
||||
a.lens_blur = crate::LensBlur { enabled: true, amount: 60.0, focal_distance: 30.0, focal_range: 20.0, ..Default::default() };
|
||||
a.optics.remove_ca = true;
|
||||
let p = Preset::from_settings("p", "P", "User", &a, &SettingsGroup::default_copy());
|
||||
let mut original = DevelopSettings::default();
|
||||
original.curve.master = pts(&[(0.0, 0.1), (0.5, 0.45), (1.0, 1.0)]);
|
||||
original.light.exposure = -0.4;
|
||||
let mut current = original.clone();
|
||||
current.light.exposure = 2.0;
|
||||
let leaves = |t: f64| {
|
||||
let mut v = Vec::new();
|
||||
non_numbers(&p.apply_on(¤t, &original, t).to_json(), "", &mut v);
|
||||
v
|
||||
};
|
||||
let (below, above) = (leaves(0.01), leaves(0.5));
|
||||
assert_ne!(below, above, "the choices step at half amount");
|
||||
let y0 = eval(&original.curve.master, 0.3);
|
||||
for i in 2..=200 {
|
||||
let t = f64::from(i) / 100.0;
|
||||
let out = p.apply_on(¤t, &original, t);
|
||||
if i != 100 {
|
||||
// (at exactly 100 % the preset is merged as it is: its own curve points)
|
||||
assert_eq!(leaves(t), if t < 0.5 { below.clone() } else { above.clone() }, "{t}: a switch, choice or list moved off its side");
|
||||
}
|
||||
let want = (-0.4 + 1.2 * t).min(5.0);
|
||||
assert!((out.light.exposure - want).abs() < 1e-9, "{t}: exposure {}", out.light.exposure);
|
||||
let (profile, blur) =
|
||||
if t < 0.5 { (original.profile.amount, original.lens_blur.amount) } else { ((140.0 * t).min(200.0), (60.0 * t).min(100.0)) };
|
||||
assert!((out.profile.amount - profile).abs() < 1e-9, "{t}: profile amount {}", out.profile.amount);
|
||||
assert!((out.lens_blur.amount - blur).abs() < 1e-9, "{t}: lens blur amount {}", out.lens_blur.amount);
|
||||
let y = eval(&out.curve.master, 0.3);
|
||||
let want = (y0 + (0.2 - y0) * t).clamp(0.0, 1.0);
|
||||
assert!((y - want).abs() < 1e-9, "{t}: curve y(0.3) {y}, want {want}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset changes only the settings it names: a setting in a group it styles but does not
|
||||
/// name keeps the photo's value, and so does a whole group it leaves out.
|
||||
#[test]
|
||||
|
||||
@@ -37,7 +37,7 @@ pub(crate) use look_fit::fit_preview;
|
||||
#[cfg(test)]
|
||||
use look_fit::{
|
||||
FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, at_most, clips_more, correct_vignetting, fit_look, fit_look_with, sony_dro_off_tone, with_dro_off_tone,
|
||||
without_clipped,
|
||||
with_pooled_tone, with_profile_colour, without_clipped,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use mono::{fit_dark_tone, fit_tone_only, monochrome, monochrome_look, to_prophoto};
|
||||
@@ -50,9 +50,10 @@ use pairs::{
|
||||
pub(crate) use proxy::LensGeometry;
|
||||
#[cfg(test)]
|
||||
use proxy::{
|
||||
Cr3Framing, MIN_PREVIEW_FRACTION, alignment, estimate_cr3_framing, into_lens_geometry, proxies, reference_at, sensor_proxy, structure_agrees,
|
||||
Cr3Framing, MIN_PREVIEW_FRACTION, THIN_TOLERANCE, alignment, estimate_cr3_framing, extend_tone, into_lens_geometry, proxies, reference_at,
|
||||
samples_from_proxies, sensor_proxy, structure_agrees,
|
||||
};
|
||||
pub(crate) use proxy::{fit_profile, lens_geometry, profile_pairs};
|
||||
pub(crate) use proxy::{fit_profile, fit_profile_tone, lens_geometry, profile_samples};
|
||||
#[cfg(test)]
|
||||
use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights};
|
||||
|
||||
@@ -86,7 +87,11 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights};
|
||||
/// the warped candidate's alignment leaves out the pixels outside the sensor instead of reading them as black.
|
||||
/// 14: bundled camera profiles also match the Nikon model spellings that differ in case, spacing or the Z8 alias,
|
||||
/// so previews made without the profile are rebuilt.
|
||||
pub const LOOK_VERSION: u32 = 14;
|
||||
/// 15: a photo no look fits keeps its camera profile's colour instead of the neutral fallback.
|
||||
/// 16: a camera profile's pooled tone curve continues a photo's own past what its JPEG showed.
|
||||
/// 17: only a look with the profile's colour continues along its pooled tone curve.
|
||||
/// 18: continuing a photo's curve keeps it as it was where its JPEG taught it (`thinned_knots`).
|
||||
pub const LOOK_VERSION: u32 = 18;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct CameraLook {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::colour::{PROXY, file_local_look};
|
||||
use super::mono::{fit_tone_only_with, monochrome};
|
||||
use super::pairs::{Attempt, TONE_FITS, fit_attempt, fit_partial, search_ordered};
|
||||
use super::proxy::{CLIP_TOLERANCE, LensGeometry, MIN_PREVIEW_FRACTION, proxies, structure_agrees};
|
||||
use super::proxy::{CLIP_TOLERANCE, LensGeometry, MIN_PREVIEW_FRACTION, extend_tone, proxies, structure_agrees};
|
||||
use super::tone::{HighlightCheck, highlights};
|
||||
use super::{CameraLook, CameraTone, CameraTransform, HsvTable, Mat3, RawImage, Rgb32f, ToneMap, luminance_2020};
|
||||
|
||||
@@ -26,18 +26,17 @@ pub(crate) fn fit_preview(
|
||||
// Sony's Dynamic Range Optimizer (on by default) brightens the camera JPEG's darker regions,
|
||||
// not the raw: keep the colour fitted to the JPEG, take the tone curve without DRO.
|
||||
let dro = lightcraft_raw::embedded_preview_dynamic_range_optimized(bytes) == Some(true);
|
||||
let look = match fit_look_with(&sensor, &reference, &clipped, colour.clone(), dro) {
|
||||
Some(look) => look,
|
||||
// A black-and-white JPEG has no colour to fit: the profile's colour and the JPEG's tone curve
|
||||
// (`monochrome_look` does it without a profile).
|
||||
None if colour.is_some() && black_and_white => {
|
||||
let unclipped = without_clipped(&sensor, &clipped);
|
||||
let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro, grey: true };
|
||||
let Some(look) = fit_tone_only_with(unclipped.as_ref().unwrap_or(&sensor), &reference, colour, &bright) else { return (None, true) };
|
||||
look
|
||||
}
|
||||
None => return (None, black_and_white),
|
||||
let pooled = profile.as_ref().and_then(|p| p.tone);
|
||||
let profile_matrix = colour.as_ref().map(|c| c.0);
|
||||
let fitted = fit_look_with(&sensor, &reference, &clipped, colour.clone(), dro);
|
||||
let tone_only = |colour| {
|
||||
let unclipped = without_clipped(&sensor, &clipped);
|
||||
let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro, grey: true };
|
||||
fit_tone_only_with(unclipped.as_ref().unwrap_or(&sensor), &reference, Some(colour), &bright)
|
||||
};
|
||||
let Some(look) = with_profile_colour(fitted, colour, pooled, tone_only) else { return (None, black_and_white) };
|
||||
// the camera's own curve past what this photo's JPEG showed
|
||||
let look = with_pooled_tone(look, profile_matrix, pooled);
|
||||
let look = if dro { with_dro_off_tone(look) } else { look };
|
||||
if lightcraft_pipeline::profiling() {
|
||||
eprintln!(
|
||||
@@ -52,6 +51,36 @@ pub(crate) fn fit_preview(
|
||||
(Some(look), black_and_white)
|
||||
}
|
||||
|
||||
/// `look` with its tone curve continued along the camera profile's `pooled` one ([`extend_tone`]), when the look
|
||||
/// takes the profile's colour (`profile_matrix`). A look fitted with the photo's own matrix keeps its curve: the pooled
|
||||
/// one maps luminance through the profile's matrix, which that photo's colours don't go through.
|
||||
pub(super) fn with_pooled_tone(look: CameraLook, profile_matrix: Option<Mat3>, pooled: Option<CameraTone>) -> CameraLook {
|
||||
match (pooled, profile_matrix) {
|
||||
(Some(pooled), Some(matrix)) if look.matrix == matrix => CameraLook { tone: extend_tone(&look.tone, &pooled), ..look },
|
||||
_ => look,
|
||||
}
|
||||
}
|
||||
|
||||
/// `fitted`, the photo's own look, or when no look fits it (a black-and-white JPEG has no colour; a dark one too few
|
||||
/// colour pairs) its camera profile's `colour`: with the JPEG's tone curve when [`fit_tone_only`] finds one
|
||||
/// (`monochrome_look` does it without a profile), else the profile's pooled tone curve, else the default raw one. Dropping the profile there for the
|
||||
/// neutral fallback left a NIKON D780 frame 3.7 EV under, pushed back up, at 37% of its properly exposed twin's chroma
|
||||
/// (88-99% with the profile's colour).
|
||||
pub(super) fn with_profile_colour(
|
||||
fitted: Option<CameraLook>,
|
||||
colour: Option<(Mat3, Option<HsvTable>)>,
|
||||
pooled: Option<CameraTone>,
|
||||
tone_only: impl FnOnce((Mat3, Option<HsvTable>)) -> Option<CameraLook>,
|
||||
) -> Option<CameraLook> {
|
||||
if fitted.is_some() {
|
||||
return fitted;
|
||||
}
|
||||
let colour = colour?;
|
||||
tone_only(colour.clone()).or_else(|| {
|
||||
Some(CameraLook { matrix: colour.0, tone: pooled.or_else(lightcraft_pipeline::tone::default_raw_camera_tone)?, hue_sat: colour.1 })
|
||||
})
|
||||
}
|
||||
|
||||
/// Sensor level (normalised, white = 1) at or above which a raw channel counts as clipped, as in
|
||||
/// the render's highlight reconstruction.
|
||||
pub(super) const SENSOR_CLIP: f32 = 0.99;
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use super::colour::{PROFILE_PROXY, PROXY, file_local_look};
|
||||
use super::hue_sat::fit_hue_sat;
|
||||
use super::look_fit::{FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, clip_mask, correct_vignetting, without_clipped};
|
||||
use super::pairs::{collect_pairs, fit_matrix};
|
||||
use super::{CameraTransform, Filter, HsvTable, Mat3, RawFormat, RawImage, Rgb32f, fit, luminance_2020, resize};
|
||||
use super::mono::monochrome;
|
||||
use super::pairs::{collect_pairs, fit_matrix, luma};
|
||||
use super::tone::fit_tone;
|
||||
use super::{CameraTone, CameraTransform, Filter, HsvTable, Mat3, RawFormat, RawImage, Rgb32f, fit, luminance_2020, resize};
|
||||
|
||||
/// The embedded preview's long edge must be at least this share of the raw's (and 384 px): a DNG whose preview is a
|
||||
/// small thumbnail is not fitted. The fit itself runs on a proxy of at most 384 px, so the 1024 px preview
|
||||
@@ -314,10 +316,19 @@ fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rg
|
||||
(apply(&sensor), apply(&clipped))
|
||||
}
|
||||
|
||||
/// Colour training pairs of one raw for a camera profile: white-balanced camera RGB (with the
|
||||
/// baseline exposure) → its camera JPEG (linear Rec.2020). `None` for formats with their own
|
||||
/// colour matrices, other files or unusable previews.
|
||||
pub(crate) fn profile_pairs(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option<Vec<([f64; 3], [f64; 3])>> {
|
||||
/// What one photo contributes to a camera profile ([`profile_samples`]), in white-balanced camera RGB.
|
||||
pub(crate) struct ProfileSamples {
|
||||
/// Colour pairs: camera RGB → the camera JPEG's linear Rec.2020 (empty when the photo has too little colour).
|
||||
pub colour: Vec<([f64; 3], [f64; 3])>,
|
||||
/// Tone samples: camera RGB → the camera JPEG's luminance, dark pixels included (as the photo's own toe fit takes
|
||||
/// them, [`fit_tone_with_shadows`](super::pairs::fit_tone_with_shadows)).
|
||||
pub tone: Vec<([f64; 3], f64)>,
|
||||
}
|
||||
|
||||
/// A raw's colour and tone samples for a pooled camera profile (`lightcraft-cli calibrate`): white-balanced camera
|
||||
/// RGB (with the baseline exposure) → its camera JPEG (linear Rec.2020). `None` for formats with their own colour
|
||||
/// matrices, other files or unusable previews.
|
||||
pub(crate) fn profile_samples(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option<ProfileSamples> {
|
||||
if !file_local_look(raw.format) || lightcraft_raw::color::has_matrix(&raw.color) {
|
||||
return None;
|
||||
}
|
||||
@@ -326,8 +337,130 @@ pub(crate) fn profile_pairs(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeom
|
||||
let to_camera = transform.matrix.inverse()?;
|
||||
// clipped sensor pixels don't record the scene's colour (see `fit_look`)
|
||||
let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor);
|
||||
let (pairs, _) = collect_pairs(&sensor, &reference, 0.05, None, false)?;
|
||||
Some(pairs.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect())
|
||||
samples_from_proxies(&sensor, &reference, &to_camera)
|
||||
}
|
||||
|
||||
/// [`profile_samples`] from a raw's sensor proxy (clipped pixels left out) and its camera JPEG's, `to_camera` taking the
|
||||
/// sensor proxy back to white-balanced camera RGB.
|
||||
pub(super) fn samples_from_proxies(sensor: &Rgb32f, reference: &Rgb32f, to_camera: &Mat3) -> Option<ProfileSamples> {
|
||||
// a black-and-white JPEG went through a monochrome picture style's own mix and curve: nothing for the profile
|
||||
if monochrome(reference) {
|
||||
return None;
|
||||
}
|
||||
// a dark or colourless photo has no colour pairs but still shows the shadows the pooled curve needs
|
||||
let colour = collect_pairs(sensor, reference, 0.05, None, false).map_or_else(Vec::new, |(pairs, _)| pairs);
|
||||
let tone: Vec<_> = sensor
|
||||
.data
|
||||
.iter()
|
||||
.zip(&reference.data)
|
||||
.filter(|(input, output)| tone_sample(**input, **output))
|
||||
.map(|(input, output)| (to_camera.apply(input.map(f64::from)), f64::from(luminance_2020(*output))))
|
||||
.collect();
|
||||
if colour.is_empty() && tone.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(ProfileSamples { colour: colour.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect(), tone })
|
||||
}
|
||||
|
||||
/// Whether a sensor/JPEG proxy pixel pair can teach the tone curve: every channel above the sensor floor, the JPEG
|
||||
/// pixel about one 8-bit sRGB code above black (no flat black segment learnt from JPEG compression) and below the
|
||||
/// highlights (clipped or rolled off).
|
||||
fn tone_sample(input: [f32; 3], output: [f32; 3]) -> bool {
|
||||
input.iter().all(|v| v.is_finite() && *v > 0.0001 && *v < 1.5)
|
||||
&& output.iter().all(|v| v.is_finite() && *v >= 0.0)
|
||||
&& (0.0003..0.85).contains(&luminance_2020(output))
|
||||
}
|
||||
|
||||
/// A camera profile's tone curve from the tone samples pooled over its photos, through the profile's `matrix`: one
|
||||
/// curve for the camera, from shadows that only dark photos show to highlights that only bright ones show. Quantile
|
||||
/// matching ([`fit_tone`]) pools correctly because every photo went through the same camera curve (picture styles and
|
||||
/// Active D-Lighting aside, which it averages). Luminance is taken with negative channels kept, as the render feeds
|
||||
/// the curve (raw decoding keeps them, `files::CameraColourModel`).
|
||||
pub(crate) fn fit_profile_tone(samples: &[([f64; 3], f64)], matrix: &Mat3) -> Option<CameraTone> {
|
||||
fit_tone(samples.iter().map(|(x, y)| (luma(matrix.apply(*x)), *y)).filter(|(x, _)| *x > 0.0).collect())
|
||||
}
|
||||
|
||||
/// `photo`'s tone curve where its JPEG taught it, `pooled`'s past that: from the photo's last knot it fades over
|
||||
/// 1 EV (`EXTEND_FADE_EV`) from its own level onto the camera's pooled curve, instead of the bounded shoulder
|
||||
/// ([`CameraTone::apply`]) whose rate comes from the photo's last two knots. A dark photo's curve ends in the shadows,
|
||||
/// and that shoulder rendered it, pushed back up, 4-7 L* darker than a properly exposed photo of the same scene.
|
||||
/// `photo` unchanged when the pooled curve doesn't reach on past it.
|
||||
pub(super) fn extend_tone(photo: &CameraTone, pooled: &CameraTone) -> CameraTone {
|
||||
/// EV over which the extension moves from the photo's level onto the pooled curve.
|
||||
const EXTEND_FADE_EV: f32 = 1.0;
|
||||
/// Knots per EV of the extension.
|
||||
const EXTEND_KNOTS_PER_EV: f32 = 3.0;
|
||||
let (own, camera) = (photo.knots(), pooled.knots());
|
||||
let (end, last) = (own[31], camera[31][0]);
|
||||
let span = (last / end[0]).log2();
|
||||
if !(span.is_finite() && span > 0.2) {
|
||||
return *photo;
|
||||
}
|
||||
// the photo's own knots, the ones its curve needs least dropped to make room: as many extension knots as keep the
|
||||
// curve within `THIN_TOLERANCE` where the JPEG taught it, at least 2, else the photo keeps its curve as it is
|
||||
let Some((extra, own)) =
|
||||
(2..=((span * EXTEND_KNOTS_PER_EV).round() as usize).clamp(2, 16)).rev().find_map(|extra| thinned_knots(own, 32 - extra).map(|k| (extra, k)))
|
||||
else {
|
||||
if lightcraft_pipeline::profiling() {
|
||||
eprintln!("[profile] camera look: the photo's curve can't make room for the pooled one, kept as fitted");
|
||||
}
|
||||
return *photo;
|
||||
};
|
||||
if lightcraft_pipeline::profiling() {
|
||||
eprintln!("[profile] camera look: pooled tone curve joined with {extra} knots past the photo's");
|
||||
}
|
||||
let at_end = pooled.apply(end[0]);
|
||||
let ratio = if at_end > 0.0 && end[1] > 0.0 { end[1] / at_end } else { 1.0 };
|
||||
let mut knots = [[0.0f32; 2]; 32];
|
||||
let kept = 32 - extra;
|
||||
for (knot, own) in knots.iter_mut().zip(&own) {
|
||||
*knot = *own;
|
||||
}
|
||||
for k in 1..=extra {
|
||||
let ev = span * k as f32 / extra as f32;
|
||||
let x = end[0] * ev.exp2();
|
||||
let t = (ev / EXTEND_FADE_EV).clamp(0.0, 1.0);
|
||||
let w = t * t * (3.0 - 2.0 * t);
|
||||
knots[kept + k - 1] = [x, pooled.apply(x) * ratio.powf(1.0 - w)];
|
||||
}
|
||||
// monotone and below white whatever the two curves do
|
||||
let mut floor = 0.0f32;
|
||||
for knot in &mut knots {
|
||||
knot[1] = knot[1].max(floor).min(0.999);
|
||||
floor = knot[1];
|
||||
}
|
||||
CameraTone::new(knots).and_then(|tone| tone.with_chroma(*photo.chroma())).unwrap_or(*photo)
|
||||
}
|
||||
|
||||
/// Largest change, in gamma-encoded display values (1/2.2), that thinning a photo's curve for [`extend_tone`] may make
|
||||
/// where its JPEG taught it: one 8-bit code.
|
||||
pub(super) const THIN_TOLERANCE: f32 = 1.0 / 255.0;
|
||||
|
||||
/// `knots` thinned to `keep` (first and last kept), dropping one at a time the knot whose removal changes the curve
|
||||
/// least (`CameraTone::apply` interpolates linearly, so the change peaks at a dropped knot); `None` when that change
|
||||
/// would exceed [`THIN_TOLERANCE`].
|
||||
fn thinned_knots(knots: &[[f32; 2]; 32], keep: usize) -> Option<Vec<[f32; 2]>> {
|
||||
let encoded = |v: f32| v.max(0.0).powf(1.0 / 2.2);
|
||||
// the change from leaving out every knot strictly between kept indices `a` and `b`
|
||||
let gap = |a: usize, b: usize| {
|
||||
let ([x0, y0], [x1, y1]) = (knots[a], knots[b]);
|
||||
(a + 1..b)
|
||||
.map(|i| {
|
||||
let [x, y] = knots[i];
|
||||
let t = if x1 > x0 { (x - x0) / (x1 - x0) } else { 0.0 };
|
||||
(encoded(y0 + t * (y1 - y0)) - encoded(y)).abs()
|
||||
})
|
||||
.fold(0.0f32, f32::max)
|
||||
};
|
||||
let mut kept: Vec<usize> = (0..knots.len()).collect();
|
||||
while kept.len() > keep.max(2) {
|
||||
let (i, change) = (1..kept.len() - 1).map(|i| (i, gap(kept[i - 1], kept[i + 1]))).min_by(|a, b| a.1.total_cmp(&b.1))?;
|
||||
if change > THIN_TOLERANCE {
|
||||
return None;
|
||||
}
|
||||
kept.remove(i);
|
||||
}
|
||||
Some(kept.into_iter().map(|i| knots[i]).collect())
|
||||
}
|
||||
|
||||
/// A camera profile's colour model (matrix from white-balanced camera RGB, hue/saturation table)
|
||||
|
||||
@@ -2457,6 +2457,171 @@ fn dng_tone_fit_takes_lightroom_sized_previews() {
|
||||
assert!(1024.0 >= floor(9504.0), "a 61 MP raw too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_photo_no_look_fits_keeps_its_camera_profiles_colour() {
|
||||
let colour = (
|
||||
Mat3([[1.8, -0.6, -0.2], [-0.3, 1.5, -0.2], [0.0, -0.4, 1.4]]),
|
||||
dro_test_look(&std::array::from_fn(|i| 0.01 + i as f32 * 0.01), &|x| x).hue_sat,
|
||||
);
|
||||
// too dark for any look, no tone either: the profile's colour, the default raw tone curve
|
||||
let look = with_profile_colour(None, Some(colour.clone()), None, |_| None).expect("the profile's colour");
|
||||
assert_eq!((look.matrix, look.hue_sat.is_some()), (colour.0, true));
|
||||
assert_eq!(look.tone, lightcraft_pipeline::tone::default_raw_camera_tone().unwrap());
|
||||
// the JPEG's tone curve when it has one
|
||||
let toned = dro_test_look(&std::array::from_fn(|i| 0.01 + i as f32 * 0.01), &|x| 0.9 * x);
|
||||
let look = with_profile_colour(None, Some(colour.clone()), None, |c| Some(CameraLook { matrix: c.0, ..toned.clone() })).unwrap();
|
||||
assert_eq!((look.matrix, look.tone), (colour.0, toned.tone));
|
||||
// a photo's own look wins; without a profile there is nothing to keep (the neutral fallback follows)
|
||||
let own = with_profile_colour(Some(toned.clone()), Some(colour), None, |_| panic!("the photo's own look is used")).unwrap();
|
||||
assert_eq!(own.matrix, toned.matrix);
|
||||
assert!(with_profile_colour(None, None, None, |_| panic!("no colour to fit")).is_none());
|
||||
}
|
||||
|
||||
/// A camera curve: a toe, then a shoulder toward 0.95, the shape camera JPEG curves have.
|
||||
fn camera_curve(x: f32) -> f32 {
|
||||
0.95 * (x / (x + 0.12)).powf(1.3) * 1.1
|
||||
}
|
||||
|
||||
fn sampled(curve: impl Fn(f32) -> f32, from: f32, to: f32) -> CameraTone {
|
||||
CameraTone::new(std::array::from_fn(|i| {
|
||||
let x = from * (to / from).powf(i as f32 / 31.0);
|
||||
[x, curve(x)]
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dark_photos_curve_goes_on_along_the_cameras_pooled_one() {
|
||||
let pooled = sampled(camera_curve, 0.0005, 0.9);
|
||||
// a dark photo's JPEG showed the curve up to 0.02, 10% darker than the camera's (a picture style)
|
||||
let photo = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02).with_chroma([1.4, 1.2, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]).unwrap();
|
||||
let tone = extend_tone(&photo, &pooled);
|
||||
assert_eq!(tone.chroma(), photo.chroma());
|
||||
// its own curve where its JPEG taught it, the pooled one from 1 EV past that, a monotone fade in between
|
||||
for x in [0.001f32, 0.005, 0.01, 0.019] {
|
||||
assert!((tone.apply(x) - photo.apply(x)).abs() < 0.02 * photo.apply(x), "{x}: {} vs {}", tone.apply(x), photo.apply(x));
|
||||
}
|
||||
for x in [0.05f32, 0.1, 0.3, 0.8] {
|
||||
assert!((tone.apply(x) - pooled.apply(x)).abs() < 0.01, "{x}: {} vs {}", tone.apply(x), pooled.apply(x));
|
||||
}
|
||||
assert!(tone.knots().windows(2).all(|k| k[1][0] > k[0][0] && k[1][1] >= k[0][1]));
|
||||
// a photo that already reaches as far keeps its curve
|
||||
let bright = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.85);
|
||||
assert_eq!(extend_tone(&bright, &pooled), bright);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extending_a_photos_curve_keeps_it_where_its_jpeg_taught_it() {
|
||||
let pooled = sampled(camera_curve, 0.0005, 0.9);
|
||||
let encoded = |v: f32| v.max(0.0).powf(1.0 / 2.2);
|
||||
// a smooth dark curve, and one with a sharp toe (flat, then a steep rise over two knots)
|
||||
let smooth = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02);
|
||||
let toe = CameraTone::new(std::array::from_fn(|i| {
|
||||
let x = 0.0005 * 40f32.powf(i as f32 / 31.0);
|
||||
[
|
||||
x,
|
||||
if i < 9 {
|
||||
0.001 + 0.0001 * i as f32
|
||||
} else if i < 11 {
|
||||
0.004 + 0.012 * (i - 8) as f32
|
||||
} else {
|
||||
0.03 + 0.004 * (i - 10) as f32
|
||||
},
|
||||
]
|
||||
}))
|
||||
.unwrap();
|
||||
for photo in [smooth, toe] {
|
||||
let tone = extend_tone(&photo, &pooled);
|
||||
for [x, _] in photo.knots() {
|
||||
let change = (encoded(tone.apply(*x)) - encoded(photo.apply(*x))).abs();
|
||||
assert!(change <= THIN_TOLERANCE + 1e-5, "{x}: {} vs {} ({change})", tone.apply(*x), photo.apply(*x));
|
||||
}
|
||||
}
|
||||
// the smooth one still goes on along the pooled curve
|
||||
assert!((extend_tone(&smooth, &pooled).apply(0.3) - pooled.apply(0.3)).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pooled_tone_curve_spans_dark_and_bright_photos() {
|
||||
// camera RGB grey (white balanced): a dark photo's pixels and a bright one's, through one camera curve
|
||||
let matrix = Mat3::IDENTITY;
|
||||
let samples: Vec<([f64; 3], f64)> = (0..4000)
|
||||
.map(|i| {
|
||||
let x = if i % 2 == 0 { 0.0005 * 40f64.powf((i / 2) as f64 / 2000.0) } else { 0.02 * 40f64.powf((i / 2) as f64 / 2000.0) };
|
||||
([x; 3], f64::from(camera_curve(x as f32)))
|
||||
})
|
||||
.collect();
|
||||
let tone = fit_profile_tone(&samples, &matrix).unwrap();
|
||||
for x in [0.001f32, 0.01, 0.05, 0.2, 0.6] {
|
||||
assert!((tone.apply(x) - camera_curve(x)).abs() < 0.01 + 0.03 * camera_curve(x), "{x}: {} vs {}", tone.apply(x), camera_curve(x));
|
||||
}
|
||||
assert!(fit_profile_tone(&samples[..64], &matrix).is_none(), "too few samples");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_photo_too_dark_for_colour_pairs_still_gives_the_pooled_curve_its_shadows() {
|
||||
// a scene of saturated colours, its camera JPEG a linear map of the sensor; `level` sets the exposure
|
||||
let colours = [[0.9, 0.2, 0.1], [0.1, 0.8, 0.2], [0.2, 0.3, 0.9], [0.8, 0.7, 0.1], [0.6, 0.2, 0.7], [0.5, 0.5, 0.5]];
|
||||
let scene = |level: f32| {
|
||||
let sensor = Rgb32f::from_fn(64, 64, |x, y| colours[(x / 8 + y / 8) % colours.len()].map(|v| v * level * (1.0 + (x % 8) as f32 / 16.0)));
|
||||
let reference = Rgb32f::from_fn(64, 64, |x, y| sensor.data[y * 64 + x].map(|v| v * 0.8));
|
||||
(sensor, reference)
|
||||
};
|
||||
let (sensor, reference) = scene(0.3);
|
||||
let bright = samples_from_proxies(&sensor, &reference, &Mat3::IDENTITY).unwrap();
|
||||
assert!(!bright.colour.is_empty() && !bright.tone.is_empty());
|
||||
// every JPEG channel under the colour-pair floor, its luminance still above the tone floor
|
||||
let (sensor, reference) = scene(0.003);
|
||||
assert!(reference.data.iter().all(|p| p.iter().all(|v| *v < 0.004)));
|
||||
let dark = samples_from_proxies(&sensor, &reference, &Mat3::IDENTITY).expect("tone samples from a dark photo");
|
||||
assert!(dark.colour.is_empty() && dark.tone.len() > 1000, "{} colour pairs, {} tone samples", dark.colour.len(), dark.tone.len());
|
||||
// a black-and-white camera JPEG gives nothing
|
||||
let grey = Rgb32f::from_fn(64, 64, |x, y| [luminance_2020(reference.data[y * 64 + x]) * 100.0; 3]);
|
||||
assert!(samples_from_proxies(&scene(0.3).0, &grey, &Mat3::IDENTITY).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pooled_tone_curve_takes_luminance_with_negative_channels_as_the_render_does() {
|
||||
// a saturating matrix sends this magenta's green channel negative; the render keeps it, so the curve's input
|
||||
// is the unclamped luminance (clamped, the magenta samples read 30% brighter and pull the pooled quantiles)
|
||||
let matrix = Mat3([[1.3, -0.2, -0.1], [-0.1, 1.2, -0.1], [-0.1, -0.5, 1.6]]);
|
||||
let magenta = [0.9, 0.05, 0.9];
|
||||
assert!(matrix.apply(magenta)[1] < 0.0);
|
||||
let samples: Vec<([f64; 3], f64)> = (0..4000)
|
||||
.map(|i| {
|
||||
let colour = if i % 2 == 0 { magenta } else { [1.0; 3] };
|
||||
let x = colour.map(|v| v * 0.001 * 500f64.powf(f64::from(i / 2) / 2000.0));
|
||||
(x, f64::from(camera_curve(luma(matrix.apply(x)) as f32)))
|
||||
})
|
||||
.collect();
|
||||
let tone = fit_profile_tone(&samples, &matrix).unwrap();
|
||||
for x in [0.002f32, 0.02, 0.1, 0.3] {
|
||||
assert!((tone.apply(x) - camera_curve(x)).abs() < 0.01 + 0.03 * camera_curve(x), "{x}: {} vs {}", tone.apply(x), camera_curve(x));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_look_with_the_profiles_colour_continues_along_its_pooled_curve() {
|
||||
let profile = Mat3([[1.2, -0.1, -0.1], [-0.1, 1.1, 0.0], [0.0, -0.2, 1.2]]);
|
||||
let pooled = sampled(camera_curve, 0.0005, 0.9);
|
||||
let dark = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02);
|
||||
let with = |matrix| CameraLook { matrix, tone: dark, hue_sat: None };
|
||||
// the profile's colour: the curve goes on along the pooled one
|
||||
assert_eq!(with_pooled_tone(with(profile), Some(profile), Some(pooled)).tone, extend_tone(&dark, &pooled));
|
||||
// the photo's own matrix (the profile's colour rejected): its curve as fitted
|
||||
assert_eq!(with_pooled_tone(with(Mat3::IDENTITY), Some(profile), Some(pooled)).tone, dark);
|
||||
assert_eq!(with_pooled_tone(with(profile), None, Some(pooled)).tone, dark);
|
||||
assert_eq!(with_pooled_tone(with(profile), Some(profile), None).tone, dark);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_photo_no_look_fits_takes_the_profiles_pooled_tone_curve() {
|
||||
let colour = (Mat3::IDENTITY, None);
|
||||
let pooled = sampled(camera_curve, 0.0005, 0.9);
|
||||
let look = with_profile_colour(None, Some(colour), Some(pooled), |_| None).unwrap();
|
||||
assert_eq!(look.tone, pooled);
|
||||
}
|
||||
|
||||
/// Pairs whose scene luminance spans `ratio` from the darkest to the brightest pixel, mapped
|
||||
/// to the JPEG through a steep camera curve (a hazy scene the camera stretches).
|
||||
fn low_contrast_pairs(ratio: f64) -> Vec<(f64, f64)> {
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
//! in; a damaged or hostile file is ignored with a warning. They hold aggregate colour statistics
|
||||
//! only, never image content.
|
||||
use lightcraft_color::Mat3;
|
||||
use lightcraft_pipeline::tone::CameraTone;
|
||||
use lightcraft_raw::profile::HsvTable;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
@@ -50,11 +51,21 @@ pub struct CameraProfile {
|
||||
matrix: [[f64; 3]; 3],
|
||||
/// Hue/saturation/value correction after `matrix` (linear ProPhoto RGB).
|
||||
pub hue_sat: Option<HsvTable>,
|
||||
/// The camera's tone curve pooled over the photos (scene luminance after `matrix` → the camera JPEG's): a photo
|
||||
/// follows it past what its own JPEG shows, and takes it whole when its JPEG teaches no curve. Absent in profiles
|
||||
/// fitted before it existed.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tone: Option<CameraTone>,
|
||||
}
|
||||
|
||||
impl CameraProfile {
|
||||
pub fn new(model: &str, files: usize, samples: usize, matrix: Mat3, hue_sat: Option<HsvTable>) -> CameraProfile {
|
||||
CameraProfile { version: VERSION, model: model.to_owned(), files, samples, matrix: matrix.0, hue_sat }
|
||||
CameraProfile { version: VERSION, model: model.to_owned(), files, samples, matrix: matrix.0, hue_sat, tone: None }
|
||||
}
|
||||
|
||||
/// The profile with its pooled tone curve.
|
||||
pub fn with_tone(self, tone: Option<CameraTone>) -> CameraProfile {
|
||||
CameraProfile { tone, ..self }
|
||||
}
|
||||
|
||||
pub fn matrix(&self) -> Mat3 {
|
||||
@@ -263,31 +274,62 @@ fn cache_key_for(directory: Option<&Path>) -> u64 {
|
||||
h.finish().0 as u64
|
||||
}
|
||||
|
||||
/// Per camera model: the photos read and their pooled colour pairs.
|
||||
/// Per camera model: the photos read and their pooled colour pairs and tone samples.
|
||||
#[derive(Default)]
|
||||
pub struct Pool {
|
||||
models: HashMap<String, (usize, Vec<([f64; 3], [f64; 3])>)>,
|
||||
models: HashMap<String, Model>,
|
||||
}
|
||||
|
||||
/// Most colour pairs kept per photo, so a few busy photos can't dominate a profile.
|
||||
#[derive(Default)]
|
||||
struct Model {
|
||||
/// Photos that gave colour pairs (the colour fit's photo count).
|
||||
files: usize,
|
||||
/// Photos that gave tone samples only (too dark or colourless for colour pairs).
|
||||
tone_files: usize,
|
||||
pairs: Vec<([f64; 3], [f64; 3])>,
|
||||
tone: Vec<([f64; 3], f64)>,
|
||||
}
|
||||
|
||||
/// What [`Pool::add`] took from one raw file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Added {
|
||||
pub model: String,
|
||||
/// Whether it gave colour pairs; `false`: tone samples only, not counted toward a profile's photos.
|
||||
pub colour: bool,
|
||||
}
|
||||
|
||||
/// Most colour pairs (and, separately, tone samples) kept per photo, so a few busy photos can't dominate a profile.
|
||||
const PAIRS_PER_FILE: usize = 4000;
|
||||
|
||||
/// Every `n`-th item, `n` chosen to keep at most [`PAIRS_PER_FILE`].
|
||||
fn thinned<T>(items: Vec<T>) -> impl Iterator<Item = T> {
|
||||
let step = items.len().div_ceil(PAIRS_PER_FILE).max(1);
|
||||
items.into_iter().step_by(step)
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
/// Add one raw file's colour pairs. `Ok(None)` when the file can't contribute (not an ARW,
|
||||
/// NEF or RAF without colour matrices, no usable camera JPEG, too little colour).
|
||||
pub fn add(&mut self, bytes: &[u8]) -> Result<Option<String>, String> {
|
||||
/// Add one raw file's colour pairs and tone samples. A photo too dark or colourless for colour pairs still gives
|
||||
/// its tone samples (the shadows the pooled curve needs) without counting toward the profile's photos. `Ok(None)`
|
||||
/// when the file can't contribute (not an ARW, NEF or RAF without colour matrices, no usable or a black-and-white
|
||||
/// camera JPEG).
|
||||
pub fn add(&mut self, bytes: &[u8]) -> Result<Option<Added>, String> {
|
||||
let mut raw = lightcraft_raw::decode(bytes).map_err(|e| e.to_string())?;
|
||||
// colour only: geometric lens corrections would stop the sensor proxy from binning (the pairs still follow
|
||||
// the warp the camera applied to its JPEG)
|
||||
let lens = crate::camera_preview::lens_geometry(&raw.opcodes.list3);
|
||||
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
|
||||
let Some(model) = raw.metadata.model.as_deref().map(str::trim).filter(|m| !m.is_empty()) else { return Ok(None) };
|
||||
let Some(pairs) = crate::camera_preview::profile_pairs(&raw, bytes, lens.as_ref()) else { return Ok(None) };
|
||||
let step = pairs.len().div_ceil(PAIRS_PER_FILE).max(1);
|
||||
let Some(samples) = crate::camera_preview::profile_samples(&raw, bytes, lens.as_ref()) else { return Ok(None) };
|
||||
let entry = self.models.entry(model.to_owned()).or_default();
|
||||
entry.0 += 1;
|
||||
entry.1.extend(pairs.into_iter().step_by(step));
|
||||
Ok(Some(model.to_owned()))
|
||||
let colour = !samples.colour.is_empty();
|
||||
if colour {
|
||||
entry.files += 1;
|
||||
entry.pairs.extend(thinned(samples.colour));
|
||||
} else {
|
||||
entry.tone_files += 1;
|
||||
}
|
||||
entry.tone.extend(thinned(samples.tone));
|
||||
Ok(Some(Added { model: model.to_owned(), colour }))
|
||||
}
|
||||
|
||||
/// Fit a profile per model with at least `min_files` photos.
|
||||
@@ -296,26 +338,29 @@ impl Pool {
|
||||
models.sort_by(|a, b| a.0.cmp(b.0));
|
||||
models
|
||||
.into_iter()
|
||||
.filter(|(_, (files, _))| *files >= min_files)
|
||||
.map(|(model, (files, pairs))| {
|
||||
let (matrix, hue_sat) = crate::camera_preview::fit_profile(pairs).ok_or_else(|| format!("{model}: no usable colour fit"))?;
|
||||
Ok(CameraProfile::new(model, *files, pairs.len(), matrix, hue_sat))
|
||||
.filter(|(_, m)| m.files >= min_files)
|
||||
.map(|(model, m)| {
|
||||
let (matrix, hue_sat) = crate::camera_preview::fit_profile(&m.pairs).ok_or_else(|| format!("{model}: no usable colour fit"))?;
|
||||
let tone = crate::camera_preview::fit_profile_tone(&m.tone, &matrix);
|
||||
Ok(CameraProfile::new(model, m.files, m.pairs.len(), matrix, hue_sat).with_tone(tone))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Add another pool's photos and pairs (pools filled on separate threads).
|
||||
pub fn merge(&mut self, other: Pool) {
|
||||
for (model, (files, pairs)) in other.models {
|
||||
for (model, m) in other.models {
|
||||
let entry = self.models.entry(model).or_default();
|
||||
entry.0 += files;
|
||||
entry.1.extend(pairs);
|
||||
entry.files += m.files;
|
||||
entry.tone_files += m.tone_files;
|
||||
entry.pairs.extend(m.pairs);
|
||||
entry.tone.extend(m.tone);
|
||||
}
|
||||
}
|
||||
|
||||
/// Photos read per model.
|
||||
pub fn files(&self) -> Vec<(String, usize)> {
|
||||
let mut v: Vec<_> = self.models.iter().map(|(m, (n, _))| (m.clone(), *n)).collect();
|
||||
let mut v: Vec<_> = self.models.iter().map(|(name, m)| (name.clone(), m.files)).collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
@@ -355,6 +400,14 @@ mod tests {
|
||||
let mut p = profile();
|
||||
p.version = 99;
|
||||
assert!(bad(p), "unknown version");
|
||||
// a pooled tone curve round-trips; a broken one (knots going backwards) is a damaged file
|
||||
let toned = profile().with_tone(lightcraft_pipeline::tone::default_raw_camera_tone());
|
||||
let path = save(&toned, &dir).unwrap();
|
||||
assert_eq!(load(&path).unwrap(), toned);
|
||||
let mut json: serde_json::Value = serde_json::to_value(&toned).unwrap();
|
||||
json["tone"]["knots"][3][0] = serde_json::json!(5.0);
|
||||
std::fs::write(dir.join("bad.json"), serde_json::to_vec(&json).unwrap()).unwrap();
|
||||
assert!(load(&dir.join("bad.json")).is_err(), "invalid tone curve");
|
||||
std::fs::write(dir.join("junk.json"), b"{not json").unwrap();
|
||||
assert!(load(&dir.join("junk.json")).is_err());
|
||||
assert!(load(&dir.join("missing.json")).is_err());
|
||||
|
||||
@@ -14,6 +14,7 @@ pub mod curves;
|
||||
pub mod dcp_profiles;
|
||||
pub(crate) mod denoise;
|
||||
mod develop;
|
||||
pub(crate) use develop::{prepare_photo_for_wb_partial, wb_partial_names_one_field};
|
||||
mod edit;
|
||||
mod export;
|
||||
pub(crate) mod face_detect;
|
||||
|
||||
@@ -120,13 +120,11 @@ fn wb_mode_ignores_its_numbers(mode: WbMode, info: &lightcraft_pipeline::SourceI
|
||||
/// numbers, neither, or a mode of its own. [`merge_settings_for_photo`] and `preset.apply` both start here, and
|
||||
/// both finish with `normalize_wb` so the photo ends on the scale it is edited on.
|
||||
pub(crate) fn prepare_photo_for_wb_partial(d: &DevelopSettings, partial: &Value, info: &lightcraft_pipeline::SourceInfo) -> Option<DevelopSettings> {
|
||||
let mut d = (*d).clone();
|
||||
let wb = partial.get("wb").and_then(Value::as_object);
|
||||
// the partial names one of the two numbers, and not both or neither
|
||||
let one_field = wb.is_some_and(|wb| wb.contains_key("temp") != wb.contains_key("tint"));
|
||||
if !one_field {
|
||||
if !wb_partial_names_one_field(partial) {
|
||||
return None;
|
||||
}
|
||||
let mut d = (*d).clone();
|
||||
let wb = partial.get("wb").and_then(Value::as_object);
|
||||
// a photo whose source is edited in Kelvin is the one with two scales to trip over
|
||||
let kelvin_source = info.raw && !info.relative_wb;
|
||||
// the scale the partial's numbers are written on: an unmentioned scale means the relative scale, as `merged` reads it
|
||||
@@ -154,6 +152,12 @@ pub(crate) fn prepare_photo_for_wb_partial(d: &DevelopSettings, partial: &Value,
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Whether `partial`'s white balance names one of the two numbers, and not both or neither: the partials
|
||||
/// [`prepare_photo_for_wb_partial`] prepares the photo for.
|
||||
pub(crate) fn wb_partial_names_one_field(partial: &Value) -> bool {
|
||||
partial.get("wb").and_then(Value::as_object).is_some_and(|wb| wb.contains_key("temp") != wb.contains_key("tint"))
|
||||
}
|
||||
|
||||
/// Merge a partial settings JSON into a photo's settings (issue #2910). `DevelopSettings::merged` keeps a white
|
||||
/// balance that names no scale on the relative scale; on a photo edited in Kelvin the field the partial does not
|
||||
/// name (a partial with only `temp`, or only `tint`) would then be read on the other scale, giving a white neither
|
||||
@@ -1323,24 +1327,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let ops = ids
|
||||
.iter()
|
||||
.filter_map(|id| s.develop_of(*id).map(|d| (*id, d)))
|
||||
.filter_map(|(id, d)| {
|
||||
// a hand-written preset may name one white balance number only, and then it means the same as
|
||||
// a partial: bring the photo onto that scale first, with its own as-shot white, and put the
|
||||
// result back on the scale the photo is edited on (issue #2910) — the merge `develop.merge` uses
|
||||
let info = s.source_info(id);
|
||||
let prepared = prepare_photo_for_wb_partial(&d, &preset.settings, &info);
|
||||
let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb;
|
||||
let base: &DevelopSettings = prepared.as_ref().unwrap_or(&d);
|
||||
// Amount is measured from the import look only when the photo has one.
|
||||
// Otherwise the current settings (on the partial's WB scale) are its baseline.
|
||||
let imported = s.catalog.photo(id).filter(|p| p.import_look.is_some() && amount != 1.0).map(|p| p.import_defaults());
|
||||
let prepared_import =
|
||||
imported.as_ref().map(|d| prepare_photo_for_wb_partial(d, &preset.settings, &info).unwrap_or_else(|| d.clone()));
|
||||
let original = prepared_import.as_ref().unwrap_or(base);
|
||||
let mut next = preset.apply_on(base, original, amount);
|
||||
if on_kelvin_scale {
|
||||
lightcraft_pipeline::local::normalize_wb(&mut next, &info);
|
||||
}
|
||||
.filter_map(|(id, _)| {
|
||||
// the same composition, white balance preparation and final scale as previews and import
|
||||
// (`Session::preset_applied`, issues #2159 and #2910)
|
||||
let next = s.preset_applied(id, &preset, amount)?;
|
||||
s.develop_op(id, next, &format!("Preset: {}", preset.name))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -6,7 +6,7 @@ use super::{
|
||||
};
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// Unsharp mask on an 8-bit image (separable box-blur approximation of a small Gaussian).
|
||||
/// Output sharpening of an 8-bit image: an unsharp mask on its luma ([`unsharp`]).
|
||||
pub fn output_sharpen(img: &mut Rgba8, target: SharpenFor, amount: SharpenAmount) {
|
||||
if !sharpens(img.width, img.height, target) {
|
||||
return;
|
||||
@@ -37,7 +37,8 @@ pub fn output_sharpen_deep(img: &mut DeepImage, target: SharpenFor, amount: Shar
|
||||
}
|
||||
}
|
||||
DeepSamples::F32(v) => {
|
||||
let src: Vec<[f32; 3]> = v.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect();
|
||||
// A NaN or infinite sample would poison its neighbours' blur and local range; treat it as black.
|
||||
let src: Vec<[f32; 3]> = v.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]].map(|x| if x.is_finite() { x } else { 0.0 })).collect();
|
||||
if let Some(out) = unsharp(w, h, &src, target, amount) {
|
||||
for (d, s) in v.iter_mut().zip(out.as_flattened()) {
|
||||
*d = s.max(0.0);
|
||||
@@ -52,47 +53,72 @@ fn sharpens(w: usize, h: usize, target: SharpenFor) -> bool {
|
||||
target != SharpenFor::None && w >= 3 && h >= 3
|
||||
}
|
||||
|
||||
/// The sharpened values of `src` (`w × h`), or `None` when nothing is to be done.
|
||||
/// How far a sharpened pixel may pass the darkest and lightest of its 3×3 neighbours, as a share
|
||||
/// of their difference: enough for crisp edges, too little for the light and dark rims (halos)
|
||||
/// a plain unsharp mask draws along strong edges.
|
||||
const SHARPEN_OVERSHOOT: f32 = 0.1;
|
||||
|
||||
/// The sharpened values of `src` (`w × h`), or `None` when nothing is to be done: an unsharp mask
|
||||
/// at the output's own pixel scale (a Gaussian of radius `sigma` output pixels), on luma only (no
|
||||
/// colour fringes), with its overshoot past the local range limited ([`SHARPEN_OVERSHOOT`]). Print
|
||||
/// media blur more than a screen and get a wider, stronger mask. The values may be on any scale.
|
||||
fn unsharp(w: usize, h: usize, src: &[[f32; 3]], target: SharpenFor, amount: SharpenAmount) -> Option<Vec<[f32; 3]>> {
|
||||
let (radius, base) = match target {
|
||||
let (sigma, base) = match target {
|
||||
SharpenFor::None => return None,
|
||||
SharpenFor::Screen => (1usize, 0.35f32),
|
||||
SharpenFor::Matte => (2, 0.6),
|
||||
SharpenFor::Glossy => (1, 0.5),
|
||||
SharpenFor::Screen => (0.7f32, 0.65f32),
|
||||
SharpenFor::Glossy => (0.8, 0.85),
|
||||
SharpenFor::Matte => (1.0, 1.05),
|
||||
};
|
||||
let k = base
|
||||
* match amount {
|
||||
SharpenAmount::Low => 0.6,
|
||||
SharpenAmount::Low => 0.5,
|
||||
SharpenAmount::Standard => 1.0,
|
||||
SharpenAmount::High => 1.5,
|
||||
SharpenAmount::High => 1.6,
|
||||
};
|
||||
if w < 3 || h < 3 {
|
||||
return None;
|
||||
}
|
||||
let r = radius as isize;
|
||||
let box_pass = |inp: &[[f32; 3]], horizontal: bool| -> Vec<[f32; 3]> {
|
||||
let mut out = vec![[0.0; 3]; inp.len()];
|
||||
// rows in parallel: each output pixel is computed on its own, so the bits don't depend on the split
|
||||
lightcraft_raster::par_rows(&mut out, w, |y, row| {
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
let mut acc = [0.0f32; 3];
|
||||
for d in -r..=r {
|
||||
let (sx, sy) = if horizontal {
|
||||
((x as isize + d).clamp(0, w as isize - 1) as usize, y)
|
||||
} else {
|
||||
(x, (y as isize + d).clamp(0, h as isize - 1) as usize)
|
||||
};
|
||||
let p = inp[sy * w + sx];
|
||||
acc = [acc[0] + p[0], acc[1] + p[1], acc[2] + p[2]];
|
||||
}
|
||||
let n = (2 * r + 1) as f32;
|
||||
*o = acc.map(|v| v / n);
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let blur = box_pass(&box_pass(src, true), false);
|
||||
Some(src.iter().zip(&blur).map(|(s, b)| std::array::from_fn(|c| s[c] + (s[c] - b[c]) * k)).collect())
|
||||
let luma: Vec<f32> = src.iter().map(|p| 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]).collect();
|
||||
let r = (3.0 * sigma).ceil() as isize;
|
||||
let taps: Vec<f32> = (-r..=r).map(|d| (-((d * d) as f32) / (2.0 * sigma * sigma)).exp()).collect();
|
||||
let norm: f32 = taps.iter().sum();
|
||||
let taps: Vec<f32> = taps.iter().map(|t| t / norm).collect();
|
||||
let gauss = |acc: f32, d: isize, v: f32| acc + v * taps[(d + r) as usize];
|
||||
let blur = separable(&separable(&luma, w, h, r, true, 0.0, gauss), w, h, r, false, 0.0, gauss);
|
||||
let lo = |acc: f32, _: isize, v: f32| acc.min(v);
|
||||
let hi = |acc: f32, _: isize, v: f32| acc.max(v);
|
||||
let lo = separable(&separable(&luma, w, h, 1, true, f32::INFINITY, lo), w, h, 1, false, f32::INFINITY, lo);
|
||||
let hi = separable(&separable(&luma, w, h, 1, true, f32::NEG_INFINITY, hi), w, h, 1, false, f32::NEG_INFINITY, hi);
|
||||
Some(
|
||||
src.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| {
|
||||
let (y, margin) = (luma[i], (hi[i] - lo[i]) * SHARPEN_OVERSHOOT);
|
||||
// max/min rather than clamp: never panics, even on bounds a non-finite input left inverted or NaN.
|
||||
let sharp = (y + (y - blur[i]) * k).max(lo[i] - margin).min(hi[i] + margin);
|
||||
p.map(|v| v + sharp - y)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// One pass of a separable filter over a `w × h` plane: each value folds (`f(acc, offset, value)`,
|
||||
/// from `init`) its neighbours up to `reach` away along a row (`horizontal`) or a column, edges repeated.
|
||||
fn separable(inp: &[f32], w: usize, h: usize, reach: isize, horizontal: bool, init: f32, f: impl Fn(f32, isize, f32) -> f32 + Sync) -> Vec<f32> {
|
||||
let mut out = vec![0.0; inp.len()];
|
||||
lightcraft_raster::par_rows(&mut out, w, |y, row| {
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
*o = (-reach..=reach).fold(init, |acc, d| {
|
||||
let i = if horizontal {
|
||||
y * w + (x as isize + d).clamp(0, w as isize - 1) as usize
|
||||
} else {
|
||||
(y as isize + d).clamp(0, h as isize - 1) as usize * w + x
|
||||
};
|
||||
f(acc, d, inp[i])
|
||||
});
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Encode a rendered display-referred image according to `o` (its pixels must already be in
|
||||
|
||||
@@ -209,7 +209,7 @@ fn sharpen_increases_edge_contrast() {
|
||||
assert!(img.data[3][0] < 80 && img.data[4][0] > 170);
|
||||
}
|
||||
|
||||
/// Output sharpening's pixels for every target and amount, pinned (its box blurs run row-parallel, which must not
|
||||
/// Output sharpening's pixels for every target and amount, pinned (its separable passes run row-parallel, which must not
|
||||
/// change a bit), on 8- and 16-bit images; with no target the image is left as it is.
|
||||
#[test]
|
||||
fn sharpened_pixels_are_pinned() {
|
||||
@@ -234,17 +234,66 @@ fn sharpened_pixels_are_pinned() {
|
||||
assert_eq!(img, test_image());
|
||||
}
|
||||
const SHARPENED: [u64; 9] = [
|
||||
0x1494_273e_0bdc_a61c,
|
||||
0x3fbb_40c4_74f4_b0c3,
|
||||
0xa27f_8ff5_82a0_99f9,
|
||||
0x6550_6571_a38d_4d9f,
|
||||
0x5e28_f4f3_fc8a_9685,
|
||||
0xdc2b_6f65_9138_3b1d,
|
||||
0x8ce6_f0b8_d8ed_8026,
|
||||
0x92d8_12e7_4b2e_81fe,
|
||||
0x139f_6d78_b1f2_a910,
|
||||
0x1a04_82d5_edaa_37c8,
|
||||
0xcb78_18b7_938e_beda,
|
||||
0x0490_bb9e_2b64_3d00,
|
||||
0x1662_0293_b8a2_2538,
|
||||
0xa3f7_7957_1af3_1b39,
|
||||
0x30b0_919c_7c6a_705b,
|
||||
0x27ef_4e5b_42e6_d1ed,
|
||||
0x1dc3_3b96_b2f9_c1b6,
|
||||
0xdab7_1280_a47a_ffeb,
|
||||
];
|
||||
|
||||
/// Output sharpening (#2970): each step crisper than the one before, Screen / Standard roughly a
|
||||
/// typical web export's, and no wide light or dark rim along a strong edge (overshoot stays
|
||||
/// within a tenth of the edge's contrast). Colour is left alone: a grey edge stays grey.
|
||||
#[test]
|
||||
fn sharpen_steps_are_crisper_without_halos() {
|
||||
let edge = || {
|
||||
let mut img = Rgba8::new(32, 8);
|
||||
for (i, p) in img.data.iter_mut().enumerate() {
|
||||
let v = if i % 32 < 16 { 40 } else { 220 };
|
||||
*p = [v, v, v, 255];
|
||||
}
|
||||
img
|
||||
};
|
||||
let mut last = 0u8;
|
||||
for amount in [SharpenAmount::Low, SharpenAmount::Standard, SharpenAmount::High] {
|
||||
let mut img = edge();
|
||||
output_sharpen(&mut img, SharpenFor::Screen, amount);
|
||||
let (dark, light) = (img.data[15], img.data[16]);
|
||||
let spread = (40 - dark[0]).max(light[0] - 220);
|
||||
assert!(spread >= last && spread > 0, "{amount:?}: {dark:?} {light:?}");
|
||||
assert!(dark[0] >= 40 - 18 && light[0] <= 220 + 18, "{amount:?}: {dark:?} {light:?}");
|
||||
assert!(dark[0] == dark[1] && dark[1] == dark[2] && light[0] == light[2], "grey stays grey");
|
||||
assert_eq!(img.data[0][0], 40, "{amount:?}: flat areas untouched");
|
||||
last = spread;
|
||||
}
|
||||
let mut none = edge();
|
||||
output_sharpen(&mut none, SharpenFor::None, SharpenAmount::High);
|
||||
assert_eq!(none.data, edge().data);
|
||||
}
|
||||
|
||||
/// Output sharpening of a float image with NaN and infinite samples does not panic (#2970 review):
|
||||
/// they are sharpened as black and every result is finite.
|
||||
#[test]
|
||||
fn sharpen_deep_survives_non_finite_samples() {
|
||||
let (nan, inf) = (f32::NAN, f32::INFINITY);
|
||||
let mut samples = vec![0.5f32; 27];
|
||||
samples[..9].copy_from_slice(&[nan, nan, nan, inf, inf, inf, -inf, nan, inf]);
|
||||
samples[12] = nan;
|
||||
samples[20] = inf;
|
||||
for target in [SharpenFor::Screen, SharpenFor::Glossy, SharpenFor::Matte] {
|
||||
let mut img = DeepImage { width: 3, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::F32(samples.clone()) };
|
||||
output_sharpen_deep(&mut img, target, SharpenAmount::High);
|
||||
let DeepSamples::F32(out) = &img.samples else { panic!("expected F32 samples") };
|
||||
assert!(out.iter().all(|v| v.is_finite() && *v >= 0.0), "{target:?}: {out:?}");
|
||||
}
|
||||
let mut all_nan = DeepImage { width: 3, height: 3, space: OutputSpace::Srgb, samples: DeepSamples::F32(vec![nan; 27]) };
|
||||
output_sharpen_deep(&mut all_nan, SharpenFor::Screen, SharpenAmount::Standard);
|
||||
}
|
||||
|
||||
/// Exported files carry keywords as Lightroom Classic writes them: names flat in `dc:subject`
|
||||
/// (with the keywords containing them), full paths in `lr:hierarchicalSubject`, and nothing of
|
||||
/// a keyword left out of export. They used to carry the `a|b` paths in `dc:subject`.
|
||||
|
||||
@@ -121,6 +121,23 @@ pub fn embedded_lens(raw: &lightcraft_raw::RawInfo) -> Option<lightcraft_develop
|
||||
Some(lightcraft_pipeline::optics::reorient_lens(&lens, raw.orientation, cw, ch))
|
||||
}
|
||||
|
||||
fn xmp_has_rating(x: &str) -> bool {
|
||||
lightcraft_meta::parse_xmp(x).ok().and_then(|d| d.metadata.rating).is_some()
|
||||
}
|
||||
|
||||
fn embedded_or_exif_xmp(bytes: &[u8], m: &lightcraft_meta::Metadata) -> Option<String> {
|
||||
match lightcraft_meta::embedded(bytes).xmp {
|
||||
Some(x) if !xmp_has_rating(&x) && m.rating.is_some() => {
|
||||
let fresh = lightcraft_meta::write_xmp(m, None);
|
||||
lightcraft_meta::merge_xmp(&x, &fresh, lightcraft_meta::MergeRules { owned_if_present: &["xmp:Rating"], ..Default::default() })
|
||||
.ok()
|
||||
.or(Some(x))
|
||||
}
|
||||
Some(x) => Some(x),
|
||||
None => m.rating.map(|_| lightcraft_meta::write_xmp(m, None)),
|
||||
}
|
||||
}
|
||||
|
||||
fn ext_upper(name: &str) -> String {
|
||||
std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_uppercase()).unwrap_or_default()
|
||||
}
|
||||
@@ -133,6 +150,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
|
||||
let content_hash = Some(lightcraft_preview::hash_bytes(bytes).to_string());
|
||||
let m = lightcraft_meta::extract(bytes);
|
||||
let (meta, captured) = meta_of(&m);
|
||||
let xmp = embedded_or_exif_xmp(bytes, &m);
|
||||
if lightcraft_raw::probe(bytes).is_some() {
|
||||
let raw = match lightcraft_raw::probe_info(bytes).map_err(|e| preview_reason(bytes, e)) {
|
||||
Ok(r) => r,
|
||||
@@ -149,7 +167,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
|
||||
meta,
|
||||
as_shot_wb: None,
|
||||
content_hash,
|
||||
xmp: lightcraft_meta::embedded(bytes).xmp,
|
||||
xmp,
|
||||
orientation: m.orientation,
|
||||
preview_only: Some(why),
|
||||
..Default::default()
|
||||
@@ -184,7 +202,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
|
||||
meta,
|
||||
as_shot_wb,
|
||||
content_hash,
|
||||
xmp: lightcraft_meta::embedded(bytes).xmp,
|
||||
xmp,
|
||||
orientation: Some(raw.orientation),
|
||||
preview_only: None,
|
||||
});
|
||||
@@ -230,7 +248,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
|
||||
as_shot_wb: None,
|
||||
content_hash,
|
||||
embedded_lens: None,
|
||||
xmp: None,
|
||||
xmp,
|
||||
orientation: m.orientation,
|
||||
preview_only: None,
|
||||
})
|
||||
|
||||
@@ -296,7 +296,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
|
||||
}
|
||||
}
|
||||
if let Some(preset) = &opts.preset {
|
||||
let d = std::sync::Arc::new(preset.apply(&p.develop, 1.0));
|
||||
let d = std::sync::Arc::new(crate::presets::apply_preset_to_photo(preset, &p.develop, None, 1.0, &crate::media::source_info(&p)));
|
||||
let label = format!("Preset: {}", preset.name);
|
||||
p.develop = d.clone();
|
||||
p.edited = Some(now.clone());
|
||||
|
||||
@@ -87,7 +87,7 @@ pub fn apply_import_defaults(s: &Session, p: &mut Photo) {
|
||||
let preset = s.import_defaults.preset_for(raw, &p.meta.camera).and_then(|id| s.presets.iter().find(|x| x.id == id));
|
||||
match preset {
|
||||
Some(pr) => {
|
||||
let look = std::sync::Arc::new(pr.apply(&base, 1.0));
|
||||
let look = std::sync::Arc::new(crate::presets::apply_preset_to_photo(pr, &base, None, 1.0, &crate::media::source_info(p)));
|
||||
p.develop = look.clone();
|
||||
p.import_look = (*look != base).then_some(look);
|
||||
}
|
||||
|
||||
@@ -372,22 +372,49 @@ impl ImportJob {
|
||||
// when the import makes a record of it, once it is read as a file import reads it)
|
||||
let duplicate_of =
|
||||
info.content_hash.as_ref().filter(|_| !opts.local).and_then(|h| self.by_hash.get(h).map(|existing| (h.clone(), *existing)));
|
||||
// the XMP sidecar (or a raw's embedded XMP), read before copying: its capture time files
|
||||
// the XMP sidecar (or a file's embedded XMP), read before copying: its capture time files
|
||||
// and names the copy when the file itself has none (a skipped duplicate needs only that time)
|
||||
let raw = info.kind == MediaKind::Raw;
|
||||
let packet = if duplicate_of.is_some() && info.captured.is_some() && !opts.read_duplicates {
|
||||
let has_embedded_xmp = raw || matches!(info.format.to_ascii_uppercase().as_str(), "JPEG" | "JPG" | "TIFF" | "TIF" | "PNG" | "WEBP");
|
||||
let skip_sidecar = duplicate_of.is_some() && info.captured.is_some() && !opts.read_duplicates;
|
||||
let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera);
|
||||
let mut embedded_sidecar = if skip_sidecar {
|
||||
None
|
||||
} else {
|
||||
found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).or_else(|| info.xmp.clone().filter(|_| raw))
|
||||
info.xmp.as_deref().filter(|_| has_embedded_xmp).and_then(|x| match crate::sidecar::parse_sidecar(x, target) {
|
||||
Ok(sc) => Some(sc),
|
||||
Err(e) => {
|
||||
log::warn!("import {path}: embedded XMP: {e}");
|
||||
None
|
||||
}
|
||||
})
|
||||
};
|
||||
let target = crate::crs::Target::for_file(info.kind, &info.format, info.preview_only.is_some(), &info.meta.camera);
|
||||
let sidecar = packet.and_then(|x| match crate::sidecar::parse_sidecar(&x, target) {
|
||||
Ok(sc) => Some(sc),
|
||||
Err(e) => {
|
||||
log::warn!("import {path}: XMP: {e}");
|
||||
None
|
||||
// Embedded XMP on a rendered file (JPEG, TIFF, PNG, WebP) has develop adjustments
|
||||
// already baked into the pixels; only raws/DNGs keep foreign develop settings from embedded XMP.
|
||||
if !raw && let Some(sc) = &mut embedded_sidecar {
|
||||
sc.develop = None;
|
||||
sc.warnings.clear();
|
||||
}
|
||||
let external_sidecar = if skip_sidecar {
|
||||
None
|
||||
} else {
|
||||
found_sidecar.and_then(|f| std::fs::read_to_string(f).ok()).and_then(|x| match crate::sidecar::parse_sidecar(&x, target) {
|
||||
Ok(sc) => Some(sc),
|
||||
Err(e) => {
|
||||
log::warn!("import {path}: XMP: {e}");
|
||||
None
|
||||
}
|
||||
})
|
||||
};
|
||||
let sidecar = match (embedded_sidecar, external_sidecar) {
|
||||
(Some(mut embedded), Some(external)) => {
|
||||
embedded.override_with(external);
|
||||
Some(embedded)
|
||||
}
|
||||
});
|
||||
(Some(embedded), None) => Some(embedded),
|
||||
(None, Some(external)) => Some(external),
|
||||
(None, None) => None,
|
||||
};
|
||||
if info.captured.is_none() {
|
||||
info.captured = sidecar.as_ref().and_then(|sc| sc.captured.clone());
|
||||
}
|
||||
@@ -416,6 +443,9 @@ impl ImportJob {
|
||||
let mut q = Photo::new(PhotoId(0), Source::File { path: path.clone() }, &own, &info.format, 0, 0, &self.now);
|
||||
q.captured = info.captured.clone();
|
||||
q.meta = info.meta.clone();
|
||||
if let Some(sc) = &sidecar {
|
||||
crate::sidecar::merge_into(&mut q, sc, &self.now);
|
||||
}
|
||||
let name = if let Some(template) = opts.rename.as_deref().filter(|t| !t.trim().is_empty()) {
|
||||
let Some(seq) = self.seq else {
|
||||
self.done.fetch_add(1, Relaxed);
|
||||
|
||||
@@ -1537,6 +1537,8 @@ pub fn json_delta(old: &Value, new: &Value) -> Option<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod lightroom_fixture;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
//!
|
||||
//! Archives use a deterministic JSON representation wrapped in zlib. The JSON
|
||||
//! writer streams through a bounded compressor, so an import cannot first build
|
||||
//! an unbounded archive buffer. Blob columns are omitted by the catalog reader;
|
||||
//! decoded XMP,
|
||||
//! settings, history, snapshots, identities, paths, collections & membership
|
||||
//! remain available for recovery.
|
||||
//! an unbounded archive buffer. The catalog reader decodes Lightroom's compressed
|
||||
//! XMP and history-step and snapshot settings and omits other blob columns, so
|
||||
//! decoded XMP, settings, history, snapshots, identities, paths, collections &
|
||||
//! membership remain available for recovery.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::{self, File};
|
||||
@@ -29,6 +29,41 @@ pub const MAX_TOTAL_ARCHIVE_BYTES: u64 = 128 * 1024 * 1024;
|
||||
/// Maximum number of managed archives retained.
|
||||
pub const MAX_MANAGED_ARCHIVES: usize = 8;
|
||||
|
||||
/// Why [`store`] stored no archive.
|
||||
#[derive(Debug)]
|
||||
pub enum StoreError {
|
||||
/// The archive would pass [`MAX_ARCHIVE_BYTES`], as JSON or on disk.
|
||||
TooBig,
|
||||
/// Anything else, such as a folder or file that can't be written.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl From<String> for StoreError {
|
||||
fn from(why: String) -> Self {
|
||||
Self::Failed(why)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for StoreError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::TooBig => write!(f, "{TooBig}"),
|
||||
Self::Failed(why) => f.write_str(why),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`store_best_effort`] kept.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Kept {
|
||||
/// The whole archive.
|
||||
All(PathBuf),
|
||||
/// The archive without history-step and snapshot settings (`text`): with them it passed [`MAX_ARCHIVE_BYTES`].
|
||||
WithoutSettings(PathBuf),
|
||||
/// No archive: it passed [`MAX_ARCHIVE_BYTES`] even without them.
|
||||
Nothing,
|
||||
}
|
||||
|
||||
const FORMAT_VERSION: u8 = 1;
|
||||
const HEADER: &[u8] = b"LC-LRARCH\0\x01Z";
|
||||
const NAME_PREFIX: &str = "lightroom-import-";
|
||||
@@ -44,13 +79,18 @@ const IO_BUFFER: usize = 16 * 1024;
|
||||
/// most [`MAX_MANAGED_ARCHIVES`] and [`MAX_TOTAL_ARCHIVE_BYTES`]. Legacy
|
||||
/// `lightroom-import-*.json` files are deliberately ignored and preserved for
|
||||
/// an explicit caller warning.
|
||||
pub fn store(directory: &Path, data: &CatalogImport) -> Result<PathBuf, String> {
|
||||
pub fn store(directory: &Path, data: &CatalogImport) -> Result<PathBuf, StoreError> {
|
||||
store_with(directory, data, true)
|
||||
}
|
||||
|
||||
/// [`store`], with the `text` of history steps and snapshots only when `settings`.
|
||||
fn store_with(directory: &Path, data: &CatalogImport, settings: bool) -> Result<PathBuf, StoreError> {
|
||||
prepare_directory(directory)?;
|
||||
let mut managed = managed_files(directory)?;
|
||||
managed.sort_by_key(|entry| entry.index);
|
||||
|
||||
let temporary = temporary_path(directory)?;
|
||||
write_archive(&temporary, data).inspect_err(|_| {
|
||||
write_archive(&temporary, data, settings).inspect_err(|_| {
|
||||
let _ = remove_managed_file(&temporary);
|
||||
})?;
|
||||
|
||||
@@ -60,7 +100,7 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result<PathBuf, String>
|
||||
Ok(same) => same,
|
||||
Err(error) => {
|
||||
let _ = remove_managed_file(&temporary);
|
||||
return Err(error.to_string());
|
||||
return Err(error.to_string().into());
|
||||
}
|
||||
};
|
||||
if same {
|
||||
@@ -75,20 +115,20 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result<PathBuf, String>
|
||||
let index = managed.last().map_or(0, |entry| entry.index.saturating_add(1));
|
||||
if managed.last().is_some_and(|entry| entry.index == u64::MAX) {
|
||||
let _ = remove_managed_file(&temporary);
|
||||
return Err("managed Lightroom archive index is exhausted".into());
|
||||
return Err(StoreError::Failed("managed Lightroom archive index is exhausted".into()));
|
||||
}
|
||||
let destination = match next_destination(directory, index) {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
let _ = remove_managed_file(&temporary);
|
||||
return Err(error);
|
||||
return Err(error.into());
|
||||
}
|
||||
};
|
||||
let size = match fs::metadata(&temporary) {
|
||||
Ok(meta) => meta.len(),
|
||||
Err(error) => {
|
||||
let _ = remove_managed_file(&temporary);
|
||||
return Err(error.to_string());
|
||||
return Err(error.to_string().into());
|
||||
}
|
||||
};
|
||||
let new_entry = Managed { index, path: destination.clone(), size };
|
||||
@@ -99,40 +139,46 @@ pub fn store(directory: &Path, data: &CatalogImport) -> Result<PathBuf, String>
|
||||
Ok(retirees) => retirees,
|
||||
Err(error) => {
|
||||
let _ = remove_managed_file(&temporary);
|
||||
return Err(error);
|
||||
return Err(error.into());
|
||||
}
|
||||
};
|
||||
let quarantined = match quarantine(&retirees) {
|
||||
Ok(quarantined) => quarantined,
|
||||
Err(error) => {
|
||||
let _ = remove_managed_file(&temporary);
|
||||
return Err(error);
|
||||
return Err(error.into());
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(error) = publish_new(&temporary, &destination) {
|
||||
rollback_quarantine(&quarantined);
|
||||
let _ = remove_managed_file(&temporary);
|
||||
return Err(error.to_string());
|
||||
return Err(error.to_string().into());
|
||||
}
|
||||
if let Err(error) = remove_managed_file(&temporary) {
|
||||
return Err(format!("archive published but temporary cleanup failed: {error}"));
|
||||
return Err(StoreError::Failed(format!("archive published but temporary cleanup failed: {error}")));
|
||||
}
|
||||
for (old, held) in quarantined {
|
||||
if let Err(error) = remove_managed_file(&held) {
|
||||
return Err(format!("archive published but could not retire {}: {error}", old.display()));
|
||||
return Err(StoreError::Failed(format!("archive published but could not retire {}: {error}", old.display())));
|
||||
}
|
||||
}
|
||||
Ok(destination)
|
||||
}
|
||||
|
||||
/// Store source data when possible. An archive that reaches its bounded size is
|
||||
/// omitted with a warning so catalog import can still complete.
|
||||
pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result<Option<PathBuf>, String> {
|
||||
/// Store source data when possible, so catalog import can still complete. An archive past
|
||||
/// [`MAX_ARCHIVE_BYTES`] is stored again without the history-step and snapshot settings, which
|
||||
/// can be most of a catalog's data; one still too big is not stored at all.
|
||||
pub fn store_best_effort(directory: &Path, data: &CatalogImport) -> Result<Kept, String> {
|
||||
match store(directory, data) {
|
||||
Ok(path) => Ok(Some(path)),
|
||||
Err(error) if error.contains("Lightroom archive exceeds 32 MiB") => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
Ok(path) => return Ok(Kept::All(path)),
|
||||
Err(StoreError::TooBig) => {}
|
||||
Err(StoreError::Failed(why)) => return Err(why),
|
||||
}
|
||||
match store_with(directory, data, false) {
|
||||
Ok(path) => Ok(Kept::WithoutSettings(path)),
|
||||
Err(StoreError::TooBig) => Ok(Kept::Nothing),
|
||||
Err(StoreError::Failed(why)) => Err(why),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,21 +259,25 @@ fn next_destination(directory: &Path, mut index: u64) -> Result<PathBuf, String>
|
||||
Err("no safe managed archive name available".into())
|
||||
}
|
||||
|
||||
fn write_archive(path: &Path, data: &CatalogImport) -> Result<(), String> {
|
||||
fn write_archive(path: &Path, data: &CatalogImport, settings: bool) -> Result<(), StoreError> {
|
||||
lightcraft_catalog::safe_file::write_atomic_with(path, &mut |raw| {
|
||||
let mut bounded = BoundedWriter { inner: raw, total: 0 };
|
||||
bounded.write_all(HEADER)?;
|
||||
let mut compressor = ZlibWriter::new(&mut bounded);
|
||||
serde_json::to_writer(&mut compressor, &ArchiveRef(data)).map_err(json_io)?;
|
||||
serde_json::to_writer(&mut compressor, &ArchiveRef(data, settings)).map_err(json_io)?;
|
||||
compressor.finish()?;
|
||||
Ok(())
|
||||
})
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("could not write Lightroom archive: {error}"))
|
||||
.map_err(|error| match error.get_ref().is_some_and(|inner| inner.is::<TooBig>()) {
|
||||
true => StoreError::TooBig,
|
||||
false => StoreError::Failed(format!("could not write Lightroom archive: {error}")),
|
||||
})
|
||||
}
|
||||
|
||||
/// A write error from the archive writers keeps its own `io::Error`, so [`TooBig`] can still be told apart.
|
||||
fn json_io(error: serde_json::Error) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, error.to_string())
|
||||
io::Error::from(error)
|
||||
}
|
||||
|
||||
struct BoundedWriter<'a> {
|
||||
@@ -251,8 +301,20 @@ impl Write for BoundedWriter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The archive writers' error when the archive would pass [`MAX_ARCHIVE_BYTES`].
|
||||
#[derive(Debug)]
|
||||
struct TooBig;
|
||||
|
||||
impl std::fmt::Display for TooBig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Lightroom archive exceeds {} MiB", MAX_ARCHIVE_BYTES >> 20)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TooBig {}
|
||||
|
||||
fn limit_error() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, "Lightroom archive exceeds 32 MiB")
|
||||
io::Error::new(io::ErrorKind::InvalidData, TooBig)
|
||||
}
|
||||
|
||||
struct ZlibWriter<'a, 'b> {
|
||||
@@ -435,67 +497,70 @@ fn remove_managed_file(path: &Path) -> io::Result<()> {
|
||||
fs::remove_file(path)
|
||||
}
|
||||
|
||||
struct ArchiveRef<'a>(&'a CatalogImport);
|
||||
/// The archive of a catalog import, with the `text` of history steps and snapshots only when `.1`.
|
||||
struct ArchiveRef<'a>(&'a CatalogImport, bool);
|
||||
|
||||
impl Serialize for ArchiveRef<'_> {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let mut out = serializer.serialize_struct("CatalogImportArchive", 7)?;
|
||||
out.serialize_field("version", &FORMAT_VERSION)?;
|
||||
out.serialize_field("source", &self.0.source)?;
|
||||
out.serialize_field("photos", &PhotoSeq(&self.0.photos))?;
|
||||
out.serialize_field("collections", &RowSeq(&self.0.collections))?;
|
||||
out.serialize_field("members", &RowSeq(&self.0.members))?;
|
||||
out.serialize_field("collection_content", &RowSeq(&self.0.collection_content))?;
|
||||
out.serialize_field("photos", &PhotoSeq(&self.0.photos, self.1))?;
|
||||
out.serialize_field("collections", &RowSeq(&self.0.collections, None))?;
|
||||
out.serialize_field("members", &RowSeq(&self.0.members, None))?;
|
||||
out.serialize_field("collection_content", &RowSeq(&self.0.collection_content, None))?;
|
||||
out.serialize_field("warnings", &self.0.warnings)?;
|
||||
out.end()
|
||||
}
|
||||
}
|
||||
|
||||
struct PhotoSeq<'a>(&'a [CatalogPhoto]);
|
||||
struct PhotoSeq<'a>(&'a [CatalogPhoto], bool);
|
||||
impl Serialize for PhotoSeq<'_> {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let mut out = serializer.serialize_seq(Some(self.0.len()))?;
|
||||
for photo in self.0 {
|
||||
out.serialize_element(&PhotoRef(photo))?;
|
||||
out.serialize_element(&PhotoRef(photo, self.1))?;
|
||||
}
|
||||
out.end()
|
||||
}
|
||||
}
|
||||
|
||||
struct PhotoRef<'a>(&'a CatalogPhoto);
|
||||
struct PhotoRef<'a>(&'a CatalogPhoto, bool);
|
||||
impl Serialize for PhotoRef<'_> {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let p = self.0;
|
||||
let skip = (!self.1).then_some("text");
|
||||
let mut out = serializer.serialize_struct("CatalogPhotoArchive", 8)?;
|
||||
out.serialize_field("source_id", &p.source_id)?;
|
||||
out.serialize_field("uuid", &p.uuid)?;
|
||||
out.serialize_field("path", &p.path)?;
|
||||
out.serialize_field("image", &RowRef(&p.image))?;
|
||||
out.serialize_field("image", &RowRef(&p.image, None))?;
|
||||
out.serialize_field("settings", &p.settings)?;
|
||||
out.serialize_field("xmp", &p.xmp)?;
|
||||
out.serialize_field("keywords", &p.keywords)?;
|
||||
out.serialize_field("history", &RowSeq(&p.history))?;
|
||||
out.serialize_field("snapshots", &RowSeq(&p.snapshots))?;
|
||||
out.serialize_field("history", &RowSeq(&p.history, skip))?;
|
||||
out.serialize_field("snapshots", &RowSeq(&p.snapshots, skip))?;
|
||||
out.end()
|
||||
}
|
||||
}
|
||||
|
||||
struct RowSeq<'a>(&'a [BTreeMap<String, Value>]);
|
||||
/// Rows, each without the column `.1` names.
|
||||
struct RowSeq<'a>(&'a [BTreeMap<String, Value>], Option<&'a str>);
|
||||
impl Serialize for RowSeq<'_> {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let mut out = serializer.serialize_seq(Some(self.0.len()))?;
|
||||
for row in self.0 {
|
||||
out.serialize_element(&RowRef(row))?;
|
||||
out.serialize_element(&RowRef(row, self.1))?;
|
||||
}
|
||||
out.end()
|
||||
}
|
||||
}
|
||||
|
||||
struct RowRef<'a>(&'a BTreeMap<String, Value>);
|
||||
struct RowRef<'a>(&'a BTreeMap<String, Value>, Option<&'a str>);
|
||||
impl Serialize for RowRef<'_> {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let mut out = serializer.serialize_map(None)?;
|
||||
for (key, value) in self.0 {
|
||||
for (key, value) in self.0.iter().filter(|(key, _)| Some(key.as_str()) != self.1) {
|
||||
out.serialize_entry(key, value)?;
|
||||
}
|
||||
out.end()
|
||||
@@ -608,40 +673,84 @@ mod tests {
|
||||
fn rejects_oversize_before_creating_archive() {
|
||||
let path = tempdir();
|
||||
let input = data("x".repeat((MAX_ARCHIVE_BYTES as usize) + 1));
|
||||
assert!(store(&path, &input).is_err());
|
||||
assert!(matches!(store(&path, &input), Err(StoreError::TooBig)), "an oversize archive is told apart by its error");
|
||||
assert_eq!(managed_count(&path), 0);
|
||||
fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_catalog_history_is_best_effort_and_does_not_abort_import() {
|
||||
let path = tempdir();
|
||||
/// 5,000 photos with 8 KiB of history settings each: about 40 MiB of JSON.
|
||||
fn large_catalog(history: bool) -> CatalogImport {
|
||||
let mut input = data("catalog.lrcat".into());
|
||||
input.photos = (0..5_000)
|
||||
.map(|index| CatalogPhoto {
|
||||
source_id: index,
|
||||
uuid: format!("photo-{index}"),
|
||||
path: format!("/photos/{index}.raw"),
|
||||
image: BTreeMap::new(),
|
||||
settings: String::new(),
|
||||
xmp: String::new(),
|
||||
keywords: Vec::new(),
|
||||
history: vec![BTreeMap::from([("text".into(), serde_json::json!(format!("history-{index}-{}", "x".repeat(8 * 1024))))])],
|
||||
snapshots: Vec::new(),
|
||||
original: crate::lightroom_catalog::Original::Local,
|
||||
.map(|index| {
|
||||
let bulk = format!("history-{index}-{}", "x".repeat(8 * 1024));
|
||||
CatalogPhoto {
|
||||
source_id: index,
|
||||
uuid: format!("photo-{index}"),
|
||||
path: format!("/photos/{index}.raw"),
|
||||
image: BTreeMap::new(),
|
||||
settings: if history { String::new() } else { bulk.clone() },
|
||||
xmp: String::new(),
|
||||
keywords: Vec::new(),
|
||||
history: vec![BTreeMap::from([
|
||||
("name".into(), serde_json::json!("Exposure")),
|
||||
("text".into(), serde_json::json!(if history { bulk.as_str() } else { "s = {}" })),
|
||||
])],
|
||||
snapshots: vec![BTreeMap::from([("name".into(), serde_json::json!("Before")), ("text".into(), serde_json::json!("s = {}"))])],
|
||||
original: crate::lightroom_catalog::Original::Local,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(store_best_effort(&path, &input).unwrap(), None);
|
||||
input
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_archive_too_big_with_its_history_settings_is_kept_without_them() {
|
||||
let path = tempdir();
|
||||
let kept = store_best_effort(&path, &large_catalog(true)).unwrap();
|
||||
let Kept::WithoutSettings(archive) = kept else { panic!("the archive should be kept without settings, not {kept:?}") };
|
||||
let decoded = crate::lightroom_fixture::read_archive(&archive);
|
||||
let photos = decoded["photos"].as_array().unwrap();
|
||||
assert_eq!(photos.len(), 5_000, "every photo is still archived");
|
||||
assert_eq!(photos[7]["uuid"], serde_json::json!("photo-7"));
|
||||
assert_eq!(photos[7]["history"], serde_json::json!([{"name": "Exposure"}]), "history steps keep everything but their settings");
|
||||
assert_eq!(photos[7]["snapshots"], serde_json::json!([{"name": "Before"}]), "and so do snapshots");
|
||||
assert_eq!(fs::read_dir(&path).unwrap().count(), 1, "the first, too big try leaves nothing behind");
|
||||
fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_catalog_is_best_effort_and_does_not_abort_import() {
|
||||
let path = tempdir();
|
||||
assert_eq!(store_best_effort(&path, &large_catalog(false)).unwrap(), Kept::Nothing, "too big even without history settings");
|
||||
assert_eq!(managed_count(&path), 0);
|
||||
fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
|
||||
/// Only the size limit leads to a smaller archive or none: any other failure is reported as such.
|
||||
#[test]
|
||||
fn a_write_failure_is_not_taken_for_an_oversize_archive() {
|
||||
let path = tempdir();
|
||||
let file = path.join("not-a-folder");
|
||||
fs::write(&file, b"x").unwrap();
|
||||
assert!(matches!(store(&file, &rich_data()), Err(StoreError::Failed(_))), "a folder that can't be made");
|
||||
let folder = path.join("Interop");
|
||||
{
|
||||
let _full = lightcraft_catalog::safe_file::fail_writes_after(0);
|
||||
assert!(matches!(store(&folder, &rich_data()), Err(StoreError::Failed(_))), "a full disk while writing");
|
||||
assert!(store_best_effort(&folder, &rich_data()).is_err(), "a failure is an error, not a skipped archive");
|
||||
}
|
||||
assert_eq!(fs::read_dir(&folder).unwrap().count(), 0, "a failed write leaves nothing behind");
|
||||
fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archive_roundtrips_zlib_payload_and_preserves_numeric_arrays() {
|
||||
let path = tempdir();
|
||||
let archive = store(&path, &rich_data()).unwrap();
|
||||
let bytes = fs::read(archive).unwrap();
|
||||
assert!(bytes.starts_with(HEADER));
|
||||
assert_eq!(crate::lightroom_fixture::ARCHIVE_HEADER, HEADER, "the fixture reads archives with this module's header");
|
||||
let json = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&bytes[HEADER.len()..], MAX_ARCHIVE_BYTES as usize).unwrap();
|
||||
let decoded: Value = serde_json::from_slice(&json).unwrap();
|
||||
assert_eq!(decoded["version"], serde_json::json!(FORMAT_VERSION));
|
||||
|
||||
@@ -48,8 +48,31 @@ struct Reader {
|
||||
db: Database,
|
||||
tables: Vec<LiveTable>,
|
||||
}
|
||||
/// Most bytes of history-step or snapshot settings decoded from one table. They are only archived, and an archive
|
||||
/// holds at most [`crate::lightroom_archive::MAX_ARCHIVE_BYTES`] of JSON, so this keeps all a catalog can archive while
|
||||
/// a hostile one can't make the reader allocate without bound (each row alone may decode to 16 MiB).
|
||||
const MAX_DECODED_SETTINGS: usize = crate::lightroom_archive::MAX_ARCHIVE_BYTES as usize;
|
||||
|
||||
/// The column of table `name` that Lightroom Classic 13 and later store as compressed text (see [`decode_compressed`]),
|
||||
/// and what a warning calls one and several of its rows.
|
||||
fn compressed_settings(name: &str) -> Option<(&'static str, &'static str, &'static str)> {
|
||||
match name {
|
||||
"Adobe_libraryImageDevelopHistoryStep" => Some(("text", "history step", "history steps")),
|
||||
"Adobe_libraryImageDevelopSnapshot" => Some(("text", "snapshot", "snapshots")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
fn table(&self, name: &str, required: bool) -> Result<Vec<Row>, String> {
|
||||
fn table(&self, name: &str, required: bool, warnings: &mut Vec<String>) -> Result<Vec<Row>, String> {
|
||||
self.table_within(name, required, MAX_DECODED_SETTINGS, warnings)
|
||||
}
|
||||
|
||||
/// The rows of table `name`. Its compressed settings column ([`compressed_settings`]) is decoded within `budget`
|
||||
/// bytes for the whole table: each value is charged its declared length before it is inflated, even one that then
|
||||
/// fails to decode. A value that can't be decoded is left out of its row with a warning naming the image, and
|
||||
/// those past the budget with one warning for all. Other BLOB columns are always left out.
|
||||
fn table_within(&self, name: &str, required: bool, budget: usize, warnings: &mut Vec<String>) -> Result<Vec<Row>, String> {
|
||||
let Some(t) = self.tables.iter().find(|t| t.name == name) else {
|
||||
return if required { Err(format!("unsupported Lightroom catalog: missing {name}")) } else { Ok(Vec::new()) };
|
||||
};
|
||||
@@ -58,37 +81,69 @@ impl Reader {
|
||||
if rows.len() > 1_000_000 {
|
||||
return Err(format!("{name}: more than one million records"));
|
||||
}
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
columns
|
||||
.iter()
|
||||
.cloned()
|
||||
.zip(r.values.into_iter().map(|v| match v {
|
||||
SqlValue::Null => Some(Value::Null),
|
||||
SqlValue::Integer(n) => Some(json!(n)),
|
||||
SqlValue::Real(n) => Some(json!(n)),
|
||||
SqlValue::Text(s) => Some(json!(s)),
|
||||
// Opaque Lightroom payloads never become JSON byte arrays.
|
||||
SqlValue::Blob(_) => None,
|
||||
}))
|
||||
.filter_map(|(column, value)| value.map(|value| (column, value)))
|
||||
.collect()
|
||||
})
|
||||
.collect())
|
||||
let compressed = compressed_settings(name);
|
||||
let mut left = budget;
|
||||
let mut over_budget = 0usize;
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
for r in rows {
|
||||
let mut row = Row::new();
|
||||
let mut settings = None;
|
||||
for (column, value) in columns.iter().zip(r.values) {
|
||||
let value = match value {
|
||||
SqlValue::Null => Value::Null,
|
||||
SqlValue::Integer(n) => json!(n),
|
||||
SqlValue::Real(n) => json!(n),
|
||||
SqlValue::Text(s) => json!(s),
|
||||
SqlValue::Blob(bytes) => {
|
||||
if compressed.is_some_and(|(settings_column, _, _)| settings_column == column) {
|
||||
settings = Some((column, bytes));
|
||||
}
|
||||
// Other opaque Lightroom payloads never become JSON byte arrays.
|
||||
continue;
|
||||
}
|
||||
};
|
||||
row.insert(column.clone(), value);
|
||||
}
|
||||
if let (Some((column, bytes)), Some((_, what, _))) = (settings, compressed) {
|
||||
// charged at its declared length before it is inflated (which never goes past that length), so
|
||||
// a row that then fails to decode counts too; past the budget, the rest aren't inflated at all
|
||||
let declared = compressed_len(&bytes);
|
||||
if declared.is_some_and(|n| over_budget > 0 || n > left) {
|
||||
over_budget += 1;
|
||||
} else {
|
||||
left -= declared.unwrap_or(0);
|
||||
match decode_compressed(&bytes, "settings") {
|
||||
Ok(text) => {
|
||||
row.insert(column.clone(), Value::String(text));
|
||||
}
|
||||
Err(why) => warnings.push(format!(
|
||||
"image {}: {what} {}: {why}; archived without its settings",
|
||||
number(&row, "image"),
|
||||
number(&row, "id_local")
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(row);
|
||||
}
|
||||
if let (Some((_, one, many)), 1..) = (compressed, over_budget) {
|
||||
let what = if over_budget == 1 { one } else { many };
|
||||
warnings.push(format!("{over_budget} {what} archived without their settings: more than {} MiB of settings in {name}", budget >> 20));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The catalog's `Adobe_storeProviderID` (a UUID), kept by Lightroom in its backups; `None`
|
||||
/// when the table or the value is missing or doesn't look like an id.
|
||||
fn catalog_id(&self) -> Option<String> {
|
||||
let rows = self.table("Adobe_variablesTable", false).ok()?;
|
||||
let rows = self.table("Adobe_variablesTable", false, &mut Vec::new()).ok()?;
|
||||
let row = rows.iter().find(|r| text(r, "name") == "Adobe_storeProviderID")?;
|
||||
let id = text(row, "value").trim();
|
||||
(!id.is_empty() && id.len() <= 128 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')).then(|| id.to_string())
|
||||
}
|
||||
|
||||
fn optional_table(&self, name: &str, warnings: &mut Vec<String>) -> Result<Vec<Row>, String> {
|
||||
match self.table(name, false) {
|
||||
match self.table(name, false, warnings) {
|
||||
Ok(rows) => Ok(rows),
|
||||
Err(error) => {
|
||||
warnings.push(format!("skipping optional Lightroom table {name}: {error}"));
|
||||
@@ -125,7 +180,7 @@ impl Reader {
|
||||
SqlValue::Integer(n) => Some(json!(n)),
|
||||
SqlValue::Real(n) => Some(json!(n)),
|
||||
SqlValue::Text(s) => Some(json!(s)),
|
||||
SqlValue::Blob(bytes) if column == "xmp" => match decode_xmp_bytes(&bytes) {
|
||||
SqlValue::Blob(bytes) if column == "xmp" => match decode_compressed(&bytes, "XMP") {
|
||||
Ok(packet) => Some(Value::String(packet)),
|
||||
Err(error) => {
|
||||
warnings.push(format!("image {image}: {error}"));
|
||||
@@ -352,17 +407,27 @@ fn xmp(v: Option<&Value>) -> Result<String, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_xmp_bytes(bytes: &[u8]) -> Result<String, String> {
|
||||
let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes).ok_or("truncated XMP header")?;
|
||||
if size > 16 << 20 {
|
||||
return Err("XMP packet exceeds 16 MiB".into());
|
||||
/// The decoded length [`decode_compressed`] reads from `bytes`' header, when it has one of at most 16 MiB.
|
||||
fn compressed_len(bytes: &[u8]) -> Option<usize> {
|
||||
let size = bytes.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map(u32::from_be_bytes)?;
|
||||
usize::try_from(size).ok().filter(|size| *size <= 16 << 20)
|
||||
}
|
||||
|
||||
/// Lightroom's compressed text (`Adobe_AdditionalMetadata.xmp`, and history-step and snapshot settings since Lightroom
|
||||
/// Classic 13): the decoded length as 4 big-endian bytes, then a zlib stream, at most 16 MiB decoded. Errors name it
|
||||
/// `what`.
|
||||
fn decode_compressed(bytes: &[u8], what: &str) -> Result<String, String> {
|
||||
if bytes.len() < 4 {
|
||||
return Err(format!("truncated {what} header"));
|
||||
}
|
||||
let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or("truncated XMP")?, 16 << 20)
|
||||
.map_err(|_| "invalid compressed XMP")?;
|
||||
if decoded.len() != size as usize {
|
||||
return Err("XMP packet length mismatch".into());
|
||||
let size = compressed_len(bytes).ok_or_else(|| format!("{what} longer than 16 MiB"))?;
|
||||
// inflated no further than its declared length: a stream that goes on is invalid, at no more cost than a valid one
|
||||
let decoded = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(bytes.get(4..).ok_or_else(|| format!("truncated {what}"))?, size)
|
||||
.map_err(|_| format!("invalid compressed {what}"))?;
|
||||
if decoded.len() != size {
|
||||
return Err(format!("{what} length mismatch"));
|
||||
}
|
||||
String::from_utf8(decoded).map_err(|e| e.to_string())
|
||||
String::from_utf8(decoded).map_err(|e| format!("{what} not UTF-8: {e}"))
|
||||
}
|
||||
|
||||
// SQLite file format §4: validate the live checksum chain in constant space, then overlay
|
||||
@@ -482,9 +547,9 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d
|
||||
}
|
||||
let reader = Reader { tables: db.live_tables()?, db };
|
||||
let mut warnings = Vec::new();
|
||||
let table = |name: &str, required: bool| -> Result<Vec<Row>, String> {
|
||||
let table = |name: &str, required: bool, warnings: &mut Vec<String>| -> Result<Vec<Row>, String> {
|
||||
ensure_read_active(cancel)?;
|
||||
let rows = reader.table(name, required)?;
|
||||
let rows = reader.table(name, required, warnings)?;
|
||||
done.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(rows)
|
||||
};
|
||||
@@ -494,9 +559,9 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d
|
||||
done.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(rows)
|
||||
};
|
||||
let roots: HashMap<_, _> = table("AgLibraryRootFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect();
|
||||
let folders: HashMap<_, _> = table("AgLibraryFolder", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect();
|
||||
let files: HashMap<_, _> = table("AgLibraryFile", true)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect();
|
||||
let roots: HashMap<_, _> = table("AgLibraryRootFolder", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect();
|
||||
let folders: HashMap<_, _> = table("AgLibraryFolder", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect();
|
||||
let files: HashMap<_, _> = table("AgLibraryFile", true, &mut warnings)?.into_iter().map(|r| (number(&r, "id_local"), r)).collect();
|
||||
let develops: HashMap<_, _> = optional_table("Adobe_imageDevelopSettings", &mut warnings)?
|
||||
.into_iter()
|
||||
.map(|r| (number(&r, "image"), text(&r, "text").to_string()))
|
||||
@@ -580,7 +645,7 @@ fn read_file(path: &Path, document: &Path, source: &Path, cancel: &AtomicBool, d
|
||||
// these behind and ignores them); they and their virtual copies are skipped and reported
|
||||
// instead of failing the import
|
||||
let mut orphans = HashSet::new();
|
||||
for image in table("Adobe_images", true)? {
|
||||
for image in table("Adobe_images", true, &mut out.warnings)? {
|
||||
ensure_read_active(cancel)?;
|
||||
let id = number(&image, "id_local");
|
||||
let record = files.get(&number(&image, "rootFile")).ok_or(SkipReason::MissingFile).and_then(|file| {
|
||||
@@ -947,7 +1012,7 @@ fn apply(s: &mut crate::Session, data: CatalogImport, update_existing: bool) ->
|
||||
let archive_dir = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join("Interop"));
|
||||
let index_path = archive_dir.as_ref().map(|p| p.join("lightroom-index.json"));
|
||||
let mut index = load_index(index_path.as_deref())?;
|
||||
let archive_path = archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map_err(error)).transpose()?;
|
||||
let archive_path = archive_dir.as_ref().map(|dir| crate::lightroom_archive::store(dir, &data).map_err(|e| error(e.to_string()))).transpose()?;
|
||||
let undo0 = s.undo.len();
|
||||
let existing: HashMap<_, _> =
|
||||
s.catalog.photos().filter(|p| p.copy_of.is_none()).filter_map(|p| source_path(p).map(|path| (key(path), p.id))).collect();
|
||||
|
||||
@@ -2012,3 +2012,62 @@ fn oversized_optional_table_warns_and_is_skipped() {
|
||||
assert!(rows.is_empty());
|
||||
assert!(warnings.iter().any(|warning| warning.contains("optional_history")));
|
||||
}
|
||||
|
||||
/// A catalog whose settings decode to more than the budget keeps every row, archives the settings that fit, and
|
||||
/// says once how many it left out, instead of allocating whatever its BLOBs inflate to.
|
||||
#[test]
|
||||
fn settings_past_the_decode_budget_are_left_out_with_one_warning() {
|
||||
use crate::lightroom_fixture::{self as fixture, Field, Table};
|
||||
let dir = fixture::dir("history-budget");
|
||||
let catalog = dir.join("test.lrcat");
|
||||
let big = "x".repeat(512 << 10);
|
||||
let rows = (1..=4).map(|id| fixture::history_step(id, 1, id as f64, "Step", Field::Blob(fixture::compressed(&big)))).collect();
|
||||
fixture::write(&catalog, &[Table { name: "Adobe_libraryImageDevelopHistoryStep", columns: fixture::HISTORY_COLUMNS, rows }]);
|
||||
let db = Database::open_file_with_wal(FileSource::open(&catalog).unwrap(), &[]).unwrap();
|
||||
let reader = Reader { tables: db.live_tables().unwrap(), db };
|
||||
let mut warnings = Vec::new();
|
||||
let rows = reader.table_within("Adobe_libraryImageDevelopHistoryStep", true, 1 << 20, &mut warnings).unwrap();
|
||||
assert_eq!(rows.len(), 4, "every step is still read");
|
||||
assert_eq!(rows.iter().filter(|r| r.contains_key("text")).count(), 2, "the two steps within 1 MiB keep their settings");
|
||||
assert_eq!(warnings, ["2 history steps archived without their settings: more than 1 MiB of settings in Adobe_libraryImageDevelopHistoryStep"]);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A stream that inflates past the length its header declares is stopped there, not inflated up to 16 MiB first.
|
||||
#[test]
|
||||
fn a_stream_longer_than_its_declared_length_is_stopped_at_that_length() {
|
||||
let mut bytes = 10u32.to_be_bytes().to_vec();
|
||||
bytes.extend(miniz_oxide::deflate::compress_to_vec_zlib(&[b'x'; 1024], 6));
|
||||
assert_eq!(decode_compressed(&bytes, "settings"), Err("invalid compressed settings".to_string()));
|
||||
let mut exact = 1024u32.to_be_bytes().to_vec();
|
||||
exact.extend(miniz_oxide::deflate::compress_to_vec_zlib(&[b'x'; 1024], 6));
|
||||
assert_eq!(decode_compressed(&exact, "settings").map(|text| text.len()), Ok(1024), "exactly its length decodes");
|
||||
}
|
||||
|
||||
/// Settings that fail to decode still cost their declared length, so a catalog of damaged rows can't make the
|
||||
/// reader inflate without bound: past the budget, the rest are left out without being inflated.
|
||||
#[test]
|
||||
fn settings_that_fail_to_decode_still_count_against_the_budget() {
|
||||
use crate::lightroom_fixture::{self as fixture, Field, Table};
|
||||
let dir = fixture::dir("history-budget-bad");
|
||||
let catalog = dir.join("test.lrcat");
|
||||
let mut damaged = (512u32 << 10).to_be_bytes().to_vec();
|
||||
damaged.extend([1, 2, 3]);
|
||||
let rows = (1..=4).map(|id| fixture::history_step(id, 1, id as f64, "Step", Field::Blob(damaged.clone()))).collect();
|
||||
fixture::write(&catalog, &[Table { name: "Adobe_libraryImageDevelopHistoryStep", columns: fixture::HISTORY_COLUMNS, rows }]);
|
||||
let db = Database::open_file_with_wal(FileSource::open(&catalog).unwrap(), &[]).unwrap();
|
||||
let reader = Reader { tables: db.live_tables().unwrap(), db };
|
||||
let mut warnings = Vec::new();
|
||||
let rows = reader.table_within("Adobe_libraryImageDevelopHistoryStep", true, 1 << 20, &mut warnings).unwrap();
|
||||
assert_eq!(rows.len(), 4, "every step is still read");
|
||||
assert_eq!(
|
||||
warnings,
|
||||
[
|
||||
"image 1: history step 1: invalid compressed settings; archived without its settings",
|
||||
"image 1: history step 2: invalid compressed settings; archived without its settings",
|
||||
"2 history steps archived without their settings: more than 1 MiB of settings in Adobe_libraryImageDevelopHistoryStep",
|
||||
],
|
||||
"the two damaged steps within 1 MiB are tried; the other two aren't"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
//! Synthetic Lightroom catalogs for tests: a small SQLite file written page by page, so the catalog reader is tested
|
||||
//! on the bytes it reads in the field (text and BLOB cells, Lightroom's compressed encoding) with no SQLite library.
|
||||
//! Each table is one leaf page; rows must fit in it without overflow pages.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const PAGE_SIZE: usize = 4096;
|
||||
/// The largest record a 4096-byte table leaf holds without an overflow page (SQLite file format §1.6: U - 35).
|
||||
const MAX_LOCAL: usize = PAGE_SIZE - 35;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Field {
|
||||
Null,
|
||||
Integer(i64),
|
||||
Real(f64),
|
||||
Text(String),
|
||||
Blob(Vec<u8>),
|
||||
}
|
||||
|
||||
pub(crate) fn text(s: &str) -> Field {
|
||||
Field::Text(s.into())
|
||||
}
|
||||
|
||||
pub(crate) struct Table {
|
||||
pub name: &'static str,
|
||||
/// The column list of its `CREATE TABLE`, as Lightroom writes it.
|
||||
pub columns: &'static str,
|
||||
pub rows: Vec<Vec<Field>>,
|
||||
}
|
||||
|
||||
/// Lightroom Classic's compressed text (as in `Adobe_AdditionalMetadata.xmp`, and history steps and snapshots since
|
||||
/// Lightroom Classic 13): the decoded length as 4 big-endian bytes, then the zlib stream.
|
||||
pub(crate) fn compressed(text: &str) -> Vec<u8> {
|
||||
compressed_bytes(text.as_bytes())
|
||||
}
|
||||
|
||||
/// [`compressed`] for any bytes, including ones that aren't UTF-8.
|
||||
pub(crate) fn compressed_bytes(bytes: &[u8]) -> Vec<u8> {
|
||||
let mut out = u32::try_from(bytes.len()).unwrap().to_be_bytes().to_vec();
|
||||
out.extend(miniz_oxide::deflate::compress_to_vec_zlib(bytes, 6));
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) const HISTORY_COLUMNS: &str = "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, dateCreated, digest, \
|
||||
hasBigData INTEGER NOT NULL DEFAULT 0, hasDevelopAdjustments, image INTEGER, name, relValueString, text, valueString";
|
||||
pub(crate) const SNAPSHOT_COLUMNS: &str = "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, digest, \
|
||||
hasBigData INTEGER NOT NULL DEFAULT 0, hasDevelopAdjustments, image INTEGER, locked, name, snapshotID, text";
|
||||
|
||||
/// A history step row for image `image` (columns as in [`HISTORY_COLUMNS`]); `settings` is a text or BLOB field.
|
||||
pub(crate) fn history_step(id: i64, image: i64, date: f64, name: &str, settings: Field) -> Vec<Field> {
|
||||
vec![
|
||||
Field::Integer(id),
|
||||
text(&format!("history-{id}")),
|
||||
Field::Real(date),
|
||||
Field::Null,
|
||||
Field::Integer(0),
|
||||
Field::Integer(1),
|
||||
Field::Integer(image),
|
||||
text(name),
|
||||
Field::Null,
|
||||
settings,
|
||||
Field::Null,
|
||||
]
|
||||
}
|
||||
|
||||
/// A snapshot row for image `image` (columns as in [`SNAPSHOT_COLUMNS`]); `settings` is a text or BLOB field.
|
||||
pub(crate) fn snapshot(id: i64, image: i64, name: &str, settings: Field) -> Vec<Field> {
|
||||
vec![
|
||||
Field::Integer(id),
|
||||
text(&format!("snapshot-{id}")),
|
||||
Field::Null,
|
||||
Field::Integer(0),
|
||||
Field::Integer(1),
|
||||
Field::Integer(image),
|
||||
Field::Null,
|
||||
text(name),
|
||||
Field::Null,
|
||||
settings,
|
||||
]
|
||||
}
|
||||
|
||||
/// The tables of a catalog with one photo, image 1 (`<originals>/Photos/test.ARW`, not created), with the develop
|
||||
/// settings `settings`. Add history, snapshot or other tables and pass them all to [`write`].
|
||||
pub(crate) fn one_photo(originals: &Path, settings: &str) -> Vec<Table> {
|
||||
let mut root = originals.to_string_lossy().into_owned();
|
||||
if !root.ends_with('/') {
|
||||
root.push('/');
|
||||
}
|
||||
vec![
|
||||
Table {
|
||||
name: "AgLibraryRootFolder",
|
||||
columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, absolutePath UNIQUE NOT NULL DEFAULT '', name NOT NULL DEFAULT '', relativePathFromCatalog",
|
||||
rows: vec![vec![Field::Integer(1), text("root-1"), Field::Text(root), text("originals"), Field::Null]],
|
||||
},
|
||||
Table {
|
||||
name: "AgLibraryFolder",
|
||||
columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, pathFromRoot NOT NULL DEFAULT '', rootFolder INTEGER NOT NULL DEFAULT 0",
|
||||
rows: vec![vec![Field::Integer(1), text("folder-1"), text("Photos/"), Field::Integer(1)]],
|
||||
},
|
||||
Table {
|
||||
name: "AgLibraryFile",
|
||||
columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, baseName NOT NULL DEFAULT '', extension NOT NULL DEFAULT '', folder INTEGER NOT NULL DEFAULT 0, idx_filename NOT NULL DEFAULT ''",
|
||||
rows: vec![vec![Field::Integer(1), text("file-1"), text("test"), text("ARW"), Field::Integer(1), text("test.ARW")]],
|
||||
},
|
||||
Table {
|
||||
name: "Adobe_images",
|
||||
columns: "id_local INTEGER PRIMARY KEY, id_global UNIQUE NOT NULL, fileFormat NOT NULL DEFAULT 'unset', fileHeight, fileWidth, masterImage INTEGER, pick NOT NULL DEFAULT 0, rating, rootFile INTEGER NOT NULL DEFAULT 0",
|
||||
rows: vec![vec![
|
||||
Field::Integer(1),
|
||||
text("image-1"),
|
||||
text("RAW"),
|
||||
Field::Integer(10),
|
||||
Field::Integer(20),
|
||||
Field::Null,
|
||||
Field::Integer(0),
|
||||
Field::Null,
|
||||
Field::Integer(1),
|
||||
]],
|
||||
},
|
||||
Table {
|
||||
name: "Adobe_imageDevelopSettings",
|
||||
columns: "id_local INTEGER PRIMARY KEY, image INTEGER, text",
|
||||
rows: vec![vec![Field::Integer(1), Field::Integer(1), text(settings)]],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// The format header an import archive starts with (`lightroom_archive`'s), before its zlib-compressed JSON.
|
||||
pub(crate) const ARCHIVE_HEADER: &[u8] = b"LC-LRARCH\0\x01Z";
|
||||
|
||||
/// The JSON the import archive at `path` holds, for tests that check what an import kept. The JSON itself is capped
|
||||
/// at `MAX_ARCHIVE_BYTES` too, so that is the most it can inflate to.
|
||||
pub(crate) fn read_archive(path: &Path) -> serde_json::Value {
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
let json = bytes.strip_prefix(ARCHIVE_HEADER).unwrap_or_else(|| panic!("{} is not an import archive", path.display()));
|
||||
serde_json::from_slice(
|
||||
&miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(json, crate::lightroom_archive::MAX_ARCHIVE_BYTES as usize).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A new, empty folder for one test's catalog.
|
||||
pub(crate) fn dir(tag: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("lightcraft-lrcat-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// Write `tables` as a SQLite database at `path`: page 1 holds the schema, table `i` page `i + 2`.
|
||||
pub(crate) fn write(path: &Path, tables: &[Table]) {
|
||||
let mut schema = Vec::new();
|
||||
let mut pages = Vec::new();
|
||||
for (i, table) in tables.iter().enumerate() {
|
||||
let root = i64::try_from(i + 2).unwrap();
|
||||
schema.push(vec![
|
||||
text("table"),
|
||||
text(table.name),
|
||||
text(table.name),
|
||||
Field::Integer(root),
|
||||
Field::Text(format!("CREATE TABLE {}({})", table.name, table.columns)),
|
||||
]);
|
||||
pages.push(leaf(0, &table.rows, table.name));
|
||||
}
|
||||
let mut first = leaf(100, &schema, "sqlite_master");
|
||||
first[..16].copy_from_slice(b"SQLite format 3\0");
|
||||
first[16..18].copy_from_slice(&u16::try_from(PAGE_SIZE).unwrap().to_be_bytes());
|
||||
first[18] = 1; // legacy journal mode: no WAL file is read unless it exists
|
||||
first[19] = 1;
|
||||
first[21] = 64;
|
||||
first[22] = 32;
|
||||
first[23] = 32;
|
||||
first[24..28].copy_from_slice(&1u32.to_be_bytes());
|
||||
first[28..32].copy_from_slice(&u32::try_from(pages.len() + 1).unwrap().to_be_bytes());
|
||||
first[40..44].copy_from_slice(&1u32.to_be_bytes());
|
||||
first[44..48].copy_from_slice(&4u32.to_be_bytes());
|
||||
first[56..60].copy_from_slice(&1u32.to_be_bytes()); // UTF-8
|
||||
first[92..96].copy_from_slice(&1u32.to_be_bytes());
|
||||
first[96..100].copy_from_slice(&3_045_000u32.to_be_bytes());
|
||||
let mut bytes = first;
|
||||
for page in pages {
|
||||
bytes.extend(page);
|
||||
}
|
||||
std::fs::write(path, bytes).unwrap();
|
||||
}
|
||||
|
||||
fn leaf(base: usize, rows: &[Vec<Field>], table: &str) -> Vec<u8> {
|
||||
let mut page = vec![0u8; PAGE_SIZE];
|
||||
page[base] = 0x0d;
|
||||
page[base + 3..base + 5].copy_from_slice(&u16::try_from(rows.len()).unwrap().to_be_bytes());
|
||||
let mut end = PAGE_SIZE;
|
||||
for (i, values) in rows.iter().enumerate() {
|
||||
let payload = record(values);
|
||||
assert!(payload.len() <= MAX_LOCAL, "{table} row {i}: {} bytes needs an overflow page, which the fixture doesn't write", payload.len());
|
||||
let rowid = match values.first() {
|
||||
Some(Field::Integer(id)) => u64::try_from(*id).unwrap(),
|
||||
_ => u64::try_from(i + 1).unwrap(),
|
||||
};
|
||||
let mut cell = varint(u64::try_from(payload.len()).unwrap());
|
||||
cell.extend(varint(rowid));
|
||||
cell.extend(payload);
|
||||
let pointers_end = base + 8 + (i + 1) * 2;
|
||||
end = end.checked_sub(cell.len()).filter(|e| *e >= pointers_end).unwrap_or_else(|| panic!("{table}: rows don't fit in one page"));
|
||||
page[end..end + cell.len()].copy_from_slice(&cell);
|
||||
page[pointers_end - 2..pointers_end].copy_from_slice(&u16::try_from(end).unwrap().to_be_bytes());
|
||||
}
|
||||
page[base + 5..base + 7].copy_from_slice(&u16::try_from(end).unwrap().to_be_bytes());
|
||||
page
|
||||
}
|
||||
|
||||
/// A record (SQLite file format §2.1). An `INTEGER PRIMARY KEY` column's value is the rowid, stored as NULL.
|
||||
fn record(values: &[Field]) -> Vec<u8> {
|
||||
let mut serials = Vec::new();
|
||||
let mut body = Vec::new();
|
||||
for (i, value) in values.iter().enumerate() {
|
||||
let serial = match value {
|
||||
Field::Integer(_) if i == 0 => 0,
|
||||
Field::Null => 0,
|
||||
Field::Integer(n) => {
|
||||
body.extend(n.to_be_bytes());
|
||||
6
|
||||
}
|
||||
Field::Real(n) => {
|
||||
body.extend(n.to_be_bytes());
|
||||
7
|
||||
}
|
||||
Field::Text(s) => {
|
||||
body.extend(s.as_bytes());
|
||||
13 + 2 * u64::try_from(s.len()).unwrap()
|
||||
}
|
||||
Field::Blob(b) => {
|
||||
body.extend(b);
|
||||
12 + 2 * u64::try_from(b.len()).unwrap()
|
||||
}
|
||||
};
|
||||
serials.extend(varint(serial));
|
||||
}
|
||||
// the header length counts its own varint
|
||||
let mut header_len = serials.len() + 1;
|
||||
if varint(u64::try_from(header_len).unwrap()).len() > 1 {
|
||||
header_len += 1;
|
||||
}
|
||||
let mut out = varint(u64::try_from(header_len).unwrap());
|
||||
out.extend(serials);
|
||||
out.extend(body);
|
||||
out
|
||||
}
|
||||
|
||||
/// SQLite's big-endian varint (values below 2^56, which is all a fixture needs).
|
||||
fn varint(mut value: u64) -> Vec<u8> {
|
||||
let mut out = vec![(value & 0x7f) as u8];
|
||||
value >>= 7;
|
||||
while value != 0 {
|
||||
out.push((value & 0x7f) as u8 | 0x80);
|
||||
value >>= 7;
|
||||
}
|
||||
out.reverse();
|
||||
out
|
||||
}
|
||||
@@ -31,11 +31,20 @@ fn cancelled() -> crate::EngineError {
|
||||
}
|
||||
|
||||
fn stage_archive(archive_dir: Option<&Path>, data: &mut CatalogImport) -> crate::Result<Option<PathBuf>> {
|
||||
let archive_path = archive_dir.map(|dir| crate::lightroom_archive::store_best_effort(dir, data).map_err(error)).transpose()?.flatten();
|
||||
if archive_dir.is_some() && archive_path.is_none() {
|
||||
data.warnings.push("Lightroom source archive exceeded 32 MiB; archive skipped".into());
|
||||
}
|
||||
Ok(archive_path)
|
||||
use crate::lightroom_archive::{Kept, MAX_ARCHIVE_BYTES};
|
||||
let Some(dir) = archive_dir else { return Ok(None) };
|
||||
let limit = MAX_ARCHIVE_BYTES >> 20;
|
||||
Ok(match crate::lightroom_archive::store_best_effort(dir, data).map_err(error)? {
|
||||
Kept::All(path) => Some(path),
|
||||
Kept::WithoutSettings(path) => {
|
||||
data.warnings.push(format!("Lightroom source archive exceeded {limit} MiB; archived without history-step and snapshot settings"));
|
||||
Some(path)
|
||||
}
|
||||
Kept::Nothing => {
|
||||
data.warnings.push(format!("Lightroom source archive exceeded {limit} MiB; archive skipped"));
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Memory identity of the library which owns a prepared completion.
|
||||
@@ -521,59 +530,67 @@ mod tests {
|
||||
assert_eq!(session.undo.len(), 3);
|
||||
}
|
||||
|
||||
/// 5,000 photos with 8 KiB each of history settings (`in_history`) or develop settings: about 40 MiB of JSON. An
|
||||
/// archive too big with its history settings is kept without them; one too big even then is skipped. Either
|
||||
/// way the import goes on and says so.
|
||||
#[test]
|
||||
fn oversized_history_archive_keeps_prepared_import_successful_with_warning() {
|
||||
let archive_dir = std::env::temp_dir().join(format!("lightcraft-lr-prepared-scale-{}", std::process::id()));
|
||||
let mut data = empty_data();
|
||||
data.photos = (0..5_000)
|
||||
.map(|source_id| {
|
||||
let image = std::collections::BTreeMap::from([
|
||||
("id_local".into(), serde_json::json!(source_id)),
|
||||
("fileFormat".into(), serde_json::json!("JPG")),
|
||||
("fileWidth".into(), serde_json::json!(1)),
|
||||
("fileHeight".into(), serde_json::json!(1)),
|
||||
]);
|
||||
lightroom_catalog::CatalogPhoto {
|
||||
source_id,
|
||||
uuid: format!("scale-{source_id}"),
|
||||
path: format!("/missing/scale-{source_id}.jpg"),
|
||||
image,
|
||||
settings: String::new(),
|
||||
xmp: String::new(),
|
||||
keywords: Vec::new(),
|
||||
history: vec![std::collections::BTreeMap::from([(
|
||||
"text".into(),
|
||||
serde_json::json!(format!("history-{source_id}-{}", "x".repeat(8 * 1024))),
|
||||
)])],
|
||||
snapshots: Vec::new(),
|
||||
original: lightroom_catalog::Original::Local,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let archive_path = stage_archive(Some(&archive_dir), &mut data).unwrap();
|
||||
assert!(archive_path.is_none());
|
||||
let mut session = crate::Session::new();
|
||||
let token = LightroomLibraryToken::capture(&session);
|
||||
let prepared = PreparedLightroom {
|
||||
data,
|
||||
normal: Prepared::default(),
|
||||
index: ImportIndex::default(),
|
||||
archive_path,
|
||||
token,
|
||||
missing_sources: HashSet::new(),
|
||||
update_existing: false,
|
||||
now: "2026-01-01T00:00:00".into(),
|
||||
cancelled: false,
|
||||
};
|
||||
let completion = commit_prepared(&mut session, prepared).unwrap();
|
||||
assert_eq!(completion.report["photos"], 5_000);
|
||||
assert!(
|
||||
completion.report["warnings"]
|
||||
.as_array()
|
||||
.is_some_and(|warnings| warnings.iter().any(|warning| warning == "Lightroom source archive exceeded 32 MiB; archive skipped"))
|
||||
);
|
||||
assert_eq!(session.catalog.len(), 5_000);
|
||||
std::fs::remove_dir_all(archive_dir).unwrap();
|
||||
fn oversized_archive_keeps_prepared_import_successful_with_warning() {
|
||||
for (in_history, warning, archived) in [
|
||||
(true, "Lightroom source archive exceeded 32 MiB; archived without history-step and snapshot settings", true),
|
||||
(false, "Lightroom source archive exceeded 32 MiB; archive skipped", false),
|
||||
] {
|
||||
let archive_dir = std::env::temp_dir().join(format!("lightcraft-lr-prepared-scale-{in_history}-{}", std::process::id()));
|
||||
let mut data = empty_data();
|
||||
data.photos = (0..5_000)
|
||||
.map(|source_id| {
|
||||
let image = std::collections::BTreeMap::from([
|
||||
("id_local".into(), serde_json::json!(source_id)),
|
||||
("fileFormat".into(), serde_json::json!("JPG")),
|
||||
("fileWidth".into(), serde_json::json!(1)),
|
||||
("fileHeight".into(), serde_json::json!(1)),
|
||||
]);
|
||||
let bulk = format!("history-{source_id}-{}", "x".repeat(8 * 1024));
|
||||
lightroom_catalog::CatalogPhoto {
|
||||
source_id,
|
||||
uuid: format!("scale-{source_id}"),
|
||||
path: format!("/missing/scale-{source_id}.jpg"),
|
||||
image,
|
||||
settings: if in_history { String::new() } else { bulk.clone() },
|
||||
xmp: String::new(),
|
||||
keywords: Vec::new(),
|
||||
history: vec![std::collections::BTreeMap::from([(
|
||||
"text".into(),
|
||||
serde_json::json!(if in_history { bulk } else { String::new() }),
|
||||
)])],
|
||||
snapshots: Vec::new(),
|
||||
original: lightroom_catalog::Original::Local,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let archive_path = stage_archive(Some(&archive_dir), &mut data).unwrap();
|
||||
assert_eq!(archive_path.is_some(), archived, "{warning}");
|
||||
let mut session = crate::Session::new();
|
||||
let token = LightroomLibraryToken::capture(&session);
|
||||
let prepared = PreparedLightroom {
|
||||
data,
|
||||
normal: Prepared::default(),
|
||||
index: ImportIndex::default(),
|
||||
archive_path,
|
||||
token,
|
||||
missing_sources: HashSet::new(),
|
||||
update_existing: false,
|
||||
now: "2026-01-01T00:00:00".into(),
|
||||
cancelled: false,
|
||||
};
|
||||
let completion = commit_prepared(&mut session, prepared).unwrap();
|
||||
assert_eq!(completion.report["photos"], 5_000);
|
||||
assert!(
|
||||
completion.report["warnings"].as_array().is_some_and(|warnings| warnings.iter().any(|w| w == warning)),
|
||||
"the report should say: {warning}"
|
||||
);
|
||||
assert_eq!(session.catalog.len(), 5_000);
|
||||
std::fs::remove_dir_all(archive_dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -601,7 +601,10 @@ impl crate::Session {
|
||||
}
|
||||
job.request.space = space;
|
||||
job.request.depth = depth;
|
||||
job.key ^= (space as u64 + 1).wrapping_mul(0xa076_1d64_78bd_642f) ^ (depth as u64 + 1).wrapping_mul(0xe703_7ed1_a0b4_28db);
|
||||
// an export shrinks with a sharp filter: a preview's soft one leaves a small export blurred (#2970)
|
||||
job.request.downscale = lightcraft_pipeline::Downscale::Sharp;
|
||||
job.key ^=
|
||||
(space as u64 + 1).wrapping_mul(0xa076_1d64_78bd_642f) ^ (depth as u64 + 1).wrapping_mul(0xe703_7ed1_a0b4_28db) ^ 0x9e37_79b9_7f4a_7c15;
|
||||
Ok(job)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
|
||||
|
||||
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
|
||||
/// 86: pushed shadows keep the camera profile's colour and tone (#2092).
|
||||
/// 85: raw decoding keeps negative channels (#2278).
|
||||
/// 84: full-size raw demosaic runs on the white-balanced mosaic with a clip mask (#1328).
|
||||
/// 83 is reserved by open #3943.
|
||||
pub const RENDER_CACHE_VERSION: u64 = 85;
|
||||
pub const RENDER_CACHE_VERSION: u64 = 86;
|
||||
|
||||
/// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache).
|
||||
pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512];
|
||||
|
||||
+59
-15
@@ -430,29 +430,72 @@ impl Session {
|
||||
/// apply Auto Settings / the auto crop. Returns `{id, path, …info}`.
|
||||
pub fn finish_merge(&mut self, job: &MergeJob, out: MergeOutput) -> Result<Value> {
|
||||
let first = &job.sources.first().ok_or_else(|| EngineError::Other("nothing merged".into()))?.1;
|
||||
// a new file under a free name (never replacing one), complete and synced before it appears
|
||||
let path = lightcraft_catalog::safe_file::write_new_unique(&mut output_names(first, job.kind.suffix()), &out.dng)
|
||||
.map_err(|e| EngineError::Other(format!("could not write the merged DNG next to {first}: {e}")))?
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
let report = crate::import::import(self, std::slice::from_ref(&path), crate::import::ImportMode::Add)?;
|
||||
let id = report
|
||||
.imported
|
||||
.first()
|
||||
.copied()
|
||||
.map(PhotoId)
|
||||
.ok_or_else(|| EngineError::Other(format!("the merged file {path} could not be imported: {:?}", report.failed)))?;
|
||||
if job.finish.stack {
|
||||
let output_hash = lightcraft_preview::hash_bytes(&out.dng).to_string();
|
||||
// Import deduplicates by content. Reuse an existing merge only while its live source has
|
||||
// matching bytes; stale, missing or deleted rows fail before another file is published.
|
||||
let candidates: Vec<(PhotoId, String, bool)> = self
|
||||
.catalog
|
||||
.photos()
|
||||
.filter_map(|p| {
|
||||
if p.content_hash.as_deref() != Some(output_hash.as_str()) {
|
||||
return None;
|
||||
}
|
||||
let Source::File { path } = &p.source else { return None };
|
||||
Some((p.id, path.clone(), p.deleted))
|
||||
})
|
||||
.collect();
|
||||
let valid_existing = candidates
|
||||
.iter()
|
||||
.find(|(_, path, deleted)| {
|
||||
if *deleted {
|
||||
return false;
|
||||
}
|
||||
let bytes = match &self.media.file_bytes {
|
||||
Some(read) => read(path).ok(),
|
||||
None => std::fs::read(path).ok(),
|
||||
};
|
||||
bytes.is_some_and(|bytes| lightcraft_preview::hash_bytes(&bytes).to_string() == output_hash)
|
||||
})
|
||||
.cloned();
|
||||
let (id, path, reused) = if let Some((id, path, _)) = valid_existing {
|
||||
(id, path, true)
|
||||
} else if let Some((id, path, deleted)) = candidates.first() {
|
||||
let state = if *deleted { "deleted" } else { "missing or changed" };
|
||||
return Err(EngineError::Other(format!(
|
||||
"existing merge result {id:?} has a {state} source at {path}; relink or remove it before repeating the merge"
|
||||
)));
|
||||
} else {
|
||||
// A new file under a free name (never replacing one), complete and synced before it appears.
|
||||
let path = lightcraft_catalog::safe_file::write_new_unique(&mut output_names(first, job.kind.suffix()), &out.dng)
|
||||
.map_err(|e| EngineError::Other(format!("could not write the merged DNG next to {first}: {e}")))?
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
let report = match crate::import::import(self, std::slice::from_ref(&path), crate::import::ImportMode::Add) {
|
||||
Ok(report) => report,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
if let Some(id) = report.imported.first().copied().map(PhotoId) {
|
||||
(id, path, false)
|
||||
} else {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return Err(EngineError::Other(format!("the merged file {path} could not be imported: {:?}", report.failed)));
|
||||
}
|
||||
};
|
||||
if !reused && job.finish.stack {
|
||||
let sources: Vec<PhotoId> = job.sources.iter().map(|(p, _)| *p).collect();
|
||||
if let Some(op) = self.catalog.stack_with_ops(id, &sources) {
|
||||
self.commit("Stack with Sources", op)?;
|
||||
}
|
||||
}
|
||||
self.selection = crate::Selection::single(id);
|
||||
if job.finish.auto_settings {
|
||||
if !reused && job.finish.auto_settings {
|
||||
self.execute("develop.auto", &json!({}))?;
|
||||
}
|
||||
if let Some(c) = out.crop
|
||||
if !reused
|
||||
&& let Some(c) = out.crop
|
||||
&& let Some(d) = self.develop_of(id)
|
||||
{
|
||||
let mut d = (*d).clone();
|
||||
@@ -463,6 +506,7 @@ impl Session {
|
||||
info["id"] = json!(id.0);
|
||||
info["path"] = json!(path);
|
||||
info["bytes"] = json!(out.dng.len());
|
||||
info["reused"] = json!(reused);
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
|
||||
@@ -178,21 +178,18 @@ impl Session {
|
||||
/// from an XMP sidecar or a catalog import, which record none) composes them on its current
|
||||
/// settings instead, since the camera defaults are not its import state. Either way, the
|
||||
/// settings the preset does not name keep the photo's values (issue #2159). The `preset.apply`
|
||||
/// command and the UI's hover previews share this, so hovering shows exactly what a click commits.
|
||||
/// command and the UI's hover previews and thumbnails share this, so hovering shows exactly what
|
||||
/// a click commits, white balance preparation included ([`apply_preset_to_photo`]).
|
||||
pub fn preset_applied(&self, id: PhotoId, preset: &Preset, amount: f64) -> Option<DevelopSettings> {
|
||||
let current = self.develop_of(id)?;
|
||||
let photo = self.catalog.photo(id)?;
|
||||
// The original is read only below 100 %: the panel asks for every visible row at 100 % on
|
||||
// every frame, and then neither the import state nor a copy of the photo's settings is built.
|
||||
let look;
|
||||
let original: &DevelopSettings = match &photo.import_look {
|
||||
Some(_) if (amount - 1.0).abs() >= 1e-9 => {
|
||||
look = photo.import_defaults();
|
||||
&look
|
||||
}
|
||||
_ => ¤t,
|
||||
};
|
||||
Some(preset.apply_on(¤t, original, amount))
|
||||
let original = photo.import_look.as_ref().filter(|_| (amount - 1.0).abs() >= 1e-9).map(|_| photo.import_defaults());
|
||||
// the photo's source is read only for a preset that needs it (one white balance number):
|
||||
// the panel asks for every visible row on every frame
|
||||
let info = if crate::cmd::wb_partial_names_one_field(&preset.settings) { self.source_info(id) } else { Default::default() };
|
||||
Some(apply_preset_to_photo(preset, ¤t, original.as_ref(), amount, &info))
|
||||
}
|
||||
|
||||
/// Add imported presets. Identical presets (same name, group and settings) already present are
|
||||
@@ -634,6 +631,41 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply `preset` to a photo's settings `current` at `amount` (1.0 = 100 %), composing on
|
||||
/// `original` (the photo's import state; `None`: `current` itself, see [`Preset::apply_on`]): the
|
||||
/// one path every caller that puts a preset on a photo takes (the `preset.apply` command,
|
||||
/// thumbnails and hover previews through [`Session::preset_applied`], importing with a preset,
|
||||
/// import defaults), so all of them show and store the same result.
|
||||
///
|
||||
/// `info` is the photo's source: a hand-written preset may name one white balance number only, and
|
||||
/// then it means what a one-field partial means (`prepare_photo_for_wb_partial`, shared with
|
||||
/// `develop.merge`, issue #2910): the photo (and its original) are brought onto the preset's scale
|
||||
/// with the photo's own as-shot white first, and the result is put back on the scale the photo is
|
||||
/// edited on. Without an import state a zero (or negative) `amount` returns `current` exactly as it
|
||||
/// was, before any preparation, so a preview at nothing never turns As Shot into Custom; with one,
|
||||
/// 0 % is the import state's value for each setting the preset names ([`Preset::apply_on`]). A NaN
|
||||
/// `amount` changes nothing.
|
||||
pub fn apply_preset_to_photo(
|
||||
preset: &Preset,
|
||||
current: &DevelopSettings,
|
||||
original: Option<&DevelopSettings>,
|
||||
amount: f64,
|
||||
info: &lightcraft_pipeline::SourceInfo,
|
||||
) -> DevelopSettings {
|
||||
if amount.is_nan() || (amount <= 0.0 && original.is_none()) {
|
||||
return current.clone();
|
||||
}
|
||||
let prepared = crate::cmd::prepare_photo_for_wb_partial(current, &preset.settings, info);
|
||||
let on_kelvin_scale = prepared.is_some() && info.raw && !info.relative_wb;
|
||||
let base = prepared.as_ref().unwrap_or(current);
|
||||
let prepared_original = original.map(|o| crate::cmd::prepare_photo_for_wb_partial(o, &preset.settings, info).unwrap_or_else(|| o.clone()));
|
||||
let mut next = preset.apply_on(base, prepared_original.as_ref().unwrap_or(base), amount);
|
||||
if on_kelvin_scale {
|
||||
lightcraft_pipeline::local::normalize_wb(&mut next, info);
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -379,6 +379,78 @@ impl SidecarData {
|
||||
self
|
||||
}
|
||||
|
||||
/// Overlay fields supplied by `other` onto `self`: any field present in `other`
|
||||
/// replaces the one in `self`.
|
||||
pub fn override_with(&mut self, other: SidecarData) {
|
||||
if other.rating.is_some() {
|
||||
self.rating = other.rating;
|
||||
if self.flag == Some(Flag::Reject) && other.flag.is_none() {
|
||||
self.flag = Some(Flag::None);
|
||||
}
|
||||
}
|
||||
if other.flag.is_some() {
|
||||
self.flag = other.flag;
|
||||
}
|
||||
if other.label.is_some() {
|
||||
self.label = other.label;
|
||||
self.label_text = other.label_text;
|
||||
}
|
||||
if other.title.is_some() {
|
||||
self.title = other.title;
|
||||
}
|
||||
if other.caption.is_some() {
|
||||
self.caption = other.caption;
|
||||
}
|
||||
if other.copyright.is_some() {
|
||||
self.copyright = other.copyright;
|
||||
}
|
||||
if other.copyright_marked.is_some() {
|
||||
self.copyright_marked = other.copyright_marked;
|
||||
}
|
||||
if other.usage_terms.is_some() {
|
||||
self.usage_terms = other.usage_terms;
|
||||
}
|
||||
if other.copyright_url.is_some() {
|
||||
self.copyright_url = other.copyright_url;
|
||||
}
|
||||
if other.creator.is_some() {
|
||||
self.creator = other.creator;
|
||||
}
|
||||
if other.location.is_some() {
|
||||
self.location = other.location;
|
||||
}
|
||||
if other.city.is_some() {
|
||||
self.city = other.city;
|
||||
}
|
||||
if other.state.is_some() {
|
||||
self.state = other.state;
|
||||
}
|
||||
if other.country.is_some() {
|
||||
self.country = other.country;
|
||||
}
|
||||
if other.alt_text.is_some() {
|
||||
self.alt_text = other.alt_text;
|
||||
}
|
||||
if other.extended_description.is_some() {
|
||||
self.extended_description = other.extended_description;
|
||||
}
|
||||
if other.keywords.is_some() {
|
||||
self.keywords = other.keywords;
|
||||
}
|
||||
if other.regions.is_some() {
|
||||
self.regions = other.regions;
|
||||
}
|
||||
if other.captured.is_some() {
|
||||
self.captured = other.captured;
|
||||
}
|
||||
if other.develop.is_some() {
|
||||
self.develop = other.develop;
|
||||
self.warnings = other.warnings;
|
||||
} else {
|
||||
self.warnings.extend(other.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the orientation of the photo file at `original` (LightCraft shows the photo turned by it, and the packet
|
||||
/// may not repeat it) when the regions need it: they were drawn on a stated size ([`SidecarData::regions_drawn_on`]).
|
||||
/// Only then is the file read ([`file_orientation`]).
|
||||
|
||||
@@ -38,6 +38,7 @@ mod lens_refresh;
|
||||
mod libops;
|
||||
mod library;
|
||||
mod lightroom_folder;
|
||||
mod lightroom_history;
|
||||
mod mask_effects;
|
||||
mod mask_geometry;
|
||||
mod merge;
|
||||
|
||||
@@ -470,3 +470,116 @@ fn one_field_wb_preset_apply_keeps_the_other_field_on_its_scale() {
|
||||
let back = (*s.develop_of(kelvin).unwrap()).clone();
|
||||
assert_eq!(back.wb, look.wb, "a preset made from the photo puts its whole white balance back: {:?} vs {:?}", back.wb, look.wb);
|
||||
}
|
||||
|
||||
/// A preset applied to a photo goes through one function whether it is the `preset.apply` command, a thumbnail or
|
||||
/// hover preview, or an import: a hand-written preset naming one white balance number (either one, on either
|
||||
/// scale) gives the same settings in all three, on a photo edited in Kelvin and on one edited relative to its
|
||||
/// as-shot white. Before, the previews (`Session::preset_applied`) and import called the source-free
|
||||
/// `Preset::apply_on` / `Preset::apply` directly, which stored the number without the photo's as-shot white.
|
||||
#[test]
|
||||
fn one_field_wb_preset_gives_the_same_result_in_command_preview_and_import() {
|
||||
use lightcraft_catalog::{MediaKind, Op, Photo, Source};
|
||||
use lightcraft_develop::{Preset, WbMode, WbScale};
|
||||
let as_shot = (4986.0, -2.0);
|
||||
let photo = |camera: &str| {
|
||||
let mut p = Photo::new(
|
||||
lightcraft_catalog::PhotoId(1),
|
||||
Source::File { path: "/photos/one-field.arw".into() },
|
||||
"one-field.arw",
|
||||
"ARW",
|
||||
64,
|
||||
64,
|
||||
"2026-01-01T00:00:00",
|
||||
);
|
||||
p.kind = MediaKind::Raw;
|
||||
p.meta.camera = camera.into();
|
||||
p.as_shot_wb = Some(as_shot);
|
||||
p.develop = std::sync::Arc::new(p.camera_defaults());
|
||||
p
|
||||
};
|
||||
let one_field = |name: &str, wb: serde_json::Value| Preset {
|
||||
id: format!("user.{name}"),
|
||||
name: name.into(),
|
||||
group: "User".into(),
|
||||
settings: json!({ "wb": wb }),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
let presets = [
|
||||
one_field("temp-only", json!({"temp": 5800.0})),
|
||||
one_field("tint-only", json!({"tint": 9.0})),
|
||||
// the reverse scale: numbers written in Kelvin on a photo edited relative to as shot, and the relative
|
||||
// scale named outright on a photo edited in Kelvin
|
||||
one_field("kelvin-temp", json!({"scale": "kelvin", "temp": 6500.0})),
|
||||
one_field("kelvin-tint", json!({"scale": "kelvin", "tint": 6.0})),
|
||||
one_field("relative-temp", json!({"scale": "legacy", "temp": 6800.0})),
|
||||
];
|
||||
for (camera, kelvin_photo) in [("SONY ILCE-7M3", true), ("Nobody X1", false)] {
|
||||
assert_eq!(photo(camera).relative_wb(), !kelvin_photo, "{camera}");
|
||||
for preset in &presets {
|
||||
let mut s = Session::new();
|
||||
let p = photo(camera);
|
||||
let id = p.id;
|
||||
s.catalog.apply(Op::AddPhoto { photo: Box::new(p.clone()) }).unwrap();
|
||||
s.presets.push(preset.clone());
|
||||
let why = format!("{camera}, {}", preset.name);
|
||||
let before = (*s.develop_of(id).unwrap()).clone();
|
||||
assert_eq!(before.wb.mode, WbMode::AsShot, "{why}");
|
||||
|
||||
// preview / hover
|
||||
let preview = s.preset_applied(id, preset, 1.0).unwrap();
|
||||
// command
|
||||
s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).unwrap();
|
||||
s.execute("preset.apply", &json!({"id": preset.id})).unwrap();
|
||||
let command = (*s.develop_of(id).unwrap()).clone();
|
||||
// import (the photo is not in a catalog yet)
|
||||
let mut imported = p;
|
||||
s.import_defaults.raw_preset = Some(preset.id.clone());
|
||||
crate::import::apply_import_defaults(&s, &mut imported);
|
||||
|
||||
assert_eq!(preview, command, "{why}: preview and command");
|
||||
assert_eq!(*imported.develop, command, "{why}: import and command");
|
||||
assert_eq!(command.wb.mode, WbMode::Custom, "{why}: the preset's number replaces As Shot: {:?}", command.wb);
|
||||
// a photo edited in Kelvin ends there; a relative one keeps the scale the preset names (as `develop.merge` does)
|
||||
let want_scale = if kelvin_photo || preset.name.starts_with("kelvin") { WbScale::Kelvin } else { WbScale::Legacy };
|
||||
assert_eq!(command.wb.scale, want_scale, "{why}: the photo stays on the scale it is edited on: {:?}", command.wb);
|
||||
assert_ne!(command.wb, before.wb, "{why}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Zero Amount changes nothing, and not by being applied and undone: the photo keeps As Shot mode and every
|
||||
/// setting, through the command and the preview, even for a preset whose preparation would write Custom values.
|
||||
#[test]
|
||||
fn zero_amount_preset_keeps_as_shot_mode_and_settings() {
|
||||
use lightcraft_catalog::{MediaKind, Op, Photo, Source};
|
||||
use lightcraft_develop::{Preset, WbMode};
|
||||
let mut s = Session::new();
|
||||
let id = s.catalog.alloc_photo_id();
|
||||
let mut p = Photo::new(id, Source::File { path: "/photos/zero.arw".into() }, "zero.arw", "ARW", 64, 64, "2026-01-01T00:00:00");
|
||||
p.kind = MediaKind::Raw;
|
||||
p.meta.camera = "SONY ILCE-7M3".into();
|
||||
p.as_shot_wb = Some((4986.0, -2.0));
|
||||
p.develop = std::sync::Arc::new(p.camera_defaults());
|
||||
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
let preset = Preset {
|
||||
id: "user.zero".into(),
|
||||
name: "Zero".into(),
|
||||
group: "User".into(),
|
||||
settings: json!({"wb": {"temp": 5800.0}, "light": {"exposure": 1.0}}),
|
||||
favorite: false,
|
||||
builtin: false,
|
||||
};
|
||||
s.presets.push(preset.clone());
|
||||
s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).unwrap();
|
||||
let before = (*s.develop_of(id).unwrap()).clone();
|
||||
assert_eq!(before.wb.mode, WbMode::AsShot);
|
||||
for amount in [0.0, -1.0, f64::NAN] {
|
||||
assert_eq!(crate::presets::apply_preset_to_photo(&preset, &before, None, amount, &s.source_info(id)), before, "preview at {amount}");
|
||||
assert_eq!(s.preset_applied(id, &preset, amount).unwrap(), before, "panel preview at {amount}");
|
||||
}
|
||||
s.execute("preset.apply", &json!({"id": preset.id, "amount": 0})).unwrap();
|
||||
let after = (*s.develop_of(id).unwrap()).clone();
|
||||
assert_eq!(after, before);
|
||||
assert_eq!(after.wb.mode, WbMode::AsShot);
|
||||
}
|
||||
@@ -728,7 +728,7 @@ fn a_date_folder_inside_the_library_can_be_renamed_but_the_librarys_own_folders_
|
||||
assert_eq!(r["relinked"], 1, "the photo inside is relinked");
|
||||
assert!(lib.join("Originals/Beach").is_dir(), "the imported date folder is renamed");
|
||||
assert!(!Path::new(&day).exists());
|
||||
let moved = lib.join("Originals/Beach/a.jpg");
|
||||
let moved = lib.join("Originals").join("Beach").join("a.jpg");
|
||||
assert_eq!(paths(&s), [moved.to_string_lossy().to_string()], "the catalog follows the photo");
|
||||
assert!(moved.is_file());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
@@ -3519,6 +3519,295 @@ fn presets_apply_the_imported_profile_they_name() {
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_preserves_embedded_xmp_rating_and_label() {
|
||||
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
|
||||
let src = temp_dir("embedded-xmp-rating-test");
|
||||
let px = [128u8; 40 * 30 * 3];
|
||||
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="5" xmp:Label="Blue"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() };
|
||||
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
|
||||
std::fs::write(src.join("photo.jpg"), &bytes).unwrap();
|
||||
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.join("photo.jpg").to_string_lossy()]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 1);
|
||||
let p = s.catalog.photos().next().unwrap();
|
||||
assert_eq!(p.rating, 5);
|
||||
assert_eq!(p.flag, lightcraft_catalog::Flag::None);
|
||||
assert_eq!(p.label, Some(lightcraft_catalog::ColorLabel::Blue));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_preserves_embedded_exif_rating() {
|
||||
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
|
||||
let src = temp_dir("embedded-exif-rating-test");
|
||||
let px = [128u8; 40 * 30 * 3];
|
||||
let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(3), ..Default::default() });
|
||||
let meta = EncodeMeta { exif: Some(&exif), ..Default::default() };
|
||||
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
|
||||
std::fs::write(src.join("exif_rating.jpg"), &bytes).unwrap();
|
||||
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.join("exif_rating.jpg").to_string_lossy()]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 1);
|
||||
let p = s.catalog.photos().next().unwrap();
|
||||
assert_eq!(p.rating, 3);
|
||||
assert_eq!(p.flag, lightcraft_catalog::Flag::None);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_preserves_embedded_rejected_rating() {
|
||||
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
|
||||
let src = temp_dir("embedded-rejected-rating-test");
|
||||
let px = [128u8; 40 * 30 * 3];
|
||||
|
||||
// Case 1: EXIF rating -1
|
||||
let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(-1), ..Default::default() });
|
||||
let meta = EncodeMeta { exif: Some(&exif), ..Default::default() };
|
||||
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
|
||||
std::fs::write(src.join("exif_rejected.jpg"), &bytes).unwrap();
|
||||
|
||||
// Case 2: XMP rating -1
|
||||
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="-1"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() };
|
||||
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
|
||||
std::fs::write(src.join("xmp_rejected.jpg"), &bytes).unwrap();
|
||||
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 2);
|
||||
let exif_p = s.catalog.photos().find(|p| p.file_name == "exif_rejected.jpg").unwrap();
|
||||
assert_eq!(exif_p.rating, 0);
|
||||
assert_eq!(exif_p.flag, lightcraft_catalog::Flag::Reject);
|
||||
|
||||
let xmp_p = s.catalog.photos().find(|p| p.file_name == "xmp_rejected.jpg").unwrap();
|
||||
assert_eq!(xmp_p.rating, 0);
|
||||
assert_eq!(xmp_p.flag, lightcraft_catalog::Flag::Reject);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_preserves_embedded_xmp_png_and_webp() {
|
||||
use lightcraft_catalog::ColorLabel;
|
||||
use lightcraft_codecs::{EncodeImage, EncodeMeta, Samples, encode_png, encode_webp_lossless};
|
||||
let src = temp_dir("embedded-xmp-png-webp-test");
|
||||
let px = [128u8; 40 * 30 * 3];
|
||||
|
||||
// PNG with embedded XMP rating and label
|
||||
let png_xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="4" xmp:Label="Red"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let png_meta = EncodeMeta { xmp: Some(png_xmp), ..Default::default() };
|
||||
let png_bytes = encode_png(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), &png_meta).unwrap();
|
||||
std::fs::write(src.join("embedded.png"), &png_bytes).unwrap();
|
||||
|
||||
// WebP with embedded XMP rating and label
|
||||
let webp_xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="2" xmp:Label="Blue"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let webp_meta = EncodeMeta { xmp: Some(webp_xmp), ..Default::default() };
|
||||
let webp_bytes = encode_webp_lossless(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), &webp_meta).unwrap();
|
||||
std::fs::write(src.join("embedded.webp"), &webp_bytes).unwrap();
|
||||
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 2);
|
||||
|
||||
let png_photo = s.catalog.photos().find(|p| p.file_name == "embedded.png").unwrap();
|
||||
assert_eq!(png_photo.rating, 4);
|
||||
assert_eq!(png_photo.label, Some(ColorLabel::Red));
|
||||
|
||||
let webp_photo = s.catalog.photos().find(|p| p.file_name == "embedded.webp").unwrap();
|
||||
assert_eq!(webp_photo.rating, 2);
|
||||
assert_eq!(webp_photo.label, Some(ColorLabel::Blue));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_preserves_exif_rating_when_xmp_has_unrelated_rating_text() {
|
||||
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
|
||||
let src = temp_dir("exif-rating-unrelated-xmp-test");
|
||||
let px = [128u8; 40 * 30 * 3];
|
||||
|
||||
let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata { rating: Some(5), ..Default::default() });
|
||||
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:exif="http://ns.adobe.com/exif/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/"><exif:ISOSpeedRatings><rdf:Seq><rdf:li>100</rdf:li></rdf:Seq></exif:ISOSpeedRatings><dc:description><rdf:Alt><rdf:li xml:lang="x-default">Rating guide mentioning xmp:Rating</rdf:li></rdf:Alt></dc:description></rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
let meta = EncodeMeta { exif: Some(&exif), xmp: Some(xmp), ..Default::default() };
|
||||
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
|
||||
std::fs::write(src.join("iso_and_desc_rating.jpg"), &bytes).unwrap();
|
||||
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.join("iso_and_desc_rating.jpg").to_string_lossy()]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 1);
|
||||
let p = s.catalog.photos().next().unwrap();
|
||||
assert_eq!(p.rating, 5);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_rendered_file_ignores_embedded_develop_settings() {
|
||||
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
|
||||
let src = temp_dir("embedded-rendered-develop-test");
|
||||
let px = [128u8; 40 * 30 * 3];
|
||||
|
||||
// A JPEG with embedded XMP containing rating and crs:Exposure2012="+1.00"
|
||||
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmp:Rating="3" crs:Exposure2012="+1.00"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() };
|
||||
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
|
||||
std::fs::write(src.join("rendered_with_crs.jpg"), &bytes).unwrap();
|
||||
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.join("rendered_with_crs.jpg").to_string_lossy()]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 1);
|
||||
let p = s.catalog.photos().next().unwrap();
|
||||
// Rating is imported from embedded XMP
|
||||
assert_eq!(p.rating, 3);
|
||||
// Develop settings from embedded XMP are ignored for rendered files (already baked into pixels)
|
||||
assert_eq!(p.develop.light.exposure, 0.0);
|
||||
assert_eq!(p.develop, std::sync::Arc::new(p.camera_defaults()));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_embedded_metadata_and_field_specific_sidecar_precedence() {
|
||||
use lightcraft_catalog::ColorLabel;
|
||||
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
|
||||
let src = temp_dir("embedded-sidecar-precedence-test");
|
||||
let px = [128u8; 40 * 30 * 3];
|
||||
|
||||
// Case 1: JPEG with embedded Rating 4 and Label Blue, external sidecar with only Label Red
|
||||
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="4" xmp:Label="Blue"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() };
|
||||
let bytes1 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
|
||||
std::fs::write(src.join("partial.jpg"), &bytes1).unwrap();
|
||||
let partial_sidecar = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Label="Red"/></rdf:RDF></x:xmpmeta>"#;
|
||||
std::fs::write(src.join("partial.xmp"), partial_sidecar).unwrap();
|
||||
|
||||
// Case 2: JPEG with embedded Rating 4 and Label Blue, without sidecar
|
||||
let px2 = [129u8; 40 * 30 * 3];
|
||||
let bytes2 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px2)), 90, ChromaSubsampling::S444, &meta).unwrap();
|
||||
std::fs::write(src.join("no_sidecar.jpg"), &bytes2).unwrap();
|
||||
|
||||
// Case 3: JPEG with embedded Rating 4 and Label Blue, complete sidecar override with Rating 1 and Label Red
|
||||
let px3 = [130u8; 40 * 30 * 3];
|
||||
let bytes3 = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px3)), 90, ChromaSubsampling::S444, &meta).unwrap();
|
||||
std::fs::write(src.join("complete.jpg"), &bytes3).unwrap();
|
||||
let complete_sidecar = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="1" xmp:Label="Red"/></rdf:RDF></x:xmpmeta>"#;
|
||||
std::fs::write(src.join("complete.xmp"), complete_sidecar).unwrap();
|
||||
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 3);
|
||||
|
||||
let partial_p = s.catalog.photos().find(|p| p.file_name == "partial.jpg").unwrap();
|
||||
assert_eq!(partial_p.rating, 4);
|
||||
assert_eq!(partial_p.label, Some(ColorLabel::Red));
|
||||
|
||||
let no_sidecar_p = s.catalog.photos().find(|p| p.file_name == "no_sidecar.jpg").unwrap();
|
||||
assert_eq!(no_sidecar_p.rating, 4);
|
||||
assert_eq!(no_sidecar_p.label, Some(ColorLabel::Blue));
|
||||
|
||||
let complete_p = s.catalog.photos().find(|p| p.file_name == "complete.jpg").unwrap();
|
||||
assert_eq!(complete_p.rating, 1);
|
||||
assert_eq!(complete_p.label, Some(ColorLabel::Red));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_partial_sidecar_override_with_rendered_develop() {
|
||||
use lightcraft_catalog::ColorLabel;
|
||||
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
|
||||
let src = temp_dir("embedded-sidecar-rendered-develop-test");
|
||||
let px = [128u8; 40 * 30 * 3];
|
||||
|
||||
// JPEG with embedded Rating 4, Label Blue, and crs:Exposure2012="+2.00"
|
||||
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmp:Rating="4" xmp:Label="Blue" crs:Exposure2012="+2.00"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let meta = EncodeMeta { xmp: Some(xmp), ..Default::default() };
|
||||
let bytes = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &meta).unwrap();
|
||||
std::fs::write(src.join("photo.jpg"), &bytes).unwrap();
|
||||
|
||||
// Sidecar overriding Label to Red and explicitly setting Exposure to +1.00 (no rating tag)
|
||||
let sidecar_xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmp:Label="Red" crs:Exposure2012="+1.00"/></rdf:RDF></x:xmpmeta>"#;
|
||||
std::fs::write(src.join("photo.xmp"), sidecar_xmp).unwrap();
|
||||
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.join("photo.jpg").to_string_lossy()]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 1);
|
||||
let p = s.catalog.photos().next().unwrap();
|
||||
// Rating 4 from embedded is kept
|
||||
assert_eq!(p.rating, 4);
|
||||
// Label Red from sidecar overrides Blue
|
||||
assert_eq!(p.label, Some(ColorLabel::Red));
|
||||
// External sidecar's develop settings apply; embedded exposure +2 stays suppressed
|
||||
assert_eq!(p.develop.light.exposure, 1.0);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_raw_with_embedded_develop_and_partial_sidecar() {
|
||||
use lightcraft_catalog::ColorLabel;
|
||||
let src = temp_dir("raw-embedded-develop-sidecar-test");
|
||||
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmp:Rating="2" xmp:Label="Blue" crs:Exposure2012="+1.50"/></rdf:RDF></x:xmpmeta>"#;
|
||||
|
||||
// Case 1: Raw with embedded develop + rating + label, external sidecar has only Label Red
|
||||
write_raw_with_xmp(&src.join("raw1.NEF"), xmp, 1);
|
||||
let sidecar1 = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Label="Red"/></rdf:RDF></x:xmpmeta>"#;
|
||||
std::fs::write(src.join("raw1.xmp"), sidecar1).unwrap();
|
||||
|
||||
// Case 2: Raw with embedded develop, external sidecar overrides develop settings to Exposure +0.50 and Rating 5
|
||||
write_raw_with_xmp(&src.join("raw2.NEF"), xmp, 2);
|
||||
let sidecar2 = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" xmp:Rating="5" crs:Exposure2012="+0.50"/></rdf:RDF></x:xmpmeta>"#;
|
||||
std::fs::write(src.join("raw2.xmp"), sidecar2).unwrap();
|
||||
|
||||
let mut s = Session::new().with_fs();
|
||||
let r = s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
|
||||
assert_eq!(ids(&r, "imported"), 2);
|
||||
|
||||
let p1 = s.catalog.photos().find(|p| p.file_name == "raw1.NEF").unwrap();
|
||||
assert_eq!(p1.rating, 2, "rating from embedded XMP is preserved");
|
||||
assert_eq!(p1.label, Some(ColorLabel::Red), "label is overridden by external sidecar");
|
||||
assert_eq!(p1.develop.light.exposure, 1.5, "raw keeps embedded develop when sidecar provides none");
|
||||
|
||||
let p2 = s.catalog.photos().find(|p| p.file_name == "raw2.NEF").unwrap();
|
||||
assert_eq!(p2.rating, 5, "rating is overridden by external sidecar");
|
||||
assert_eq!(p2.label, Some(ColorLabel::Blue), "label from embedded XMP is preserved");
|
||||
assert_eq!(p2.develop.light.exposure, 0.5, "external sidecar develop overrides embedded develop");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
/// A raw container LightCraft shows by its embedded JPEG: a TIFF whose IFD0 points at one,
|
||||
/// optionally with an embedded XMP packet in tag 700.
|
||||
fn write_raw_with_xmp(path: &Path, xmp: &str, seed: u8) {
|
||||
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
|
||||
let px: Vec<u8> = (0..48 * 32).flat_map(|i| [(i % 251) as u8, 91, seed]).collect();
|
||||
let j = encode_jpeg(&EncodeImage::new(48, 32, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap();
|
||||
let xmp_bytes = xmp.as_bytes();
|
||||
let xmp_off = 8 + 2 + 36 + 4;
|
||||
let jpeg_off = xmp_off + xmp_bytes.len();
|
||||
let mut f = b"II*\0\x08\0\0\0\x03\0".to_vec();
|
||||
for (tag, v) in [(513u16, jpeg_off as u32), (514, j.len() as u32)] {
|
||||
f.extend_from_slice(&tag.to_le_bytes());
|
||||
f.extend_from_slice(&[4, 0, 1, 0, 0, 0]);
|
||||
f.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
f.extend_from_slice(&700u16.to_le_bytes());
|
||||
f.extend_from_slice(&[1, 0]);
|
||||
f.extend_from_slice(&(xmp_bytes.len() as u32).to_le_bytes());
|
||||
f.extend_from_slice(&(xmp_off as u32).to_le_bytes());
|
||||
f.extend_from_slice(&[0, 0, 0, 0]);
|
||||
f.extend_from_slice(xmp_bytes);
|
||||
f.extend_from_slice(&j);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, f).unwrap();
|
||||
}
|
||||
|
||||
/// A raw container LightCraft shows by its embedded JPEG: a TIFF whose IFD0 points at one.
|
||||
fn write_raw(path: &Path) {
|
||||
use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Lightroom history steps and snapshots read from a catalog file into the import archive: stored as text
|
||||
//! (Lightroom 6) or as compressed BLOBs (history steps since Lightroom Classic 13, which also converts an upgraded
|
||||
//! catalog's steps).
|
||||
|
||||
use crate::lightroom_fixture::{self as fixture, Field, Table};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const CURRENT: &str = "s = { Exposure2012 = 1.25, Contrast2012 = 17 }";
|
||||
const FIRST: &str = "s = { Exposure2012 = 1.25 }";
|
||||
|
||||
/// Write a one-photo catalog with `extra` tables, read it, archive it, and return the archive's JSON.
|
||||
fn archive(tag: &str, extra: Vec<Table>) -> Value {
|
||||
let dir = fixture::dir(tag);
|
||||
let mut tables = fixture::one_photo(&dir.join("originals"), CURRENT);
|
||||
tables.extend(extra);
|
||||
let catalog = dir.join("test.lrcat");
|
||||
fixture::write(&catalog, &tables);
|
||||
let data = crate::lightroom_catalog::read(&catalog).unwrap();
|
||||
let stored = crate::lightroom_archive::store(&dir.join("Interop"), &data).unwrap();
|
||||
let archived = fixture::read_archive(&stored);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
archived
|
||||
}
|
||||
|
||||
fn steps(settings: impl Fn(&str) -> Field) -> Table {
|
||||
Table {
|
||||
name: "Adobe_libraryImageDevelopHistoryStep",
|
||||
columns: fixture::HISTORY_COLUMNS,
|
||||
rows: vec![fixture::history_step(3, 1, 20.0, "Contrast", settings(CURRENT)), fixture::history_step(2, 1, 10.0, "Exposure", settings(FIRST))],
|
||||
}
|
||||
}
|
||||
|
||||
/// `(name, dateCreated, text)` of each archived row, in the order the archive holds them.
|
||||
fn rows(archive: &Value, key: &str) -> Vec<(Value, Value, Value)> {
|
||||
let rows = archive["photos"][0][key].as_array().unwrap_or_else(|| panic!("the archive should list {key}: {archive}"));
|
||||
rows.iter().map(|r| (r["name"].clone(), r["dateCreated"].clone(), r["text"].clone())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_history_steps_keep_their_settings_in_the_archive() {
|
||||
let archived = archive("history-blob", vec![steps(|t| Field::Blob(fixture::compressed(t)))]);
|
||||
let mut steps = rows(&archived, "history");
|
||||
steps.sort_by(|a, b| a.1.as_f64().partial_cmp(&b.1.as_f64()).unwrap());
|
||||
assert_eq!(
|
||||
steps,
|
||||
[(json!("Exposure"), json!(10.0), json!(FIRST)), (json!("Contrast"), json!(20.0), json!(CURRENT))],
|
||||
"each compressed step should be archived with its decoded settings: {archived}"
|
||||
);
|
||||
assert_eq!(archived["warnings"], json!([]), "no step should be reported unreadable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_history_steps_are_archived_as_before() {
|
||||
let archived = archive("history-text", vec![steps(fixture::text)]);
|
||||
let mut steps = rows(&archived, "history");
|
||||
steps.sort_by(|a, b| a.1.as_f64().partial_cmp(&b.1.as_f64()).unwrap());
|
||||
assert_eq!(steps, [(json!("Exposure"), json!(10.0), json!(FIRST)), (json!("Contrast"), json!(20.0), json!(CURRENT))], "{archived}");
|
||||
assert_eq!(archived["warnings"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_and_text_snapshots_keep_their_settings_in_the_archive() {
|
||||
let snapshots = Table {
|
||||
name: "Adobe_libraryImageDevelopSnapshot",
|
||||
columns: fixture::SNAPSHOT_COLUMNS,
|
||||
rows: vec![
|
||||
fixture::snapshot(5, 1, "Bright", Field::Blob(fixture::compressed("s = { Exposure2012 = 2 }"))),
|
||||
fixture::snapshot(6, 1, "Plain", fixture::text("s = { Contrast2012 = 30 }")),
|
||||
],
|
||||
};
|
||||
let archived = archive("snapshot-blob", vec![snapshots]);
|
||||
let mut kept: Vec<_> = rows(&archived, "snapshots").into_iter().map(|(name, _, text)| (name, text)).collect();
|
||||
kept.sort_by_key(|(name, _)| name.to_string());
|
||||
assert_eq!(
|
||||
kept,
|
||||
[(json!("Bright"), json!("s = { Exposure2012 = 2 }")), (json!("Plain"), json!("s = { Contrast2012 = 30 }"))],
|
||||
"compressed and text snapshots should both be archived with their settings: {archived}"
|
||||
);
|
||||
assert_eq!(archived["warnings"], json!([]));
|
||||
}
|
||||
|
||||
/// A hostile or damaged catalog: each bad BLOB costs only its own row's settings, with a warning naming the image.
|
||||
#[test]
|
||||
fn a_malformed_settings_blob_is_archived_without_its_settings_and_warned_about() {
|
||||
let mut mismatch = fixture::compressed(FIRST);
|
||||
mismatch[3] = mismatch[3].wrapping_add(1);
|
||||
let mut over_cap = fixture::compressed(FIRST);
|
||||
over_cap[..4].copy_from_slice(&((16u32 << 20) + 1).to_be_bytes());
|
||||
let bad = [
|
||||
("Short", vec![0, 0]),
|
||||
("Not zlib", vec![0, 0, 0, 5, 1, 2, 3, 4, 5]),
|
||||
("Wrong length", mismatch),
|
||||
("Too big", over_cap),
|
||||
("Not UTF-8", fixture::compressed_bytes(&[0xff, 0xfe])),
|
||||
];
|
||||
let mut history = steps(|t| Field::Blob(fixture::compressed(t)));
|
||||
for (i, (name, bytes)) in bad.iter().enumerate() {
|
||||
let id = 10 + i64::try_from(i).unwrap();
|
||||
history.rows.push(fixture::history_step(id, 1, 30.0 + id as f64, name, Field::Blob(bytes.clone())));
|
||||
}
|
||||
let snapshots = Table {
|
||||
name: "Adobe_libraryImageDevelopSnapshot",
|
||||
columns: fixture::SNAPSHOT_COLUMNS,
|
||||
rows: vec![fixture::snapshot(5, 1, "Broken", Field::Blob(vec![0, 0, 0, 9, 9]))],
|
||||
};
|
||||
let archived = archive("history-bad", vec![history, snapshots]);
|
||||
assert_eq!(archived["photos"].as_array().map(Vec::len), Some(1), "the photo is still read: {archived}");
|
||||
let steps = rows(&archived, "history");
|
||||
assert_eq!(steps.len(), 7, "every step is still archived: {archived}");
|
||||
for (name, _, text) in &steps {
|
||||
let good = name == "Exposure" || name == "Contrast";
|
||||
assert_eq!(text.is_string(), good, "{name}: only the good steps keep settings: {archived}");
|
||||
}
|
||||
assert_eq!(rows(&archived, "snapshots")[0].2, Value::Null, "the broken snapshot is archived without settings");
|
||||
let warnings: Vec<_> = archived["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(warnings.len(), bad.len() + 1, "one warning per bad step and snapshot: {warnings:?}");
|
||||
assert!(warnings.iter().all(|w| w.starts_with("image 1: ")), "each warning names the image: {warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("history step 10")), "a warning names the step: {warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("snapshot 5")), "a warning names the snapshot: {warnings:?}");
|
||||
}
|
||||
|
||||
/// Only the settings column is decoded; any other BLOB (even one in Lightroom's compressed encoding) stays out of
|
||||
/// the archive, as before.
|
||||
#[test]
|
||||
fn other_blob_columns_never_reach_the_archive() {
|
||||
let mut history = steps(|t| Field::Blob(fixture::compressed(t)));
|
||||
for row in &mut history.rows {
|
||||
row[3] = Field::Blob(vec![1, 2, 3, 4]); // digest
|
||||
row[10] = Field::Blob(fixture::compressed("s = { Exposure2012 = 3 }")); // valueString
|
||||
}
|
||||
let archived = archive("history-other-blobs", vec![history]);
|
||||
for step in archived["photos"][0]["history"].as_array().unwrap() {
|
||||
assert!(step.get("digest").is_none() && step.get("valueString").is_none(), "other BLOB columns leaked: {step}");
|
||||
assert!(step["text"].is_string(), "the settings are still decoded: {step}");
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@ fn hdr_merge_command_creates_and_imports_a_dng() {
|
||||
let r = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap();
|
||||
let path = r["path"].as_str().unwrap();
|
||||
assert!(path.ends_with("IMG_0-HDR.dng"), "{path}");
|
||||
assert_eq!(r["reused"].as_bool(), Some(false));
|
||||
let id = lightcraft_catalog::PhotoId(r["id"].as_u64().unwrap());
|
||||
let p = s.catalog.photo(id).unwrap().clone();
|
||||
assert_eq!((p.width, p.height), (480, 320));
|
||||
@@ -55,15 +56,25 @@ fn hdr_merge_command_creates_and_imports_a_dng() {
|
||||
assert_eq!(st.photos[1..].iter().map(|p| p.0).collect::<Vec<_>>(), ids);
|
||||
assert!(st.collapsed);
|
||||
assert_eq!(s.visible_cloned(), vec![id]);
|
||||
// the second merge doesn't overwrite the first
|
||||
let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})).unwrap();
|
||||
assert!(r2["path"].as_str().unwrap().ends_with("IMG_0-HDR-2.dng"));
|
||||
let id2 = lightcraft_catalog::PhotoId(r2["id"].as_u64().unwrap());
|
||||
assert!(s.catalog.stack_of(id2).is_none(), "no stack without the option");
|
||||
// A repeated deterministic merge reuses the existing content instead of publishing an
|
||||
// unimported uniquely named orphan.
|
||||
s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.73})).unwrap();
|
||||
let edited = s.develop_of(id).unwrap().as_ref().clone();
|
||||
let stack_before = s.catalog.stack_of(id).unwrap().clone();
|
||||
let undo_before = s.undo.len();
|
||||
let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap();
|
||||
assert_eq!(r2["id"].as_u64(), Some(id.0));
|
||||
assert_eq!(r2["reused"].as_bool(), Some(true));
|
||||
assert_eq!(r2["path"].as_str(), Some(path));
|
||||
assert!(!dir.join("IMG_0-HDR-2.dng").exists(), "duplicate merge left an orphan");
|
||||
assert_eq!(s.catalog.photos().count(), 4);
|
||||
assert_eq!(s.undo.len(), undo_before, "reusing merge content added an undo step");
|
||||
assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "reusing merge content changed edits");
|
||||
assert_eq!(s.catalog.stack_of(id), Some(&stack_before), "reusing merge content changed stack");
|
||||
// the type filter finds merge results (and only them)
|
||||
s.execute("library.filter", &json!({"merged": "hdr"})).unwrap();
|
||||
let found: std::collections::HashSet<_> = s.catalog.query(&s.filter, &Default::default()).into_iter().collect();
|
||||
assert_eq!(found, [id, id2].into_iter().collect());
|
||||
assert_eq!(found, [id].into_iter().collect());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -143,6 +154,55 @@ fn a_merge_of_raws_without_colour_matrices_keeps_their_colour() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hdr_merge_refuses_stale_result_before_writing() {
|
||||
let dir = temp_dir("hdr-stale");
|
||||
let mut paths = Vec::new();
|
||||
for (i, b) in lightcraft_merge::synth::bracket_dngs(240, 160, &[-2.0, 0.0, 2.0]).unwrap().into_iter().enumerate() {
|
||||
let p = dir.join(format!("IMG_{i}.dng"));
|
||||
std::fs::write(&p, b).unwrap();
|
||||
paths.push(p.to_string_lossy().to_string());
|
||||
}
|
||||
let mut s = Session::new().with_fs();
|
||||
let ids = import(&mut s, paths.clone());
|
||||
let first = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})).unwrap();
|
||||
let id = lightcraft_catalog::PhotoId(first["id"].as_u64().unwrap());
|
||||
let path = first["path"].as_str().unwrap().to_string();
|
||||
s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.73})).unwrap();
|
||||
let edited = s.develop_of(id).unwrap().as_ref().clone();
|
||||
let stack_before = s.catalog.stack_of(id).cloned();
|
||||
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let undo_before = s.undo.len();
|
||||
let missing = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true}));
|
||||
assert!(missing.as_ref().unwrap_err().to_string().contains("missing or changed"));
|
||||
assert!(!std::path::Path::new(&path).exists());
|
||||
assert!(!dir.join("IMG_0-HDR-2.dng").exists());
|
||||
assert_eq!(s.undo.len(), undo_before);
|
||||
assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "repair changed edits");
|
||||
assert_eq!(s.catalog.stack_of(id).cloned(), stack_before);
|
||||
|
||||
std::fs::write(&path, std::fs::read(&paths[0]).unwrap()).unwrap();
|
||||
let changed_bytes = std::fs::read(&path).unwrap();
|
||||
let changed = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true}));
|
||||
assert!(changed.as_ref().unwrap_err().to_string().contains("missing or changed"));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), changed_bytes);
|
||||
assert!(!dir.join("IMG_0-HDR-2.dng").exists());
|
||||
assert_eq!(s.undo.len(), undo_before);
|
||||
assert_eq!(s.develop_of(id).unwrap().as_ref(), &edited, "changed-source repair changed edits");
|
||||
assert_eq!(s.catalog.stack_of(id).cloned(), stack_before);
|
||||
|
||||
s.execute("photo.delete", &json!({"ids": [id.0]})).unwrap();
|
||||
let deleted_bytes = std::fs::read(&path).unwrap();
|
||||
let undo_after_delete = s.undo.len();
|
||||
let failed = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false}));
|
||||
assert!(failed.as_ref().unwrap_err().to_string().contains("deleted"));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), deleted_bytes);
|
||||
assert!(!dir.join("IMG_0-HDR-3.dng").exists(), "failed import left an orphan");
|
||||
assert_eq!(s.undo.len(), undo_after_delete);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panorama_command_with_auto_crop() {
|
||||
let dir = temp_dir("pano");
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
//!
|
||||
//! The model directory is `LIGHTCRAFT_SAM3_DIR`, else `~/.config/lightcraft/models/sam3`. Prints the device and
|
||||
//! kernel creation, the weight upload, the first and the warm forward passes, each neck's first run (which builds
|
||||
//! it) and warm runs, the CPU forward pass and how far the two outputs are apart. `--app` then times what the app
|
||||
//! does per photo, with the model loaded as the app loads it (GPU backbone, necks and DETR encoder, the rest in candle on the CPU): encode,
|
||||
//! click features, first click, first and second Describe (`--cpu-necks`: with the necks in candle, as before they
|
||||
//! ran on the GPU).
|
||||
//! it) and warm runs, the text detector's mask decoder (first and warm, on made-up inputs), the CPU forward pass and
|
||||
//! how far the two outputs are apart. `--app` then times what the app does per photo, with the model loaded as the
|
||||
//! app loads it (GPU backbone, necks, DETR encoder and mask decoder, the rest in candle on the CPU): encode, click
|
||||
//! features, first click, first and second Describe (`--cpu-necks`: with the necks in candle, as before they ran on
|
||||
//! the GPU; `--cpu-masks`: with the mask decoder in candle).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Instant;
|
||||
@@ -35,6 +36,7 @@ fn main() -> Result<(), String> {
|
||||
let cpu = !args.iter().any(|a| a == "--no-cpu");
|
||||
let app = args.iter().any(|a| a == "--app");
|
||||
let cpu_necks = args.iter().any(|a| a == "--cpu-necks");
|
||||
let cpu_masks = args.iter().any(|a| a == "--cpu-masks");
|
||||
let dir = model_dir().ok_or("no SAM 3 model: set LIGHTCRAFT_SAM3_DIR")?;
|
||||
|
||||
let scene = &lightcraft_scenes::demo_library()[0];
|
||||
@@ -75,6 +77,23 @@ fn main() -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
println!("neck device memory: {:.0} MB", gpu.neck_bytes() as f64 / 1e6);
|
||||
{
|
||||
let (memory, text, valid) = (vec![0.1f32; 5184 * 256], vec![0.3f32; 32 * 256], vec![true; 32]);
|
||||
let (l1, l0) = (vec![0.2f32; 256 * 144 * 144], vec![0.4f32; 256 * 288 * 288]);
|
||||
let (rows, bias) = (vec![0.01f32; 200 * 256], vec![0.5f32; 200]);
|
||||
match timed(runs, || gpu.mask_decoder(&memory, &text, &valid, [&l1, &l0], &rows, &bias).map(drop)) {
|
||||
Ok((first, best, mean)) => {
|
||||
let (w, b) = gpu.mask_decoder_bytes().unwrap_or_default();
|
||||
println!(
|
||||
"mask decoder (200 queries): first {first:7.1} ms, warm {best:.1} ms (mean of {runs}: {mean:.1} ms); {:.0} MB weights, {:.0} MB work buffers",
|
||||
w as f64 / 1e6,
|
||||
b as f64 / 1e6
|
||||
);
|
||||
}
|
||||
Err(e) => println!("mask decoder failed on the GPU: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
if cpu {
|
||||
let model = Sam3::load_on(&dir, candle_core::Device::Cpu).map_err(|e| e.to_string())?;
|
||||
let px = candle_core::Tensor::from_vec(pixels.clone(), (1, 3, INPUT, INPUT), &candle_core::Device::Cpu).map_err(|e| e.to_string())?;
|
||||
@@ -96,7 +115,7 @@ fn main() -> Result<(), String> {
|
||||
}
|
||||
drop(gpu);
|
||||
if app {
|
||||
as_the_app(&dir, &rgb, (img.width, img.height), runs, cpu_necks)?;
|
||||
as_the_app(&dir, &rgb, (img.width, img.height), runs, (cpu_necks, cpu_masks))?;
|
||||
}
|
||||
// no GPU work in flight when the process ends (issue #620)
|
||||
lightcraft_gpu::begin_shutdown();
|
||||
@@ -124,10 +143,11 @@ fn ms(t: Instant) -> String {
|
||||
format!("{:.0} ms", t.elapsed().as_secs_f64() * 1e3)
|
||||
}
|
||||
|
||||
/// The model's GPU accelerator with the necks left to candle (`--cpu-necks`).
|
||||
/// The model's GPU accelerator with the necks (`--cpu-necks`) or the mask decoder (`--cpu-masks`) left to candle.
|
||||
struct Heads {
|
||||
gpu: Box<dyn BackboneAccel>,
|
||||
necks: bool,
|
||||
masks: bool,
|
||||
}
|
||||
|
||||
impl BackboneAccel for Heads {
|
||||
@@ -144,7 +164,7 @@ impl BackboneAccel for Heads {
|
||||
self.gpu.runs_detr_encoder()
|
||||
}
|
||||
fn runs_mask_decoder(&self) -> bool {
|
||||
self.gpu.runs_mask_decoder()
|
||||
self.masks && self.gpu.runs_mask_decoder()
|
||||
}
|
||||
fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result<Vec<Vec<f32>>, String> {
|
||||
self.gpu.neck(which, backbone, n)
|
||||
@@ -166,9 +186,11 @@ impl BackboneAccel for Heads {
|
||||
}
|
||||
|
||||
/// The model as the app loads it, timed per photo: encode, click features, a click, two Describes.
|
||||
fn as_the_app(dir: &std::path::Path, rgb: &[u8], (w, h): (usize, usize), runs: usize, cpu_necks: bool) -> Result<(), String> {
|
||||
fn as_the_app(dir: &std::path::Path, rgb: &[u8], (w, h): (usize, usize), runs: usize, (cpu_necks, cpu_masks): (bool, bool)) -> Result<(), String> {
|
||||
let t = Instant::now();
|
||||
let make = |r: &WeightReader| -> Result<Box<dyn BackboneAccel>, String> { Ok(Box::new(Heads { gpu: sam3::backbone(r)?, necks: !cpu_necks })) };
|
||||
let make = |r: &WeightReader| -> Result<Box<dyn BackboneAccel>, String> {
|
||||
Ok(Box::new(Heads { gpu: sam3::backbone(r)?, necks: !cpu_necks, masks: !cpu_masks }))
|
||||
};
|
||||
let mut model = Sam3::load_accelerated(dir, candle_core::Device::Cpu, make).map_err(|e| e.to_string())?;
|
||||
println!("app: load {} on {}", ms(t), model.backbone_device());
|
||||
let click = |x, y| lightcraft_segment::Click { x, y, positive: true };
|
||||
|
||||
@@ -255,6 +255,7 @@ fn plan(net: &Net, tile: usize, max_binding: u64) -> Result<(Layout, Vec<Layer>)
|
||||
let reads: Vec<usize> = match op {
|
||||
Op::Conv(c) => std::iter::once(c.src).chain(c.src2).collect(),
|
||||
Op::ConvT2(c) => vec![c.src],
|
||||
Op::Add { src, src2 } => vec![*src, *src2],
|
||||
Op::MaxPool2 { src } | Op::DepthToSpace2 { src } => vec![*src],
|
||||
};
|
||||
for t in reads {
|
||||
@@ -448,6 +449,7 @@ fn plan(net: &Net, tile: usize, max_binding: u64) -> Result<(Layout, Vec<Layer>)
|
||||
}
|
||||
// run as part of the 1 × 1 convolution before it
|
||||
Op::DepthToSpace2 { .. } => {}
|
||||
Op::Add { .. } => return unsupported("an elementwise add is not supported on the GPU"),
|
||||
}
|
||||
// buffers whose last reader was this layer are free for the next layer's result
|
||||
for t in 0..=i {
|
||||
|
||||
@@ -609,7 +609,7 @@ fn sample(cx: &mut Cx<'_>, src: &Arc<Rgb32f>, src_buf: Arc<Buf>, plan: &Plan<'_>
|
||||
Arc::new(out)
|
||||
};
|
||||
let (base, (bw, bh)) = match sp.prefilter {
|
||||
Some(d) => (Arc::new(resize(cx, &oriented, (sp.ow, sp.oh), d, 3, Filter::Mitchell)), d),
|
||||
Some(d) => (Arc::new(resize(cx, &oriented, (sp.ow, sp.oh), d, 3, fr.downscale)), d),
|
||||
None => (oriented, (sp.ow, sp.oh)),
|
||||
};
|
||||
let mut affine = |xf: &lightcraft_geom::Affine| {
|
||||
|
||||
+54
-6
@@ -17,8 +17,8 @@
|
||||
//! per layer and reads the result back once. No subgroups or shader-f16 needed. The two necks that follow the
|
||||
//! backbone run on the same device, built when first asked for (`sam3/neck.rs`).
|
||||
//!
|
||||
//! The same accelerator runs the text detector's DETR encoder (`sam3/detr.rs`); its weights load on the first text
|
||||
//! prompt. The mask decoder stays in candle on the CPU.
|
||||
//! The same accelerator runs the text detector's DETR encoder (`sam3/detr.rs`) and its mask decoder (`sam3/pixel.rs`);
|
||||
//! their weights load on the first text prompt.
|
||||
//!
|
||||
//! The device is its own (like denoise's and faces'): it respects the same switches as GPU rendering
|
||||
//! (`LIGHTCRAFT_GPU`, `LIGHTCRAFT_GPU_BACKEND`, `LIGHTCRAFT_GPU_ADAPTER`, the GPU preference), the crash sentinel
|
||||
@@ -35,6 +35,7 @@ use wgpu::util::DeviceExt;
|
||||
|
||||
mod detr;
|
||||
mod neck;
|
||||
mod pixel;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -58,10 +59,16 @@ const PATCH_K: usize = 3 * PATCH * PATCH;
|
||||
|
||||
/// Longest wait for one forward pass before the device is given up on.
|
||||
const TIMEOUT: Duration = Duration::from_secs(120);
|
||||
/// Workgroup memory the attention kernel needs: its key and value tiles (2 × [`ATTENTION_KEYS`] × 64 floats).
|
||||
/// Conservative workgroup memory for key and value tiles (2 × [`ATTENTION_KEYS`] × 64 floats).
|
||||
const ATTENTION_BYTES: u32 = 2 * ATTENTION_KEYS * HEAD_DIM as u32 * 4;
|
||||
/// Keys per step of the attention kernel.
|
||||
/// The maximum keys per step; also used to bound the required workgroup memory.
|
||||
const ATTENTION_KEYS: u32 = 32;
|
||||
|
||||
/// On DX12, creating the fully unrolled 32-key shader can be very slow on some drivers. Smaller
|
||||
/// tiles shorten initialization; the existing 32-key limits remain conservative for every backend.
|
||||
fn attention_keys(backend: wgpu::Backend) -> u32 {
|
||||
if backend == wgpu::Backend::Dx12 { 8 } else { ATTENTION_KEYS }
|
||||
}
|
||||
/// The matrix product's blocking.
|
||||
const TILE: Tile = Tile { rows: 4, cols: 4, bk: 16 };
|
||||
|
||||
@@ -254,7 +261,7 @@ fn make_device(backends: wgpu::Backends) -> Result<Dev, String> {
|
||||
let k = Kernels {
|
||||
matmul: Matmul { pipeline: pipe("sam3 matmul", &matmul_source(TILE, false), "main"), tile: TILE },
|
||||
matmul16: OnceLock::new(),
|
||||
attention: pipe("sam3 attention", &attention_source(ATTENTION_KEYS), "main"),
|
||||
attention: pipe("sam3 attention", &attention_source(attention_keys(info.backend)), "main"),
|
||||
layernorm: pipe("sam3 ops", ops, "layernorm"),
|
||||
rope: pipe("sam3 ops", ops, "rope"),
|
||||
im2col: pipe("sam3 ops", ops, "im2col"),
|
||||
@@ -956,6 +963,8 @@ pub struct Sam3Gpu {
|
||||
detr: detr::Encoder,
|
||||
/// The feature pyramids, built on first use.
|
||||
necks: neck::Necks,
|
||||
/// The detector's mask decoder, loaded on the first text prompt.
|
||||
masks: pixel::MaskDecoder,
|
||||
}
|
||||
|
||||
/// The SAM 3 backbone on the GPU with the checkpoint's weights uploaded, or why it can't run there (GPU off, missing,
|
||||
@@ -1051,7 +1060,18 @@ fn build_inner(dev: &'static Dev, weights: &WeightReader, precision: Precision)
|
||||
let recorded = g.record();
|
||||
let detr = detr::Encoder::new(weights.clone());
|
||||
let necks = neck::Necks::new(weights.clone());
|
||||
Ok(Sam3Gpu { dev, recorded, work: Mutex::new(Work { pixels, out: y, staging }), weight_bytes: ld.bytes, work_bytes, precision, detr, necks })
|
||||
let masks = pixel::MaskDecoder::new(weights.clone());
|
||||
Ok(Sam3Gpu {
|
||||
dev,
|
||||
recorded,
|
||||
work: Mutex::new(Work { pixels, out: y, staging }),
|
||||
weight_bytes: ld.bytes,
|
||||
work_bytes,
|
||||
precision,
|
||||
detr,
|
||||
necks,
|
||||
masks,
|
||||
})
|
||||
}
|
||||
|
||||
/// Run `f`, the work of `stage`, turning a panic into a broken device (with the stage's name).
|
||||
@@ -1078,6 +1098,11 @@ impl Sam3Gpu {
|
||||
self.detr.bytes()
|
||||
}
|
||||
|
||||
/// Bytes of device memory the mask decoder's weights and work buffers take, once a text prompt loaded them.
|
||||
pub fn mask_decoder_bytes(&self) -> Option<(u64, u64)> {
|
||||
self.masks.bytes()
|
||||
}
|
||||
|
||||
fn run(&self, pixels: &[f32]) -> Result<Vec<f32>, String> {
|
||||
if pixels.len() != 3 * IMAGE * IMAGE {
|
||||
return Err(format!("{} pixel values, expected 3 × {IMAGE} × {IMAGE}", pixels.len()));
|
||||
@@ -1125,6 +1150,25 @@ impl BackboneAccel for Sam3Gpu {
|
||||
guarded("the SAM 3 DETR encoder", || self.detr.run(self.dev, image, pos, text, valid))
|
||||
}
|
||||
|
||||
fn mask_decoder(
|
||||
&self,
|
||||
memory: &[f32],
|
||||
text: &[f32],
|
||||
valid: &[bool],
|
||||
levels: [&[f32]; 2],
|
||||
rows: &[f32],
|
||||
bias: &[f32],
|
||||
) -> Result<Vec<f32>, String> {
|
||||
if let Some(why) = broken_reason() {
|
||||
return Err(format!("the GPU is not used any more: {why}"));
|
||||
}
|
||||
if let Some(why) = crate::switched_off() {
|
||||
return Err(why);
|
||||
}
|
||||
let Some(_work) = crate::exit::enter() else { return Err("LightCraft is closing".into()) };
|
||||
guarded("the SAM 3 mask decoder", || self.masks.run(self.dev, memory, text, valid, levels, rows, bias))
|
||||
}
|
||||
|
||||
fn closing(&self) -> bool {
|
||||
crate::shutting_down()
|
||||
}
|
||||
@@ -1137,6 +1181,10 @@ impl BackboneAccel for Sam3Gpu {
|
||||
true
|
||||
}
|
||||
|
||||
fn runs_mask_decoder(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn device(&self) -> String {
|
||||
let weights = match self.precision {
|
||||
Precision::F32 => "",
|
||||
|
||||
@@ -30,7 +30,7 @@ const MLP: usize = 2048;
|
||||
const LAYERS: usize = 6;
|
||||
/// PyTorch's `nn.LayerNorm` default (`TORCH_LN_EPS`).
|
||||
const EPS: f32 = 1e-5;
|
||||
/// Keys per step of the attention kernel (the prompt's 32 tokens are one step).
|
||||
/// Required key-count alignment, kept at 32 even when the DX12 kernel uses smaller tiles.
|
||||
const KEYS: u32 = 32;
|
||||
/// `p.gelu` of the matrix product: ReLU.
|
||||
const RELU: u32 = 2;
|
||||
@@ -49,7 +49,7 @@ pub(super) fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> {
|
||||
KERNELS
|
||||
.get_or_init(|| {
|
||||
let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let source = attention_source(KEYS);
|
||||
let source = attention_source(super::attention_keys(dev.info.backend));
|
||||
let pipe = |entry: &str| pipeline(&dev.device, &dev.pipeline_layout, "sam3 detr", &source, entry);
|
||||
let k = Kernels { attention: pipe("attention"), add: pipe("add") };
|
||||
match pollster::block_on(validation.pop()) {
|
||||
|
||||
@@ -83,6 +83,8 @@ fn the_kernel_source_is_written_out() {
|
||||
assert!(!src.contains("{{"), "a mark is left");
|
||||
assert!(src.contains("let s31 = ") && !src.contains("let s32 = "));
|
||||
assert!(src.contains("let q7 = ") && !src.contains("let q8 = "));
|
||||
let dx12 = attention_source(super::super::attention_keys(wgpu::Backend::Dx12));
|
||||
assert!(dx12.contains("let s7 = ") && !dx12.contains("let s8 = "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
//! The mask decoder of SAM 3's text detector on the GPU (`lightcraft-segment`'s `detector.rs` is the reference): the
|
||||
//! DETR encoder's memory (72 × 72 tokens of 256) attends to the prompt and is added to it (`prompt_cross_attn`, after
|
||||
//! its layer norm), then the pixel decoder brings it up to 288 × 288 in two stages, each a nearest 2 × up-sampling plus
|
||||
//! the detector neck's level of that size (144², then 288²) → 3 × 3 convolution → GroupNorm (8 groups, eps 1e-5) →
|
||||
//! ReLU; last, every row of a `[r, 256]` matrix (with its bias) is a 1 × 1 projection of the decoder's output, an image
|
||||
//! `[r, 288, 288]`. The detector passes its 200 mask embeddings with the instance projection folded in, so these are the
|
||||
//! per-query mask logits. ~0.9–1.4 s per prompt on the CPU through candle, most of it the 288² convolution.
|
||||
//!
|
||||
//! Images are pixel rows (`[pixels, channels]`), as in the necks (`sam3/neck.rs`): the convolutions are the necks'
|
||||
//! implicit GEMM, the projection the backbone's matrix product (`[pixels, 256] · [r, 256]ᵀ`, then `to_chw`), the
|
||||
//! prompt attention the DETR encoder's kernels (`sam3/detr.rs`). `wgsl/sam3_pixel.wgsl` adds the up-sampling, which
|
||||
//! adds the channels-first neck level as uploaded, and GroupNorm + ReLU: two-pass statistics per chunk of 256 pixels,
|
||||
//! merged per group (the parallel variance formula), then applied in place.
|
||||
//!
|
||||
//! Loaded on the first prompt, like the encoder: kernels, 6 MB of weights, ~280 MB of work buffers. A prompt uploads
|
||||
//! the memory, the prompt's tokens and padding bias, both neck levels (106 MB; they stay on the CPU with the image's
|
||||
//! features, see `docs/gpu-pipeline.md`) and the rows, submits once and reads `r · 288²` numbers back. The dispatches
|
||||
//! are recorded once per row count.
|
||||
|
||||
use std::sync::{Mutex, OnceLock, PoisonError};
|
||||
|
||||
use lightcraft_segment::WeightReader;
|
||||
|
||||
use super::detr::{self, Operand};
|
||||
use super::neck::{self, conv_weights, scoped};
|
||||
use super::{Dev, Graph, Precision, Recorded, buffer, pipeline, u32_of, upload};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Where the decoder's weights are in the checkpoint.
|
||||
const PREFIX: &str = "detector_model.mask_decoder";
|
||||
/// The memory's side (72 × 72 tokens), the width of everything, the prompt's tokens.
|
||||
const GRID: usize = 72;
|
||||
const WIDTH: usize = 256;
|
||||
const TEXT: usize = 32;
|
||||
const HEAD_DIM: usize = 32;
|
||||
/// The decoder's stages (each doubles the side): 144², 288².
|
||||
const STAGES: usize = 2;
|
||||
/// The output's side.
|
||||
const SIDE: usize = GRID << STAGES;
|
||||
/// GroupNorm's groups and eps (`candle_nn::group_norm(8, 256, 1e-5)`), and PyTorch's layer norm eps.
|
||||
const GROUPS: usize = 8;
|
||||
const EPS: f32 = 1e-5;
|
||||
/// Pixels per workgroup of the GroupNorm statistics.
|
||||
const CHUNK: usize = 256;
|
||||
|
||||
struct Kernels {
|
||||
upsample_add: wgpu::ComputePipeline,
|
||||
group_stats: wgpu::ComputePipeline,
|
||||
group_merge: wgpu::ComputePipeline,
|
||||
group_norm_relu: wgpu::ComputePipeline,
|
||||
}
|
||||
|
||||
static KERNELS: OnceLock<Result<Kernels, String>> = OnceLock::new();
|
||||
|
||||
/// The decoder's own kernels, compiled on first use.
|
||||
fn kernels(dev: &'static Dev) -> Result<&'static Kernels, String> {
|
||||
KERNELS
|
||||
.get_or_init(|| {
|
||||
let validation = dev.device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let source = include_str!("../wgsl/sam3_pixel.wgsl");
|
||||
let pipe = |entry: &str| pipeline(&dev.device, &dev.pipeline_layout, "sam3 pixel", source, entry);
|
||||
let k = Kernels {
|
||||
upsample_add: pipe("upsample_add"),
|
||||
group_stats: pipe("group_stats"),
|
||||
group_merge: pipe("group_merge"),
|
||||
group_norm_relu: pipe("group_norm_relu"),
|
||||
};
|
||||
match pollster::block_on(validation.pop()) {
|
||||
Some(e) => Err(format!("{}: the SAM 3 mask decoder kernels did not compile ({e})", dev.info.name)),
|
||||
None => Ok(k),
|
||||
}
|
||||
})
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
}
|
||||
|
||||
/// Floats of the GroupNorm statistics of chunks for an image of `pixels`, `groups` groups.
|
||||
fn partials_len(pixels: usize, groups: usize) -> usize {
|
||||
pixels.div_ceil(CHUNK) * groups * 2
|
||||
}
|
||||
|
||||
impl Graph {
|
||||
/// Nearest up-sampling of the rows `src` (`[from², channels]`) to `to × to`, plus the channels-first image `skip`
|
||||
/// (`[channels, to, to]`), into the rows `dst` (`[to², channels]`).
|
||||
fn upsample_add(
|
||||
&mut self,
|
||||
k: &'static Kernels,
|
||||
[src, skip, dst]: [&wgpu::Buffer; 3],
|
||||
channels: usize,
|
||||
(from, to): (usize, usize),
|
||||
) -> Result<(), String> {
|
||||
if from == 0 || to < from || channels == 0 {
|
||||
return Err("an up-sampling the SAM 3 kernel cannot do".into());
|
||||
}
|
||||
let count = channels.checked_mul(to * to).ok_or("an image too large")?;
|
||||
let (g, row) = self.flat(count.div_ceil(256))?;
|
||||
let params = [u32_of(channels)?, u32_of(to)?, u32_of(from)?, 0, 0, 0, u32_of(count)?, row];
|
||||
self.push(&k.upsample_add, params, [src, skip, &self.dev.dummy, dst], g);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// GroupNorm (`groups` groups of channels, eps) and ReLU in place on the rows `x` (`[pixels, channels]`, channels
|
||||
/// ≤ 256), with the per-channel `gamma` and `beta`; `partials` (at least [`partials_len`] floats) and `stats`
|
||||
/// (2 · groups) hold the statistics on the way.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn group_norm_relu(
|
||||
&mut self,
|
||||
k: &'static Kernels,
|
||||
[x, gamma, beta]: [&wgpu::Buffer; 3],
|
||||
[partials, stats]: [&wgpu::Buffer; 2],
|
||||
(pixels, channels, groups): (usize, usize, usize),
|
||||
eps: f32,
|
||||
) -> Result<(), String> {
|
||||
if pixels == 0 || channels == 0 || channels > 256 || groups == 0 || !channels.is_multiple_of(groups) {
|
||||
return Err("a GroupNorm the SAM 3 kernel cannot do".into());
|
||||
}
|
||||
let dummy = &self.dev.dummy;
|
||||
let chunks = pixels.div_ceil(CHUNK);
|
||||
let (g, row) = self.flat(chunks)?;
|
||||
let params = [u32_of(channels)?, u32_of(pixels)?, u32_of(CHUNK)?, u32_of(groups)?, 0, 0, 0, row];
|
||||
self.push(&k.group_stats, params, [x, dummy, dummy, partials], g);
|
||||
let params = [u32_of(chunks)?, u32_of(pixels)?, u32_of(CHUNK)?, u32_of(groups)?, eps.to_bits(), u32_of(channels / groups)?, 0, 0];
|
||||
self.push(&k.group_merge, params, [partials, dummy, dummy, stats], [u32_of(groups)?, 1, 1]);
|
||||
let count = pixels.checked_mul(channels).ok_or("an image too large")?;
|
||||
let (g, row) = self.flat(count.div_ceil(256))?;
|
||||
self.push(&k.group_norm_relu, [u32_of(channels)?, 0, 0, u32_of(groups)?, 0, 0, u32_of(count)?, row], [stats, gamma, beta, x], g);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The decoder's weights on the device: (weight, bias) pairs, the prompt attention's k | v concatenated, the
|
||||
/// convolutions as rows `[cout, 3, 3, cin]`.
|
||||
struct Weights {
|
||||
ln: [wgpu::Buffer; 2],
|
||||
q: [wgpu::Buffer; 2],
|
||||
kv: [wgpu::Buffer; 2],
|
||||
o: [wgpu::Buffer; 2],
|
||||
convs: Vec<[wgpu::Buffer; 2]>,
|
||||
norms: Vec<[wgpu::Buffer; 2]>,
|
||||
}
|
||||
|
||||
/// Reads the decoder's tensors, checking their shapes.
|
||||
struct Loader<'a> {
|
||||
weights: &'a WeightReader,
|
||||
bytes: u64,
|
||||
}
|
||||
|
||||
impl Loader<'_> {
|
||||
/// The tensors `names` (each of `shape`) concatenated along the first axis.
|
||||
fn read(&mut self, names: &[String], shape: &[usize]) -> Result<Vec<f32>, String> {
|
||||
let mut all = Vec::with_capacity(names.len() * shape.iter().product::<usize>());
|
||||
for name in names {
|
||||
let full = format!("{PREFIX}.{name}");
|
||||
let (got, data) = self.weights.read(&full).map_err(|e| format!("{full}: {e}"))?;
|
||||
if got != shape {
|
||||
return Err(format!("{full}: shape {got:?}, expected {shape:?}"));
|
||||
}
|
||||
all.extend(data);
|
||||
}
|
||||
self.bytes += all.len() as u64 * 4;
|
||||
Ok(all)
|
||||
}
|
||||
|
||||
/// A pair of `{name}.weight` (`[n, k]`, several concatenated along n) and `{name}.bias` (or a norm's scale and shift
|
||||
/// with `k` 0), uploaded.
|
||||
fn pair(&mut self, dev: &Dev, names: &[String], n: usize, k: usize) -> Result<[wgpu::Buffer; 2], String> {
|
||||
let w: Vec<String> = names.iter().map(|n| format!("{n}.weight")).collect();
|
||||
let b: Vec<String> = names.iter().map(|n| format!("{n}.bias")).collect();
|
||||
let shape: &[usize] = if k == 0 { &[n] } else { &[n, k] };
|
||||
let label = names.first().map_or("weight", String::as_str);
|
||||
Ok([upload(dev, label, &self.read(&w, shape)?), upload(dev, label, &self.read(&b, &[n])?)])
|
||||
}
|
||||
|
||||
fn load(&mut self, dev: &Dev) -> Result<Weights, String> {
|
||||
let a = "prompt_cross_attn";
|
||||
let proj = |ps: &[&str]| -> Vec<String> { ps.iter().map(|p| format!("{a}.{p}_proj")).collect() };
|
||||
let mut convs = Vec::with_capacity(STAGES);
|
||||
let mut norms = Vec::with_capacity(STAGES);
|
||||
for i in 0..STAGES {
|
||||
let name = format!("pixel_decoder.conv_layers.{i}");
|
||||
let w = self.read(&[format!("{name}.weight")], &[WIDTH, WIDTH, 3, 3])?;
|
||||
let b = self.read(&[format!("{name}.bias")], &[WIDTH])?;
|
||||
convs.push(conv_weights(dev, &name, &w, &b, (WIDTH, WIDTH, 3)));
|
||||
norms.push(self.pair(dev, &[format!("pixel_decoder.norms.{i}")], WIDTH, 0)?);
|
||||
}
|
||||
Ok(Weights {
|
||||
ln: self.pair(dev, &["prompt_cross_attn_norm".to_string()], WIDTH, 0)?,
|
||||
q: self.pair(dev, &proj(&["q"]), WIDTH, WIDTH)?,
|
||||
kv: self.pair(dev, &proj(&["k", "v"]), WIDTH, WIDTH)?,
|
||||
o: self.pair(dev, &proj(&["o"]), WIDTH, WIDTH)?,
|
||||
convs,
|
||||
norms,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The buffers a prompt writes and reads, and its dispatches (recorded for one row count).
|
||||
struct Work {
|
||||
/// The memory in, then the memory after the prompt attention.
|
||||
x: wgpu::Buffer,
|
||||
text: wgpu::Buffer,
|
||||
/// The prompt attention's k | v of the prompt (`[32, 512]`), then its padding bias (32 floats).
|
||||
text_kv: wgpu::Buffer,
|
||||
/// The neck's levels as uploaded (`[256, 144, 144]`, `[256, 288, 288]`); the projection's channels-first result
|
||||
/// ends in the second.
|
||||
skip1: wgpu::Buffer,
|
||||
skip0: wgpu::Buffer,
|
||||
/// Two 288² images the steps alternate between (the prompt attention's smaller ones too).
|
||||
a: wgpu::Buffer,
|
||||
b: wgpu::Buffer,
|
||||
rows: wgpu::Buffer,
|
||||
row_bias: wgpu::Buffer,
|
||||
partials: wgpu::Buffer,
|
||||
stats: wgpu::Buffer,
|
||||
staging: wgpu::Buffer,
|
||||
recorded: Option<(usize, Recorded)>,
|
||||
}
|
||||
|
||||
impl Work {
|
||||
fn new(dev: &Dev) -> Work {
|
||||
let image = |label: &str| buffer(dev, label, SIDE * SIDE * WIDTH);
|
||||
Work {
|
||||
x: buffer(dev, "mask memory", GRID * GRID * WIDTH),
|
||||
text: buffer(dev, "mask prompt", TEXT * WIDTH),
|
||||
text_kv: buffer(dev, "mask prompt k|v", TEXT * 2 * WIDTH + TEXT),
|
||||
skip1: buffer(dev, "mask level 1", WIDTH * (SIDE / 2) * (SIDE / 2)),
|
||||
skip0: image("mask level 0"),
|
||||
a: image("mask ping"),
|
||||
b: image("mask pong"),
|
||||
rows: buffer(dev, "mask rows", WIDTH * WIDTH),
|
||||
row_bias: buffer(dev, "mask row bias", WIDTH),
|
||||
partials: buffer(dev, "mask norm partials", partials_len(SIDE * SIDE, GROUPS)),
|
||||
stats: buffer(dev, "mask norm stats", 2 * GROUPS),
|
||||
staging: dev.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("mask read-back"),
|
||||
size: (SIDE * SIDE * WIDTH * 4) as u64,
|
||||
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
}),
|
||||
recorded: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes on the device: the read-back buffer is host memory on discrete GPUs and not counted.
|
||||
fn bytes() -> u64 {
|
||||
let floats = GRID * GRID * WIDTH
|
||||
+ TEXT * (3 * WIDTH + 1)
|
||||
+ WIDTH * (SIDE / 2) * (SIDE / 2)
|
||||
+ 3 * SIDE * SIDE * WIDTH
|
||||
+ WIDTH * (WIDTH + 1)
|
||||
+ partials_len(SIDE * SIDE, GROUPS)
|
||||
+ 2 * GROUPS;
|
||||
(floats * 4) as u64
|
||||
}
|
||||
}
|
||||
|
||||
/// The dispatches of a prompt with `r` rows: everything after the uploads, the result in `work.skip0`.
|
||||
fn record(dev: &'static Dev, w: &Weights, work: &Work, r: usize) -> Result<Recorded, String> {
|
||||
let (kd, kn, k) = (detr::kernels(dev)?, neck::kernels(dev)?, kernels(dev)?);
|
||||
let mut g = Graph::new(dev);
|
||||
let tokens = GRID * GRID;
|
||||
// the memory attends to the prompt (padding masked): x += o(attention(q(ln(x)), k | v(text)))
|
||||
g.layernorm_torch([&work.x, &w.ln[0], &w.ln[1], &work.a], tokens, WIDTH)?;
|
||||
g.matmul([&work.a, &w.q[0], &w.q[1], &work.b], (tokens, WIDTH, WIDTH), 1, false, false, Precision::F32)?;
|
||||
g.matmul([&work.text, &w.kv[0], &w.kv[1], &work.text_kv], (TEXT, 2 * WIDTH, WIDTH), 1, false, false, Precision::F32)?;
|
||||
let q = Operand { buffer: &work.b, stride: WIDTH, offset: 0 };
|
||||
let (tk, tv) =
|
||||
(Operand { buffer: &work.text_kv, stride: 2 * WIDTH, offset: 0 }, Operand { buffer: &work.text_kv, stride: 2 * WIDTH, offset: WIDTH });
|
||||
g.attention_detr(kd, [q, tk, tv], Some(TEXT * 2 * WIDTH), &work.a, (tokens, TEXT, WIDTH / HEAD_DIM))?;
|
||||
g.matmul([&work.a, &w.o[0], &w.o[1], &work.x], (tokens, WIDTH, WIDTH), 1, false, true, Precision::F32)?;
|
||||
// the pixel decoder: up-sample + the neck's level → 3 × 3 convolution → GroupNorm → ReLU, at 144² and at 288²
|
||||
let mut cur = &work.x;
|
||||
let mut side = GRID;
|
||||
for (i, skip) in [&work.skip1, &work.skip0].into_iter().enumerate() {
|
||||
let (Some(conv), Some(norm)) = (w.convs.get(i), w.norms.get(i)) else { return Err("a pixel decoder stage without weights".into()) };
|
||||
g.upsample_add(k, [cur, skip, &work.a], WIDTH, (side, 2 * side))?;
|
||||
side *= 2;
|
||||
g.conv3(kn, [&work.a, &conv[0], &conv[1], &work.b], side, (WIDTH, WIDTH))?;
|
||||
g.group_norm_relu(k, [&work.b, &norm[0], &norm[1]], [&work.partials, &work.stats], (side * side, WIDTH, GROUPS), EPS)?;
|
||||
cur = &work.b;
|
||||
}
|
||||
// each row a 1 × 1 projection of the decoder's output: [pixels, r], then channels-first into the spent level 0
|
||||
g.matmul([&work.b, &work.rows, &work.row_bias, &work.a], (side * side, r, WIDTH), 1, false, false, Precision::F32)?;
|
||||
g.channels_first(&work.a, &work.skip0, r, side, side)?;
|
||||
Ok(g.record())
|
||||
}
|
||||
|
||||
/// The decoder with its weights on the device.
|
||||
struct Built {
|
||||
weights: Weights,
|
||||
/// One prompt at a time (they share the work buffers).
|
||||
work: Mutex<Work>,
|
||||
weight_bytes: u64,
|
||||
}
|
||||
|
||||
fn build(dev: &'static Dev, weights: &WeightReader) -> Result<Built, String> {
|
||||
// every kernel compiles before anything is uploaded
|
||||
detr::kernels(dev)?;
|
||||
neck::kernels(dev)?;
|
||||
kernels(dev)?;
|
||||
scoped(dev, "the SAM 3 mask decoder", || {
|
||||
let mut ld = Loader { weights, bytes: 0 };
|
||||
let w = ld.load(dev)?;
|
||||
Ok(Built { weights: w, work: Mutex::new(Work::new(dev)), weight_bytes: ld.bytes })
|
||||
})
|
||||
}
|
||||
|
||||
/// The mask decoder, built on first use from the checkpoint the backbone came from.
|
||||
pub(super) struct MaskDecoder {
|
||||
weights: WeightReader,
|
||||
built: OnceLock<Result<Built, String>>,
|
||||
}
|
||||
|
||||
impl MaskDecoder {
|
||||
pub(super) fn new(weights: WeightReader) -> Self {
|
||||
Self { weights, built: OnceLock::new() }
|
||||
}
|
||||
|
||||
/// Bytes of device memory the weights and the work buffers take, once built.
|
||||
pub(super) fn bytes(&self) -> Option<(u64, u64)> {
|
||||
self.built.get().and_then(|b| b.as_ref().ok()).map(|b| (b.weight_bytes, Work::bytes()))
|
||||
}
|
||||
|
||||
/// `[r, 288, 288]` for the encoder memory `[5184, 256]`, the prompt's tokens `[32, 256]` (`valid`: its real ones),
|
||||
/// the detector neck's levels `[256, 144, 144]` and `[256, 288, 288]` (channels-first) and the rows `[r, 256]`
|
||||
/// with their bias `[r]` (1 ≤ r ≤ 256).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn run(
|
||||
&self,
|
||||
dev: &'static Dev,
|
||||
memory: &[f32],
|
||||
text: &[f32],
|
||||
valid: &[bool],
|
||||
[level1, level0]: [&[f32]; 2],
|
||||
rows: &[f32],
|
||||
row_bias: &[f32],
|
||||
) -> Result<Vec<f32>, String> {
|
||||
let r = row_bias.len();
|
||||
let (l1, l0) = (WIDTH * (SIDE / 2) * (SIDE / 2), WIDTH * SIDE * SIDE);
|
||||
if memory.len() != GRID * GRID * WIDTH || text.len() != TEXT * WIDTH || valid.len() != TEXT || level1.len() != l1 || level0.len() != l0 {
|
||||
return Err(format!(
|
||||
"{} memory, {} prompt values, {} prompt tokens and levels of {} and {} values, expected {GRID}² × {WIDTH}, {TEXT} × {WIDTH}, {TEXT}, {l1} and {l0}",
|
||||
memory.len(),
|
||||
text.len(),
|
||||
valid.len(),
|
||||
level1.len(),
|
||||
level0.len()
|
||||
));
|
||||
}
|
||||
if r == 0 || r > WIDTH || rows.len() != r * WIDTH {
|
||||
return Err(format!("{} row values and {r} biases, expected r × {WIDTH} and r (1 ≤ r ≤ {WIDTH})", rows.len()));
|
||||
}
|
||||
let b = self.built.get_or_init(|| build(dev, &self.weights)).as_ref().map_err(Clone::clone)?;
|
||||
let bias: Vec<f32> = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect();
|
||||
let mut work = b.work.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if work.recorded.as_ref().is_none_or(|(n, _)| *n != r) {
|
||||
let recorded = scoped(dev, "the SAM 3 mask decoder", || record(dev, &b.weights, &work, r))?;
|
||||
work.recorded = Some((r, recorded));
|
||||
}
|
||||
let q = &dev.queue;
|
||||
q.write_buffer(&work.x, 0, bytemuck::cast_slice(memory));
|
||||
q.write_buffer(&work.text, 0, bytemuck::cast_slice(text));
|
||||
q.write_buffer(&work.text_kv, (TEXT * 2 * WIDTH * 4) as u64, bytemuck::cast_slice(&bias));
|
||||
q.write_buffer(&work.skip1, 0, bytemuck::cast_slice(level1));
|
||||
q.write_buffer(&work.skip0, 0, bytemuck::cast_slice(level0));
|
||||
q.write_buffer(&work.rows, 0, bytemuck::cast_slice(rows));
|
||||
q.write_buffer(&work.row_bias, 0, bytemuck::cast_slice(row_bias));
|
||||
let Some((_, recorded)) = &work.recorded else { return Err("the mask decoder was not recorded".into()) };
|
||||
let out = recorded.run("the SAM 3 mask decoder", dev, &work.skip0, &work.staging, r * SIDE * SIDE)?;
|
||||
if !out.iter().fold(true, |ok, v| ok & v.is_finite()) {
|
||||
return Err("the GPU mask decoder produced non-finite values".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! The mask decoder's kernels against plain loops in f64: the up-sampling with the channels-first level added (odd
|
||||
//! sides, cut-off workgroups), GroupNorm + ReLU (chunks cut off, a large mean, group sizes), and one whole pixel
|
||||
//! decoder stage (up-sampling → 3 × 3 convolution at every border → GroupNorm → ReLU) on small images. The real
|
||||
//! decoder against candle: `tests/it/sam3_mask_decoder.rs`.
|
||||
|
||||
use super::super::neck::tests::{conv_ref, f32s, f64s};
|
||||
use super::super::tests::{gpu, read, values, worst};
|
||||
use super::*;
|
||||
|
||||
fn pixel_kernels(d: &'static Dev) -> &'static Kernels {
|
||||
kernels(d).unwrap()
|
||||
}
|
||||
|
||||
/// Nearest up-sampling of the rows `x` (`[from², c]`) to `to²`, plus the channels-first `skip` (`[c, to, to]`).
|
||||
fn upsample_add_ref(x: &[f64], skip: &[f32], c: usize, (from, to): (usize, usize)) -> Vec<f64> {
|
||||
let mut y = vec![0f64; to * to * c];
|
||||
for r in 0..to {
|
||||
for col in 0..to {
|
||||
// candle's upsample_nearest2d: floor(i · from / to)
|
||||
let (sr, sc) = ((r as f64 * from as f64 / to as f64) as usize, (col as f64 * from as f64 / to as f64) as usize);
|
||||
for ch in 0..c {
|
||||
y[(r * to + col) * c + ch] = x[(sr * from + sc) * c + ch] + skip[ch * to * to + r * to + col] as f64;
|
||||
}
|
||||
}
|
||||
}
|
||||
y
|
||||
}
|
||||
|
||||
/// GroupNorm (centred two-pass variance, as candle's) and ReLU on the rows `x` (`[pixels, c]`).
|
||||
fn group_norm_relu_ref(x: &[f64], c: usize, groups: usize, gamma: &[f32], beta: &[f32], eps: f64) -> Vec<f64> {
|
||||
let pixels = x.len() / c;
|
||||
let per = c / groups;
|
||||
let mut y = x.to_vec();
|
||||
for g in 0..groups {
|
||||
let at = |p: usize, i: usize| x[p * c + g * per + i];
|
||||
let n = (pixels * per) as f64;
|
||||
let mean = (0..pixels).flat_map(|p| (0..per).map(move |i| (p, i))).map(|(p, i)| at(p, i)).sum::<f64>() / n;
|
||||
let var = (0..pixels).flat_map(|p| (0..per).map(move |i| (p, i))).map(|(p, i)| (at(p, i) - mean).powi(2)).sum::<f64>() / n;
|
||||
for p in 0..pixels {
|
||||
for i in 0..per {
|
||||
let ch = g * per + i;
|
||||
let v = (x[p * c + ch] - mean) / (var + eps).sqrt() * gamma[ch] as f64 + beta[ch] as f64;
|
||||
y[p * c + ch] = v.max(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
y
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn up_sampling_adds_the_channels_first_level() {
|
||||
let Some(d) = gpu() else { return };
|
||||
let k = pixel_kernels(d);
|
||||
// the decoder's doublings, an odd one, and channels that leave the last workgroup part empty
|
||||
for (case, (from, to, c)) in [(3usize, 6usize, 4usize), (5, 10, 12), (4, 7, 3), (1, 2, 256)].into_iter().enumerate() {
|
||||
let x = values(from * from * c, 100 + case as u64, 1.0);
|
||||
let skip = values(c * to * to, 110 + case as u64, 1.0);
|
||||
let (bx, bs, by) = (upload(d, "x", &x), upload(d, "skip", &skip), buffer(d, "y", to * to * c));
|
||||
let mut g = Graph::new(d);
|
||||
g.upsample_add(k, [&bx, &bs, &by], c, (from, to)).unwrap();
|
||||
let got = read(d, g, &by, to * to * c);
|
||||
let err = worst(&got, &f32s(&upsample_add_ref(&f64s(&x), &skip, c, (from, to))));
|
||||
assert!(err < 1e-6, "case {case}: off by {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_norm_and_relu_give_the_definition() {
|
||||
let Some(d) = gpu() else { return };
|
||||
let k = pixel_kernels(d);
|
||||
// one chunk cut short; several with the last cut short; the decoder's 256 channels in 8 groups over chunks of
|
||||
// 256 pixels, around a mean far from 0 (where E[x²] − E[x]² in f32 would lose the variance)
|
||||
for (case, (pixels, c, groups, offset)) in
|
||||
[(37usize, 16usize, 4usize, 0f32), (700, 24, 3, 0.0), (1100, 256, 8, 0.0), (600, 256, 8, 50.0), (5, 8, 1, 0.0)].into_iter().enumerate()
|
||||
{
|
||||
let x: Vec<f32> = values(pixels * c, 120 + case as u64, 2.0).iter().map(|v| v + offset).collect();
|
||||
let gamma = values(c, 130 + case as u64, 1.5);
|
||||
let beta = values(c, 140 + case as u64, 0.5);
|
||||
// normed in place, then read back: a buffer that can be copied from
|
||||
let bx = buffer(d, "x", pixels * c);
|
||||
d.queue.write_buffer(&bx, 0, bytemuck::cast_slice(&x));
|
||||
let (bg, bb) = (upload(d, "gamma", &gamma), upload(d, "beta", &beta));
|
||||
let (partials, stats) = (buffer(d, "partials", partials_len(pixels, groups)), buffer(d, "stats", 2 * groups));
|
||||
let mut g = Graph::new(d);
|
||||
g.group_norm_relu(k, [&bx, &bg, &bb], [&partials, &stats], (pixels, c, groups), EPS).unwrap();
|
||||
let got = read(d, g, &bx, pixels * c);
|
||||
let want = f32s(&group_norm_relu_ref(&f64s(&x), c, groups, &gamma, &beta, f64::from(EPS)));
|
||||
let err = worst(&got, &want);
|
||||
assert!(err < 2e-5, "case {case} ({pixels} pixels, {c} channels, {groups} groups): off by {err}");
|
||||
assert!(got.iter().all(|v| *v >= 0.0), "case {case}: ReLU");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_pixel_decoder_stage_gives_the_definition() {
|
||||
let Some(d) = gpu() else { return };
|
||||
let (k, kn) = (pixel_kernels(d), neck::kernels(d).unwrap());
|
||||
// two stages as in the decoder (3² → 6² → 12²), 16 channels in 4 groups
|
||||
let (c, groups) = (16usize, 4usize);
|
||||
let x = values(3 * 3 * c, 150, 1.0);
|
||||
let mut want = f64s(&x);
|
||||
let mut cur = upload(d, "x", &x);
|
||||
let mut g = Graph::new(d);
|
||||
let mut side = 3;
|
||||
for stage in 0..2u64 {
|
||||
let skip = values(c * 4 * side * side, 160 + stage, 1.0);
|
||||
let (w, b) = (values(c * c * 9, 170 + stage, 0.3), values(c, 180 + stage, 0.3));
|
||||
let (gamma, beta) = (values(c, 190 + stage, 1.0), values(c, 200 + stage, 0.3));
|
||||
want = upsample_add_ref(&want, &skip, c, (side, 2 * side));
|
||||
side *= 2;
|
||||
want = conv_ref(&want, side, (c, c, 3), &w, &b);
|
||||
want = group_norm_relu_ref(&want, c, groups, &gamma, &beta, f64::from(EPS));
|
||||
|
||||
let up = buffer(d, "up", side * side * c);
|
||||
let out = buffer(d, "out", side * side * c);
|
||||
let [bw, bb] = conv_weights(d, "conv", &w, &b, (c, c, 3));
|
||||
let (bs, bg, bt) = (upload(d, "skip", &skip), upload(d, "gamma", &gamma), upload(d, "beta", &beta));
|
||||
let (partials, stats) = (buffer(d, "partials", partials_len(side * side, groups)), buffer(d, "stats", 2 * groups));
|
||||
g.upsample_add(k, [&cur, &bs, &up], c, (side / 2, side)).unwrap();
|
||||
g.conv3(kn, [&up, &bw, &bb, &out], side, (c, c)).unwrap();
|
||||
g.group_norm_relu(k, [&out, &bg, &bt], [&partials, &stats], (side * side, c, groups), EPS).unwrap();
|
||||
cur = out;
|
||||
}
|
||||
let got = read(d, g, &cur, side * side * c);
|
||||
let err = worst(&got, &f32s(&want));
|
||||
assert!(err < 1e-4, "off by {err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mask_decoder_kernels_refuse_what_they_cannot_do() {
|
||||
let Some(d) = gpu() else { return };
|
||||
let k = pixel_kernels(d);
|
||||
let b = buffer(d, "b", 16);
|
||||
let mut g = Graph::new(d);
|
||||
assert!(g.upsample_add(k, [&b, &b, &b], 4, (0, 2)).is_err(), "an empty image");
|
||||
assert!(g.upsample_add(k, [&b, &b, &b], 4, (4, 2)).is_err(), "down-sampling");
|
||||
assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (4, 12, 8), EPS).is_err(), "channels not a multiple of the groups");
|
||||
assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (4, 512, 8), EPS).is_err(), "more channels than threads");
|
||||
assert!(g.group_norm_relu(k, [&b, &b, &b], [&b, &b], (0, 8, 8), EPS).is_err(), "no pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_decoder_refuses_inputs_of_the_wrong_size() {
|
||||
let Some(d) = gpu() else { return };
|
||||
// checked before the checkpoint is read: an empty reader is never touched
|
||||
let dir = std::env::temp_dir().join(format!("lc-sam3-pixel-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut st = 2u64.to_le_bytes().to_vec();
|
||||
st.extend_from_slice(b"{}");
|
||||
std::fs::write(dir.join("model.safetensors"), st).unwrap();
|
||||
std::fs::write(dir.join("vocab.json"), "{}").unwrap();
|
||||
std::fs::write(dir.join("merges.txt"), "").unwrap();
|
||||
let m = MaskDecoder::new(WeightReader::open(&dir).unwrap());
|
||||
let (mem, text, valid) = (vec![0f32; GRID * GRID * WIDTH], vec![0f32; TEXT * WIDTH], vec![true; TEXT]);
|
||||
let (l1, l0) = (vec![0f32; WIDTH * 144 * 144], vec![0f32; WIDTH * SIDE * SIDE]);
|
||||
let rows = vec![0f32; 3 * WIDTH];
|
||||
assert!(m.run(d, &mem[1..], &text, &valid, [&l1, &l0], &rows, &[0.0; 3]).is_err_and(|e| e.contains("expected")));
|
||||
assert!(m.run(d, &mem, &text, &valid, [&l0, &l1], &rows, &[0.0; 3]).is_err_and(|e| e.contains("expected")));
|
||||
assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &rows, &[0.0; 2]).is_err_and(|e| e.contains("row values")));
|
||||
assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &[], &[]).is_err_and(|e| e.contains("row values")));
|
||||
// the right sizes reach the checkpoint, which has no decoder
|
||||
assert!(m.run(d, &mem, &text, &valid, [&l1, &l0], &rows, &[0.0; 3]).is_err_and(|e| e.contains("mask_decoder")));
|
||||
assert!(m.bytes().is_none());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -456,3 +456,12 @@ fn an_adapter_short_of_the_limits_is_refused_with_what_it_lacks() {
|
||||
assert_eq!(short.len(), 1, "{short:?}");
|
||||
assert!(short[0].starts_with("max_compute_workgroup_storage_size 8192 <"), "{short:?}");
|
||||
}
|
||||
|
||||
/// DX12 pipeline creation can take minutes for the fully unrolled attention shader; other backends keep the larger tile.
|
||||
#[test]
|
||||
fn attention_tiles_are_smaller_on_dx12() {
|
||||
assert_eq!(attention_keys(wgpu::Backend::Dx12), 8);
|
||||
assert_eq!(attention_keys(wgpu::Backend::Vulkan), ATTENTION_KEYS);
|
||||
let src = attention_source(attention_keys(wgpu::Backend::Dx12));
|
||||
assert!(src.contains("let s7 = ") && !src.contains("let s8 = "));
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
// The small steps of the text detector's pixel decoder (`sam3/pixel.rs`) around its 3 x 3 convolutions: nearest
|
||||
// up-sampling plus the neck level it is added to, and GroupNorm + ReLU (statistics per chunk of pixels, merged per
|
||||
// group, then applied in place).
|
||||
//
|
||||
// Images are pixel rows (`[pixels, channels]`, row-major); the neck levels come channels-first, as uploaded. Same
|
||||
// bindings and parameter block as `sam3_ops.wgsl`; flat dispatches cover `count` items, 256 per workgroup, workgroups
|
||||
// in rows of `row`.
|
||||
|
||||
struct P {
|
||||
a: u32,
|
||||
b: u32,
|
||||
c: u32,
|
||||
d: u32,
|
||||
e: u32,
|
||||
f: u32,
|
||||
count: u32,
|
||||
row: u32,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<uniform> p: P;
|
||||
@group(0) @binding(1) var<storage, read> src: array<f32>;
|
||||
@group(0) @binding(2) var<storage, read> aux: array<f32>;
|
||||
@group(0) @binding(3) var<storage, read> aux2: array<f32>;
|
||||
@group(0) @binding(4) var<storage, read_write> dst: array<f32>;
|
||||
|
||||
fn flat_id(wg: vec3<u32>, lid: u32) -> u32 {
|
||||
return (wg.y * p.row + wg.x) * 256u + lid;
|
||||
}
|
||||
|
||||
// Nearest up-sampling of the rows `src` (a: channels, c: side) to side b, plus the channels-first image `aux`
|
||||
// (`[a, b, b]`): dst[row · b + col, ch] = src[(row · c / b) · c + col · c / b, ch] + aux[ch, row, col]. (candle's
|
||||
// `upsample_nearest2d` takes floor(i · c / b), the same for the decoder's exact doublings.)
|
||||
@compute @workgroup_size(256)
|
||||
fn upsample_add(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) lid: u32) {
|
||||
let g = flat_id(wg, lid);
|
||||
if (g >= p.count) {
|
||||
return;
|
||||
}
|
||||
let ch = g % p.a;
|
||||
let pixel = g / p.a;
|
||||
let row = pixel / p.b;
|
||||
let col = pixel % p.b;
|
||||
let at = row * p.c / p.b * p.c + col * p.c / p.b;
|
||||
dst[g] = src[at * p.a + ch] + aux[ch * p.b * p.b + pixel];
|
||||
}
|
||||
|
||||
var<workgroup> red: array<f32, 256>;
|
||||
|
||||
fn reduce(lid: u32, v: f32) -> f32 {
|
||||
red[lid] = v;
|
||||
workgroupBarrier();
|
||||
for (var s = 128u; s > 0u; s >>= 1u) {
|
||||
if (lid < s) {
|
||||
red[lid] += red[lid + s];
|
||||
}
|
||||
workgroupBarrier();
|
||||
}
|
||||
let total = red[0];
|
||||
workgroupBarrier();
|
||||
return total;
|
||||
}
|
||||
|
||||
// Thread `lid` holds channel lid's `v`: leaves the sum over each group's channels in red[group] (a: channels,
|
||||
// d: groups).
|
||||
fn group_sums(lid: u32, v: f32) {
|
||||
red[lid] = v;
|
||||
workgroupBarrier();
|
||||
let per = p.a / p.d;
|
||||
var s = 0.0;
|
||||
if (lid < p.d) {
|
||||
for (var i = 0u; i < per; i++) {
|
||||
s += red[lid * per + i];
|
||||
}
|
||||
}
|
||||
workgroupBarrier();
|
||||
if (lid < p.d) {
|
||||
red[lid] = s;
|
||||
}
|
||||
workgroupBarrier();
|
||||
}
|
||||
|
||||
// GroupNorm statistics of one chunk of pixels (a: channels ≤ 256, b: pixels, c: pixels per chunk, d: groups), one
|
||||
// workgroup per chunk, thread = channel: each group's mean over the chunk and the sum of squared differences from
|
||||
// it, at dst[(chunk · d + group) · 2 + 0 | 1]. Two passes over the chunk (the second from the cache), so a large mean
|
||||
// costs no precision.
|
||||
@compute @workgroup_size(256)
|
||||
fn group_stats(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) lid: u32) {
|
||||
let chunk = wg.y * p.row + wg.x;
|
||||
let first = chunk * p.c;
|
||||
if (first >= p.b) {
|
||||
return;
|
||||
}
|
||||
let last = min(first + p.c, p.b);
|
||||
let live = lid < p.a;
|
||||
let ch = min(lid, p.a - 1u);
|
||||
let per = p.a / p.d;
|
||||
let n = f32((last - first) * per);
|
||||
var s = 0.0;
|
||||
if (live) {
|
||||
for (var px = first; px < last; px++) {
|
||||
s += src[px * p.a + ch];
|
||||
}
|
||||
}
|
||||
group_sums(lid, s);
|
||||
let mean = red[ch / per] / n;
|
||||
let own = red[min(lid, p.d - 1u)] / n;
|
||||
workgroupBarrier();
|
||||
var q = 0.0;
|
||||
if (live) {
|
||||
for (var px = first; px < last; px++) {
|
||||
let d = src[px * p.a + ch] - mean;
|
||||
q += d * d;
|
||||
}
|
||||
}
|
||||
group_sums(lid, q);
|
||||
if (lid < p.d) {
|
||||
let o = (chunk * p.d + lid) * 2u;
|
||||
dst[o] = own;
|
||||
dst[o + 1u] = red[lid];
|
||||
}
|
||||
}
|
||||
|
||||
// The chunks' statistics merged, one workgroup per group (a: chunks, b: pixels, c: pixels per chunk, d: groups,
|
||||
// e: eps bits, f: channels per group): dst[group · 2 + 0 | 1] = the group's mean and 1 / sqrt(variance + eps), the
|
||||
// variance biased (over all of the group's numbers), as candle's GroupNorm.
|
||||
@compute @workgroup_size(256)
|
||||
fn group_merge(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) lid: u32) {
|
||||
let g = wg.x;
|
||||
let total = f32(p.b * p.f);
|
||||
var s = 0.0;
|
||||
for (var i = lid; i < p.a; i += 256u) {
|
||||
let n = f32(min(p.c, p.b - i * p.c) * p.f);
|
||||
s += n * src[(i * p.d + g) * 2u];
|
||||
}
|
||||
let mean = reduce(lid, s) / total;
|
||||
var q = 0.0;
|
||||
for (var i = lid; i < p.a; i += 256u) {
|
||||
let n = f32(min(p.c, p.b - i * p.c) * p.f);
|
||||
let o = (i * p.d + g) * 2u;
|
||||
let d = src[o] - mean;
|
||||
q += src[o + 1u] + n * d * d;
|
||||
}
|
||||
let variance = reduce(lid, q) / total;
|
||||
if (lid == 0u) {
|
||||
dst[g * 2u] = mean;
|
||||
dst[g * 2u + 1u] = inverseSqrt(variance + bitcast<f32>(p.e));
|
||||
}
|
||||
}
|
||||
|
||||
// GroupNorm and ReLU in place on the rows `dst` (a: channels, d: groups) with the merged statistics `src`, the scale
|
||||
// `aux` and the shift `aux2` (`[a]` each): dst = max((dst − mean) · rstd · aux + aux2, 0).
|
||||
@compute @workgroup_size(256)
|
||||
fn group_norm_relu(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) lid: u32) {
|
||||
let g = flat_id(wg, lid);
|
||||
if (g >= p.count) {
|
||||
return;
|
||||
}
|
||||
let ch = g % p.a;
|
||||
let group = ch / (p.a / p.d);
|
||||
dst[g] = max((dst[g] - src[group * 2u]) * src[group * 2u + 1u] * aux[ch] + aux2[ch], 0.0);
|
||||
}
|
||||
@@ -13,5 +13,7 @@ mod sam3_backbone;
|
||||
#[cfg(feature = "sam")]
|
||||
mod sam3_detr;
|
||||
#[cfg(feature = "sam")]
|
||||
mod sam3_mask_decoder;
|
||||
#[cfg(feature = "sam")]
|
||||
mod sam3_necks;
|
||||
mod thumbs_bench;
|
||||
@@ -0,0 +1,287 @@
|
||||
//! The text detector's mask decoder on the GPU against the candle decoder (the reference), on one photo: the per-query
|
||||
//! mask logits of all 200 queries, and the merged Describe mask, for a few prompts. Both models get the same backbone
|
||||
//! output, necks and DETR encoder memory (one GPU accelerator, shared), so only the mask decoder differs. For the first
|
||||
//! prompt, the instance features also against the decoder transcribed with candle's tensor ops in f64 (and in f32, to
|
||||
//! show how far candle's own f32 decoder is from it).
|
||||
//!
|
||||
//! Needs the checkpoint: `LIGHTCRAFT_SAM3_DIR=<model dir> cargo test --release -p lightcraft-gpu --features sam
|
||||
//! --test it sam3_mask_decoder:: -- --nocapture`. The photo is a procedural one, or the input of a reference file made by
|
||||
//! `tools/sam3_reference.py` (`LIGHTCRAFT_SAM3_REF=<ref.safetensors>`). `LIGHTCRAFT_SAM3_PROMPTS` lists the prompts,
|
||||
//! comma-separated (default "person,sky,the red car"). Skipped without a model or a GPU.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use candle_core::{Device, Tensor};
|
||||
use lightcraft_gpu::sam3::{self, Precision, Sam3Gpu};
|
||||
use lightcraft_segment::{BackboneAccel, DetectorOutput, INPUT, NeckKind, Sam3, WeightReader};
|
||||
|
||||
fn values(t: &Tensor) -> Vec<f32> {
|
||||
t.to_device(&Device::Cpu).unwrap().flatten_all().unwrap().to_vec1::<f32>().unwrap()
|
||||
}
|
||||
|
||||
/// Max |a − b|, that relative to max |b|, and mean |a − b|.
|
||||
fn errors(name: &str, a: &[f32], b: &[f32]) -> (f32, f32, f64) {
|
||||
assert_eq!(a.len(), b.len(), "{name}: length");
|
||||
let scale = b.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6);
|
||||
let max = a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs()));
|
||||
let mean = a.iter().zip(b).map(|(x, y)| f64::from((x - y).abs())).sum::<f64>() / a.len().max(1) as f64;
|
||||
eprintln!(" {name}: max abs {max:.3e}, max rel {:.3e} (scale {scale:.2}), mean abs {mean:.3e}", max / scale);
|
||||
(max, max / scale, mean)
|
||||
}
|
||||
|
||||
/// Intersection over union of two masks (logits > 0).
|
||||
fn iou(a: &[f32], b: &[f32]) -> f32 {
|
||||
// masks of different sizes are no match (`zip` would compare only the shorter's pixels)
|
||||
assert_eq!(a.len(), b.len(), "mask sizes");
|
||||
let (mut both, mut either) = (0usize, 0usize);
|
||||
for (x, y) in a.iter().zip(b) {
|
||||
let (x, y) = (*x > 0.0, *y > 0.0);
|
||||
both += usize::from(x && y);
|
||||
either += usize::from(x || y);
|
||||
}
|
||||
if either == 0 { 1.0 } else { both as f32 / either as f32 }
|
||||
}
|
||||
|
||||
fn sigmoid(x: f32) -> f32 {
|
||||
1.0 / (1.0 + (-x).exp())
|
||||
}
|
||||
|
||||
/// The Describe mask of `out` as `Sam3::segment_text` merges it at 0.5 (the per-pixel maximum over the instances
|
||||
/// scoring above it), the instances, and the best-scoring query.
|
||||
fn merged(out: &DetectorOutput, masks: &[f32]) -> (Vec<f32>, Vec<usize>, usize) {
|
||||
let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE;
|
||||
let mut merged = vec![f32::MIN; side];
|
||||
let keep: Vec<usize> = (0..out.logits.len()).filter(|&i| sigmoid(out.logits[i]) * sigmoid(out.presence) > 0.5).collect();
|
||||
for i in &keep {
|
||||
for (m, v) in merged.iter_mut().zip(&masks[i * side..(i + 1) * side]) {
|
||||
*m = m.max(*v);
|
||||
}
|
||||
}
|
||||
let best = (0..out.logits.len()).max_by(|a, b| out.logits[*a].total_cmp(&out.logits[*b])).unwrap();
|
||||
(merged, keep, best)
|
||||
}
|
||||
|
||||
/// The photo as preprocessed pixels `[1, 3, 1008, 1008]`.
|
||||
fn photo() -> Tensor {
|
||||
if let Some(path) = std::env::var_os("LIGHTCRAFT_SAM3_REF").map(PathBuf::from) {
|
||||
let mut r = candle_core::safetensors::load(&path, &Device::Cpu).unwrap();
|
||||
return r.remove("pixel_values").unwrap();
|
||||
}
|
||||
let img = lightcraft_scenes::demo_library()[0].render_fit(1600).to_srgb8();
|
||||
let rgb: Vec<u8> = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect();
|
||||
let px = lightcraft_segment::mask::preprocess(&rgb, img.width, img.height, INPUT).unwrap();
|
||||
Tensor::from_vec(px, (1, 3, INPUT, INPUT), &Device::Cpu).unwrap()
|
||||
}
|
||||
|
||||
/// The mask decoder transcribed with candle's tensor ops in `dtype` (f64: the arbiter between the two f32 decoders):
|
||||
/// the instance features `[256, 288 · 288]` for the encoder memory `[5184, 256]`, the prompt `[32, 256]` (`valid`: its
|
||||
/// real tokens) and the neck levels `[256, 144, 144]`, `[256, 288, 288]`.
|
||||
fn decoder_ref(w: &WeightReader, memory: &Tensor, (text, valid): (&Tensor, &[bool]), [l1, l0]: [&Tensor; 2], dtype: candle_core::DType) -> Tensor {
|
||||
let get = |name: &str| {
|
||||
let (shape, data) = w.read(&format!("detector_model.mask_decoder.{name}")).unwrap();
|
||||
Tensor::from_vec(data, shape, &Device::Cpu).unwrap().to_dtype(dtype).unwrap()
|
||||
};
|
||||
let lin = |x: &Tensor, name: &str| {
|
||||
x.matmul(&get(&format!("{name}.weight")).t().unwrap()).unwrap().broadcast_add(&get(&format!("{name}.bias"))).unwrap()
|
||||
};
|
||||
let (memory, text) = (memory.to_dtype(dtype).unwrap(), text.to_dtype(dtype).unwrap());
|
||||
// prompt attention: LN (eps 1e-5) → 8 heads of 32 over the prompt (padding masked) → output projection, added
|
||||
let mean = memory.mean_keepdim(1).unwrap();
|
||||
let centred = memory.broadcast_sub(&mean).unwrap();
|
||||
let var = centred.sqr().unwrap().mean_keepdim(1).unwrap();
|
||||
let h = centred.broadcast_div(&(var + 1e-5).unwrap().sqrt().unwrap()).unwrap();
|
||||
let h = h.broadcast_mul(&get("prompt_cross_attn_norm.weight")).unwrap().broadcast_add(&get("prompt_cross_attn_norm.bias")).unwrap();
|
||||
let heads = |x: Tensor| x.reshape((x.dim(0).unwrap(), 8, 32)).unwrap().transpose(0, 1).unwrap().contiguous().unwrap();
|
||||
let q = heads(lin(&h, "prompt_cross_attn.q_proj"));
|
||||
let k = heads(lin(&text, "prompt_cross_attn.k_proj"));
|
||||
let v = heads(lin(&text, "prompt_cross_attn.v_proj"));
|
||||
let bias: Vec<f32> = valid.iter().map(|&ok| if ok { 0.0 } else { f32::MIN }).collect();
|
||||
let bias = Tensor::from_vec(bias, (1, 1, 32), &Device::Cpu).unwrap().to_dtype(dtype).unwrap();
|
||||
let s = (q.matmul(&k.t().unwrap()).unwrap() * (32f64).powf(-0.5)).unwrap().broadcast_add(&bias).unwrap();
|
||||
let e = s.broadcast_sub(&s.max_keepdim(2).unwrap()).unwrap().exp().unwrap();
|
||||
let p = e.broadcast_div(&e.sum_keepdim(2).unwrap()).unwrap();
|
||||
let o = p.matmul(&v).unwrap().transpose(0, 1).unwrap().reshape((5184, 256)).unwrap();
|
||||
let mem = (memory + lin(&o, "prompt_cross_attn.o_proj")).unwrap();
|
||||
// the pixel decoder
|
||||
let mut prev = mem.t().unwrap().reshape((1, 256, 72, 72)).unwrap();
|
||||
for (i, skip) in [l1, l0].into_iter().enumerate() {
|
||||
let side = skip.dim(1).unwrap();
|
||||
prev = (prev.upsample_nearest2d(side, side).unwrap() + skip.to_dtype(dtype).unwrap().unsqueeze(0).unwrap()).unwrap();
|
||||
let c = format!("pixel_decoder.conv_layers.{i}");
|
||||
prev = prev
|
||||
.conv2d(&get(&format!("{c}.weight")), 1, 1, 1, 1)
|
||||
.unwrap()
|
||||
.broadcast_add(&get(&format!("{c}.bias")).reshape((1, 256, 1, 1)).unwrap())
|
||||
.unwrap();
|
||||
let g = prev.reshape((8, 32 * side * side)).unwrap();
|
||||
let centred = g.broadcast_sub(&g.mean_keepdim(1).unwrap()).unwrap();
|
||||
let var = centred.sqr().unwrap().mean_keepdim(1).unwrap();
|
||||
let normed = centred.broadcast_div(&(var + 1e-5).unwrap().sqrt().unwrap()).unwrap().reshape((1, 256, side, side)).unwrap();
|
||||
let n = format!("pixel_decoder.norms.{i}");
|
||||
let (gamma, beta) =
|
||||
(get(&format!("{n}.weight")).reshape((1, 256, 1, 1)).unwrap(), get(&format!("{n}.bias")).reshape((1, 256, 1, 1)).unwrap());
|
||||
prev = normed.broadcast_mul(&gamma).unwrap().broadcast_add(&beta).unwrap().relu().unwrap();
|
||||
}
|
||||
let inst = prev.conv2d(&get("instance_projection.weight"), 0, 1, 1, 1).unwrap();
|
||||
inst.broadcast_add(&get("instance_projection.bias").reshape((1, 256, 1, 1)).unwrap()).unwrap().reshape((256, 288 * 288)).unwrap()
|
||||
}
|
||||
|
||||
/// One GPU accelerator for both models; the mask decoder only for one of them, the other gets a result of the wrong
|
||||
/// size (and then runs the candle decoder; `asked` counts the calls).
|
||||
struct Shared {
|
||||
gpu: Arc<Sam3Gpu>,
|
||||
masks: bool,
|
||||
asked: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl BackboneAccel for Shared {
|
||||
fn forward(&self, pixels: &[f32]) -> Result<Vec<f32>, String> {
|
||||
self.gpu.forward(pixels)
|
||||
}
|
||||
|
||||
fn device(&self) -> String {
|
||||
self.gpu.device()
|
||||
}
|
||||
|
||||
fn runs_necks(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn runs_detr_encoder(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn runs_mask_decoder(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn neck(&self, which: NeckKind, backbone: &[f32], n: usize) -> Result<Vec<Vec<f32>>, String> {
|
||||
self.gpu.neck(which, backbone, n)
|
||||
}
|
||||
|
||||
fn detr_encoder(&self, image: &[f32], pos: &[f32], text: &[f32], valid: &[bool]) -> Result<Vec<f32>, String> {
|
||||
self.gpu.detr_encoder(image, pos, text, valid)
|
||||
}
|
||||
|
||||
fn mask_decoder(
|
||||
&self,
|
||||
memory: &[f32],
|
||||
text: &[f32],
|
||||
valid: &[bool],
|
||||
levels: [&[f32]; 2],
|
||||
rows: &[f32],
|
||||
bias: &[f32],
|
||||
) -> Result<Vec<f32>, String> {
|
||||
self.asked.fetch_add(1, Ordering::Relaxed);
|
||||
if self.masks { self.gpu.mask_decoder(memory, text, valid, levels, rows, bias) } else { Ok(vec![0.0; 10]) }
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gpu_mask_decoder_matches_the_candle_decoder() {
|
||||
let Some(dir) = std::env::var_os("LIGHTCRAFT_SAM3_DIR").map(PathBuf::from).filter(|d| lightcraft_segment::is_model_dir(d)) else {
|
||||
lightcraft_testkit::skip!(Model, "set LIGHTCRAFT_SAM3_DIR to the SAM 3 model directory");
|
||||
return;
|
||||
};
|
||||
let adapter = match sam3::adapter() {
|
||||
Ok(a) => a,
|
||||
// a kernel that doesn't compile is a failure, not a missing GPU
|
||||
Err(e) if e.contains("did not compile") => panic!("{e}"),
|
||||
Err(e) => {
|
||||
lightcraft_testkit::skip!(Gpu, "no GPU for the SAM 3 kernels ({e})");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let gpu = Arc::new(sam3::load(&WeightReader::open(&dir).unwrap(), Precision::F32).unwrap());
|
||||
let (asked_cpu, asked_gpu) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
|
||||
let with = |masks: bool, asked: &Arc<AtomicUsize>| {
|
||||
let (gpu, asked) = (gpu.clone(), asked.clone());
|
||||
move |_: &WeightReader| -> Result<Box<dyn BackboneAccel>, String> { Ok(Box::new(Shared { gpu, masks, asked })) }
|
||||
};
|
||||
let mut cpu = Sam3::load_accelerated(&dir, Device::Cpu, with(false, &asked_cpu)).unwrap();
|
||||
let mut acc = Sam3::load_accelerated(&dir, Device::Cpu, with(true, &asked_gpu)).unwrap();
|
||||
let pixels = photo();
|
||||
let mut enc_cpu = cpu.encode_pixels(&pixels).unwrap();
|
||||
let mut enc_acc = acc.encode_pixels(&pixels).unwrap();
|
||||
|
||||
let prompts = std::env::var("LIGHTCRAFT_SAM3_PROMPTS").unwrap_or_else(|_| "person,sky,the red car".into());
|
||||
let prompts: Vec<&str> = prompts.split(',').map(str::trim).filter(|p| !p.is_empty()).collect();
|
||||
for (n, prompt) in prompts.iter().copied().enumerate() {
|
||||
let t = Instant::now();
|
||||
let want = cpu.detect(&mut enc_cpu, prompt).unwrap();
|
||||
let cpu_time = t.elapsed();
|
||||
let t = Instant::now();
|
||||
let got = acc.detect(&mut enc_acc, prompt).unwrap();
|
||||
let gpu_time = t.elapsed();
|
||||
let first = if n == 0 { " (first prompt: with the detector neck and loading)" } else { "" };
|
||||
eprintln!("{prompt:?}: detector with the candle mask decoder {cpu_time:?}, with the GPU one {gpu_time:?}{first}");
|
||||
assert_eq!(acc.mask_fallback(), None, "the GPU mask decoder ran");
|
||||
assert!(cpu.mask_fallback().is_some_and(|w| w.contains("returned 10 values")));
|
||||
assert_eq!(acc.heads_device(), "CPU; the necks, the DETR encoder and the mask decoder on the GPU");
|
||||
assert_eq!(cpu.heads_device(), "CPU; the necks and the DETR encoder on the GPU");
|
||||
|
||||
if n == 0 {
|
||||
// the instance features (the instance projection as the rows) against the f64 transcription, and how far
|
||||
// the same transcription in f32 is from it
|
||||
let reader = WeightReader::open(&dir).unwrap();
|
||||
let (_, valid) = lightcraft_segment::tokenizer::Tokenizer::load(&dir).unwrap().encode(prompt);
|
||||
let levels = acc.neck_levels(NeckKind::Detector, &enc_acc).unwrap();
|
||||
let (l1, l0) = (levels[1].squeeze(0).unwrap(), levels[0].squeeze(0).unwrap());
|
||||
let (memory, text) = (got.memory.squeeze(0).unwrap(), got.text.squeeze(0).unwrap());
|
||||
let (_, rows) = reader.read("detector_model.mask_decoder.instance_projection.weight").unwrap();
|
||||
let (_, bias) = reader.read("detector_model.mask_decoder.instance_projection.bias").unwrap();
|
||||
let t = Instant::now();
|
||||
let ours = gpu.mask_decoder(&values(&memory), &values(&text), &valid, [&values(&l1), &values(&l0)], &rows, &bias).unwrap();
|
||||
eprintln!(" GPU instance features {:?}", t.elapsed());
|
||||
let t = Instant::now();
|
||||
let f64_ref: Vec<f32> = values(
|
||||
&decoder_ref(&reader, &memory, (&text, &valid), [&l1, &l0], candle_core::DType::F64).to_dtype(candle_core::DType::F32).unwrap(),
|
||||
);
|
||||
let f32_ref = values(&decoder_ref(&reader, &memory, (&text, &valid), [&l1, &l0], candle_core::DType::F32));
|
||||
eprintln!(" references {:?}", t.elapsed());
|
||||
let (_, rel, mean) = errors("instance features, GPU vs f64", &ours, &f64_ref);
|
||||
errors("instance features, candle f32 vs f64", &f32_ref, &f64_ref);
|
||||
assert!(rel < 1e-4 && mean < 1e-5, "the GPU instance features are off");
|
||||
}
|
||||
|
||||
// the same memory and decoder for both: only the masks may differ, by candle's own error (its f32 decoder is
|
||||
// ~400 × further from the f64 one than the GPU's, above)
|
||||
let (_, logits, _) = errors("query logits", &got.logits, &want.logits);
|
||||
assert!(logits < 1e-4, "the query logits moved");
|
||||
let (mg, mc) = (values(&got.masks), values(&want.masks));
|
||||
let (_, rel, mean) = errors("mask logits (200 queries), GPU vs candle", &mg, &mc);
|
||||
assert!(rel < 1e-2 && mean < 0.1, "the GPU mask logits are off");
|
||||
let ((mask_g, kept_g, best_g), (mask_c, kept_c, best_c)) = (merged(&got, &mg), merged(&want, &mc));
|
||||
let side = lightcraft_segment::MASK_SIDE * lightcraft_segment::MASK_SIDE;
|
||||
let best = iou(&mg[best_g * side..(best_g + 1) * side], &mc[best_c * side..(best_c + 1) * side]);
|
||||
let i = iou(&mask_g, &mask_c);
|
||||
eprintln!(" instances {} vs {}, Describe mask IoU {i:.5}, best query's mask IoU {best:.5}", kept_g.len(), kept_c.len());
|
||||
assert_eq!(kept_g, kept_c, "the same instances");
|
||||
assert!(i > 0.99 && best > 0.99, "describe mask IoU {i}, best query {best}");
|
||||
// the semantic mask (one more row of the GPU's mask product)
|
||||
let (_, rel, mean) = errors("semantic mask logits, GPU vs candle", &got.semantic, &want.semantic);
|
||||
let semantic = iou(&got.semantic, &want.semantic);
|
||||
eprintln!(" semantic mask IoU {semantic:.5}");
|
||||
assert!(rel < 1e-2 && mean < 0.1 && semantic > 0.99, "the GPU semantic mask is off");
|
||||
}
|
||||
// an accelerator whose decoder failed once isn't asked again
|
||||
assert_eq!(asked_cpu.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(asked_gpu.load(Ordering::Relaxed), prompts.len());
|
||||
|
||||
// the decoder alone (with the uploads and the read-back)
|
||||
let (memory, text) = (vec![0.1f32; 5184 * 256], vec![0.3f32; 32 * 256]);
|
||||
let valid: Vec<bool> = (0..32).map(|i| i < 4).collect();
|
||||
let (l1, l0) = (vec![0.2f32; 256 * 144 * 144], vec![0.4f32; 256 * 288 * 288]);
|
||||
let (rows, bias) = (vec![0.01f32; 200 * 256], vec![0.5f32; 200]);
|
||||
let mut best = f64::MAX;
|
||||
for _ in 0..5 {
|
||||
let t = Instant::now();
|
||||
gpu.mask_decoder(&memory, &text, &valid, [&l1, &l0], &rows, &bias).unwrap();
|
||||
best = best.min(t.elapsed().as_secs_f64());
|
||||
}
|
||||
let (w, b) = gpu.mask_decoder_bytes().unwrap();
|
||||
eprintln!("GPU mask decoder alone: {:.1} ms on {adapter}; {:.0} MB weights, {:.0} MB work buffers", best * 1e3, w as f64 / 1e6, b as f64 / 1e6);
|
||||
}
|
||||
@@ -68,6 +68,7 @@ mod write_tests {
|
||||
focal_length: Some(35.0),
|
||||
lens_model: Some("35mm F2".into()),
|
||||
gps: Some(Gps { latitude: 43.7904, longitude: -110.6818, altitude: Some(2000.0) }),
|
||||
rating: Some(4),
|
||||
..Default::default()
|
||||
};
|
||||
let back = read_exif(&write_exif(&m));
|
||||
@@ -80,8 +81,12 @@ mod write_tests {
|
||||
assert!((back.f_number.unwrap() - 2.8).abs() < 1e-6);
|
||||
assert!((back.exposure_time.unwrap() - 0.004).abs() < 1e-9);
|
||||
assert_eq!(back.lens_model, m.lens_model);
|
||||
assert_eq!(back.rating, Some(4));
|
||||
let g = back.gps.unwrap();
|
||||
assert!((g.latitude - 43.7904).abs() < 1e-5 && (g.longitude + 110.6818).abs() < 1e-5, "{g:?}");
|
||||
|
||||
let rejected = read_exif(&write_exif(&Metadata { rating: Some(-1), ..Default::default() }));
|
||||
assert_eq!(rejected.rating, Some(-1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -37,6 +37,9 @@ pub struct Frame {
|
||||
/// `lightcraft_develop::Mask::on_photo`); otherwise they are normalized coordinates of this
|
||||
/// frame's transformed image, like spots and the crop.
|
||||
pub masks_on_photo: bool,
|
||||
/// Filter of the area downscale ahead of the bilinear resample ([`Frame::sample`]); see
|
||||
/// [`crate::Downscale`].
|
||||
pub downscale: Filter,
|
||||
}
|
||||
|
||||
/// Where a windowed [`Frame`]'s pixels sit in the full output: its offset and the full output's
|
||||
@@ -82,6 +85,7 @@ impl Frame {
|
||||
warp: (!warp.is_identity()).then_some(warp),
|
||||
view: None,
|
||||
masks_on_photo: false,
|
||||
downscale: Filter::Mitchell,
|
||||
};
|
||||
if apply_crop {
|
||||
f.constrain_to_image(s.geometry.constrain_crop);
|
||||
@@ -312,8 +316,12 @@ impl Frame {
|
||||
pub fn sample_plan(&self, src_w: usize, src_h: usize, w: usize, h: usize) -> SamplePlan {
|
||||
let (ow, oh) = if self.orient.swaps_axes() { (src_h, src_w) } else { (src_w, src_h) };
|
||||
let crop_px = self.crop.rect_px(self.ow, self.oh);
|
||||
let k = crop_px.width() / w as f64;
|
||||
let prefilter = (k > 1.25).then(|| (((ow as f64 / k).round() as usize).max(1), ((oh as f64 / k).round() as usize).max(1)));
|
||||
// the larger of the two axes' reductions: the prefilter then takes every axis at least as small
|
||||
// as its output needs, so the bilinear pass after it never minifies (and aliases) either one
|
||||
let k = (crop_px.width() / w as f64).max(crop_px.height() / h as f64);
|
||||
// Sharp exports use their selected filter for every downscale; keep smooth previews' threshold.
|
||||
let threshold = if self.downscale == Filter::Lanczos3 { 1.0 } else { 1.25 };
|
||||
let prefilter = (k > threshold).then(|| (((ow as f64 / k).round() as usize).max(1), ((oh as f64 / k).round() as usize).max(1)));
|
||||
let (bw, bh) = prefilter.unwrap_or((ow, oh));
|
||||
let (sx, sy) = (bw as f64 / ow as f64, bh as f64 / oh as f64);
|
||||
let mode = if self.warp.is_some() {
|
||||
@@ -333,7 +341,7 @@ impl Frame {
|
||||
let o = oriented.as_ref().unwrap_or(src);
|
||||
let plan = self.sample_plan(src.width, src.height, w, h);
|
||||
let base = match plan.prefilter {
|
||||
Some((nw, nh)) => std::borrow::Cow::Owned(resize(o, nw, nh, Filter::Mitchell)),
|
||||
Some((nw, nh)) => std::borrow::Cow::Owned(resize(o, nw, nh, self.downscale)),
|
||||
None => std::borrow::Cow::Borrowed(o),
|
||||
};
|
||||
self.sample_base(base, plan, w, h)
|
||||
@@ -355,7 +363,7 @@ impl Frame {
|
||||
let mut bases: Vec<((usize, usize), Rgb32f)> = Vec::new();
|
||||
for dims in plans.iter().filter_map(|p| p.1.prefilter) {
|
||||
if !bases.iter().any(|b| b.0 == dims) {
|
||||
bases.push((dims, resize(o, dims.0, dims.1, Filter::Mitchell)));
|
||||
bases.push((dims, resize(o, dims.0, dims.1, self.downscale)));
|
||||
}
|
||||
}
|
||||
plans
|
||||
@@ -443,7 +451,7 @@ pub struct SamplePlan {
|
||||
/// Oriented source size.
|
||||
pub ow: usize,
|
||||
pub oh: usize,
|
||||
/// Size of the Mitchell prefilter (area downscale before the bilinear resample), if any.
|
||||
/// Size of the prefilter ([`Frame::downscale`]: area downscale before the bilinear resample), if any.
|
||||
pub prefilter: Option<(usize, usize)>,
|
||||
/// Oriented-source px → prefiltered px.
|
||||
pub sx: f64,
|
||||
@@ -529,6 +537,24 @@ mod tests {
|
||||
assert!((f.px_per_long(300) - 300.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sharp_downscale_filters_mild_reductions_and_native_size_stays_identical() {
|
||||
let src = Rgb32f::from_fn(100, 100, |x, y| [((x + y) % 2) as f32; 3]);
|
||||
for filter in [Filter::Mitchell, Filter::Lanczos3] {
|
||||
let mut f = Frame::new(100, 100, &DevelopSettings::default(), true);
|
||||
f.downscale = filter;
|
||||
let edge = if filter == Filter::Lanczos3 { 90 } else { 70 };
|
||||
assert_eq!(f.sample_plan(100, 100, edge, edge).prefilter, Some((edge, edge)));
|
||||
assert_eq!(f.sample(&src, edge, edge).data, resize(&src, edge, edge, filter).data);
|
||||
if filter == Filter::Mitchell {
|
||||
assert_eq!(f.sample_plan(100, 100, 90, 90).prefilter, None);
|
||||
}
|
||||
assert_eq!(f.sample_plan(100, 100, 100, 100).prefilter, None);
|
||||
assert_eq!(f.sample(&src, 100, 100).data, src.data);
|
||||
assert_eq!(f.sample_plan(100, 100, 110, 110).prefilter, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_swaps_aspect() {
|
||||
let s = DevelopSettings { orientation: Orientation::Rotate90, ..Default::default() };
|
||||
|
||||
@@ -129,6 +129,26 @@ impl Default for SourceInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a render shrinks its source to the output size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Downscale {
|
||||
/// Mitchell–Netravali: soft, no visible ringing. Previews and thumbnails.
|
||||
#[default]
|
||||
Smooth,
|
||||
/// Lanczos-3: keeps the detail a smaller output can hold, as a dedicated downscale does
|
||||
/// (exports, #2970). Its slight overshoot at hard edges stays below the output sharpening's.
|
||||
Sharp,
|
||||
}
|
||||
|
||||
impl Downscale {
|
||||
pub fn filter(self) -> lightcraft_raster::resample::Filter {
|
||||
match self {
|
||||
Downscale::Smooth => lightcraft_raster::resample::Filter::Mitchell,
|
||||
Downscale::Sharp => lightcraft_raster::resample::Filter::Lanczos3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Quality {
|
||||
/// Interactive drags: skips the most expensive refinements.
|
||||
@@ -162,6 +182,8 @@ pub struct RenderRequest {
|
||||
/// Previews for a monitor with a display profile: render 8-bit into its primaries instead of
|
||||
/// `space` (see [`DisplaySpace`]; ignored by deep renders).
|
||||
pub display: Option<DisplaySpace>,
|
||||
/// Filter of the downscale to the output size.
|
||||
pub downscale: Downscale,
|
||||
}
|
||||
|
||||
/// A window of the (virtual) full output, in its pixels: what a zoomed view needs, rendered
|
||||
@@ -236,6 +258,7 @@ impl RenderRequest {
|
||||
proof: None,
|
||||
window: None,
|
||||
display: None,
|
||||
downscale: Downscale::Smooth,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -491,7 +514,8 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
|
||||
}
|
||||
}
|
||||
let s = &*settings;
|
||||
let frame = frame_for(src, info, s, req.apply_crop);
|
||||
let mut frame = frame_for(src, info, s, req.apply_crop);
|
||||
frame.downscale = req.downscale.filter();
|
||||
let (full_w, full_h) = req.size(&frame);
|
||||
// sizes and scale are those of the whole output; a window only narrows what is drawn
|
||||
let px_per_long = frame.px_per_long(full_w);
|
||||
|
||||
@@ -107,6 +107,27 @@ fn dehaze_does_not_crush_dark_regions_next_to_bright_ones() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An export's sharp downscale (#2970) keeps more of the fine detail a smaller output can hold
|
||||
/// than a preview's smooth one, and changes nothing when the output is the source's own size.
|
||||
#[test]
|
||||
fn sharp_downscale_keeps_detail() {
|
||||
use crate::Downscale;
|
||||
// fine stripes: a period of 5 source pixels, 3 output pixels at 600 → 360
|
||||
let src = Rgb32f::from_fn(600, 400, |x, _| [0.18 * (1.0 + 0.8 * (x as f32 * std::f32::consts::TAU / 5.0).sin()); 3]);
|
||||
let swing = |down: Downscale, edge: usize| {
|
||||
let r =
|
||||
render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest { downscale: down, ..RenderRequest::fit(edge, edge) });
|
||||
let row: Vec<f32> = (40..r.image.width - 40).map(|x| r.image.data[(r.image.height / 2) * r.image.width + x][1] as f32).collect();
|
||||
let m = row.iter().sum::<f32>() / row.len() as f32;
|
||||
(row.iter().map(|v| (v - m).abs()).sum::<f32>() / row.len() as f32, r.image)
|
||||
};
|
||||
let ((smooth, _), (sharp, _)) = (swing(Downscale::Smooth, 360), swing(Downscale::Sharp, 360));
|
||||
assert!(sharp > smooth * 1.25, "sharp {sharp} vs smooth {smooth}");
|
||||
let ((_, a), (_, b)) = (swing(Downscale::Smooth, 600), swing(Downscale::Sharp, 600));
|
||||
assert_eq!((b.width, b.height), (600, 400));
|
||||
assert_eq!(a.data, b.data, "no resize, no difference");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_independence_of_local_contrast() {
|
||||
// Clarity at two preview sizes should give similar results after downscaling.
|
||||
|
||||
@@ -1,3 +1,30 @@
|
||||
//! The global tone map: scene luminance → display-linear luminance, backed by `craft_develop::tone`.
|
||||
|
||||
pub use craft_develop::tone::{CHROMA_N, CameraTone, GENERIC_KNEE_STOPS, GREY, LUT_MAX_EV, LUT_MIN_EV, LUT_N, ROLLOFF_STOPS, ToneMap};
|
||||
|
||||
/// The default raw tone curve ([`ToneMap::new`] at neutral settings) as camera-curve knots, about 1/3 EV apart
|
||||
/// from 8 EV below grey to just under display white: for a camera look that knows a photo's colour but not its tone.
|
||||
pub fn default_raw_camera_tone() -> Option<CameraTone> {
|
||||
const FROM_EV: f32 = -8.0;
|
||||
const TO_EV: f32 = 2.6;
|
||||
let map = ToneMap::new(0.0, 0.0, 0.0);
|
||||
CameraTone::new(std::array::from_fn(|i| {
|
||||
let x = GREY * 2f32.powf(FROM_EV + (TO_EV - FROM_EV) * i as f32 / 31.0);
|
||||
[x, map.apply(x)]
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn default_raw_camera_tone_follows_the_default_tone_curve() {
|
||||
let (camera, default) = (default_raw_camera_tone().unwrap(), ToneMap::new(0.0, 0.0, 0.0));
|
||||
for ev in [-8.0f32, -6.0, -4.0, -2.0, -1.0, 0.0, 1.0, 2.0, 2.5] {
|
||||
let y = GREY * 2f32.powf(ev);
|
||||
let (a, b) = (camera.apply(y), default.apply(y));
|
||||
assert!((a - b).abs() <= 0.01 * b.max(0.01), "{ev} EV: {a} vs {b}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! A pure above-Nyquist carrier must be suppressed rather than folded into a smaller export.
|
||||
use lightcraft_develop::DevelopSettings;
|
||||
use lightcraft_pipeline::geometry::Frame;
|
||||
use lightcraft_raster::{Rgb32f, resample::Filter};
|
||||
|
||||
#[test]
|
||||
fn mild_sharp_reductions_suppress_above_target_nyquist_aliases() {
|
||||
// 0.49 cycles/source pixel is above the 90% and 80% outputs' Nyquist limits.
|
||||
let source = Rgb32f::from_fn(1000, 100, |x, _| [0.5 + 0.25 * (std::f32::consts::TAU * 0.49 * x as f32).sin(); 3]);
|
||||
let power = |image: &Rgb32f| {
|
||||
let values: Vec<f64> = (12..image.width - 12).map(|x| f64::from(image.get(x, image.height / 2)[0])).collect();
|
||||
let mean = values.iter().sum::<f64>() / values.len() as f64;
|
||||
values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / values.len() as f64
|
||||
};
|
||||
let mut frame = Frame::new(1000, 100, &DevelopSettings::default(), true);
|
||||
frame.downscale = Filter::Lanczos3;
|
||||
for (w, h) in [(900, 90), (800, 80)] {
|
||||
let k = 1000.0 / w as f64;
|
||||
let unfiltered = Rgb32f::from_fn(w, h, |x, y| source.sample_bilinear(((x as f64 + 0.5) * k) as f32, ((y as f64 + 0.5) * k) as f32));
|
||||
let (sharp, bilinear) = (power(&frame.sample(&source, w, h)), power(&unfiltered));
|
||||
assert!(sharp < bilinear * 0.95, "{w}: residual alias power {sharp} vs unfiltered {bilinear}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_height_only_reduction_is_prefiltered_too() {
|
||||
// the width stays 1:1, the height shrinks 1000 → 900: the vertical carrier must not fold in
|
||||
let source = Rgb32f::from_fn(100, 1000, |_, y| [0.5 + 0.25 * (std::f32::consts::TAU * 0.49 * y as f32).sin(); 3]);
|
||||
let power = |image: &Rgb32f| {
|
||||
let values: Vec<f64> = (12..image.height - 12).map(|y| f64::from(image.get(image.width / 2, y)[0])).collect();
|
||||
let mean = values.iter().sum::<f64>() / values.len() as f64;
|
||||
values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / values.len() as f64
|
||||
};
|
||||
let mut frame = Frame::new(100, 1000, &DevelopSettings::default(), true);
|
||||
frame.downscale = Filter::Lanczos3;
|
||||
let (w, h) = (100, 900);
|
||||
assert!(frame.sample_plan(100, 1000, w, h).prefilter.is_some(), "a reduction on either axis is prefiltered");
|
||||
let k = 1000.0 / h as f64;
|
||||
let unfiltered = Rgb32f::from_fn(w, h, |x, y| source.sample_bilinear(x as f32 + 0.5, ((y as f64 + 0.5) * k) as f32));
|
||||
let (sharp, bilinear) = (power(&frame.sample(&source, w, h)), power(&unfiltered));
|
||||
assert!(sharp < bilinear * 0.95, "residual alias power {sharp} vs unfiltered {bilinear}");
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use serde::{Deserialize, Serialize};
|
||||
const CONTROL_LIMIT: usize = 16 * 1024;
|
||||
const RESPONSE_LIMIT: usize = 4 * 1024 * 1024;
|
||||
const TIMEOUT: Duration = Duration::from_secs(9 * 60);
|
||||
const ACCEPT_RETRY_DELAY: Duration = Duration::from_millis(100);
|
||||
pub const ENV: &str = "LIGHTCRAFT_SAM3_REMOTE";
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -194,6 +195,30 @@ fn serve_client(stream: &mut TcpStream, dir: &Path, device: candle_core::Device)
|
||||
}
|
||||
}
|
||||
|
||||
fn serve_connections<I, C, H, S>(incoming: I, mut handle_client: H, mut retry_sleep: S)
|
||||
where
|
||||
I: IntoIterator<Item = io::Result<C>>,
|
||||
H: FnMut(&mut C) -> Result<(), String>,
|
||||
S: FnMut(Duration),
|
||||
{
|
||||
for connection in incoming {
|
||||
let mut stream = match connection {
|
||||
Ok(stream) => stream,
|
||||
Err(error) => {
|
||||
eprintln!("SAM3 accept failed: {error}");
|
||||
retry_sleep(ACCEPT_RETRY_DELAY);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handle_client(&mut stream)));
|
||||
match result {
|
||||
Ok(Err(error)) => eprintln!("SAM3 session closed: {error}"),
|
||||
Err(_) => eprintln!("SAM3 session panicked; model released"),
|
||||
Ok(Ok(())) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serve(address: SocketAddr, dir: &Path, device: candle_core::Device) -> Result<(), String> {
|
||||
if !address.ip().is_loopback() || !device.is_metal() {
|
||||
return Err("SAM worker requires a loopback address and a Metal device".into());
|
||||
@@ -203,14 +228,97 @@ pub fn serve(address: SocketAddr, dir: &Path, device: candle_core::Device) -> Re
|
||||
}
|
||||
let listener = TcpListener::bind(address).map_err(|e| e.to_string())?;
|
||||
eprintln!("SAM3 worker listening on {address}; device=Metal; idle unload=600s");
|
||||
for stream in listener.incoming() {
|
||||
let mut stream = stream.map_err(|e| e.to_string())?;
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| serve_client(&mut stream, dir, device.clone())));
|
||||
match result {
|
||||
Ok(Err(error)) => eprintln!("SAM3 session closed: {error}"),
|
||||
Err(_) => eprintln!("SAM3 session panicked; model released"),
|
||||
Ok(Ok(())) => {}
|
||||
}
|
||||
}
|
||||
serve_connections(listener.incoming(), |stream| serve_client(stream, dir, device.clone()), std::thread::sleep);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn accept_error<T>() -> io::Result<T> {
|
||||
Err(io::Error::new(io::ErrorKind::ConnectionAborted, "injected accept failure"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sam_accept_error_before_client_keeps_serving() {
|
||||
let mut handled = Vec::new();
|
||||
serve_connections(
|
||||
[accept_error(), Ok(1_u8)],
|
||||
|stream| {
|
||||
handled.push(*stream);
|
||||
Ok(())
|
||||
},
|
||||
|_| {},
|
||||
);
|
||||
|
||||
assert_eq!(handled, [1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sam_accept_error_between_clients_keeps_serving() {
|
||||
let mut handled = Vec::new();
|
||||
serve_connections(
|
||||
[Ok(1_u8), accept_error(), Ok(2_u8)],
|
||||
|stream| {
|
||||
handled.push(*stream);
|
||||
Ok(())
|
||||
},
|
||||
|_| {},
|
||||
);
|
||||
|
||||
assert_eq!(handled, [1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sam_accept_repeated_errors_back_off() {
|
||||
let mut handled = Vec::new();
|
||||
let mut delays = Vec::new();
|
||||
serve_connections(
|
||||
[accept_error(), accept_error(), Ok(1_u8)],
|
||||
|stream| {
|
||||
handled.push(*stream);
|
||||
Ok(())
|
||||
},
|
||||
|delay| delays.push(delay),
|
||||
);
|
||||
|
||||
assert_eq!(handled, [1]);
|
||||
assert_eq!(delays, [Duration::from_millis(100), Duration::from_millis(100)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sam_accept_client_failure_keeps_serving() {
|
||||
let mut handled = Vec::new();
|
||||
let mut delays = Vec::new();
|
||||
serve_connections(
|
||||
[Ok(1_u8), Ok(2_u8)],
|
||||
|stream| {
|
||||
handled.push(*stream);
|
||||
if *stream == 1 { Err("injected client failure".into()) } else { Ok(()) }
|
||||
},
|
||||
|delay| delays.push(delay),
|
||||
);
|
||||
|
||||
assert_eq!(handled, [1, 2]);
|
||||
assert!(delays.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sam_accept_client_panic_keeps_serving() {
|
||||
let mut handled = Vec::new();
|
||||
serve_connections(
|
||||
[Ok(1_u8), Ok(2_u8)],
|
||||
|stream| {
|
||||
handled.push(*stream);
|
||||
if *stream == 1 {
|
||||
std::panic::resume_unwind(Box::new("injected client panic"));
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
|_| {},
|
||||
);
|
||||
|
||||
assert_eq!(handled, [1, 2]);
|
||||
}
|
||||
}
|
||||
@@ -303,10 +303,10 @@
|
||||
"Color space: Rec. 2020 {curve} (HDR AVIF)": "Barevný prostor: Rec. 2020 {curve} (HDR AVIF)",
|
||||
"{n} selected photo{} · {pages} page{}": "Vybrané fotografie: {n} · stránek: {pages}{:.0}{:.0}",
|
||||
"Already in “{}”": "Již v „{}“",
|
||||
"Move {n} photo{} to “{}”": "Přesunout do „{1}“ fotografie: {n}{0:.0}",
|
||||
"Move {n} photo{} to “{}”?": "Přesunout do „{1}“ fotografie: {n}{0:.0}?",
|
||||
"Move {n} file{} to “{}”": "Přesunout do „{1}“ soubory: {n}{0:.0}",
|
||||
"Move {n} file{} to “{}”?": "Přesunout do „{1}“ soubory: {n}{0:.0}?",
|
||||
"Listing folders — folders: {folders}, files: {files}": "Procházení složek – složky: {folders}, soubory: {files}",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto fotografií: {n}{0:.0}. Úpravy → Zpět je vrátí.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Do „{1}“ přesunuto souborů: {n}{0:.0}. Úpravy → Zpět je vrátí.",
|
||||
"Drop to review {n} item{} for import": "Pusťte pro kontrolu před importem (položek: {n}){:.0}",
|
||||
"Drop to import {n} item{}": "Pusťte pro import (položek: {n}){:.0}",
|
||||
"Drop to import {n} preset{}": "Pusťte pro import přednastavení: {n}{:.0}",
|
||||
@@ -328,6 +328,9 @@
|
||||
"File › Export… · File › Print… ({keys}).": "Soubor › Exportovat… · Soubor › Tisk… ({keys}).",
|
||||
"{n} folder{} could not be read": "Složky, které se nepodařilo přečíst: {n}{:.0}",
|
||||
"{n} file{} skipped (not a supported photo type)": "Přeskočené soubory (nejde o podporovaný typ fotografie): {n}{:.0}",
|
||||
"Add {n} photo{} to “{}”": "Přidat do „{1}“ fotografie: {n}{0:.0}",
|
||||
"{n} already there": "již tam je: {n}",
|
||||
"Add “{keyword}” to {n} photo{}": "Přidat „{keyword}“ k fotografiím: {n}{:.0}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Pravidlo {n} z {m}: {what}. Přesun pomocí šipek",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Skupina {n} z {m}: shoda {mode}, uvnitř {count}. Přesun pomocí šipek",
|
||||
", rating {} of 5": ", hodnocení: {} z 5"
|
||||
|
||||
@@ -60,6 +60,7 @@
|
||||
"Import photos with File → Import Photos…, or drop them here": "Importujte fotografie přes Soubor → Importovat fotografie… nebo je přetáhněte sem",
|
||||
"This row covers more than one disk: drop on a folder inside it": "Tento řádek zahrnuje více disků: přetáhněte položky na některou ze složek v něm",
|
||||
"Local photos aren't in the library yet: Add to My Photos first, then move them": "Místní fotografie zatím nejsou v knihovně: nejprve použijte Přidat do mých fotografií a pak je přesuňte",
|
||||
"Demo photos have no file on disk, so they can't be moved": "Ukázkové fotografie nemají soubor na disku, proto je nelze přesunout",
|
||||
"Add to My Photos First": "Nejprve přidat do mých fotografií",
|
||||
"Add to Selected Photos": "Přidat k vybraným fotografiím",
|
||||
"Add to Target Album": "Přidat do cílového alba",
|
||||
@@ -2519,6 +2520,14 @@
|
||||
"Next": "Další",
|
||||
"Get Started": "Začít",
|
||||
"Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie",
|
||||
"Can't add to an album folder": "Nelze přidat do složky alb",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "Složka alb obsahuje alba, ne fotografie: pusťte je na album uvnitř",
|
||||
"Can't add to a smart album": "Nelze přidat do inteligentního alba",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "O fotografiích inteligentního alba rozhodují jeho pravidla: změníte je přes Upravit inteligentní album…",
|
||||
"Add keywords in the Keyword List": "Klíčová slova přidávejte v Seznamu klíčových slov",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Klíčové slovo fotografiím přidáte v Seznamu klíčových slov (Okno → Klíčová slova, K): pusťte je tam na klíčové slovo",
|
||||
"Already on these photos": "Už je mají",
|
||||
"Can't go inside itself": "Nemůže jít samo do sebe",
|
||||
"Same Content as Another Photo": "Stejný obsah jako jiná fotografie",
|
||||
"Reduce Motion": "Omezit pohyb",
|
||||
"Reduce motion": "Omezit pohyb",
|
||||
|
||||
@@ -306,10 +306,10 @@
|
||||
"{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}-Zusammenfügung mit {mp} hinzugefügt: die volle Größe, {full}, braucht mehr Arbeitsspeicher, als dieser Computer hat",
|
||||
"{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}-Zusammenfügung mit {mp} hinzugefügt, der größten möglichen Panoramagröße (volle Größe: {full})",
|
||||
"Already in “{}”": "Bereits in „{}“",
|
||||
"Move {n} photo{} to “{}”": "{n} Foto{0} nach „{1}“ verschieben",
|
||||
"Move {n} photo{} to “{}”?": "{n} Foto{0} nach „{1}“ verschieben?",
|
||||
"Move {n} file{} to “{}”": "Nach „{1}“ verschieben (Dateien: {n}){0:.0}",
|
||||
"Move {n} file{} to “{}”?": "Nach „{1}“ verschieben (Dateien: {n})?{0:.0}",
|
||||
"Listing folders — folders: {folders}, files: {files}": "Ordner werden aufgelistet – Ordner: {folders}, Dateien: {files}",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} Foto{0} nach „{1}“ verschoben. Bearbeiten → Rückgängig holt sie zurück.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Nach „{1}“ verschoben (Dateien: {n}). Bearbeiten → Rückgängig holt sie zurück.{0:.0}",
|
||||
"Drop to review {n} item{} for import": "Ablegen, um vor dem Import zu prüfen (Objekte: {n}){:.0}",
|
||||
"Drop to import {n} item{}": "Ablegen zum Importieren (Objekte: {n}){:.0}",
|
||||
"Drop to import {n} preset{}": "Ablegen zum Importieren von Vorgaben: {n}{:.0}",
|
||||
@@ -329,6 +329,9 @@
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "Fotos holen Sie mit Datei › Fotos importieren… ({keys}) in die Bibliothek.",
|
||||
"View › Detail View ({keys}).": "Ansicht › Detailansicht ({keys}).",
|
||||
"File › Export… · File › Print… ({keys}).": "Datei › Exportieren… · Datei › Drucken… ({keys}).",
|
||||
"Add {n} photo{} to “{}”": "{n} Foto{0} zu „{1}“ hinzufügen",
|
||||
"{n} already there": "{n} bereits enthalten",
|
||||
"Add “{keyword}” to {n} photo{}": "„{keyword}“ zu {n} Foto{} hinzufügen",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Regel {n} von {m}: {what}. Mit den Pfeiltasten verschieben",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Gruppe {n} von {m}: erfülle {mode}, {count} darin. Mit den Pfeiltasten verschieben",
|
||||
", rating {} of 5": ", Bewertung: {} von 5"
|
||||
|
||||
@@ -60,6 +60,7 @@
|
||||
"Import photos with File → Import Photos…, or drop them here": "Importiere Fotos über Datei → Fotos importieren… oder lege sie hier ab",
|
||||
"This row covers more than one disk: drop on a folder inside it": "Diese Zeile umfasst mehr als ein Laufwerk: auf einem Ordner darin ablegen",
|
||||
"Local photos aren't in the library yet: Add to My Photos first, then move them": "Lokale Fotos sind noch nicht in der Bibliothek: erst zu „Meine Fotos“ hinzufügen, dann verschieben",
|
||||
"Demo photos have no file on disk, so they can't be moved": "Demofotos haben keine Datei auf dem Datenträger und lassen sich deshalb nicht verschieben",
|
||||
"Add to Selected Photos": "Zu ausgewählten Fotos hinzufügen",
|
||||
"Add to Target Album": "Zu Zielalbum hinzufügen",
|
||||
"Add to this mask": "Zu dieser Maske hinzufügen",
|
||||
@@ -3577,6 +3578,14 @@
|
||||
"Welcome": "Willkommen",
|
||||
"Next": "Weiter",
|
||||
"Get Started": "Loslegen",
|
||||
"Can't add to an album folder": "Nicht zu einem Albenordner hinzufügbar",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "Ein Albenordner enthält Alben, keine Fotos: auf ein Album darin ablegen",
|
||||
"Can't add to a smart album": "Nicht zu einem Smart-Album hinzufügbar",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "Die Regeln eines Smart-Albums bestimmen seine Fotos: ändere sie mit Smart-Album bearbeiten…",
|
||||
"Add keywords in the Keyword List": "Stichwörter in der Stichwortliste hinzufügen",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Stichwörter vergibst du in der Stichwortliste (Fenster → Stichwörter, K): Fotos dort auf ein Stichwort ziehen",
|
||||
"Already on these photos": "Bereits bei diesen Fotos",
|
||||
"Can't go inside itself": "Kann nicht in sich selbst liegen",
|
||||
"Same Content as Another Photo": "Gleicher Inhalt wie ein anderes Foto",
|
||||
"Reduce Motion": "Bewegung reduzieren",
|
||||
"Reduce motion": "Bewegung reduzieren",
|
||||
|
||||
@@ -306,10 +306,10 @@
|
||||
"{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Combinación {what} añadida a {mp}: el tamaño completo, {full}, necesita más memoria de la que tiene este ordenador",
|
||||
"{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Combinación {what} añadida a {mp}, el tamaño máximo de una panorámica (tamaño completo: {full})",
|
||||
"Already in “{}”": "Ya está en “{}”",
|
||||
"Move {n} photo{} to “{}”": "Mover {n} foto{0} a “{1}”",
|
||||
"Move {n} photo{} to “{}”?": "¿Mover {n} foto{0} a “{1}”?",
|
||||
"Move {n} file{} to “{}”": "Mover {n} archivo{0} a “{1}”",
|
||||
"Move {n} file{} to “{}”?": "¿Mover {n} archivo{0} a “{1}”?",
|
||||
"Listing folders — folders: {folders}, files: {files}": "Listando carpetas — carpetas: {folders}, archivos: {files}",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} a “{1}”. Editar → Deshacer las devuelve.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n} archivo{0} movido{0} a “{1}”. Editar → Deshacer los devuelve.",
|
||||
"Drop to review {n} item{} for import": "Suelta para revisar {n} elemento{} antes de importar",
|
||||
"Drop to import {n} item{}": "Suelta para importar {n} elemento{}",
|
||||
"Drop to import {n} preset{}": "Suelta para importar {n} ajuste{0} preestablecido{0}",
|
||||
@@ -329,6 +329,9 @@
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "Importa fotos con Archivo › Importar fotos… ({keys}).",
|
||||
"View › Detail View ({keys}).": "Vista › Vista de detalle ({keys}).",
|
||||
"File › Export… · File › Print… ({keys}).": "Archivo › Exportar… · Archivo › Imprimir… ({keys}).",
|
||||
"Add {n} photo{} to “{}”": "Añadir {n} foto{0} a “{1}”",
|
||||
"{n} already there": "ya en el álbum: {n}",
|
||||
"Add “{keyword}” to {n} photo{}": "Añadir “{keyword}” a {n} foto{}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Regla {n} de {m}: {what}. Mover con las teclas de flecha",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupo {n} de {m}: coincidir con {mode}, {count} dentro. Mover con las teclas de flecha",
|
||||
", rating {} of 5": ", valoración: {} de 5"
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
"Import photos with File → Import Photos…, or drop them here": "Importar fotos con Archivo → Importar fotos… o soltarlas aquí",
|
||||
"This row covers more than one disk: drop on a folder inside it": "Esta fila abarca más de un disco: suéltalas en una carpeta dentro de ella",
|
||||
"Local photos aren't in the library yet: Add to My Photos first, then move them": "Las fotos locales aún no están en la biblioteca: primero Añadir a Mis fotos y luego muévelas",
|
||||
"Demo photos have no file on disk, so they can't be moved": "Las fotos de demostración no tienen archivo en el disco, así que no se pueden mover",
|
||||
"Add to Selected Photos": "Añadir a las fotos seleccionadas",
|
||||
"Add to Target Album": "Añadir al álbum de destino",
|
||||
"Add to this mask": "Añadir a esta máscara",
|
||||
@@ -2473,6 +2474,14 @@
|
||||
"Welcome": "Bienvenido",
|
||||
"Next": "Siguiente",
|
||||
"Get Started": "Empezar",
|
||||
"Can't add to an album folder": "No se puede añadir a una carpeta de álbumes",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "Una carpeta de álbumes contiene álbumes, no fotos: suéltalas en un álbum de dentro",
|
||||
"Can't add to a smart album": "No se puede añadir a un álbum inteligente",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "Las reglas de un álbum inteligente eligen sus fotos: cámbialas con Editar álbum inteligente…",
|
||||
"Add keywords in the Keyword List": "Añade palabras clave en la Lista de palabras clave",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Para dar una palabra clave a las fotos, usa la Lista de palabras clave (Ventana → Palabras clave, K): suéltalas allí sobre ella",
|
||||
"Already on these photos": "Ya las tienen estas fotos",
|
||||
"Can't go inside itself": "No puede ir dentro de sí misma",
|
||||
"Same Content as Another Photo": "Mismo contenido que otra foto",
|
||||
"Reduce Motion": "Reducir movimiento",
|
||||
"Reduce motion": "Reducir movimiento",
|
||||
|
||||
@@ -130,10 +130,10 @@
|
||||
"Making the denoised picture… {}%": "Tehdään kohinanpoistettua kuvaa… {}%",
|
||||
"Matches: {}": "Täsmäävät: {}",
|
||||
"Merging… {stage} {:.0}%": "Yhdistetään… {stage} {:.0}%",
|
||||
"Move {n} photo{} to “{}”": "Siirrä kuvia kohteeseen ”{1}”: {n}{0:.0}",
|
||||
"Move {n} photo{} to “{}”?": "Siirretäänkö kuvat kohteeseen ”{1}” ({n}){0:.0}?",
|
||||
"Move {n} file{} to “{}”": "Siirrä tiedostoja kohteeseen ”{1}”: {n}{0:.0}",
|
||||
"Move {n} file{} to “{}”?": "Siirretäänkö tiedostot kohteeseen ”{1}” ({n}){0:.0}?",
|
||||
"Move {what} to Recently Deleted?": "Siirretäänkö {what} Äskettäin poistettuihin?",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Siirretty kuvia kohteeseen ”{1}”: {n}{0:.0}. Muokkaa → Kumoa siirtää ne takaisin.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Siirretty tiedostoja kohteeseen ”{1}”: {n}{0:.0}. Muokkaa → Kumoa siirtää ne takaisin.",
|
||||
"Moved {} photo(s)": "Siirretty kuvia: {}",
|
||||
"Moved; {} photo(s) relinked": "Siirretty; yhdistetty uudelleen kuvia: {}",
|
||||
"Named ({named_n})": "Nimetyt ({named_n})",
|
||||
@@ -325,6 +325,9 @@
|
||||
"File › Export… · File › Print… ({keys}).": "Tiedosto › Vie… · Tiedosto › Tulosta… ({keys}).",
|
||||
"{n} folder{} could not be read": "Kansiot, joita ei voitu lukea: {n}{:.0}",
|
||||
"{n} file{} skipped (not a supported photo type)": "Ohitetut tiedostot (ei tuettu valokuvatyyppi): {n}{:.0}",
|
||||
"Add {n} photo{} to “{}”": "Lisää kuvia albumiin ”{1}”: {n}{0:.0}",
|
||||
"Add “{keyword}” to {n} photo{}": "Lisää ”{keyword}” kuviin: {n}{:.0}",
|
||||
"{n} already there": "jo albumissa: {n}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Sääntö {n}/{m}: {what}. Siirrä nuolinäppäimillä",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Ryhmä {n}/{m}: täsmää {mode}, sisällä: {count}. Siirrä nuolinäppäimillä",
|
||||
", rating {} of 5": ", luokitus: {} / 5"
|
||||
|
||||
@@ -2429,6 +2429,15 @@
|
||||
"Filter settings": "Suodata asetuksia",
|
||||
"No setting matches what is typed.": "Mikään asetus ei vastaa kirjoitettua.",
|
||||
"Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Kokeile yhtä sanaa tai sen osaa: haku kattaa välilehtien ja osioiden nimet, otsikot ja selitykset.",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "Älyalbumin säännöt valitsevat sen kuvat: muuta niitä komennolla Muokkaa älyalbumia…",
|
||||
"Add keywords in the Keyword List": "Lisää avainsanoja avainsanaluettelossa",
|
||||
"Already on these photos": "Jo näissä kuvissa",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "Albumikansio sisältää albumeja, ei kuvia: pudota kuvat sen sisällä olevalle albumille",
|
||||
"Can't add to a smart album": "Älyalbumiin ei voi lisätä",
|
||||
"Can't add to an album folder": "Albumikansioon ei voi lisätä",
|
||||
"Can't go inside itself": "Ei voi siirtää itsensä sisään",
|
||||
"Demo photos have no file on disk, so they can't be moved": "Demokuvilla ei ole tiedostoa levyllä, joten niitä ei voi siirtää",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Anna kuville avainsana avainsanaluettelossa (Ikkuna → Avainsanat, K): pudota ne siellä avainsanan päälle",
|
||||
"Same Content as Another Photo": "Sama sisältö kuin toisella kuvalla",
|
||||
"Reduce Motion": "Vähennä liikettä",
|
||||
"Reduce motion": "Vähennä liikettä",
|
||||
|
||||
@@ -306,10 +306,10 @@
|
||||
"{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "Fusion de {what} ajoutée en {mp} : la taille complète, {full}, demande plus de mémoire que n’en a cet ordinateur",
|
||||
"{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "Fusion de {what} ajoutée en {mp}, la plus grande taille possible pour un panorama (taille complète : {full})",
|
||||
"Already in “{}”": "Déjà dans « {} »",
|
||||
"Move {n} photo{} to “{}”": "Déplacer {n} photo{} vers « {} »",
|
||||
"Move {n} photo{} to “{}”?": "Déplacer {n} photo{} vers « {} » ?",
|
||||
"Move {n} file{} to “{}”": "Déplacer {n} fichier{} vers « {} »",
|
||||
"Move {n} file{} to “{}”?": "Déplacer {n} fichier{} vers « {} » ?",
|
||||
"Listing folders — folders: {folders}, files: {files}": "Liste des dossiers — dossiers : {folders}, fichiers : {files}",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} photo{0} déplacée{0} vers « {1} ». Modifier → Annuler les remet en place.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n} fichier{0} déplacé{0} vers « {1} ». Modifier → Annuler les remet en place.",
|
||||
"Drop to review {n} item{} for import": "Déposez pour vérifier {n} élément{} avant l'import",
|
||||
"Drop to import {n} item{}": "Déposez pour importer {n} élément{}",
|
||||
"Drop to import {n} preset{}": "Déposez pour importer {n} préréglage{}",
|
||||
@@ -329,6 +329,9 @@
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "Importez des photos avec Fichier › Importer des photos… ({keys}).",
|
||||
"View › Detail View ({keys}).": "Affichage › Vue de détail ({keys}).",
|
||||
"File › Export… · File › Print… ({keys}).": "Fichier › Exporter… · Fichier › Imprimer… ({keys}).",
|
||||
"Add {n} photo{} to “{}”": "Ajouter {n} photo{} à « {} »",
|
||||
"{n} already there": "{n} déjà présent(s)",
|
||||
"Add “{keyword}” to {n} photo{}": "Ajouter « {keyword} » à {n} photo{}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Règle {n} sur {m} : {what}. Déplacer avec les flèches",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Groupe {n} sur {m} : correspondre à {mode}, {count} à l’intérieur. Déplacer avec les flèches",
|
||||
", rating {} of 5": ", note : {} sur 5"
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
"Import photos with File → Import Photos…, or drop them here": "Importez des photos avec Fichier → Importer des photos… ou déposez-les ici",
|
||||
"This row covers more than one disk: drop on a folder inside it": "Cette ligne couvre plusieurs disques : déposez-les sur un dossier qu’elle contient",
|
||||
"Local photos aren't in the library yet: Add to My Photos first, then move them": "Les photos locales ne sont pas encore dans la bibliothèque : Ajouter à Mes photos d’abord, puis déplacez-les",
|
||||
"Demo photos have no file on disk, so they can't be moved": "Les photos de démonstration n’ont pas de fichier sur le disque : on ne peut pas les déplacer",
|
||||
"Add to Selected Photos": "Ajouter aux photos sélectionnées",
|
||||
"Add to Target Album": "Ajouter à l'album cible",
|
||||
"Add to this mask": "Ajouter à ce masque",
|
||||
@@ -3656,6 +3657,14 @@
|
||||
"Welcome": "Bienvenue",
|
||||
"Next": "Suivant",
|
||||
"Get Started": "Commencer",
|
||||
"Can't add to an album folder": "Impossible d’ajouter à un dossier d’albums",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "Un dossier d’albums contient des albums, pas des photos : déposez-les sur un album à l’intérieur",
|
||||
"Can't add to a smart album": "Impossible d’ajouter à un album intelligent",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "Les règles d’un album intelligent choisissent ses photos : modifiez-les avec Modifier l'album intelligent…",
|
||||
"Add keywords in the Keyword List": "Ajoutez des mots-clés dans la Liste des mots-clés",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Pour donner un mot-clé à des photos, utilisez la Liste des mots-clés (Fenêtre → Mots-clés, K) : déposez-les sur le mot-clé",
|
||||
"Already on these photos": "Déjà sur ces photos",
|
||||
"Can't go inside itself": "Ne peut pas aller dans lui-même",
|
||||
"Same Content as Another Photo": "Même contenu qu'une autre photo",
|
||||
"Reduce Motion": "Réduire les animations",
|
||||
"Reduce motion": "Réduire les animations",
|
||||
|
||||
@@ -44,10 +44,10 @@
|
||||
"LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraft tidak dapat membuka jendela: {e}\n\nDetailnya ada di file log: {path}",
|
||||
"Matches: {}": "Cocok: {}",
|
||||
"Merging… {stage} {:.0}%": "Menggabungkan… {stage} {:.0}%",
|
||||
"Move {n} photo{} to “{}”": "Pindahkan {n} foto{0:.0} ke “{1}”",
|
||||
"Move {n} photo{} to “{}”?": "Pindahkan {n} foto{0:.0} ke “{1}”?",
|
||||
"Move {n} file{} to “{}”": "Pindahkan {n} file{0:.0} ke “{1}”",
|
||||
"Move {n} file{} to “{}”?": "Pindahkan {n} file{0:.0} ke “{1}”?",
|
||||
"Move {what} to Recently Deleted?": "Pindahkan {what} ke Baru dihapus?",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto dipindahkan ke “{1}”{0:.0}. Pilih Edit → Urungkan untuk mengembalikannya.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n} file dipindahkan ke “{1}”{0:.0}. Pilih Edit → Urungkan untuk mengembalikannya.",
|
||||
"Named ({named_n})": "Bernama ({named_n})",
|
||||
"Paste into {n} photo{} — only settings that were copied are pasted": "Tempel ke {n} foto{:.0} — hanya menempelkan pengaturan yang disalin",
|
||||
"Preset: {name}": "Preset: {name}",
|
||||
@@ -328,6 +328,9 @@
|
||||
"File › Export… · File › Print… ({keys}).": "File › Ekspor… · File › Cetak… ({keys}).",
|
||||
"{n} folder{} could not be read": "Folder yang tidak bisa dibaca: {n}{:.0}",
|
||||
"{n} file{} skipped (not a supported photo type)": "File yang dilewati (bukan jenis foto yang didukung): {n}{:.0}",
|
||||
"Add {n} photo{} to “{}”": "Tambahkan {n} foto{0:.0} ke “{1}”",
|
||||
"Add “{keyword}” to {n} photo{}": "Tambahkan “{keyword}” ke {n} foto{:.0}",
|
||||
"{n} already there": "{n} sudah ada",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Aturan {n} dari {m}: {what}. Pindahkan dengan tombol panah",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grup {n} dari {m}: cocokkan {mode}, isi: {count}. Pindahkan dengan tombol panah",
|
||||
", rating {} of 5": ", rating: {} dari 5"
|
||||
|
||||
@@ -2443,6 +2443,15 @@
|
||||
"Filter settings": "Filter pengaturan",
|
||||
"No setting matches what is typed.": "Tidak ada pengaturan yang cocok dengan yang diketik.",
|
||||
"Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Coba satu kata atau sebagiannya: yang dicari adalah nama tab dan bagian, label, serta penjelasan.",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "Aturan album pintar menentukan fotonya: ubah dengan Edit album pintar…",
|
||||
"Add keywords in the Keyword List": "Tambahkan kata kunci di Daftar kata kunci",
|
||||
"Already on these photos": "Sudah ada pada foto ini",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "Folder album berisi album, bukan foto: jatuhkan ke album di dalamnya",
|
||||
"Can't add to a smart album": "Tidak dapat menambahkan ke album pintar",
|
||||
"Can't add to an album folder": "Tidak dapat menambahkan ke folder album",
|
||||
"Can't go inside itself": "Tidak dapat dimasukkan ke dalam dirinya sendiri",
|
||||
"Demo photos have no file on disk, so they can't be moved": "Foto demo tidak memiliki file di disk, sehingga tidak dapat dipindahkan",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Beri foto kata kunci di Daftar kata kunci (Jendela → Kata kunci, K): jatuhkan ke kata kunci di sana",
|
||||
"Same Content as Another Photo": "Konten sama dengan foto lain",
|
||||
"Reduce Motion": "Kurangi gerakan",
|
||||
"Reduce motion": "Kurangi gerakan",
|
||||
|
||||
@@ -303,9 +303,9 @@
|
||||
"Color space: Rec. 2020 {curve} (HDR AVIF)": "Spazio colore: Rec. 2020 {curve} (AVIF HDR)",
|
||||
"{n} selected photo{} · {pages} page{}": "Foto selezionate: {n} · pagine: {pages}{:.0}{:.0}",
|
||||
"Already in “{}”": "Già in “{}”",
|
||||
"Move {n} photo{} to “{}”": "Sposta foto in “{1}” ({n}){0:.0}",
|
||||
"Move {n} photo{} to “{}”?": "Spostare le foto in “{1}” ({n})?{0:.0}",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Foto spostate in “{1}”: {n}{0:.0}. Modifica → Annulla le riporta indietro.",
|
||||
"Move {n} file{} to “{}”": "Sposta file in “{1}” ({n}){0:.0}",
|
||||
"Move {n} file{} to “{}”?": "Spostare i file in “{1}” ({n})?{0:.0}",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "File spostati in “{1}”: {n}{0:.0}. Modifica → Annulla li riporta indietro.",
|
||||
"Listing folders — folders: {folders}, files: {files}": "Elenco delle cartelle — cartelle: {folders}, file: {files}",
|
||||
"Drop to review {n} item{} for import": "Rilascia per rivedere prima dell'importazione (elementi: {n}){:.0}",
|
||||
"Drop to import {n} item{}": "Rilascia per importare (elementi: {n}){:.0}",
|
||||
@@ -328,6 +328,9 @@
|
||||
"File › Export… · File › Print… ({keys}).": "File › Esporta… · File › Stampa… ({keys}).",
|
||||
"{n} folder{} could not be read": "Cartelle non leggibili: {n}{:.0}",
|
||||
"{n} file{} skipped (not a supported photo type)": "File saltati (non è un tipo di foto supportato): {n}{:.0}",
|
||||
"Add {n} photo{} to “{}”": "Aggiungi {n} foto{0:.0} a “{1}”",
|
||||
"{n} already there": "{n} già presenti",
|
||||
"Add “{keyword}” to {n} photo{}": "Aggiungi “{keyword}” a {n} foto{:.0}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Regola {n} di {m}: {what}. Sposta con le frecce",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Gruppo {n} di {m}: corrispondenza {mode}, {count} all’interno. Sposta con le frecce",
|
||||
", rating {} of 5": ", valutazione: {} su 5"
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
"Import photos with File → Import Photos…, or drop them here": "Importa le foto con File → Importa foto…, oppure trascinale qui",
|
||||
"This row covers more than one disk: drop on a folder inside it": "Questa riga comprende più di un disco: rilascia su una cartella al suo interno",
|
||||
"Local photos aren't in the library yet: Add to My Photos first, then move them": "Le foto locali non sono ancora nella libreria: prima Aggiungi a Le mie foto, poi spostale",
|
||||
"Demo photos have no file on disk, so they can't be moved": "Le foto dimostrative non hanno un file su disco, quindi non si possono spostare",
|
||||
"Add to Selected Photos": "Aggiungi alle foto selezionate",
|
||||
"Add to Target Album": "Aggiungi all'album di destinazione",
|
||||
"Add to this mask": "Aggiungi a questa maschera",
|
||||
@@ -2637,6 +2638,14 @@
|
||||
"Next": "Avanti",
|
||||
"Get Started": "Inizia",
|
||||
"Stopped at the scan limit: there may be more photos": "Fermati al limite di scansione: potrebbero esserci altre foto",
|
||||
"Can't add to an album folder": "Impossibile aggiungere a una cartella di album",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "Una cartella di album contiene album, non foto: rilascia su un album al suo interno",
|
||||
"Can't add to a smart album": "Impossibile aggiungere a un album smart",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "Le regole di un album smart scelgono le sue foto: cambiale con Modifica album smart…",
|
||||
"Add keywords in the Keyword List": "Aggiungi le parole chiave nell'Elenco parole chiave",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Per dare una parola chiave alle foto usa l'Elenco parole chiave (Finestra → Parole chiave, K): rilasciale lì sulla parola chiave",
|
||||
"Already on these photos": "Già presente su queste foto",
|
||||
"Can't go inside itself": "Non può andare dentro se stessa",
|
||||
"Same Content as Another Photo": "Stesso contenuto di un'altra foto",
|
||||
"Reduce Motion": "Riduci movimento",
|
||||
"Reduce motion": "Riduci movimento",
|
||||
|
||||
@@ -44,10 +44,10 @@
|
||||
"LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraftのウィンドウを開けませんでした: {e}\n\n詳しくはログファイルをご覧ください: {path}",
|
||||
"Matches: {}": "一致条件:{}",
|
||||
"Merging… {stage} {:.0}%": "合成中… {stage} {:.0}%",
|
||||
"Move {n} photo{} to “{}”": "{n}枚を「{1}」に移動{0:.0}",
|
||||
"Move {n} photo{} to “{}”?": "{n}枚を「{1}」に移動しますか?{0:.0}",
|
||||
"Move {n} file{} to “{}”": "{n}件のファイルを「{1}」に移動{0:.0}",
|
||||
"Move {n} file{} to “{}”?": "{n}件のファイルを「{1}」に移動しますか?{0:.0}",
|
||||
"Move {what} to Recently Deleted?": "{what}を「最近削除した写真」に移動しますか?",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n}枚を「{1}」に移動しました。編集 → 取り消す で元に戻せます。{0:.0}",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n}件のファイルを「{1}」に移動しました。編集 → 取り消す で元に戻せます。{0:.0}",
|
||||
"Named ({named_n})": "名前付き({named_n})",
|
||||
"Paste into {n} photo{} — only settings that were copied are pasted": "{n}枚に貼り付け{:.0}(コピーされた設定だけを適用)",
|
||||
"Preset: {name}": "プリセット:{name}",
|
||||
@@ -329,6 +329,9 @@
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "ファイル › 写真を読み込む… ({keys}) で写真を読み込みます。",
|
||||
"View › Detail View ({keys}).": "表示 › 詳細表示 ({keys})。",
|
||||
"File › Export… · File › Print… ({keys}).": "ファイル › 書き出す… · ファイル › 印刷… ({keys})。",
|
||||
"Add {n} photo{} to “{}”": "{n}枚を「{1}」に追加{0:.0}",
|
||||
"{n} already there": "{n}枚は追加済み",
|
||||
"Add “{keyword}” to {n} photo{}": "写真{n}枚に「{keyword}」を追加{:.0}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "条件 {n}/{m}:{what}。矢印キーで移動",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "グループ {n}/{m}:一致条件 {mode}、中に {count} 件。矢印キーで移動",
|
||||
", rating {} of 5": "、評価: 5段階中{}"
|
||||
|
||||
@@ -46,6 +46,7 @@
|
||||
"Import photos with File → Import Photos…, or drop them here": "「ファイル → 写真を読み込む…」から読み込むか、ここに写真をドロップしてください",
|
||||
"This row covers more than one disk: drop on a folder inside it": "この行は複数のディスクにまたがっています。中のフォルダにドロップしてください",
|
||||
"Local photos aren't in the library yet: Add to My Photos first, then move them": "ローカルの写真はまだライブラリにありません。先に「マイフォトに追加」してから移動してください",
|
||||
"Demo photos have no file on disk, so they can't be moved": "デモの写真にはディスク上のファイルがないため、移動できません",
|
||||
"Add to Selected Photos": "選択した写真に追加",
|
||||
"Add to Target Album": "追加先アルバムに追加",
|
||||
"Add to this mask": "このマスクに追加",
|
||||
@@ -2471,6 +2472,14 @@
|
||||
"Welcome": "ようこそ",
|
||||
"Next": "次へ",
|
||||
"Get Started": "始める",
|
||||
"Can't add to an album folder": "アルバムフォルダには追加できません",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "アルバムフォルダに入れられるのはアルバムだけです:中のアルバムにドロップしてください",
|
||||
"Can't add to a smart album": "スマートアルバムには追加できません",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "スマートアルバムの写真はルールで決まります:「スマートアルバムを編集…」で変更してください",
|
||||
"Add keywords in the Keyword List": "キーワードはキーワードリストで追加します",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "写真にキーワードを付けるには、キーワードリスト(ウィンドウ → キーワード、K)で、そのキーワードにドロップしてください",
|
||||
"Already on these photos": "すでにこの写真にあります",
|
||||
"Can't go inside itself": "自分の中には入れられません",
|
||||
"Same Content as Another Photo": "他の写真と同じ内容",
|
||||
"Reduce Motion": "動きを減らす",
|
||||
"Reduce motion": "動きを減らす",
|
||||
|
||||
@@ -306,10 +306,10 @@
|
||||
"{n} selected photos · {pages} pages": "მონიშნული ფოტო: {n} · გვერდი: {pages}",
|
||||
"{n} selected photo{} · {pages} page{}": "არჩეული ფოტო: {n} · გვერდი: {pages}{:.0}{:.0}",
|
||||
"Already in “{}”": "უკვე „{}“-შია",
|
||||
"Move {n} photo{} to “{}”": "ფოტოს გადატანა „{1}“-ში: {n}{0:.0}",
|
||||
"Move {n} photo{} to “{}”?": "გადავიდეს „{1}“-ში ფოტო: {n}{0:.0}?",
|
||||
"Move {n} file{} to “{}”": "ფაილის გადატანა „{1}“-ში: {n}{0:.0}",
|
||||
"Move {n} file{} to “{}”?": "გადავიდეს „{1}“-ში ფაილი: {n}{0:.0}?",
|
||||
"Listing folders — folders: {folders}, files: {files}": "საქაღალდეების ჩამოთვლა — საქაღალდეები: {folders}, ფაილები: {files}",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "„{1}“-ში გადავიდა ფოტო: {n}{0:.0}. რედაქტირება → დაბრუნება მათ უკან აბრუნებს.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "„{1}“-ში გადავიდა ფაილი: {n}{0:.0}. რედაქტირება → დაბრუნება მათ უკან აბრუნებს.",
|
||||
"Drop to review {n} item{} for import": "ჩააგდეთ იმპორტამდე გადასახედად (ელემენტები: {n}){:.0}",
|
||||
"Drop to import {n} item{}": "ჩააგდეთ იმპორტისთვის (ელემენტები: {n}){:.0}",
|
||||
"Drop to import {n} preset{}": "ჩააგდეთ პრესეტების იმპორტისთვის: {n}{:.0}",
|
||||
@@ -331,6 +331,9 @@
|
||||
"File › Export… · File › Print… ({keys}).": "ფაილი › ექსპორტი… · ფაილი › დაბეჭდვა… ({keys}).",
|
||||
"{n} folder{} could not be read": "საქაღალდეები, რომლებიც ვერ წაიკითხა: {n}{:.0}",
|
||||
"{n} file{} skipped (not a supported photo type)": "გამოტოვებული ფაილები (მხარდაუჭერელი ფოტოს ტიპია): {n}{:.0}",
|
||||
"Add {n} photo{} to “{}”": "დაამატეთ ფოტო „{1}“-ში: {n}{0:.0}",
|
||||
"{n} already there": "{n} უკვე არის",
|
||||
"Add “{keyword}” to {n} photo{}": "დაამატეთ „{keyword}“ ფოტოებს: {n}{:.0}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "წესი {n}/{m}: {what}. გადაადგილება ისრებით",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "ჯგუფი {n}/{m}: დამთხვევა {mode}, შიგნით {count}. გადაადგილება ისრებით",
|
||||
", rating {} of 5": ", შეფასება: {} 5-დან"
|
||||
|
||||
@@ -3740,6 +3740,15 @@
|
||||
"Filter settings": "პარამეტრების გაფილტვრა",
|
||||
"No setting matches what is typed.": "აკრეფილს არც ერთი პარამეტრი არ ემთხვევა.",
|
||||
"Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "სცადეთ ერთი სიტყვა ან მისი ნაწილი: იძებნება ჩანართებისა და სექციების სახელებში, წარწერებსა და განმარტებებში.",
|
||||
"Can't add to an album folder": "ალბომების საქაღალდეში დამატება შეუძლებელია",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "ალბომების საქაღალდეში ალბომებია, არა ფოტოები: ჩააგდეთ მასში არსებულ ალბომზე",
|
||||
"Can't add to a smart album": "სმარტ-ალბომში დამატება შეუძლებელია",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "სმარტ-ალბომის ფოტოებს მისი წესები ირჩევს: შეცვალეთ „სმარტ-ალბომის რედაქტირება…“-ით",
|
||||
"Add keywords in the Keyword List": "საკვანძო სიტყვები დაამატეთ საკვანძო სიტყვების სიაში",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "ფოტოებისთვის საკვანძო სიტყვის მისაცემად გამოიყენეთ საკვანძო სიტყვების სია (ფანჯარა → საკვანძო სიტყვები, K): ჩააგდეთ იქ სასურველ სიტყვაზე",
|
||||
"Already on these photos": "ამ ფოტოებს უკვე აქვთ",
|
||||
"Can't go inside itself": "საკუთარ თავში ვერ მოხვდება",
|
||||
"Demo photos have no file on disk, so they can't be moved": "სადემონსტრაციო ფოტოებს დისკზე ფაილი არ აქვთ, ამიტომ მათი გადატანა შეუძლებელია",
|
||||
"Same Content as Another Photo": "იგივე შიგთავსი, რაც სხვა ფოტოს",
|
||||
"Reduce Motion": "მოძრაობის შემცირება",
|
||||
"Reduce motion": "მოძრაობის შემცირება",
|
||||
|
||||
@@ -302,10 +302,10 @@
|
||||
"Color space: Rec. 2020 {curve} (HDR AVIF)": "Przestrzeń kolorów: Rec. 2020 {curve} (HDR AVIF)",
|
||||
"{n} selected photo{} · {pages} page{}": "Wybrane zdjęcia: {n} · stron: {pages}{:.0}{:.0}",
|
||||
"Already in “{}”": "Już w „{}”",
|
||||
"Move {n} photo{} to “{}”": "Przenieś do „{1}” — zdjęcia: {n}{0:.0}",
|
||||
"Move {n} photo{} to “{}”?": "Przenieść do „{1}” — zdjęcia: {n}{0:.0}?",
|
||||
"Move {n} file{} to “{}”": "Przenieś do „{1}” — pliki: {n}{0:.0}",
|
||||
"Move {n} file{} to “{}”?": "Przenieść do „{1}” — pliki: {n}{0:.0}?",
|
||||
"Listing folders — folders: {folders}, files: {files}": "Przeglądanie folderów — foldery: {folders}, pliki: {files}",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — zdjęcia: {n}{0:.0}. Edytuj → Cofnij przywróci je.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Przeniesiono do „{1}” — pliki: {n}{0:.0}. Edytuj → Cofnij przywróci je.",
|
||||
"Drop to review {n} item{} for import": "Upuść, aby przejrzeć przed importem (elementy: {n}){:.0}",
|
||||
"Drop to import {n} item{}": "Upuść, aby zaimportować (elementy: {n}){:.0}",
|
||||
"Drop to import {n} preset{}": "Upuść, aby zaimportować ustawienia wstępne: {n}{:.0}",
|
||||
@@ -328,6 +328,9 @@
|
||||
"File › Export… · File › Print… ({keys}).": "Plik › Eksportuj… · Plik › Drukuj… ({keys}).",
|
||||
"{n} folder{} could not be read": "Nie udało się odczytać folderów: {n}{:.0}",
|
||||
"{n} file{} skipped (not a supported photo type)": "Pominięte pliki (nieobsługiwany typ zdjęcia): {n}{:.0}",
|
||||
"Add {n} photo{} to “{}”": "Dodaj do „{1}” — zdjęcia: {n}{0:.0}",
|
||||
"{n} already there": "{n} już tam jest",
|
||||
"Add “{keyword}” to {n} photo{}": "Dodaj „{keyword}” do zdjęć: {n}{:.0}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Reguła {n} z {m}: {what}. Przenoś strzałkami",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupa {n} z {m}: dopasuj {mode}, w środku {count}. Przenoś strzałkami",
|
||||
", rating {} of 5": ", ocena: {} na 5"
|
||||
|
||||
@@ -2398,6 +2398,15 @@
|
||||
"Next": "Dalej",
|
||||
"Get Started": "Zaczynamy",
|
||||
"Stopped at the scan limit: there may be more photos": "Zatrzymano na limicie skanowania: możliwe, że jest więcej zdjęć",
|
||||
"Can't add to an album folder": "Nie można dodać do folderu albumów",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "Folder albumów zawiera albumy, nie zdjęcia: upuść na album w jego wnętrzu",
|
||||
"Can't add to a smart album": "Nie można dodać do albumu inteligentnego",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "O zdjęciach albumu inteligentnego decydują jego reguły: zmienisz je przez Edytuj album inteligentny…",
|
||||
"Add keywords in the Keyword List": "Dodawaj słowa kluczowe na Liście słów kluczowych",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Aby nadać zdjęciom słowo kluczowe, użyj Listy słów kluczowych (Okno → Słowa kluczowe, K): upuść je tam na to słowo",
|
||||
"Already on these photos": "Już mają je te zdjęcia",
|
||||
"Can't go inside itself": "Nie może trafić do siebie samego",
|
||||
"Demo photos have no file on disk, so they can't be moved": "Zdjęcia demonstracyjne nie mają pliku na dysku, więc nie można ich przenieść",
|
||||
"Same Content as Another Photo": "Ta sama zawartość co inne zdjęcie",
|
||||
"Reduce Motion": "Ogranicz ruch",
|
||||
"Reduce motion": "Ogranicz ruch",
|
||||
|
||||
@@ -61,10 +61,10 @@
|
||||
"LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "O LightCraft não conseguiu abrir sua janela: {e}\n\nO arquivo de log tem os detalhes: {path}",
|
||||
"Matches: {}": "Correspondências: {}",
|
||||
"Merging… {stage} {:.0}%": "Mesclando… {stage} {:.0}%",
|
||||
"Move {n} photo{} to “{}”": "Mover {n} foto{0} para “{1}”",
|
||||
"Move {n} photo{} to “{}”?": "Mover {n} foto{0} para “{1}”?",
|
||||
"Move {n} file{} to “{}”": "Mover {n} arquivo{0} para “{1}”",
|
||||
"Move {n} file{} to “{}”?": "Mover {n} arquivo{0} para “{1}”?",
|
||||
"Move {what} to Recently Deleted?": "Mover {what} para Excluídos recentemente?",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} para “{1}”. Editar → Desfazer as traz de volta.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "{n} arquivo{0} movido{0} para “{1}”. Editar → Desfazer os traz de volta.",
|
||||
"Named ({named_n})": "Nomeadas ({named_n})",
|
||||
"Paste into {n} photo{} — only settings that were copied are pasted": "Colar em {n} foto{} — somente os ajustes copiados são colados",
|
||||
"Preset: {name}": "Predefinição: {name}",
|
||||
@@ -329,6 +329,9 @@
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "Traga fotos com Arquivo › Importar fotos… ({keys}).",
|
||||
"View › Detail View ({keys}).": "Exibir › Exibição de detalhe ({keys}).",
|
||||
"File › Export… · File › Print… ({keys}).": "Arquivo › Exportar… · Arquivo › Imprimir… ({keys}).",
|
||||
"Add {n} photo{} to “{}”": "Adicionar {n} foto{0} a “{1}”",
|
||||
"{n} already there": "já no álbum: {n}",
|
||||
"Add “{keyword}” to {n} photo{}": "Adicionar “{keyword}” a {n} foto{}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Regra {n} de {m}: {what}. Mova com as setas",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupo {n} de {m}: igualar {mode}, {count} dentro. Mova com as setas",
|
||||
", rating {} of 5": ", avaliação: {} de 5"
|
||||
|
||||
@@ -47,6 +47,7 @@
|
||||
"Import photos with File → Import Photos…, or drop them here": "Importe fotos com Arquivo → Importar fotos… ou solte-as aqui",
|
||||
"This row covers more than one disk: drop on a folder inside it": "Esta linha abrange mais de um disco: solte em uma pasta dentro dela",
|
||||
"Local photos aren't in the library yet: Add to My Photos first, then move them": "As fotos locais ainda não estão na biblioteca: primeiro Adicionar às Minhas fotos, depois mova-as",
|
||||
"Demo photos have no file on disk, so they can't be moved": "As fotos de demonstração não têm arquivo no disco, então não podem ser movidas",
|
||||
"Add to Selected Photos": "Adicionar às fotos selecionadas",
|
||||
"Add to Target Album": "Adicionar ao álbum de destino",
|
||||
"Add to this mask": "Adicionar a esta máscara",
|
||||
@@ -2317,6 +2318,14 @@
|
||||
"Welcome": "Bem-vindo",
|
||||
"Next": "Próximo",
|
||||
"Get Started": "Começar",
|
||||
"Can't add to an album folder": "Não é possível adicionar a uma pasta de álbuns",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "Uma pasta de álbuns contém álbuns, não fotos: solte em um álbum dentro dela",
|
||||
"Can't add to a smart album": "Não é possível adicionar a um álbum inteligente",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "As regras de um álbum inteligente escolhem suas fotos: altere-as com Editar álbum inteligente…",
|
||||
"Add keywords in the Keyword List": "Adicione palavras-chave na Lista de palavras-chave",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Para dar uma palavra-chave às fotos, use a Lista de palavras-chave (Janela → Palavras-chave, K): solte-as lá sobre ela",
|
||||
"Already on these photos": "Já estão nestas fotos",
|
||||
"Can't go inside itself": "Não pode ficar dentro de si mesma",
|
||||
"Same Content as Another Photo": "Mesmo conteúdo que outra foto",
|
||||
"Reduce Motion": "Reduzir movimento",
|
||||
"Reduce motion": "Reduzir movimento",
|
||||
|
||||
@@ -306,10 +306,10 @@
|
||||
"{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}: слияние добавлено в размере {mp}: для полного размера ({full}) не хватает памяти этого компьютера",
|
||||
"{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}: слияние добавлено в размере {mp} — это наибольший размер панорамы (полный размер: {full})",
|
||||
"Already in “{}”": "Уже в «{}»",
|
||||
"Move {n} photo{} to “{}”": "Переместить в «{1}» фото: {n}{0:.0}",
|
||||
"Move {n} photo{} to “{}”?": "Переместить в «{1}» фото: {n}{0:.0}?",
|
||||
"Move {n} file{} to “{}”": "Переместить в «{1}» файлов: {n}{0:.0}",
|
||||
"Move {n} file{} to “{}”?": "Переместить в «{1}» файлов: {n}{0:.0}?",
|
||||
"Listing folders — folders: {folders}, files: {files}": "Просмотр папок — папок: {folders}, файлов: {files}",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено фото: {n}{0:.0}. Правка → Отменить вернёт их.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "В «{1}» перемещено файлов: {n}{0:.0}. Правка → Отменить вернёт их.",
|
||||
"Drop to review {n} item{} for import": "Отпустите для проверки перед импортом (элементов: {n}){:.0}",
|
||||
"Drop to import {n} item{}": "Отпустите для импорта (элементов: {n}){:.0}",
|
||||
"Drop to import {n} preset{}": "Отпустите для импорта пресетов: {n}{:.0}",
|
||||
@@ -329,6 +329,9 @@
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "Фотографии добавляются через Файл › Импорт фото… ({keys}).",
|
||||
"View › Detail View ({keys}).": "Вид › Режим детализации ({keys}).",
|
||||
"File › Export… · File › Print… ({keys}).": "Файл › Экспорт… · Файл › Печать… ({keys}).",
|
||||
"Add {n} photo{} to “{}”": "Добавить в «{1}» фото: {n}{0:.0}",
|
||||
"{n} already there": "{n} уже там",
|
||||
"Add “{keyword}” to {n} photo{}": "Добавить «{keyword}» к фото: {n}{:.0}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Условие {n} из {m}: {what}. Перемещение стрелками",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Группа {n} из {m}: совпадение {mode}, внутри {count}. Перемещение стрелками",
|
||||
", rating {} of 5": ", оценка: {} из 5"
|
||||
|
||||
@@ -221,6 +221,7 @@
|
||||
"Import photos with File → Import Photos…, or drop them here": "Импортируйте фото через Файл → Импорт фото… или перетащите их сюда",
|
||||
"This row covers more than one disk: drop on a folder inside it": "Эта строка охватывает несколько дисков: перетащите на папку внутри неё",
|
||||
"Local photos aren't in the library yet: Add to My Photos first, then move them": "Локальных фото ещё нет в библиотеке: сначала «Добавить в «Мои фото»», затем перемещайте",
|
||||
"Demo photos have no file on disk, so they can't be moved": "У демонстрационных фото нет файла на диске, поэтому их нельзя переместить",
|
||||
"Add to Selected Photos": "Добавить к выбранным фото",
|
||||
"Add to Target Album": "Добавить в целевой альбом",
|
||||
"Add to this mask": "Добавить к этой маске",
|
||||
@@ -2679,6 +2680,14 @@
|
||||
"Welcome": "Добро пожаловать",
|
||||
"Next": "Далее",
|
||||
"Get Started": "Начать",
|
||||
"Can't add to an album folder": "Нельзя добавить в папку альбомов",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "В папке альбомов лежат альбомы, а не фото: бросьте на альбом внутри неё",
|
||||
"Can't add to a smart album": "Нельзя добавить в смарт-альбом",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "Фото смарт-альбома определяются его правилами: измените их через «Изменить смарт-альбом…»",
|
||||
"Add keywords in the Keyword List": "Добавляйте ключевые слова в списке ключевых слов",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Чтобы задать фото ключевое слово, используйте список ключевых слов (Окно → Ключевые слова, K): бросьте фото там на нужное слово",
|
||||
"Already on these photos": "Уже есть у этих фото",
|
||||
"Can't go inside itself": "Нельзя поместить внутрь себя",
|
||||
"Same Content as Another Photo": "То же содержимое, что у другого фото",
|
||||
"Reduce Motion": "Уменьшить движение",
|
||||
"Reduce motion": "Уменьшить движение",
|
||||
|
||||
@@ -299,9 +299,9 @@
|
||||
"…and {more} more": "…och {more} till",
|
||||
"Already in “{}”": "Already in “{}”",
|
||||
"Color space: Rec. 2020 {curve} (HDR AVIF)": "Color space: Rec. 2020 {curve} (HDR AVIF)",
|
||||
"Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”",
|
||||
"Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.",
|
||||
"Move {n} file{} to “{}”": "Move {n} file{} to “{}”",
|
||||
"Move {n} file{} to “{}”?": "Move {n} file{} to “{}”?",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Moved {n} file{} to “{}”. Edit → Undo moves them back.",
|
||||
"{n} selected photos · {pages} pages": "{n} selected photos · {pages} pages",
|
||||
"{in_trash} catalog photos are in this library's Recently Deleted and stay there; restore them from Recently Deleted to see them.": "{in_trash} katalogfoton finns i Nyligen raderade i det här biblioteket och ligger kvar där; återställ dem från Nyligen raderade för att se dem.",
|
||||
"{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} catalog images were not imported because their records in the catalog are incomplete.",
|
||||
@@ -328,6 +328,9 @@
|
||||
"File › Export… · File › Print… ({keys}).": "Fil › Exportera… · Fil › Skriv ut… ({keys}).",
|
||||
"{n} folder{} could not be read": "Mappar som inte gick att läsa: {n}{:.0}",
|
||||
"{n} file{} skipped (not a supported photo type)": "Hoppade över filer (fotoformat som inte stöds): {n}{:.0}",
|
||||
"Add {n} photo{} to “{}”": "Lägg till foton i ”{1}”: {n}{0:.0}",
|
||||
"Add “{keyword}” to {n} photo{}": "Lägg till ”{keyword}” på foton: {n}{:.0}",
|
||||
"{n} already there": "redan i albumet: {n}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Regel {n} av {m}: {what}. Flytta med piltangenterna",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Grupp {n} av {m}: matcha {mode}, antal i gruppen: {count}. Flytta med piltangenterna",
|
||||
", rating {} of 5": ", betyg: {} av 5"
|
||||
|
||||
@@ -2533,6 +2533,15 @@
|
||||
"Filter settings": "Filtrera inställningar",
|
||||
"No setting matches what is typed.": "Ingen inställning matchar det som skrivits.",
|
||||
"Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Prova ett ord eller en del av ett: namnen på flikar och avsnitt, etiketter och förklaringar genomsöks.",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "Ett smart albums regler väljer dess foton: ändra dem med Redigera smart album…",
|
||||
"Add keywords in the Keyword List": "Lägg till nyckelord i nyckelordslistan",
|
||||
"Already on these photos": "Finns redan på de här fotona",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "En albummapp innehåller album, inte foton: släpp på ett album i den",
|
||||
"Can't add to a smart album": "Kan inte läggas till i ett smart album",
|
||||
"Can't add to an album folder": "Kan inte läggas till i en albummapp",
|
||||
"Can't go inside itself": "Kan inte läggas inuti sig själv",
|
||||
"Demo photos have no file on disk, so they can't be moved": "Demofoton har ingen fil på disken och kan därför inte flyttas",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Ge foton ett nyckelord i nyckelordslistan (Fönster → Nyckelord, K): släpp dem på det där",
|
||||
"Same Content as Another Photo": "Samma innehåll som ett annat foto",
|
||||
"Reduce Motion": "Minska rörelse",
|
||||
"Reduce motion": "Minska rörelse",
|
||||
|
||||
@@ -306,10 +306,10 @@
|
||||
"{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what}: об’єднання додано в розмірі {mp}: для повного розміру ({full}) бракує пам’яті цього комп’ютера",
|
||||
"{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what}: об’єднання додано в розмірі {mp} — це найбільший розмір панорами (повний розмір: {full})",
|
||||
"Already in “{}”": "Уже в «{}»",
|
||||
"Move {n} photo{} to “{}”": "Перемістити до «{1}» фото: {n}{0:.0}",
|
||||
"Move {n} photo{} to “{}”?": "Перемістити до «{1}» фото: {n}{0:.0}?",
|
||||
"Move {n} file{} to “{}”": "Перемістити до «{1}» файлів: {n}{0:.0}",
|
||||
"Move {n} file{} to “{}”?": "Перемістити до «{1}» файлів: {n}{0:.0}?",
|
||||
"Listing folders — folders: {folders}, files: {files}": "Перегляд тек — тек: {folders}, файлів: {files}",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено фото: {n}{0:.0}. Редагування → Скасувати поверне їх.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "До «{1}» переміщено файлів: {n}{0:.0}. Редагування → Скасувати поверне їх.",
|
||||
"Drop to review {n} item{} for import": "Відпустіть для перегляду перед імпортом (елементів: {n}){:.0}",
|
||||
"Drop to import {n} item{}": "Відпустіть для імпорту (елементів: {n}){:.0}",
|
||||
"Drop to import {n} preset{}": "Відпустіть для імпорту наборів налаштувань: {n}{:.0}",
|
||||
@@ -329,6 +329,9 @@
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "Фотографії імпортуйте через Файл › Імпортувати фото… ({keys}).",
|
||||
"View › Detail View ({keys}).": "Вигляд › Детальне подання ({keys}).",
|
||||
"File › Export… · File › Print… ({keys}).": "Файл › Експортувати… · Файл › Друк… ({keys}).",
|
||||
"Add {n} photo{} to “{}”": "Додати до «{1}» фото: {n}{0:.0}",
|
||||
"{n} already there": "{n} уже там",
|
||||
"Add “{keyword}” to {n} photo{}": "Додати «{keyword}» до фото: {n}{:.0}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Правило {n} з {m}: {what}. Переміщення стрілками",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Група {n} з {m}: збіг {mode}, усередині {count}. Переміщення стрілками",
|
||||
", rating {} of 5": ", оцінка: {} з 5"
|
||||
|
||||
@@ -398,6 +398,7 @@
|
||||
"Can't be moved here": "Сюди перемістити не можна",
|
||||
"This row covers more than one disk: drop on a folder inside it": "Цей рядок охоплює кілька дисків: перетягніть на теку всередині нього",
|
||||
"Local photos aren't in the library yet: Add to My Photos first, then move them": "Локальних фото ще немає в бібліотеці: спершу «Додати до моїх фото», потім переміщуйте",
|
||||
"Demo photos have no file on disk, so they can't be moved": "Демонстраційні фото не мають файлу на диску, тому їх не можна перемістити",
|
||||
"Add to Selected Photos": "Додати до вибраних фото",
|
||||
"Add to Target Album": "Додати до цільового альбому",
|
||||
"Add to this mask": "Додати до цієї маски",
|
||||
@@ -2469,6 +2470,14 @@
|
||||
"Welcome": "Ласкаво просимо",
|
||||
"Next": "Далі",
|
||||
"Get Started": "Почати",
|
||||
"Can't add to an album folder": "Не можна додати до теки альбомів",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "У теці альбомів лежать альбоми, а не фото: киньте на альбом усередині неї",
|
||||
"Can't add to a smart album": "Не можна додати до смарт-альбому",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "Фото смарт-альбому визначаються його правилами: змініть їх через «Редагувати смарт-альбом…»",
|
||||
"Add keywords in the Keyword List": "Додавайте ключові слова у списку ключових слів",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Щоб задати фото ключове слово, скористайтеся списком ключових слів (Вікно → Ключові слова, K): киньте фото там на потрібне слово",
|
||||
"Already on these photos": "Уже є в цих фото",
|
||||
"Can't go inside itself": "Не можна помістити всередину себе",
|
||||
"Same Content as Another Photo": "Той самий вміст, що й в іншого фото",
|
||||
"Reduce Motion": "Зменшити рух",
|
||||
"Reduce motion": "Зменшити рух",
|
||||
|
||||
@@ -130,10 +130,10 @@
|
||||
"Making the denoised picture… {}%": "Đang tạo ảnh đã khử nhiễu… {}%",
|
||||
"Matches: {}": "Khớp: {}",
|
||||
"Merging… {stage} {:.0}%": "Đang ghép… {stage} {:.0}%",
|
||||
"Move {n} photo{} to “{}”": "Move {n} photo{} to “{}”",
|
||||
"Move {n} photo{} to “{}”?": "Move {n} photo{} to “{}”?",
|
||||
"Move {n} file{} to “{}”": "Move {n} file{} to “{}”",
|
||||
"Move {n} file{} to “{}”?": "Move {n} file{} to “{}”?",
|
||||
"Move {what} to Recently Deleted?": "Chuyển {what} vào Đã xóa gần đây?",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "Moved {n} photo{} to “{}”. Edit → Undo moves them back.",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "Moved {n} file{} to “{}”. Edit → Undo moves them back.",
|
||||
"Moved {} photo(s)": "Đã di chuyển {} ảnh",
|
||||
"Moved; {} photo(s) relinked": "Đã di chuyển; liên kết lại {} ảnh",
|
||||
"Named ({named_n})": "Có tên ({named_n})",
|
||||
@@ -325,6 +325,9 @@
|
||||
"File › Export… · File › Print… ({keys}).": "Tệp › Xuất… · Tệp › In… ({keys}).",
|
||||
"{n} folder{} could not be read": "Thư mục không đọc được: {n}{:.0}",
|
||||
"{n} file{} skipped (not a supported photo type)": "Đã bỏ qua tệp (không phải loại ảnh được hỗ trợ): {n}{:.0}",
|
||||
"Add {n} photo{} to “{}”": "Thêm {n} ảnh{0:.0} vào “{1}”",
|
||||
"Add “{keyword}” to {n} photo{}": "Thêm “{keyword}” vào {n} ảnh{:.0}",
|
||||
"{n} already there": "{n} đã có sẵn",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "Quy tắc {n}/{m}: {what}. Di chuyển bằng phím mũi tên",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "Nhóm {n}/{m}: khớp {mode}, bên trong: {count}. Di chuyển bằng phím mũi tên",
|
||||
", rating {} of 5": ", xếp hạng: {} trên 5"
|
||||
|
||||
@@ -2757,6 +2757,15 @@
|
||||
"Filter settings": "Lọc cài đặt",
|
||||
"No setting matches what is typed.": "Không có cài đặt nào khớp với nội dung đã nhập.",
|
||||
"Try one word, or part of one: the names of tabs and sections, labels and explanations are all looked through.": "Hãy thử một từ hoặc một phần của từ: tên các tab và mục, nhãn và phần giải thích đều được tìm.",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "Quy tắc của album thông minh chọn ảnh của nó: thay đổi bằng Chỉnh sửa album thông minh…",
|
||||
"Add keywords in the Keyword List": "Thêm từ khóa trong Danh sách từ khóa",
|
||||
"Already on these photos": "Đã có trên các ảnh này",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "Thư mục album chứa album, không chứa ảnh: hãy thả vào một album bên trong nó",
|
||||
"Can't add to a smart album": "Không thể thêm vào album thông minh",
|
||||
"Can't add to an album folder": "Không thể thêm vào thư mục album",
|
||||
"Can't go inside itself": "Không thể đặt vào chính nó",
|
||||
"Demo photos have no file on disk, so they can't be moved": "Ảnh demo không có tệp trên đĩa nên không thể di chuyển",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "Gán từ khóa cho ảnh trong Danh sách từ khóa (Cửa sổ → Từ khóa, K): hãy thả ảnh lên từ khóa ở đó",
|
||||
"Same Content as Another Photo": "Cùng nội dung với ảnh khác",
|
||||
"Reduce Motion": "Giảm chuyển động",
|
||||
"Reduce motion": "Giảm chuyển động",
|
||||
|
||||
@@ -44,10 +44,10 @@
|
||||
"LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraft 无法打开窗口:{e}\n\n详细信息见日志文件:{path}",
|
||||
"Matches: {}": "匹配项:{0}",
|
||||
"Merging… {stage} {:.0}%": "合成中… {stage} {0:.0}%",
|
||||
"Move {n} photo{} to “{}”": "将 {n} 张照片移到“{1}”{0:.0}",
|
||||
"Move {n} photo{} to “{}”?": "将 {n} 张照片移到“{1}”?{0:.0}",
|
||||
"Move {n} file{} to “{}”": "将 {n} 个文件移到“{1}”{0:.0}",
|
||||
"Move {n} file{} to “{}”?": "将 {n} 个文件移到“{1}”?{0:.0}",
|
||||
"Move {what} to Recently Deleted?": "将 {what} 移到最近删除?",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "已将 {n} 张照片移到“{1}”{0:.0}。编辑 → 撤销 可移回。",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "已将 {n} 个文件移到“{1}”{0:.0}。编辑 → 撤销 可移回。",
|
||||
"Named ({named_n})": "已命名({named_n})",
|
||||
"Paste into {n} photo{} — only settings that were copied are pasted": "粘贴到 {n} 张照片 — 仅粘贴已复制的设置{0:.0}",
|
||||
"Preset: {name}": "预设:{name}",
|
||||
@@ -329,6 +329,9 @@
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "通过 文件 › 导入照片… ({keys}) 导入照片。",
|
||||
"View › Detail View ({keys}).": "视图 › 详细视图 ({keys})。",
|
||||
"File › Export… · File › Print… ({keys}).": "文件 › 导出… · 文件 › 打印… ({keys})。",
|
||||
"Add {n} photo{} to “{}”": "将 {n} 张照片添加到“{1}”{0:.0}",
|
||||
"{n} already there": "{n} 张已在其中",
|
||||
"Add “{keyword}” to {n} photo{}": "将“{keyword}”添加到 {n} 张照片{:.0}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "规则 {n}/{m}:{what}。用方向键移动",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "组 {n}/{m}:匹配{mode},内含 {count} 项。用方向键移动",
|
||||
", rating {} of 5": ",评分:{}/5"
|
||||
|
||||
@@ -47,6 +47,7 @@
|
||||
"Import photos with File → Import Photos…, or drop them here": "使用“文件 → 导入照片…”导入照片,或将照片拖放到此处",
|
||||
"This row covers more than one disk: drop on a folder inside it": "此行涵盖多个磁盘:请拖放到其中的文件夹",
|
||||
"Local photos aren't in the library yet: Add to My Photos first, then move them": "本地照片尚未在图库中:请先“添加到我的照片”,再移动",
|
||||
"Demo photos have no file on disk, so they can't be moved": "演示照片在磁盘上没有文件,因此无法移动",
|
||||
"Add to Selected Photos": "添加到所选照片",
|
||||
"Add to Target Album": "添加到目标相册",
|
||||
"Add to this mask": "添加到此蒙版",
|
||||
@@ -2472,6 +2473,14 @@
|
||||
"Welcome": "欢迎",
|
||||
"Next": "下一步",
|
||||
"Get Started": "开始使用",
|
||||
"Can't add to an album folder": "无法添加到相册文件夹",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "相册文件夹里放的是相册,不是照片:请拖到其中的某个相册上",
|
||||
"Can't add to a smart album": "无法添加到智能相册",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "智能相册的照片由其规则决定:请用“编辑智能相册…”更改规则",
|
||||
"Add keywords in the Keyword List": "请在关键字列表中添加关键字",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "要给照片添加关键字,请使用关键字列表(窗口 → 关键字,K),把照片拖到那里的关键字上",
|
||||
"Already on these photos": "这些照片已有",
|
||||
"Can't go inside itself": "不能放入自身",
|
||||
"Same Content as Another Photo": "与另一张照片内容相同",
|
||||
"Reduce Motion": "减少动态效果",
|
||||
"Reduce motion": "减少动态效果",
|
||||
|
||||
@@ -58,10 +58,10 @@
|
||||
"LightCraft could not open its window: {e}\n\nThe log file has the details: {path}": "LightCraft 無法開啟視窗:{e}\n\n詳細資訊請見記錄檔:{path}",
|
||||
"Matches: {}": "符合條件:{}",
|
||||
"Merging… {stage} {:.0}%": "正在合併… {stage} {:.0}%",
|
||||
"Move {n} photo{} to “{}”": "將 {n} 張照片移到「{1}」{0:.0}",
|
||||
"Move {n} photo{} to “{}”?": "將 {n} 張照片移到「{1}」?{0:.0}",
|
||||
"Move {n} file{} to “{}”": "將 {n} 個檔案移到「{1}」{0:.0}",
|
||||
"Move {n} file{} to “{}”?": "將 {n} 個檔案移到「{1}」?{0:.0}",
|
||||
"Move {what} to Recently Deleted?": "要將{what}移至「最近刪除」嗎?",
|
||||
"Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "已將 {n} 張照片移到「{1}」{0:.0}。編輯 → 復原 可移回。",
|
||||
"Moved {n} file{} to “{}”. Edit → Undo moves them back.": "已將 {n} 個檔案移到「{1}」{0:.0}。編輯 → 復原 可移回。",
|
||||
"Named ({named_n})": "已命名({named_n})",
|
||||
"Paste into {n} photo{} — only settings that were copied are pasted": "貼上至 {n} 張照片{:.0} — 只貼上已複製的設定",
|
||||
"Preset: {name}": "預設集:{name}",
|
||||
@@ -329,6 +329,9 @@
|
||||
"Bring photos in with File › Import Photos… ({keys}).": "透過 檔案 › 匯入照片… ({keys}) 匯入照片。",
|
||||
"View › Detail View ({keys}).": "檢視 › 詳細檢視 ({keys})。",
|
||||
"File › Export… · File › Print… ({keys}).": "檔案 › 匯出… · 檔案 › 列印… ({keys})。",
|
||||
"Add {n} photo{} to “{}”": "將 {n} 張照片加入「{1}」{0:.0}",
|
||||
"{n} already there": "{n} 張已在其中",
|
||||
"Add “{keyword}” to {n} photo{}": "將「{keyword}」加入 {n} 張照片{:.0}",
|
||||
"Rule {n} of {m}: {what}. Move with the arrow keys": "規則 {n}/{m}:{what}。用方向鍵移動",
|
||||
"Group {n} of {m}: match {mode}, {count} inside. Move with the arrow keys": "群組 {n}/{m}:符合{mode},內含 {count} 項。用方向鍵移動",
|
||||
", rating {} of 5": ",評分:{}/5"
|
||||
|
||||
@@ -47,6 +47,7 @@
|
||||
"Import photos with File → Import Photos…, or drop them here": "使用「檔案 → 匯入照片…」,或將照片拖放至此",
|
||||
"This row covers more than one disk: drop on a folder inside it": "此列涵蓋多個磁碟:請拖放到其中的資料夾",
|
||||
"Local photos aren't in the library yet: Add to My Photos first, then move them": "本機照片尚未在照片庫中:請先「加入我的照片」,再移動",
|
||||
"Demo photos have no file on disk, so they can't be moved": "示範照片在磁碟上沒有檔案,因此無法移動",
|
||||
"Add to Selected Photos": "加入選取的照片",
|
||||
"Add to Target Album": "加入目標相簿",
|
||||
"Add to this mask": "加入此遮色片",
|
||||
@@ -2473,6 +2474,14 @@
|
||||
"Welcome": "歡迎",
|
||||
"Next": "下一步",
|
||||
"Get Started": "開始使用",
|
||||
"Can't add to an album folder": "無法加入相簿資料夾",
|
||||
"An album folder holds albums, not photos: drop on an album inside it": "相簿資料夾裡放的是相簿,不是照片:請拖到其中的某個相簿上",
|
||||
"Can't add to a smart album": "無法加入智慧型相簿",
|
||||
"A smart album's rules choose its photos: change them with Edit Smart Album…": "智慧型相簿的照片由其規則決定:請用「編輯智慧型相簿…」變更規則",
|
||||
"Add keywords in the Keyword List": "請在關鍵字清單中加入關鍵字",
|
||||
"Give photos a keyword in the Keyword List (Window → Keywords, K): drop them on it there": "要替照片加入關鍵字,請使用關鍵字清單(視窗 → 關鍵字,K),把照片拖到那裡的關鍵字上",
|
||||
"Already on these photos": "這些照片已有",
|
||||
"Can't go inside itself": "不能放入自身",
|
||||
"Same Content as Another Photo": "與另一張照片內容相同",
|
||||
"Reduce Motion": "減少動態效果",
|
||||
"Reduce motion": "減少動態效果",
|
||||
|
||||
@@ -70,6 +70,7 @@ impl LightcraftApp {
|
||||
#[cfg(test)]
|
||||
missing_count_test_delay: None,
|
||||
shadow: None,
|
||||
drawing_offscreen: false,
|
||||
synthetic: vec![],
|
||||
pointer_cleanup: false,
|
||||
drop_hover: vec![],
|
||||
@@ -212,6 +213,9 @@ impl LightcraftApp {
|
||||
// UI passes still counts as changed)
|
||||
self.selection_changes();
|
||||
let r = self.run_command(id, params);
|
||||
// the panel a command left on show is noted now, not at the next frame, success or not: the next command
|
||||
// of the same frame (a script, queued shortcuts) sees it (Close Panel, B, Done = the column stays hidden)
|
||||
self.ui.note_right();
|
||||
self.selection_changes();
|
||||
r
|
||||
}
|
||||
@@ -710,6 +714,31 @@ impl LightcraftApp {
|
||||
self.perf.max_update_ms = self.perf.max_update_ms.max(self.perf.update_ms);
|
||||
}
|
||||
|
||||
/// Ends drags that must not go on, before any panel or dialog sees the frame: Esc gives up a
|
||||
/// drag and is taken, so a dialog open over it doesn't also close; and a drag outlives its
|
||||
/// button in no layout (full screen and the slideshow don't run the panels that end it).
|
||||
/// The frame a button is released in is left to the drop targets, except in full screen, which has none.
|
||||
fn end_drags(&mut self, ctx: &egui::Context) {
|
||||
if self.drawing_offscreen || !self.ui.drag_active() {
|
||||
return;
|
||||
}
|
||||
let (esc, down, released) = ctx.input(|i| (i.key_pressed(egui::Key::Escape), i.pointer.any_down(), i.pointer.any_released()));
|
||||
// a release is left to the drop targets, except in full screen, where there are none: the
|
||||
// drag ends on that frame, so an Esc on the next one can't find it still going
|
||||
if !esc && (down || (released && !self.ui.fullscreen)) {
|
||||
return;
|
||||
}
|
||||
if esc {
|
||||
widgets::take_escape(ctx);
|
||||
}
|
||||
if self.ui.dragging_album.take().is_some() {
|
||||
panels::left::forget_hover(self, ctx);
|
||||
}
|
||||
self.ui.dragging_photos = None;
|
||||
self.ui.dragging_section = None;
|
||||
self.ui.dragging_keyword = None;
|
||||
}
|
||||
|
||||
/// Lay out the whole window: input/setup for the known UI phase, then presentation, then the
|
||||
/// frame bookkeeping. A hidden `run_logic` never reaches this.
|
||||
pub fn ui(&mut self, ui: &mut egui::Ui) {
|
||||
|
||||
@@ -437,8 +437,11 @@ impl LightcraftApp {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
self.library_changed(&ctx);
|
||||
// (a tool panel opened some other way still remembers the panel it took the place of)
|
||||
self.ui.note_right();
|
||||
// panels set it again this frame while the pointer rests on a preset or profile
|
||||
self.hover_preview = None;
|
||||
self.end_drags(&ctx);
|
||||
if self.ui.fullscreen {
|
||||
// full-screen preview: the photo alone on black
|
||||
egui::CentralPanel::default()
|
||||
@@ -491,10 +494,13 @@ impl LightcraftApp {
|
||||
panels::activity::show(self, &ctx);
|
||||
export_task::poll_photos(self, &ctx);
|
||||
pick::poll(self, &ctx);
|
||||
panels::grid::drag_feedback(self, &ctx);
|
||||
panels::left::album_drag_feedback(self, &ctx);
|
||||
panels::left::section_drag_feedback(self, &ctx);
|
||||
panels::keyword_list::drag_feedback(self, &ctx);
|
||||
// (each ends its drag when the button is up, which an offscreen frame's pointer never is)
|
||||
if !self.drawing_offscreen {
|
||||
panels::grid::drag_feedback(self, &ctx);
|
||||
panels::left::album_drag_feedback(self, &ctx);
|
||||
panels::left::section_drag_feedback(self, &ctx);
|
||||
panels::keyword_list::drag_feedback(self, &ctx);
|
||||
}
|
||||
panels::toast(self, &ctx);
|
||||
drop_overlay::show(self, &ctx);
|
||||
// AppKit moves the window on a drag anywhere in the title-bar band unless the window isn't
|
||||
|
||||
@@ -267,7 +267,9 @@ impl LightcraftApp {
|
||||
// same scroll offsets, open sections, style… as the window
|
||||
let memory = main.memory(|m| m.clone());
|
||||
view.ctx.memory_mut(|m| *m = memory);
|
||||
self.drawing_offscreen = true;
|
||||
view.run(headless::HeadlessView::raw_input(size, ppp, time, vec![]), |ui| self.draw_window(ui));
|
||||
self.drawing_offscreen = false;
|
||||
let img = capture.then(|| {
|
||||
let mut tex = self.renderer.cpu_textures();
|
||||
if let (Some((t, ..)), Some(px)) = (&self.merge.preview, &self.merge.preview_pixels) {
|
||||
|
||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user