LR-LIB-PEOPLE: the image's own size decides, and its orientation is found past the first MiB (#2674)

From CodeRabbit's review of #2857:

- Import: when the file's orientation swaps the axes and the XMP's boxes were
  drawn on a stated size, the probe turns the boxes as written by the image
  header's stored size, not by a size the metadata states (missing, or
  written for the upright photo).
- Read Metadata from File and Synchronize Folder: the file's orientation is
  read from its first MiB and, when that part states none, from the rest of
  the file. WebP keeps its EXIF chunk after the image data, many TIFF
  writers put the first IFD after the strips, and a JPEG's Exif can follow
  other long segments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016TuX1qw9ieyuJ1ZFrrUxzc
This commit is contained in:
insideTheFlux
2026-10-24 18:01:25 -07:00
co-authored by Claude Opus 5.5
parent 30780eb9a8
commit e69f8b160d
4 changed files with 91 additions and 17 deletions
+7 -6
View File
@@ -198,15 +198,16 @@ 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` turned them upright where the metadata says how
// big the photo is; otherwise the header does (#2674)
// 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 (m.width.is_none() || m.height.is_none())
&& o.swaps_axes()
if o.swaps_axes()
&& !meta.regions.is_empty()
&& let Some(drawn_on) =
lightcraft_meta::embedded(bytes).xmp.and_then(|x| lightcraft_meta::parse_xmp(&x).ok()).and_then(|x| x.regions_drawn_on())
&& 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() {
+57 -7
View File
@@ -359,20 +359,33 @@ impl SidecarData {
/// 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 start of the file read.
/// 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;
}
let mut head = Vec::new();
let read = std::fs::File::open(original).and_then(|f| f.take(ORIENTATION_SPAN).read_to_end(&mut head));
let orientation = read.ok().and_then(|_| lightcraft_meta::extract(&head).orientation);
SidecarData { orientation: orientation.or(self.orientation), ..self }
SidecarData { orientation: file_orientation(original).or(self.orientation), ..self }
}
}
/// How much of a photo file [`SidecarData::with_file_orientation`] reads: Exif sits at the start of every format
/// LightCraft reads.
/// The orientation the photo file at `path` states. Most files state it in their first [`ORIENTATION_SPAN`]; when
/// that part doesn't, the rest is read too: WebP keeps its EXIF chunk after the image data, many TIFF writers put the
/// first IFD after the strips, and a JPEG's Exif can follow other long segments.
fn file_orientation(path: &str) -> Option<lightcraft_meta::Orientation> {
let mut file = std::fs::File::open(path).ok()?;
let mut bytes = Vec::new();
(&mut file).take(ORIENTATION_SPAN).read_to_end(&mut bytes).ok()?;
if let Some(o) = lightcraft_meta::extract(&bytes).orientation {
return Some(o);
}
if (bytes.len() as u64) < ORIENTATION_SPAN {
return None;
}
file.read_to_end(&mut bytes).ok()?;
lightcraft_meta::extract(&bytes).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
@@ -975,6 +988,43 @@ impl Session {
#[cfg(test)]
mod tests {
/// Issue #2674: a WebP keeps its EXIF chunk after the image data, so its 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;
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),
] {
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()));
+24 -2
View File
@@ -495,6 +495,18 @@ fn write_turned_jpeg(path: &Path, packet: Option<&str>) {
std::fs::write(path, bytes).unwrap();
}
/// Put more than the first MiB of APP15 segments between the JPEG at `path`'s start and its Exif.
fn pad_before_exif(path: &Path) {
let bytes = std::fs::read(path).unwrap();
let mut padded = bytes[..2].to_vec();
for _ in 0..17 {
padded.extend_from_slice(&[0xFF, 0xEF, 0xFF, 0xFF]);
padded.extend(std::iter::repeat_n(0, 0xFFFD));
}
padded.extend_from_slice(&bytes[2..]);
std::fs::write(path, padded).unwrap();
}
/// The face's box from [`STORED_FRAME_REGIONS`] on the upright photo: turned a quarter turn clockwise with it.
fn assert_on_the_upright_face(s: &Session, id: PhotoId, when: &str) {
let p = s.catalog.photo(id).unwrap();
@@ -508,7 +520,8 @@ fn assert_on_the_upright_face(s: &Session, id: PhotoId, when: &str) {
/// Issue #2674: face boxes an app drew on a photo as stored (its sideways size as `AppliedToDimensions`, no
/// `mwg-rs:Rotation`) land on the faces of the photo as LightCraft shows it, upright: when imported, and when the
/// file's metadata is read again (the packet itself doesn't say how the photo turns; the file's Exif does).
/// file's metadata is read again (the packet itself doesn't say how the photo turns; the file's Exif does). The
/// image's own size decides, not one the XMP states upright, and the Exif is found past the first MiB of the file.
#[test]
fn regions_drawn_on_the_photo_as_stored_land_on_the_upright_photo() {
let src = temp_dir("regions-stored-frame");
@@ -517,7 +530,16 @@ fn regions_drawn_on_the_photo_as_stored_land_on_the_upright_photo() {
let beside = src.join("sidecar.jpg");
write_turned_jpeg(&beside, None);
std::fs::write(src.join("sidecar.xmp"), STORED_FRAME_REGIONS).unwrap();
for (file, what) in [(&embedded, "embedded XMP"), (&beside, "sidecar")] {
// an Exif without a pixel size, and an XMP size of the upright photo
let stated = src.join("stated.jpg");
let upright_size = r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:ImageWidth="24" tiff:ImageLength="32""#;
write_turned_jpeg(&stated, Some(&STORED_FRAME_REGIONS.replace(r#"rdf:about="""#, upright_size)));
let late = src.join("late.jpg");
write_turned_jpeg(&late, None);
pad_before_exif(&late);
std::fs::write(src.join("late.xmp"), STORED_FRAME_REGIONS).unwrap();
for (file, what) in [(&embedded, "embedded XMP"), (&beside, "sidecar"), (&stated, "upright size in the XMP"), (&late, "Exif after the first MiB")]
{
let mut s = Session::new().with_fs();
let r = s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap();
assert_eq!(r["imported"].as_array().map(Vec::len), Some(1), "{r}");
+3 -2
View File
@@ -122,8 +122,9 @@ write them, from sidecars and from XMP embedded in the file. Named faces become
taken as written. Other applications mark boxes drawn on the photo as stored only by their size: when
`mwg-rs:AppliedToDimensions` has the shape of the photo as stored rather than upright (a photo that Exif orientation
5–8 turns a quarter turn, and no `mwg-rs:Rotation`), the boxes are turned with the file's own Exif orientation,
mirror included, when imported and when read again (#2674). A square photo or size looks the same both ways and is
taken as written. Boxes follow LightCraft's own Rotate Left/Right and flips.
mirror included, when imported and when read again (#2674). The image's own pixel size decides, not a size the
metadata states, and the orientation is found wherever the file keeps its Exif (WebP after the image data, for
one). A square photo or size looks the same both ways and is taken as written. Boxes follow LightCraft's own Rotate Left/Right and flips.
- **Re-reading**: a sidecar that has `mwg-rs:Regions` — even with an empty list — replaces the photo's regions, so
regions removed in another application go away here too. A sidecar without `mwg-rs:Regions` (an application that
doesn't do regions) leaves the photo's regions as they are.