diff --git a/Cargo.lock b/Cargo.lock index 07cad4e799..f1bda324c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -48,13 +48,28 @@ version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + [[package]] name = "alloc-stdlib" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" dependencies = [ - "alloc-no-stdlib", + "alloc-no-stdlib 2.0.4", +] + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib 3.0.0", ] [[package]] @@ -453,9 +468,20 @@ version = "8.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", - "brotli-decompressor", + "alloc-no-stdlib 2.0.4", + "alloc-stdlib 0.2.4", + "brotli-decompressor 5.0.3", +] + +[[package]] +name = "brotli" +version = "9.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", + "brotli-decompressor 6.3.1", ] [[package]] @@ -464,8 +490,18 @@ version = "5.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", + "alloc-no-stdlib 2.0.4", + "alloc-stdlib 0.2.4", +] + +[[package]] +name = "brotli-decompressor" +version = "6.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", ] [[package]] @@ -1167,6 +1203,8 @@ dependencies = [ name = "craft-metadata" version = "0.1.0" dependencies = [ + "brotli 9.1.1", + "brotli-decompressor 6.3.1", "chrono", "craft-tiff", "proptest", @@ -2739,7 +2777,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" name = "hayro-cmap" version = "0.1.0" dependencies = [ - "brotli", + "brotli 8.0.4", "hayro-postscript", ] @@ -3489,7 +3527,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46" dependencies = [ - "brotli-decompressor", + "brotli-decompressor 5.0.3", "jxl-bitstream", "jxl-frame", "jxl-grid", @@ -3521,7 +3559,7 @@ version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3" dependencies = [ - "brotli-decompressor", + "brotli-decompressor 5.0.3", "jxl-bitstream", "jxl-color", "jxl-frame", diff --git a/crates/metadata/Cargo.toml b/crates/metadata/Cargo.toml index 2074926190..28764c0411 100644 --- a/crates/metadata/Cargo.toml +++ b/crates/metadata/Cargo.toml @@ -15,7 +15,11 @@ craft-tiff = { workspace = true } serde = { workspace = true } quick-xml = "0.41" chrono = { workspace = true } +# JPEG XL `brob` metadata boxes +brotli-decompressor = { version = "6", default-features = false, features = ["std"] } [dev-dependencies] proptest = { workspace = true } serde_json = { workspace = true } +# writes the `brob` boxes of the JPEG XL tests +brotli = { version = "9", default-features = false, features = ["std"] } diff --git a/crates/metadata/README.md b/crates/metadata/README.md index 1345ead5f0..5bdb7f1c07 100644 --- a/crates/metadata/README.md +++ b/crates/metadata/README.md @@ -19,8 +19,9 @@ are one crate. | `write_xmp(&Metadata) -> String` | A complete `` packet. `write_xmp_with` sets the toolkit name and adds simple properties in the caller's namespace. | | `merge_xmp(existing, fresh, MergeRules)` | Updates a packet another program wrote: owned properties are replaced, everything else stays byte for byte. | | `parse_gpx(&str) -> Result` | GPX track points; `Tracklog::locate` gives the position at a capture time. | -| `embedded(&[u8]) -> Embedded` | Sniffs JPEG, PNG, WebP, TIFF-based files, Fujifilm RAF and Canon CR3 and returns the Exif, XMP (and extended XMP), ICC and IPTC blocks. `jpeg_segments`, `png_chunks`, `webp_chunks` are the walkers. | +| `embedded(&[u8]) -> Embedded` | Sniffs JPEG, PNG, WebP, TIFF-based files, Fujifilm RAF, Canon CR3 and JPEG XL containers and returns the Exif, XMP (and extended XMP), ICC and IPTC blocks. `jpeg_segments`, `png_chunks`, `webp_chunks` are the walkers. | | `cr3::parse_cr3` | The Canon CR3 container: `CMT1`…`CMT4`, the XMP `uuid` box, the thumbnail, the tracks. | +| `jxl::metadata` | The `Exif` and `xml ` boxes of a JPEG XL container, plain or Brotli-wrapped in `brob`. | | `extract(&[u8]) -> Metadata` | All of it for a whole file. Precedence: EXIF, then IPTC fills gaps, then XMP overrides the user fields (rating, label, title, caption, artist, copyright, keywords, GPS) and fills the rest. `from_embedded` does the same for blocks already located. | HEIF, PSD and MRW files are read by `craft-heif`, `craft-psd` and `craft-raw`. Put the blocks they @@ -47,7 +48,7 @@ A foreign namespace that uses a recognised prefix cannot supply recognised prope ## Limits XMP: 64 levels, 200 000 nodes, 1 MiB of flattened keys and 8 MiB of opaque names per packet -(`XmpError::TooComplex`). GPX: 64 levels, 5 000 000 points. CR3: 4096 boxes. JPEG ICC is returned only when its APP2 chunks form a +(`XmpError::TooComplex`). GPX: 64 levels, 5 000 000 points. CR3 and JPEG XL: 4096 boxes; a `brob` box inflates to at most 32 MiB. JPEG ICC is returned only when its APP2 chunks form a complete, consistent, uniquely numbered sequence. TIFF limits are `craft-tiff`'s. No input panics: proptests feed random bytes to every container walker and random text to the XMP parser, and a sample JPEG is cut at every byte. diff --git a/crates/metadata/src/container.rs b/crates/metadata/src/container.rs index 6606775811..439771b989 100644 --- a/crates/metadata/src/container.rs +++ b/crates/metadata/src/container.rs @@ -9,6 +9,8 @@ //! IPTC (33723) from IFD0. //! - Canon CR3 (ISO base media file, see [`crate::cr3`]): `CMT1`/`CMT2`/`CMT4` merged into one Exif block; the //! XMP `uuid` box. +//! - JPEG XL (ISO base media file, see [`crate::jxl`]): the `Exif` and `xml ` boxes, plain or Brotli-wrapped +//! in `brob`; a bare codestream has no metadata. //! //! PSD, MRW and HEIF files are read by `craft-psd`, `craft-raw` and `craft-heif`. @@ -41,6 +43,9 @@ pub fn embedded(bytes: &[u8]) -> Embedded { if let Some(c) = crate::cr3::parse_cr3(bytes) { return Embedded { exif: crate::cr3::merged_exif(&c), xmp: c.xmp.map(|b| String::from_utf8_lossy(b).into_owned()), ..Default::default() }; } + if crate::jxl::is_jxl_container(bytes) { + return crate::jxl::metadata(bytes); + } if bytes.starts_with(&[0xff, 0xd8]) { jpeg_segments(bytes) } else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { diff --git a/crates/metadata/src/jxl.rs b/crates/metadata/src/jxl.rs new file mode 100644 index 0000000000..f7a860099b --- /dev/null +++ b/crates/metadata/src/jxl.rs @@ -0,0 +1,198 @@ +//! JPEG XL container metadata (ISO/IEC 18181-2): the `Exif` and `xml ` boxes. +//! +//! A JPEG XL file is either a bare codestream (`FF 0A`, no metadata) or an ISO base media file +//! that starts with the 12-byte `JXL ` signature box. Its metadata boxes may be stored as they +//! are, or wrapped in a `brob` box: the real box type followed by a Brotli stream of the payload. +//! An `Exif` payload starts with a four-byte big-endian `tiff_header_offset`: the TIFF header +//! begins that many bytes after the prefix. + +use crate::container::Embedded; +use crate::cr3::{MAX_BOXES, be32, boxes}; + +/// The signature box every JPEG XL container starts with. +const SIGNATURE: &[u8; 12] = b"\0\0\0\x0cJXL \r\n\x87\n"; + +/// A decompressed `brob` payload larger than this is left out, as too large for metadata. +const MAX_BROB: usize = 32 << 20; + +/// Whether `bytes` are a JPEG XL container (a bare codestream is not: it carries no metadata). +pub fn is_jxl_container(bytes: &[u8]) -> bool { + bytes.starts_with(SIGNATURE) +} + +/// The Exif and XMP blocks of a JPEG XL container: the first `Exif` and the first `xml ` box, +/// plain or inside `brob`. Anything malformed is left out rather than reported. +pub fn metadata(bytes: &[u8]) -> Embedded { + let mut out = Embedded::default(); + if !is_jxl_container(bytes) { + return out; + } + let mut budget = MAX_BOXES; + for b in boxes(bytes, SIGNATURE.len(), bytes.len(), &mut budget) { + if out.exif.is_some() && out.xmp.is_some() { + break; + } + let Some(payload) = bytes.get(b.body..b.end) else { break }; + let (kind, payload) = match &b.kind { + b"brob" => { + let (Some(kind), Some(stream)) = (payload.get(..4), payload.get(4..)) else { continue }; + let mut k = [0u8; 4]; + k.copy_from_slice(kind); + if (&k == b"Exif" && out.exif.is_none()) || (&k == b"xml " && out.xmp.is_none()) { + let Some(data) = unbrotli(stream) else { continue }; + (k, std::borrow::Cow::Owned(data)) + } else { + continue; + } + } + k => (*k, std::borrow::Cow::Borrowed(payload)), + }; + match &kind { + b"Exif" if out.exif.is_none() => out.exif = exif_tiff(&payload).map(<[u8]>::to_vec), + b"xml " if out.xmp.is_none() => out.xmp = Some(String::from_utf8_lossy(&payload).trim_end_matches('\0').to_string()), + _ => {} + } + } + out +} + +/// The TIFF stream of an `Exif` box payload: after the four-byte prefix and the offset it holds. +/// `None` when the offset points past the payload, or at nothing. +pub(crate) fn exif_tiff(payload: &[u8]) -> Option<&[u8]> { + let skip = be32(payload, 0).and_then(|v| usize::try_from(v).ok())?.checked_add(4)?; + payload.get(skip..).filter(|b| !b.is_empty()) +} + +/// Decompress a `brob` stream, giving up on a malformed stream or one past [`MAX_BROB`]. +fn unbrotli(stream: &[u8]) -> Option> { + use std::io::Read; + let mut out = Vec::new(); + let limit = u64::try_from(MAX_BROB).ok()?.checked_add(1)?; + brotli_decompressor::Decompressor::new(stream, 4096).take(limit).read_to_end(&mut out).ok()?; + (out.len() <= MAX_BROB).then_some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::embedded; + + fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec { + let mut v = Vec::new(); + v.extend_from_slice(&u32::try_from(payload.len() + 8).unwrap().to_be_bytes()); + v.extend_from_slice(kind); + v.extend_from_slice(payload); + v + } + + fn brob(kind: &[u8; 4], payload: &[u8]) -> Vec { + use std::io::Write; + let mut body = kind.to_vec(); + let mut w = brotli::CompressorWriter::new(&mut body, 4096, 5, 22); + w.write_all(payload).unwrap(); + drop(w); + bx(b"brob", &body) + } + + /// A container whose codestream is a stand-in: the metadata reader never parses it. + fn container(boxes: &[Vec]) -> Vec { + let mut v = SIGNATURE.to_vec(); + v.extend(bx(b"ftyp", b"jxl \0\0\0\0jxl ")); + v.extend(bx(b"jxlc", &[0xff, 0x0a, 1, 2, 3])); + for b in boxes { + v.extend_from_slice(b); + } + v + } + + /// A little-endian TIFF with one IFD0 entry: `Make` = `m`. + fn tiff(make: &str) -> Vec { + let m = format!("{make}\0"); + let mut v = b"II*\0\x08\0\0\0\x01\0\x0f\x01\x02\0".to_vec(); + v.extend_from_slice(&(m.len() as u32).to_le_bytes()); + v.extend_from_slice(&26u32.to_le_bytes()); + v.extend_from_slice(&[0; 4]); + v.extend_from_slice(m.as_bytes()); + v + } + + fn exif_box(tiff: &[u8], offset: u32) -> Vec { + let mut p = offset.to_be_bytes().to_vec(); + p.extend(std::iter::repeat_n(0u8, offset as usize)); + p.extend_from_slice(tiff); + p + } + + const XMP: &str = "Golden horizon"; + + #[test] + fn plain_exif_and_xml_boxes_are_read() { + let t = tiff("NIKON CORPORATION"); + let f = container(&[bx(b"Exif", &exif_box(&t, 0)), bx(b"xml ", XMP.as_bytes())]); + let e = embedded(&f); + assert_eq!(e.exif.as_deref(), Some(t.as_slice())); + assert_eq!(e.xmp.as_deref(), Some(XMP)); + let m = crate::extract(&f); + assert_eq!(m.make.as_deref(), Some("NIKON CORPORATION")); + assert_eq!(m.title.as_deref(), Some("Golden horizon")); + } + + #[test] + fn brotli_wrapped_boxes_are_read() { + let t = tiff("SONY"); + let f = container(&[brob(b"Exif", &exif_box(&t, 0)), brob(b"xml ", XMP.as_bytes())]); + let e = embedded(&f); + assert_eq!(e.exif.as_deref(), Some(t.as_slice())); + assert_eq!(e.xmp.as_deref(), Some(XMP)); + } + + /// The `Exif` prefix is an offset to the TIFF header, not always 0. + #[test] + fn the_tiff_header_offset_is_honoured() { + let t = tiff("Canon"); + let f = container(&[bx(b"Exif", &exif_box(&t, 6))]); + assert_eq!(embedded(&f).exif.as_deref(), Some(t.as_slice())); + assert_eq!(crate::extract(&f).make.as_deref(), Some("Canon")); + // an offset past the payload yields nothing + let f = container(&[bx(b"Exif", &[0, 0, 0, 100, 1, 2, 3, 4])]); + assert_eq!(embedded(&f).exif, None); + assert_eq!(exif_tiff(&[0, 0, 1, 0, 1, 2, 3]), None); + assert_eq!(exif_tiff(&[0, 0]), None); + } + + #[test] + fn the_first_of_each_box_wins_and_the_bare_codestream_has_none() { + let (a, b) = (tiff("A"), tiff("B")); + let f = container(&[bx(b"Exif", &exif_box(&a, 0)), bx(b"Exif", &exif_box(&b, 0)), bx(b"xml ", b""), bx(b"xml ", b"")]); + let e = embedded(&f); + assert_eq!(e.exif.as_deref(), Some(a.as_slice())); + assert_eq!(e.xmp.as_deref(), Some("")); + assert_eq!(embedded(&[0xff, 0x0a, 1, 2, 3, 4]), Embedded::default()); + assert!(!is_jxl_container(b"\0\0\0\x0cJXL \r\n\x87")); + } + + #[test] + fn broken_files_yield_nothing_without_panicking() { + let t = tiff("X"); + let good = container(&[brob(b"Exif", &exif_box(&t, 0)), bx(b"xml ", XMP.as_bytes())]); + for n in 0..good.len() { + let _ = embedded(&good[..n]); + } + // a box that claims more than the file holds, a zero size, a 64-bit size and junk Brotli + let mut huge = bx(b"Exif", &exif_box(&t, 0)); + huge[..4].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(embedded(&container(&[huge])), Embedded::default()); + let mut zero = bx(b"xml ", b""); + zero[..4].copy_from_slice(&[0; 4]); + assert_eq!(embedded(&container(&[zero])).xmp.as_deref(), Some("")); + let mut large = vec![0, 0, 0, 1]; + large.extend_from_slice(b"xml "); + large.extend_from_slice(&(8u64 + 8 + 4).to_be_bytes()); + large.extend_from_slice(b""); + assert_eq!(embedded(&container(&[large])).xmp.as_deref(), Some("")); + assert_eq!(embedded(&container(&[bx(b"brob", b"Exif\x01\x02\x03\x04\x05"), bx(b"brob", b"xm")])), Embedded::default()); + // a brob that inflates past the cap is left out + let big = vec![0u8; MAX_BROB + 1]; + assert_eq!(embedded(&container(&[brob(b"xml ", &big)])), Embedded::default()); + } +} diff --git a/crates/metadata/src/lib.rs b/crates/metadata/src/lib.rs index f2b6f85118..a74b12e7fa 100644 --- a/crates/metadata/src/lib.rs +++ b/crates/metadata/src/lib.rs @@ -10,7 +10,8 @@ //! another program wrote without losing what it does not understand. //! - GPX: [`parse_gpx`] reads track logs for geotagging by capture time. //! - Containers: [`embedded`], [`jpeg_segments`], [`png_chunks`] and [`webp_chunks`] locate the Exif, -//! XMP, ICC and IPTC blocks of JPEG, PNG, WebP, TIFF-based, Fujifilm RAF and Canon CR3 ([`cr3`]) files. +//! XMP, ICC and IPTC blocks of JPEG, PNG, WebP, TIFF-based, Fujifilm RAF, Canon CR3 ([`cr3`]) and +//! JPEG XL ([`jxl`]) files. //! [`extract`] does all of the above for a whole file. //! //! HEIF, PSD and MRW files are read by their own crates. Put the blocks they return into an @@ -25,6 +26,7 @@ mod focus_read; mod geom; mod gpx; mod iptc; +pub mod jxl; pub mod tags; mod xmp; mod xmp_merge; @@ -305,7 +307,7 @@ impl Metadata { } } -/// Read everything understood from a whole file (JPEG, PNG, WebP, TIFF-based incl. DNG and most raws, RAF, CR3). +/// Read everything understood from a whole file (JPEG, PNG, WebP, TIFF-based incl. DNG and most raws, RAF, CR3, JPEG XL). /// Precedence: EXIF, then IPTC fills gaps, then XMP overrides user fields and fills the rest. pub fn extract(bytes: &[u8]) -> Metadata { from_embedded(&embedded(bytes))