Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
30780eb
LR-LIB-PEOPLE: face boxes drawn on a photo as stored land on the upri…
insideTheFlux Oct 24, 2026
e69f8b1
LR-LIB-PEOPLE: the image's own size decides, and its orientation is f…
insideTheFlux Oct 25, 2026
4eecf8b
LR-LIB-PEOPLE: find a late orientation by the file's structure, not b…
insideTheFlux Oct 25, 2026
26f73e4
LR-LIB-PEOPLE: a late TIFF orientation is one SHORT; a late WebP one …
insideTheFlux Oct 25, 2026
4e350dc
LR-LIB-PEOPLE: a re-read takes the file's orientation in the import's…
insideTheFlux Oct 25, 2026
64998a1
LR-LIB-PEOPLE: a WebP's EXIF chunk of any size is read by its IFD, an…
insideTheFlux Oct 25, 2026
1c499ca
Merge storytold/main into fix/2674-stored-frame-regions
insideTheFlux Oct 25, 2026
82a45a9
Merge storytold/main into fix/2674-stored-frame-regions
insideTheFlux Oct 26, 2026
8c8c29f
Merge storytold/main into fix/2674-stored-frame-regions
insideTheFlux Oct 27, 2026
772bb82
Merge storytold/main into fix/2674-stored-frame-regions
insideTheFlux Oct 30, 2026
72a074b
LR-LIB-PEOPLE: a size only the XMP states doesn't turn face boxes (#2…
insideTheFlux Oct 31, 2026
a763c3c
LR-LIB-PEOPLE: a re-read finds a PNG's or PSD's orientation past the …
insideTheFlux Oct 31, 2026
8fd4e3b
Merge storytold/main into fix/2674-stored-frame-regions
insideTheFlux Oct 31, 2026
4dd0f71
Merge storytold/main into fix/2674-stored-frame-regions
insideTheFlux Oct 31, 2026
e5f6b02
Merge storytold/main into fix/2674-stored-frame-regions
insideTheFlux Nov 3, 2026
7ff9f15
Merge storytold/main into fix/2674-stored-frame-regions
insideTheFlux Nov 4, 2026
85c1265
LR-LIB-PEOPLE: face boxes turn only by an orientation the Exif states…
insideTheFlux Nov 5, 2026
9fdafc0
Merge storytold/main into fix/2674-stored-frame-regions
insideTheFlux Nov 5, 2026
d372719
Merge storytold/main at eaef01e9
insideTheFlux Nov 5, 2026
8f77982
Merge storytold/main at 61005f3d
insideTheFlux Nov 5, 2026
419373a
LR-LIB-PEOPLE: re-read uses a raw's decoder orientation (#2674, review)
FredApps Nov 5, 2026
eb44185
Merge storytold/main into fix/2674-stored-frame-regions
FredApps Nov 5, 2026
3438a00
style: rustfmt for MEF orientation regression test
FredApps Nov 5, 2026
1a39b60
Merge origin/main into fix/2674-stored-frame-regions
Nov 5, 2026
df79328
Merge origin/main into fix/2674-stored-frame-regions
Nov 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions crates/engine/src/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
as_shot_wb: None,
content_hash,
xmp: lightcraft_meta::embedded(bytes).xmp,
orientation: m.orientation,
preview_only: Some(why),
..Default::default()
});
Expand Down Expand Up @@ -181,6 +182,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
as_shot_wb,
content_hash,
xmp: lightcraft_meta::embedded(bytes).xmp,
orientation: Some(raw.orientation),
preview_only: None,
});
}
Expand All @@ -196,6 +198,18 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
if o.swaps_axes() {
std::mem::swap(&mut w, &mut h);
}
// regions another app drew on the photo as stored: `extract` could only tell by the size the metadata states, which
// can be missing or wrong; the header's is the size as stored, so the boxes as written are turned by it (#2674)
let mut meta = meta;
if o.swaps_axes()
&& !meta.regions.is_empty()
&& let Some(xmp) = lightcraft_meta::embedded(bytes).xmp.and_then(|x| lightcraft_meta::parse_xmp(&x).ok())
&& let Some(drawn_on) = xmp.regions_drawn_on()
&& !xmp.metadata.regions.is_empty()
{
meta.regions = xmp.metadata.regions;
lightcraft_meta::upright_regions(&mut meta.regions, drawn_on, o, (header.width, header.height));
}
let format = match ext_upper(name).as_str() {
"JPG" | "JPEG" => "JPEG".to_string(),
"" => format!("{fmt:?}").to_uppercase(),
Expand All @@ -214,6 +228,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
content_hash,
embedded_lens: None,
xmp: None,
orientation: m.orientation,
preview_only: None,
})
}
Expand Down
2 changes: 2 additions & 0 deletions crates/engine/src/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1461,6 +1461,8 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
}
}
let sidecar = sidecar.map(|sc| sc.resolve_label(&s.catalog)).filter(|sc| *sc != crate::sidecar::SidecarData::default());
// the photo is upright as the file's own orientation turns it, when the file states one
let sidecar = sidecar.map(|sc| crate::sidecar::SidecarData { orientation: info.orientation.or(sc.orientation), ..sc });
// a copy is catalogued under its new name
let name = Path::new(&stored).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.clone());
let mut p = Photo::new(id, Source::File { path: stored }, &name, &info.format, info.width, info.height, &now);
Expand Down
3 changes: 3 additions & 0 deletions crates/engine/src/media.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1744,6 +1744,9 @@ pub struct ProbeInfo {
pub embedded_lens: Option<lightcraft_develop::EmbeddedLens>,
/// The file's embedded XMP packet (raw/DNG files), for develop settings stored inside the file.
pub xmp: Option<String>,
/// The file's Exif orientation, when it states one: how its stored pixels turn upright (`width` and `height` are
/// the upright size).
pub orientation: Option<lightcraft_geom::Orientation>,
/// A raw variant that can't be decoded yet: why. The file is described (and will be shown and
/// edited) from its embedded preview; see [`lightcraft_catalog::Photo::preview_only`].
pub preview_only: Option<String>,
Expand Down
175 changes: 173 additions & 2 deletions crates/engine/src/sidecar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,12 @@ pub struct SidecarData {
pub extended_description: Option<String>,
pub keywords: Option<Vec<String>>,
pub regions: Option<Vec<lightcraft_meta::Region>>,
/// The size the regions were drawn on, when they don't say how the photo was turned
/// ([`lightcraft_meta::XmpData::regions_drawn_on`]), and how the photo's stored pixels turn upright: the
/// sidecar's `tiff:Orientation`, or the file's own Exif orientation where the caller knows it. With both,
/// [`merge_into`] puts boxes drawn on the photo as stored where the upright photo has them (#2674).
pub regions_drawn_on: Option<(f64, f64)>,
pub orientation: Option<lightcraft_meta::Orientation>,
/// Capture time (ISO 8601) from `exif:DateTimeOriginal`, `photoshop:DateCreated` or
/// `xmp:CreateDate` (first found). Used only when the file itself has no capture time.
pub captured: Option<String>,
Expand Down Expand Up @@ -184,6 +190,9 @@ pub fn parse_sidecar(xmp: &str, target: crate::crs::Target) -> std::result::Resu
// `mwg-rs:Regions` byte for byte but never writes one) says nothing about regions, and the
// photo's are kept.
regions: d.values.contains_key("mwg-rs:Regions").then(|| m.regions.clone()),
regions_drawn_on: d.regions_drawn_on(),
// (only what the regions need: a packet that says nothing else still says nothing)
orientation: d.regions_drawn_on().and(m.orientation),
captured: m.capture_time.map(|d| d.to_iso()),
..Default::default()
};
Expand Down Expand Up @@ -313,6 +322,11 @@ pub fn merge_into(p: &mut Photo, sc: &SidecarData, now: &str) -> bool {
}
if let Some(r) = &sc.regions {
m.regions = r.clone();
// (the photo's size is the upright one)
if let (Some(drawn_on), Some(o)) = (sc.regions_drawn_on, sc.orientation) {
let stored = if o.swaps_axes() { (p.height, p.width) } else { (p.width, p.height) };
lightcraft_meta::upright_regions(&mut m.regions, drawn_on, o, stored);
}
}
let develop = match &sc.develop {
Some(DevelopPatch::Full(s)) => (**s).clone(),
Expand Down Expand Up @@ -342,8 +356,95 @@ impl SidecarData {
}
self
}

/// 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`]).
pub fn with_file_orientation(self, original: &str) -> Self {
if self.regions_drawn_on.is_none() {
return self;
}
SidecarData { orientation: file_orientation(original).or(self.orientation), ..self }
}
}

