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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ License or the Apache License, Version 2.0. It also includes code from PhotoCraf
Copyright (c) the PhotoCraft contributors. Code inherited from these projects is used here
under the MIT License; the upstream copyright notices are kept in LICENSE and in this file.

Fixes in crates/raw, crates/meta and crates/tiff marked "adapted from craft-libs #<n>" are hand ports
of changes to craft-libs (https://github.com/storytold/craft-libs), the shared libraries LightCraft
moved its decoders and metadata code into, Copyright (c) the ArtCraft Team and the craft-libs
contributors, licensed under the MIT License or the Apache License, Version 2.0, and used here under
the MIT License (LICENSE). Each port's commit names the craft-libs pull request and its author.

The ArtCraft name, wordmark and logos are trademarks of the ArtCraft Team and are not part of
this project. The upstream LightCraft app icon in assets/app-icon/ is covered by its own
licence file (assets/app-icon/LICENSE.txt).
Expand Down
112 changes: 104 additions & 8 deletions crates/meta/src/cr3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,16 @@ fn moov<'a>(bytes: &'a [u8], m: &BoxRef, out: &mut Cr3<'a>, budget: &mut usize)
}
_ => continue,
};
out.cmt[slot] = bytes.get(c.body..c.end);
// the first readable box of a slot wins; a later readable one replaces a damaged one, and a lone
// damaged box still fills the slot (adapted from craft-libs #1080)
let readable = |b: Option<&[u8]>| b.is_some_and(|b| lcc_tiff::Tiff::parse(b).is_ok());
let body = bytes.get(c.body..c.end);
if let Some(kept) = out.cmt.get_mut(slot)
&& !readable(*kept)
&& (kept.is_none() || readable(body))
{
*kept = body;
}
}
}
b"trak" => {
Expand Down Expand Up @@ -351,16 +360,33 @@ fn trak(bytes: &[u8], t: &BoxRef, budget: &mut usize) -> Option<Cr3Track> {
// full box: version/flags, entry count, entries
b"stsd" if be32(body, 4)? > 0 => kind = boxes(bytes, b.body + 8, b.end, budget).first().map(|e| sample_entry(bytes, e, budget)),
// version/flags, sample_size (0 = per-sample table), count, sizes
// A truncated or impossible table denies the track's sample data but never drops the track: a missing
// main track would let the largest-raw selector decode the reduced raw as the photo (adapted from
// craft-libs #1300).
b"stsz" => {
size = match be32(body, 4)? {
0 if be32(body, 8)? > 0 => be32(body, 12),
0 => None,
n if be32(body, 8)? > 0 => Some(n),
let count = be32(body, 8).unwrap_or(0);
size = match be32(body, 4) {
Some(0) if count > 0 && count as usize <= body.len().saturating_sub(12) / 4 => be32(body, 12),
Some(n) if n > 0 && count > 0 && u64::from(n).checked_mul(u64::from(count)).is_some_and(|t| t <= bytes.len() as u64) => Some(n),
_ => None,
}
}
b"co64" => {
offset = match be32(body, 4) {
Some(count) if count > 0 && count as usize <= body.len().saturating_sub(8) / 8 => {
be64(body, 8).and_then(|v| usize::try_from(v).ok())
}
_ => None,
}
}
b"stco" => {
offset = match be32(body, 4) {
Some(count) if count > 0 && count as usize <= body.len().saturating_sub(8) / 4 => {
be32(body, 8).and_then(|v| usize::try_from(v).ok())
}
_ => None,
}
}
b"co64" if be32(body, 4)? > 0 => offset = be64(body, 8).and_then(|v| usize::try_from(v).ok()),
b"stco" if be32(body, 4)? > 0 => offset = be32(body, 8).map(|v| v as usize),
_ => {}
}
}
Expand Down Expand Up @@ -495,11 +521,78 @@ mod tests {
let stbl = [full(b"stsd", &stsd), full(b"stsz", &stsz), full(b"co64", &co64)].concat();
bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &stbl))))
}
/// [`trak`] with one of its sample tables (`stsz`, `co64`, or `stco` in place of `co64`) replaced by `payload`
/// after the full box's version/flags.
fn trak_with_table(entry: Vec<u8>, table: &[u8; 4], payload: &[u8]) -> Vec<u8> {
let mut stsd = 1u32.to_be_bytes().to_vec();
stsd.extend(entry);
let stsz = [0u32, 1, 16].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>();
let mut co64 = 1u32.to_be_bytes().to_vec();
co64.extend(4096u64.to_be_bytes());
let offsets = match table {
b"stco" => full(b"stco", payload),
b"co64" => full(b"co64", payload),
_ => full(b"co64", &co64),
};
let stbl = [full(b"stsd", &stsd), full(b"stsz", if table == b"stsz" { payload } else { &stsz }), offsets].concat();
bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &stbl))))
}

