PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Open Canon CR3 camera JPEG previews with container orientation (#4595)
optimalbytee70537058eb89
diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rsindex 26e62d25f..008173839 100644--- a/crates/io/src/raw.rs+++ b/crates/io/src/raw.rs@@ -38,7 +38,7 @@ fn limits() -> Limits {fn upright_preview(raw: &[u8], jpeg: &[u8]) -> Result<Image, IoError> {let img = codecs::decode_as_with(Format::Jpeg, jpeg, &codecs::DecodeOptions { keep_orientation: true, ..Default::default() })?;let own = img.meta.exif.as_deref().map_or(1, codecs::exif_orientation);- let o = if own != 1 { own } else { codecs::exif_orientation(raw) };+ let o = if own != 1 { own } else { photocraft_raw::orientation(raw).unwrap_or_else(|| codecs::exif_orientation(raw)) };Ok(img.oriented(o)?)}diff --git a/crates/io/tests/raw.rs b/crates/io/tests/raw.rsindex 7a11f4fb0..d9e31a87c 100644--- a/crates/io/tests/raw.rs+++ b/crates/io/tests/raw.rs@@ -94,6 +94,18 @@ fn unsupported_raw_without_preview_is_a_clear_error() {}}+#[test]+fn cr3_opens_its_upright_camera_jpeg_with_explicit_preview_warning() {+ let img = Image::from_u8(32, 20, ChannelLayout::Rgb, vec![180; 32 * 20 * 3]).unwrap();+ let jpeg = photocraft_codecs::encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();+ let raw = photocraft_raw::testgen::cr3_preview(&jpeg, 6);+ let r = import("shot.cr3", &raw).unwrap();+ assert_eq!((r.document.size.width, r.document.size.height), (20, 32));+ assert_eq!(r.document.depth, SampleType::U8);+ assert!(r.warnings[0].contains("8-bit, not the raw sensor data"));+ assert!(r.warnings[0].contains("CR3"));+}+#[test]fn truncated_raws_do_not_panic() {let b = nef_with_preview();diff --git a/crates/raw/README.md b/crates/raw/README.mdindex efba4e833..232ef83b3 100644--- a/crates/raw/README.md+++ b/crates/raw/README.md@@ -75,7 +75,7 @@ camera colour tables were copied.| Nikon "lossy after split" NEF, Sony "Compressed RAW 2", Pentax compressed PEF, RW2 RawFormat 4 and older, Olympus compressed ORF | Unsupported: no public description of these codes was found apart from GPL decoder source, which this crate may not use (clean-room). `photocraft-io` opens the embedded JPEG preview instead || Fujifilm RAF, uncompressed (X-Trans I–V, GFX and Bayer bodies since about 2010) | Decoded: 16-bit containers (either byte order), 12-bit LSB-first packing, 14-bit packing in 32-bit words; X-Trans 6×6 or Bayer 2×2 layout, black, as-shot WB, crop, RawExposureBias, orientation from the preview's EXIF || Fujifilm compressed RAF, early FinePix / SuperCCD RAF (no CFA TIFF) | Unsupported (no public description of the compression); preview fallback |-| CR3 | Recognised, unsupported (preview fallback where a preview is found) |+| CR3 | Native CRX unsupported; bounded JPEG-track/PRVW preview fallback with CMT1 orientation. I/O labels the result as an 8-bit camera preview || X-Trans and other periodic non-Bayer CFAs (up to 16×16) | Demosaiced by one pattern-agnostic edge-directed method, whatever `Demosaic` is chosen |## Development pipelinediff --git a/crates/raw/src/cr3.rs b/crates/raw/src/cr3.rsnew file mode 100644index 000000000..bb2119e7d--- /dev/null+++ b/crates/raw/src/cr3.rs@@ -0,0 +1,202 @@+//! Bounded CR3 container reading, independently implemented from ISO BMFF and+//! Laurent Clévy's public format description (canon_cr3/readme.md). This extracts+//! camera JPEGs and orientation, not CRX sensor data. Never scan compressed data+//! for JPEG signatures: offsets must come from a validated sample table or PRVW.++use crate::preview::{Preview, candidate};+use crate::tiff::{Tiff, tag};++const META_UUID: &[u8] = &[0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48];+const PREVIEW_UUID: &[u8] = &[0xea, 0xf4, 0x2b, 0x5e, 0x1c, 0x98, 0x4b, 0x88, 0xb9, 0xfb, 0xb7, 0xdc, 0x40, 0x6e, 0x4d, 0x16];+const MAX_BOXES: usize = 8192;+const MAX_DEPTH: usize = 12;++fn u32_at(b: &[u8], p: usize) -> Option<u32> {+ Some(u32::from_be_bytes(b.get(p..p.checked_add(4)?)?.try_into().ok()?))+}++fn u64_at(b: &[u8], p: usize) -> Option<u64> {+ Some(u64::from_be_bytes(b.get(p..p.checked_add(8)?)?.try_into().ok()?))+}++struct BoxRef<'a> {+ kind: &'a [u8],+ body: &'a [u8],+}++/// Walks only complete sibling boxes, including extended lengths and a final+/// zero-length box. Invalid lengths end this container; siblings never escape it.+fn boxes<'a>(mut b: &'a [u8], budget: &mut usize, mut f: impl FnMut(BoxRef<'a>, &mut usize)) {+ while b.len() >= 8 && *budget > 0 {+ *budget -= 1;+ let Some(n) = u32_at(b, 0) else {+ return;+ };+ let (size, header) = match n {+ 0 => (b.len(), 8),+ 1 => {+ let Some(size) = u64_at(b, 8).and_then(|n| usize::try_from(n).ok()) else {+ return;+ };+ (size, 16)+ }+ n => (n as usize, 8),+ };+ if size < header {+ return;+ }+ let Some(body) = b.get(header..size) else {+ return;+ };+ let Some(kind) = b.get(4..8) else {+ return;+ };+ f(BoxRef { kind, body }, budget);+ let Some(rest) = b.get(size..) else {+ return;+ };+ b = rest;+ }+}++#[derive(Default)]+struct Track<'a> {+ jpeg: bool,+ sizes: Option<&'a [u8]>,+ offsets: Option<(&'a [u8], bool)>,+ mapping: bool,+}++/// Accept only a single JPEG sample description, with CRAW's fixed sample-entry+/// header followed by an explicit JPEG codec box.+fn jpeg_description(b: &[u8], budget: &mut usize) -> bool {+ if u32_at(b, 0) != Some(0) || u32_at(b, 4) != Some(1) {+ return false;+ }+ let mut jpeg = false;+ if let Some(entries) = b.get(8..) {+ boxes(entries, budget, |entry, budget| {+ if entry.kind == b"CRAW"+ && let Some(children) = entry.body.get(82..)+ {+ boxes(children, budget, |codec, _| {+ jpeg |= codec.kind == b"JPEG";+ });+ }+ });+ }+ jpeg+}++fn track_boxes<'a>(b: &'a [u8], depth: usize, budget: &mut usize, t: &mut Track<'a>) {+ if depth > MAX_DEPTH {+ return;+ }+ boxes(b, budget, |item, budget| match item.kind {+ b"mdia" | b"minf" | b"stbl" => track_boxes(item.body, depth + 1, budget, t),+ b"stsd" => t.jpeg = jpeg_description(item.body, budget),+ b"stsz" => t.sizes = Some(item.body),+ b"co64" => t.offsets = Some((item.body, true)),+ b"stco" => t.offsets = Some((item.body, false)),+ // One entry, starting at chunk 1, one sample per chunk, description 1.+ b"stsc" => t.mapping = item.body.len() == 20 && (0..5).all(|i| u32_at(item.body, i * 4) == Some(if i == 0 { 0 } else { 1 })),+ _ => {}+ });+}++fn track_preview<'a>(raw: &'a [u8], track: &'a [u8], budget: &mut usize, media: &[(usize, usize)]) -> Option<Preview<'a>> {+ let mut t = Track::default();+ track_boxes(track, 0, budget, &mut t);+ if !t.jpeg || !t.mapping {+ return None;+ }+ let sizes = t.sizes?;+ let (offsets, wide) = t.offsets?;+ // Burst sequences are deliberately not paired by ordinal index: their+ // sample-to-chunk mapping and picture selection need a separate implementation.+ if u32_at(sizes, 0) != Some(0) || u32_at(sizes, 8) != Some(1) || u32_at(offsets, 0) != Some(0) || u32_at(offsets, 4) != Some(1) {+ return None;+ }+ let fixed = u32_at(sizes, 4)?;+ let len = if fixed == 0 { u32_at(sizes, 12)? } else { fixed };+ let off = if wide { u64_at(offsets, 8)? } else { u64::from(u32_at(offsets, 8)?) };+ let off = usize::try_from(off).ok()?;+ let end = off.checked_add(len as usize)?;+ if !media.iter().any(|(start, stop)| off >= *start && end <= *stop) {+ return None;+ }+ candidate(raw, off, len as usize)+}++#[derive(Default)]+struct Found<'a> {+ previews: Vec<Preview<'a>>,+ orientation: Option<u16>,+ media: Vec<(usize, usize)>,+}++fn walk<'a>(raw: &'a [u8], b: &'a [u8], depth: usize, budget: &mut usize, found: &mut Found<'a>) {+ if depth > MAX_DEPTH {+ return;+ }+ boxes(b, budget, |item, budget| match item.kind {+ b"moov" => walk(raw, item.body, depth + 1, budget, found),+ b"trak" => {+ if found.previews.len() < 128 {+ found.previews.extend(track_preview(raw, item.body, budget, &found.media));+ }+ }+ b"uuid" => {+ if item.body.get(..16) == Some(META_UUID)+ && let Some(children) = item.body.get(16..)+ {+ walk(raw, children, depth + 1, budget, found);+ } else if item.body.get(..16) == Some(PREVIEW_UUID)+ && let Some(children) = item.body.get(24..)+ {+ walk(raw, children, depth + 1, budget, found);+ }+ }+ b"PRVW" => {+ if found.previews.len() < 128+ && let Some(len) = u32_at(item.body, 12)+ && let Some(p) = candidate(item.body, 16, len as usize)+ {+ found.previews.push(p);+ }+ }+ b"CMT1" => {+ if let Some(tiff) = Tiff::new(item.body)+ && let Some(ifd) = tiff.ifd_at(tiff.first_ifd, 0)+ && let Some(o) = tiff.tag_uint(&ifd, tag::ORIENTATION).filter(|o| (1..=8).contains(o))+ {+ found.orientation = Some(o as u16);+ }+ }+ _ => {}+ });+}++fn read(raw: &[u8]) -> Found<'_> {+ let mut found = Found::default();+ if raw.get(4..12) == Some(b"ftypcrx ") {+ let mut budget = MAX_BOXES;+ boxes(raw, &mut budget, |item, _| {+ if item.kind == b"mdat" && found.media.len() < 128 {+ let start = (item.body.as_ptr() as usize).saturating_sub(raw.as_ptr() as usize);+ if let Some(end) = start.checked_add(item.body.len()) {+ found.media.push((start, end));+ }+ }+ });+ walk(raw, raw, 0, &mut budget, &mut found);+ }+ found+}++pub(crate) fn previews(raw: &[u8]) -> Vec<Preview<'_>> {+ read(raw).previews+}+pub(crate) fn orientation(raw: &[u8]) -> Option<u16> {+ read(raw).orientation+}diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rsindex d5a3e987c..f8304b3cf 100644--- a/crates/raw/src/lib.rs+++ b/crates/raw/src/lib.rs@@ -46,6 +46,7 @@mod cameras;mod color;mod cr2;+mod cr3;mod demosaic;mod develop;mod dng;@@ -85,6 +86,17 @@ use crate::tiff::{Tiff, tag};/// Name of the output colour space of [`develop`].pub const OUTPUT_SPACE: &str = "ProPhoto RGB (ROMM primaries, D50, gamma 1.8)";+/// The raw container's orientation, when recorded (CR3 metadata or TIFF IFD0).+/// Useful for camera JPEGs that carry no orientation of their own.+pub fn orientation(bytes: &[u8]) -> Option<u16> {+ if bytes.get(4..12) == Some(b"ftypcrx ") {+ return cr3::orientation(bytes);+ }+ let tiff = Tiff::new(bytes)?;+ let ifd = tiff.ifd_at(tiff.first_ifd, 0)?;+ tiff.tag_uint(&ifd, tag::ORIENTATION).filter(|o| (1..=8).contains(o)).map(|o| o as u16)+}+/// Camera raw container families.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum RawFormat {diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rsindex ec0c041fb..d5dd01331 100644--- a/crates/raw/src/preview.rs+++ b/crates/raw/src/preview.rs@@ -41,13 +41,13 @@ fn dct_jpeg_size(b: &[u8]) -> Option<(u32, u32)> {None}-fn candidate(data: &[u8], offset: usize, len: usize) -> Option<Preview<'_>> {+pub(crate) fn candidate(data: &[u8], offset: usize, len: usize) -> Option<Preview<'_>> {let jpeg = data.get(offset..offset.checked_add(len)?)?;let (width, height) = dct_jpeg_size(jpeg)?;Some(Preview { jpeg, width, height })}-/// The largest embedded JPEG preview of a raw file (TIFF-based raws and RAF).+/// The largest embedded JPEG preview of a raw file (TIFF-based raws, RAF and CR3).pub fn embedded_preview(bytes: &[u8]) -> Option<Preview<'_>> {embedded_previews(bytes).into_iter().max_by_key(|p| u64::from(p.width) * u64::from(p.height))}@@ -56,7 +56,9 @@ pub fn embedded_preview(bytes: &[u8]) -> Option<Preview<'_>> {/// full-size and a smaller rendering of the same picture).pub fn embedded_previews(bytes: &[u8]) -> Vec<Preview<'_>> {let mut found: Vec<Preview> = Vec::new();- if bytes.starts_with(crate::raf::MAGIC) {+ if bytes.get(4..12) == Some(b"ftypcrx ") {+ found = crate::cr3::previews(bytes);+ } else if bytes.starts_with(crate::raf::MAGIC) {// RAF header: big-endian JPEG offset and length at bytes 84 and 88.if let Some((off, len)) = crate::raf::preview_range(bytes) {found.extend(candidate(bytes, off, len));diff --git a/crates/raw/src/testgen.rs b/crates/raw/src/testgen.rsindex fdacc1982..823cd97ae 100644--- a/crates/raw/src/testgen.rs+++ b/crates/raw/src/testgen.rs@@ -7,6 +7,41 @@// ---------------------------------------------------------------- lossless JPEG+/// A CR3 container holding one JPEG track and CMT1 orientation. It deliberately+/// contains no CRX data: used to test explicit preview fallback and BMFF bounds.+pub fn cr3_preview(jpeg: &[u8], orientation: u16) -> Vec<u8> {+ fn bx(kind: &[u8; 4], data: &[u8]) -> Vec<u8> {+ let mut b = ((data.len() + 8) as u32).to_be_bytes().to_vec();+ b.extend_from_slice(kind);+ b.extend_from_slice(data);+ b+ }+ fn moov(jpeg_len: usize, offset: u64, orientation: u16) -> Vec<u8> {+ let mut tiff = TiffBuilder::default();+ let ifd = tiff.ifd(vec![(274, Val::Short(vec![orientation]))]);+ tiff.chain = vec![ifd];+ let mut meta = vec![0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48];+ meta.extend(bx(b"CMT1", &tiff.build()));+ let mut entry = vec![0; 82];+ entry.extend(bx(b"JPEG", &[0; 4]));+ let mut description = vec![0, 0, 0, 0, 0, 0, 0, 1];+ description.extend(bx(b"CRAW", &entry));+ let mut sizes = vec![0; 4];+ sizes.extend_from_slice(&(jpeg_len as u32).to_be_bytes());+ sizes.extend_from_slice(&1u32.to_be_bytes());+ let mut offsets = vec![0, 0, 0, 0, 0, 0, 0, 1];+ offsets.extend_from_slice(&offset.to_be_bytes());+ let mapping: Vec<u8> = [0u32, 1, 1, 1, 1].iter().flat_map(|n| n.to_be_bytes()).collect();+ let table = [bx(b"stsd", &description), bx(b"stsz", &sizes), bx(b"co64", &offsets), bx(b"stsc", &mapping)].concat();+ let track = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &table))));+ bx(b"moov", &[bx(b"uuid", &meta), track].concat())+ }+ let ftyp = bx(b"ftyp", b"crx \0\0\0\x01crx isom");+ let header = moov(jpeg.len(), 0, orientation);+ let offset = ftyp.len() + header.len() + 8;+ [ftyp, moov(jpeg.len(), offset as u64, orientation), bx(b"mdat", jpeg)].concat()+}+/// Huffman code lengths assigned to categories in decreasing frequency/// order. Kraft sum < 1 and no code is all ones.const LENGTHS: [u8; 17] = [2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13];diff --git a/crates/raw/tests/cr3.rs b/crates/raw/tests/cr3.rsnew file mode 100644index 000000000..690717246--- /dev/null+++ b/crates/raw/tests/cr3.rs@@ -0,0 +1,119 @@+//! CR3 preview extraction never mistakes encoded sensor data for a JPEG.+use photocraft_raw::testgen::cr3_preview;+use photocraft_raw::{RawFormat, embedded_preview, embedded_previews, identify, orientation};++fn jpeg() -> Vec<u8> {+ vec![0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 20, 0, 32, 1, 1, 0x11, 0, 0xff, 0xd9]+}++fn position(b: &[u8], marker: &[u8]) -> usize {+ b.windows(marker.len()).position(|w| w == marker).unwrap()+}++#[test]+fn full_size_jpeg_and_orientation_are_read_from_their_boxes() {+ let j = jpeg();+ let b = cr3_preview(&j, 6);+ assert_eq!(identify(&b), Some(RawFormat::Cr3));+ let p = embedded_preview(&b).unwrap();+ assert_eq!((p.width, p.height), (32, 20));+ assert_eq!(p.jpeg, j);+ assert_eq!(embedded_previews(&b).len(), 1);+ assert_eq!(orientation(&b), Some(6));+}++#[test]+fn variable_sizes_and_32_bit_chunk_offsets_work() {+ let mut b = cr3_preview(&jpeg(), 1);+ let at = position(&b, b"stsz") + 8;+ // Add a single variable-size entry and repair ancestor lengths/offset.+ let len = u32::from_be_bytes(b[at..at + 4].try_into().unwrap());+ b[at..at + 4].fill(0);+ b.splice(at + 8..at + 8, len.to_be_bytes());+ for marker in [b"moov", b"trak", b"mdia", b"minf", b"stbl", b"stsz"] {+ let at = position(&b, marker) - 4;+ let n = u32::from_be_bytes(b[at..at + 4].try_into().unwrap());+ b[at..at + 4].copy_from_slice(&(n + 4).to_be_bytes());+ }+ let at = position(&b, b"co64");+ let off = u64::from_be_bytes(b[at + 12..at + 20].try_into().unwrap()) + 4;+ b[at..at + 4].copy_from_slice(b"stco");+ b[at + 12..at + 16].copy_from_slice(&(off as u32).to_be_bytes());+ assert_eq!(embedded_preview(&b).unwrap().jpeg, jpeg());+}++#[test]+fn broken_tables_and_raw_codec_tracks_are_not_used() {+ let good = cr3_preview(&jpeg(), 1);+ for marker in [b"stsz", b"co64", b"stsc", b"JPEG"] {+ let mut b = good.clone();+ let at = position(&b, marker);+ b[at..at + 4].copy_from_slice(b"xxxx");+ assert!(embedded_preview(&b).is_none());+ }+ let mut b = good.clone();+ let at = position(&b, b"co64") + 12;+ b[at..at + 8].copy_from_slice(&u64::MAX.to_be_bytes());+ assert!(embedded_preview(&b).is_none());+ let mut b = good;+ let at = position(&b, b"stsz") + 12;+ b[at..at + 4].copy_from_slice(&u32::MAX.to_be_bytes());+ assert!(embedded_preview(&b).is_none());+}++#[test]+fn truncations_and_corrupted_box_lengths_never_panic() {+ let b = cr3_preview(&jpeg(), 8);+ for n in 0..b.len() {+ let _ = embedded_previews(&b[..n]);+ let _ = orientation(&b[..n]);+ }+ for marker in [b"ftyp", b"moov", b"trak", b"mdat"] {+ for len in [0u32, 1, 2, 7, u32::MAX] {+ let mut corrupt = b.clone();+ let at = position(&b, marker) - 4;+ corrupt[at..at + 4].copy_from_slice(&len.to_be_bytes());+ let _ = embedded_previews(&corrupt);+ }+ }+}++#[test]+fn extended_mdat_length_is_supported() {+ let mut b = cr3_preview(&jpeg(), 1);+ let at = position(&b, b"mdat") - 4;+ let size = u32::from_be_bytes(b[at..at + 4].try_into().unwrap()) as u64 + 8;+ b[at..at + 4].copy_from_slice(&1u32.to_be_bytes());+ b.splice(at + 8..at + 8, size.to_be_bytes());+ let off = position(&b, b"co64") + 12;+ let n = u64::from_be_bytes(b[off..off + 8].try_into().unwrap()) + 8;+ b[off..off + 8].copy_from_slice(&n.to_be_bytes());+ assert_eq!(embedded_preview(&b).unwrap().jpeg, jpeg());+}++#[test]+fn prvw_is_used_when_no_jpeg_track_exists() {+ fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {+ [(body.len() as u32 + 8).to_be_bytes().as_slice(), kind, body].concat()+ }+ let ftyp = bx(b"ftyp", b"crx \0\0\0\x01crx isom");+ let mut body = vec![0; 12];+ body.extend_from_slice(&(jpeg().len() as u32).to_be_bytes());+ body.extend(jpeg());+ let mut uuid = vec![0xea, 0xf4, 0x2b, 0x5e, 0x1c, 0x98, 0x4b, 0x88, 0xb9, 0xfb, 0xb7, 0xdc, 0x40, 0x6e, 0x4d, 0x16];+ uuid.extend([0; 8]);+ uuid.extend(bx(b"PRVW", &body));+ let b = [ftyp, bx(b"uuid", &uuid)].concat();+ assert_eq!(embedded_preview(&b).unwrap().jpeg, jpeg());+ assert_eq!(orientation(&b), None);+}++#[test]+fn deeply_nested_containers_are_bounded() {+ let mut b = vec![0; 8];+ for _ in 0..1000 {+ b = [((b.len() + 8) as u32).to_be_bytes().as_slice(), b"moov", &b].concat();+ }+ let ftyp = [24u32.to_be_bytes().as_slice(), b"ftypcrx \0\0\0\x01crx isom"].concat();+ assert!(embedded_previews(&[ftyp, b].concat()).is_empty());+}