/// The orientation the photo file at `path` states. Most files state it in their first [`ORIENTATION_SPAN`]; when
/// that part doesn't, the Exif may come later ([`late_orientation`]).
fn file_orientation(path: &str) -> Option<lightcraft_meta::Orientation> {
let mut file = std::fs::File::open(path).ok()?;
let mut head = Vec::new();
(&mut file).take(ORIENTATION_SPAN).read_to_end(&mut head).ok()?;
if let Some(o) = lightcraft_meta::extract(&head).orientation {
return Some(o);
}
if (head.len() as u64) < ORIENTATION_SPAN {
return None;
}
late_orientation(&mut file, &head)
}

/// The orientation of a file whose `head` doesn't state it, found by the file's structure without reading its image
/// data: a JPEG's Exif can follow other long segments, WebP keeps its EXIF chunk after the image data, and many TIFF
/// writers put the first IFD after the strips.
fn late_orientation(file: &mut (impl Read + Seek), head: &[u8]) -> Option<lightcraft_meta::Orientation> {
file.rewind().ok()?;
match head.get(..4)? {
[0xff, 0xd8, ..] => read_jpeg_app1(file, JPEG_XMP_HEADER_SPAN, JPEG_XMP_HEADER_STEPS, |s| lightcraft_meta::extract(s).orientation),
b"RIFF" if head.get(8..12) == Some(b"WEBP") => webp_orientation(file),
b"II*\0" => tiff_orientation(file, head, true),
b"MM\0*" => tiff_orientation(file, head, false),
_ => None,
}
}