/// craft-libs #1300: a sample table too short for its own count (or with none) denies the track's data but keeps
/// the track, so the largest-raw selector can't fall back to a reduced raw and decode it as the photo.
#[test]
fn a_truncated_sample_table_keeps_the_track_without_data() {
let file = |track: Vec<u8>| {
let mut file = bx(b"ftyp", b"crx crx isom");
file.extend(bx(b"moov", &track));
file.resize(4112, 0);
file
};
let entry = || craw(16, 16, &bx(b"CMP1", &[0xff, 0x10, 0, 0x30]));
let whole = trak_with_table(entry(), b"none", &[]);
assert_eq!(parse_cr3(&file(whole)).unwrap().tracks[0].data, Some((4096, 16)));
let short_count = 3u32.to_be_bytes();
for table in [b"stsz", b"co64", b"stco"] {
for payload in [&[][..], &[0u8; 4][..], &short_count[..], &[0, 0, 0, 0, 0, 0, 0, 9][..]] {
let bytes = file(trak_with_table(entry(), table, payload));
let parsed = parse_cr3(&bytes).unwrap();
assert_eq!(parsed.tracks.len(), 1, "{} {payload:?}: the track is kept", String::from_utf8_lossy(table));
assert!(parsed.tracks[0].data.is_none(), "{} {payload:?}: no data", String::from_utf8_lossy(table));
}
}
// a constant sample size whose count overruns the file
let huge = [64u32, u32::MAX].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>();
let bytes = file(trak_with_table(entry(), b"stsz", &huge));
assert!(parse_cr3(&bytes).unwrap().tracks[0].data.is_none());
}

fn tiff_with(tag: u16, v: lcc_tiff::Value) -> Vec<u8> {
let b = lcc_tiff::IfdBuilder::new().with(tag, v);
lcc_tiff::TiffWriter::new(lcc_tiff::ByteOrder::Little, false).write(&[b]).unwrap()
}

/// craft-libs #1080: a damaged CMT2 gives way to a later readable one, the first readable box stays, and a lone
/// damaged box still fills its slot.
#[test]
fn a_damaged_cmt_box_gives_way_to_a_later_readable_one() {
use lcc_tiff::{Value, tags as t};
let cmt1 = tiff_with(t::MAKE, Value::Ascii("Canon".into()));
let iso = |v: u16| tiff_with(t::ISO_SPEED, Value::Short(vec![v]));
let file = |boxes: &[Vec<u8>]| {
let mut file = bx(b"ftyp", b"crx crx isom");
file.extend(bx(b"moov", &uuid(&CANON_UUID, &boxes.concat())));
file
};
let damaged = bx(b"CMT2", b"not a tiff");
let bytes = file(&[bx(b"CMT1", &cmt1), damaged.clone(), bx(b"CMT2", &iso(800)), bx(b"CMT2", &iso(100))]);
let c = parse_cr3(&bytes).unwrap();
assert_eq!(c.cmt[1], Some(&iso(800)[..]), "the first readable CMT2 is kept");
let bytes = file(&[bx(b"CMT1", &cmt1), damaged]);
let c = parse_cr3(&bytes).unwrap();
assert_eq!(c.cmt[1], Some(&b"not a tiff"[..]), "a lone damaged box still fills its slot");
assert_eq!(c.cmt[0], Some(&cmt1[..]));
}