/// A WebP's orientation from its `EXIF` chunk (at most [`ORIENTATION_SPAN`]), found by walking the chunk headers from
/// the start of `file` (at most [`WEBP_CHUNK_STEPS`]).
fn webp_orientation(file: &mut (impl Read + Seek)) -> Option<lightcraft_meta::Orientation> {
file.seek(SeekFrom::Start(12)).ok()?;
for _ in 0..WEBP_CHUNK_STEPS {
let mut header = [0; 8];
file.read_exact(&mut header).ok()?;
let [a, b, c, d, s0, s1, s2, s3] = header;
let size = u32::from_le_bytes([s0, s1, s2, s3]);
if [a, b, c, d] == *b"EXIF" {
if u64::from(size) > ORIENTATION_SPAN {
return None;
}
let mut chunk = b"RIFF\0\0\0\0WEBP".to_vec();
chunk.extend_from_slice(&header);
(&mut *file).take(u64::from(size)).read_to_end(&mut chunk).ok()?;
return lightcraft_meta::extract(&chunk).orientation;
}
// chunks are padded to an even size
file.seek(SeekFrom::Current(i64::from(size) + i64::from(size & 1))).ok()?;
}
None
}

/// How many chunks [`webp_orientation`] passes over (an animated WebP has one per frame).
const WEBP_CHUNK_STEPS: usize = 4096;

/// A TIFF's orientation from the first IFD that `head` points to, of which only the 12-byte entries are read (at most
/// 65535 of them, under 1 MiB). `le`: little-endian (`II`).
fn tiff_orientation(file: &mut (impl Read + Seek), head: &[u8], le: bool) -> Option<lightcraft_meta::Orientation> {
let u16_of = |b: [u8; 2]| if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) };
let [o0, o1, o2, o3] = <[u8; 4]>::try_from(head.get(4..8)?).ok()?;
let ifd = if le { u32::from_le_bytes([o0, o1, o2, o3]) } else { u32::from_be_bytes([o0, o1, o2, o3]) };
file.seek(SeekFrom::Start(u64::from(ifd))).ok()?;
let mut count = [0; 2];
file.read_exact(&mut count).ok()?;
let mut entries = vec![0; usize::from(u16_of(count)) * 12];
file.read_exact(&mut entries).ok()?;
let orientation = entries.as_chunks::<12>().0.iter().find_map(|&[t0, t1, y0, y1, _, _, _, _, v0, v1, _, _]| {
// tag 274, one SHORT
(u16_of([t0, t1]) == 274 && u16_of([y0, y1]) == 3).then(|| u16_of([v0, v1]))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
})?;
(1..=8).contains(&orientation).then(|| lightcraft_meta::Orientation::from_exif(orientation))
}

/// How much of a photo file [`file_orientation`] reads first.
const ORIENTATION_SPAN: u64 = 1 << 20;

/// The sidecar packet for a photo; the colour label is written by its name in `cat` (custom
/// label names included, as other editors do).
pub fn sidecar_packet(p: &Photo, cat: &lightcraft_catalog::Catalog) -> String {
Expand Down Expand Up @@ -549,6 +650,11 @@ const JPEG_XMP_HEADER_STEPS: usize = 4096;
/// consumes one iteration. Only a complete APP1 payload (at most 65533 bytes) reaches the shared
/// parser, in a single SOI+APP1 wrapper (at most 65539 bytes). This does not validate the whole JPEG.
fn read_jpeg_xmp(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize) -> Option<String> {
read_jpeg_app1(reader, header_span, marker_steps, |segment| lightcraft_meta::jpeg_segments(segment).xmp)
}

/// Like [`read_jpeg_xmp`], stopping at the first APP1 segment (in its SOI+APP1 wrapper) that `pick` finds something in.
fn read_jpeg_app1<T>(reader: &mut (impl Read + Seek), header_span: u64, marker_steps: usize, pick: impl Fn(&[u8]) -> Option<T>) -> Option<T> {
let mut header = reader.take(header_span);
let mut soi = [0; 2];
header.read_exact(&mut soi).ok()?;
Expand Down Expand Up @@ -589,8 +695,8 @@ fn read_jpeg_xmp(reader: &mut (impl Read + Seek), header_span: u64, marker_steps
segment.extend_from_slice(&[0xff, 0xd8, 0xff, 0xe1, hi, lo]);
segment.resize(segment_len, 0);
header.read_exact(segment.get_mut(6..)?).ok()?;
if let Some(xmp) = lightcraft_meta::jpeg_segments(&segment).xmp {
return Some(xmp);
if let Some(found) = pick(&segment) {
return Some(found);
}
}
None
Expand Down Expand Up @@ -832,6 +938,7 @@ impl Session {
let Some(orig) = file_path(p) else { return Ok(None) };
let Some((packet, from)) = read_packet(orig, p.kind, self.sidecar_naming(id)) else { return Ok(None) };
let sc = parse_sidecar(&packet, crate::crs::Target::for_photo(p)).map_err(|e| EngineError::Other(format!("{}: {e}", from.display())))?;
let sc = sc.with_file_orientation(orig);
let mut warnings = sc.warnings.clone();
for warning in &mut warnings {
warning.path = orig.to_string();
Expand Down Expand Up @@ -943,6 +1050,70 @@ impl Session {

#[cfg(test)]
mod tests {
/// Issue #2674: a WebP keeps its EXIF chunk after the image data, and a TIFF's first IFD can follow its strips, so
/// the orientation can be past the first [`super::ORIENTATION_SPAN`] of the file; a file that states none has none.
#[test]
fn the_file_orientation_is_found_after_the_image_data() {
let dir = std::env::temp_dir().join(format!("lightcraft-file-orientation-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let exif = lightcraft_meta::write_exif(&lightcraft_meta::Metadata {
orientation: Some(lightcraft_meta::Orientation::Rotate90),
..Default::default()
});
let webp = |image: usize| {
let mut w = b"RIFF\0\0\0\0WEBP".to_vec();
for (id, data) in [(&b"VP8X"[..], vec![0; 10]), (b"VP8L", vec![0; image]), (b"EXIF", [&b"Exif\0\0"[..], &exif].concat())] {
w.extend_from_slice(id);
w.extend_from_slice(&(data.len() as u32).to_le_bytes());
w.extend_from_slice(&data);
if data.len() % 2 == 1 {
w.push(0);
}
}
w
};
let span = super::ORIENTATION_SPAN as usize;
// a TIFF whose first IFD (orientation 8, then a tag pointing elsewhere) follows `strips` bytes of image data
let tiff = |le: bool, strips: usize| {
let (u16_of, u32_of): (fn(u16) -> [u8; 2], fn(u32) -> [u8; 4]) =
if le { (u16::to_le_bytes, u32::to_le_bytes) } else { (u16::to_be_bytes, u32::to_be_bytes) };
let mut t = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() };
t.extend_from_slice(&u32_of(8 + strips as u32));
t.resize(8 + strips, 0);
t.extend_from_slice(&u16_of(2));
for (tag, kind, count, value) in [(274u16, 3u16, 1u32, [u16_of(8), [0, 0]].concat()), (305, 2, 64, u32_of(4).to_vec())] {
t.extend_from_slice(&u16_of(tag));
t.extend_from_slice(&u16_of(kind));
t.extend_from_slice(&u32_of(count));
t.extend_from_slice(&value);
}
t.extend_from_slice(&[0; 4]);
t
};
// a JPEG whose first MiB is other segments, then the start of its image data: no Exif
let mut jpeg = vec![0xff, 0xd8];
for _ in 0..17 {
jpeg.extend_from_slice(&[0xff, 0xef, 0xff, 0xff]);
jpeg.resize(jpeg.len() + 0xfffd, 0);
}
jpeg.extend_from_slice(&[0xff, 0xda, 0, 2, 0xff, 0xd9]);
for (name, bytes, want) in [
("small.webp", webp(64), Some(lightcraft_meta::Orientation::Rotate90)),
("large.webp", webp(span + 64), Some(lightcraft_meta::Orientation::Rotate90)),
("none.webp", webp(span + 64)[..span + 100].to_vec(), None),
("le.tif", tiff(true, span + 64), Some(lightcraft_meta::Orientation::Rotate270)),
("be.tif", tiff(false, span + 64), Some(lightcraft_meta::Orientation::Rotate270)),
("none.jpg", jpeg, None),
] {
let path = dir.join(name);
std::fs::write(&path, bytes).unwrap();
assert_eq!(super::file_orientation(&path.to_string_lossy()), want, "{name}");
}
assert_eq!(super::file_orientation(&dir.join("missing.webp").to_string_lossy()), None);
std::fs::remove_dir_all(dir).unwrap();
}

#[test]
fn sidecars_are_written_only_beside_an_existing_original() {
let dir = std::env::temp_dir().join(format!("lightcraft-sidecar-local-{}", std::process::id()));
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ fn sidecar_has_news(labels: &Catalog, p: &Photo, naming: SidecarNaming, listing:
}
let Ok(text) = std::fs::read_to_string(&file) else { return false };
let Ok(sc) = crate::sidecar::parse_sidecar(&text, crate::crs::Target::for_photo(p)) else { return false };
let sc = sc.resolve_label(labels);
let sc = sc.with_file_orientation(path).resolve_label(labels);
let mut q = p.clone();
crate::sidecar::merge_into(&mut q, &sc, "");
(q.rating, q.flag, q.label, &q.meta, &q.captured, &q.develop) != (p.rating, p.flag, p.label, &p.meta, &p.captured, &p.develop)
Expand Down Expand Up @@ -801,7 +801,7 @@ fn read_sidecar(path: &str, naming: SidecarNaming, target: crate::crs::Target) -
return Err(format!("{}: too large for an XMP sidecar", file.display()));
}
let text = std::fs::read_to_string(&file).map_err(|e| format!("{}: {e}", file.display()))?;
crate::sidecar::parse_sidecar(&text, target).map_err(|e| format!("{}: {e}", file.display()))
crate::sidecar::parse_sidecar(&text, target).map(|sc| sc.with_file_orientation(path)).map_err(|e| format!("{}: {e}", file.display()))
}

impl SyncCommit {
Expand Down
Loading
Loading