/// A small synthetic CR3: Canon uuid with CMT1/CMT2/CMT4, a JPEG track, a raw track, XMP.
pub(crate) fn sample() -> Vec<u8> {
use lcc_tiff::{Value, tags as t};
Expand Down Expand Up @@ -731,7 +824,10 @@ mod tests {
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"moov", &bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &stbl))))));
file.resize(512, 0);
assert!(parse_cr3(&file).unwrap().tracks.is_empty());
// the track stays (craft-libs #1300: dropping it would let a reduced raw stand in), but without data
let tracks = parse_cr3(&file).unwrap().tracks;
assert_eq!(tracks.len(), 1);
assert!(tracks[0].data.is_none());
}

#[test]
Expand Down
16 changes: 15 additions & 1 deletion crates/meta/src/exif.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ pub fn from_tiff(tiff: &Tiff) -> Metadata {
}
m.stabilization = nikon_vibration_reduction(exif, m.make.as_deref(), tiff.order);
m.orientation = ifd0.and_then(|i| i.u16(t::ORIENTATION)).filter(|v| (1..=8).contains(v)).map(Orientation::from_exif);
m.rating = ifd0.and_then(|i| i.i64(t::RATING)).map(|r| r.clamp(-1, 5) as i8);
// a SHORT 0xFFFF is how writers store -1 (rejected), not a five-star rating (adapted from craft-libs #967)
m.rating = ifd0.and_then(|i| i.i64(t::RATING)).map(|r| if r == 0xFFFF { -1 } else { r.clamp(-1, 5) } as i8);

m.exposure_time = pos(either(t::EXPOSURE_TIME).and_then(|v| v.get_f64(0)))
.or_else(|| exif.and_then(|e| e.f64(t::SHUTTER_SPEED_VALUE)).filter(|v| v.abs() < 64.0).map(|tv| 2f64.powf(-tv)));
Expand Down Expand Up @@ -417,6 +418,19 @@ pub(crate) mod tests {
assert_eq!(crate::extract(&rw2).lens_model.as_deref(), Some("LUMIX S 85/F1.8"));
}

/// craft-libs #967 (upstream #1995): the Exif Rating 0xFFFF reads as rejected (-1), not as five stars.
#[test]
fn rating_65535_reads_as_rejected() {
let rating = |v: u16| {
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::RATING, Value::Short(vec![v]));
read_exif(&TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap()).rating
};
assert_eq!(rating(0xFFFF), Some(-1));
assert_eq!(rating(3), Some(3));
assert_eq!(rating(9), Some(5));
}

/// A RW2 whose own short Exif IFD lacks ISO, with `inner` as the Exif of its JpgFromRaw and `raw_iso` in
/// the Panasonic IFD0 tag 0x0017.
fn rw2_with(inner: Option<IfdBuilder>, raw_iso: Option<u16>) -> Vec<u8> {
Expand Down
44 changes: 38 additions & 6 deletions crates/meta/src/xmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@ fn xml_legal(s: &str) -> std::borrow::Cow<'_, str> {
if s.chars().all(xml_char) { std::borrow::Cow::Borrowed(s) } else { std::borrow::Cow::Owned(s.chars().filter(|c| xml_char(*c)).collect()) }
}

// A literal carriage return reads back as a line feed (XML end-of-line handling), so it is written as `&#13;`
// (adapted from craft-libs #1042, from upstream #4119).
fn escape(s: &str) -> String {
xml_escape(xml_legal(s)).into_owned()
xml_escape(xml_legal(s)).replace('\r', "&#13;")
}

fn partial_escape(s: &str) -> String {
xml_partial_escape(xml_legal(s)).into_owned()
xml_partial_escape(xml_legal(s)).replace('\r', "&#13;")
}
use quick_xml::events::Event;
use std::collections::BTreeMap;
Expand Down Expand Up @@ -487,9 +489,9 @@ fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<Str
return;
}
if p.attr("rdf:parseType") == Some("Resource") {
for c in &p.children {
collect_property(c, &struct_prefix, props, budget);
}
// the struct's fields may be attributes of the property as well as elements, as in an rdf:Description
// (adapted from craft-libs #967, from upstream #1226)
collect_description(p, &struct_prefix, props, budget);
return;
}
if let Some(d) = p.children.iter().find(|c| c.name == "rdf:Description") {
Expand Down Expand Up @@ -1840,6 +1842,33 @@ mod tests {
assert!(plugin_fields(&parse_xmp(&write_xmp_ext(&Metadata::default(), &[], &[])).unwrap()).is_empty());
}

/// craft-libs #967 (upstream #1226): a `rdf:parseType="Resource"` struct's attribute fields flatten like an
/// rdf:Description's, in all four equivalent forms.
#[test]
fn resource_struct_attributes_and_elements_flatten_like_description_fields() {
let forms = [
r#"<c:Parameters rdf:parseType="Resource" c:ConvertToGrayscale="True"><c:Version>1</c:Version></c:Parameters>"#,
r#"<c:Parameters><rdf:Description c:ConvertToGrayscale="True"><c:Version>1</c:Version></rdf:Description></c:Parameters>"#,
r#"<c:Parameters rdf:parseType="Resource"><c:ConvertToGrayscale>True</c:ConvertToGrayscale><c:Version>1</c:Version></c:Parameters>"#,
r#"<c:Parameters rdf:parseType="Resource" c:ConvertToGrayscale="True" c:Version="1"/>"#,
];
let mut previous = None;
for form in forms {
let xml = format!(
r#"<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:c="http://ns.adobe.com/camera-raw-settings/1.0/"><c:Look rdf:parseType="Resource">{form}</c:Look></rdf:Description>"#
);
let packet = parse_xmp(&xml).unwrap();
assert_eq!(packet.properties["crs:Look/crs:Parameters/crs:ConvertToGrayscale"], vec!["True"], "{form}");
assert_eq!(packet.properties["crs:Look/crs:Parameters/crs:Version"], vec!["1"], "{form}");
assert!(packet.properties.keys().all(|key| !key.contains("rdf:")), "{form}");
if let Some((properties, values)) = previous {
assert_eq!(packet.properties, properties);
assert_eq!(packet.values, values);
}
previous = Some((packet.properties, packet.values));
}
}

#[test]
fn writer_drops_characters_xml_1_0_forbids() {
let bad = "a\u{1}b\u{0}c\u{FFFE}d\u{FFFF}e\u{1F}\tf\ng\rh";
Expand All @@ -1848,7 +1877,10 @@ mod tests {
let illegal: Vec<char> =
x.chars().filter(|&c| (c < '\u{20}' && !matches!(c, '\t' | '\n' | '\r')) || c == '\u{FFFE}' || c == '\u{FFFF}').collect();
assert!(illegal.is_empty(), "illegal XML chars in output: {illegal:?}");
assert!(x.contains(">abcde\tf\ng\rh<"), "allowed characters must survive: {x}");
assert!(x.contains(">abcde\tf\ng&#13;h<"), "allowed characters must survive: {x}");
// a carriage return survives the round trip: a literal one would read back as a line feed (craft-libs #1042)
let back = parse_xmp(&x).unwrap();
assert!(back.properties.values().flatten().any(|v| v == "abcde\tf\ng\rh"), "{:?}", back.properties);
}

#[test]
Expand Down
Loading