Merge pull request #3185 from ruchirguitar/fix/raw-preview-fallback-guard

craft-raw: add preview fallback and bounded dimensions guard
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 11:20:40 +01:00
commit 782998dfd1
6 files changed
+205 -39

No files matched your search

+57 -12
View File
@@ -276,20 +276,29 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma
let widths: Vec<usize> = match &slices {
Some(s) => {
let n = s[0].min(64) as usize;
let mut v = vec![s[1] as usize; n];
v.push(s[2] as usize);
let (Some(w0), Some(w1)) = (usize::try_from(s[1]).ok(), usize::try_from(s[2]).ok()) else {
return Err(RawError::Corrupt("CR2 slice width exceeds address space".into()));
};
let mut v = vec![w0; n];
v.push(w1);
v
}
None => {
let w = (fw as u64).checked_mul(nc as u64).ok_or_else(|| RawError::Corrupt("bad CR2 frame size".into()))?;
vec![w as usize]
let w = (fw as u64)
.checked_mul(nc as u64)
.and_then(|v| usize::try_from(v).ok())
.ok_or_else(|| RawError::Corrupt("bad CR2 frame size".into()))?;
vec![w]
}
};
let width: usize = widths.iter().sum();
let width: usize = widths.iter().try_fold(0usize, |acc, &w| acc.checked_add(w)).ok_or(RawError::Limit("CR2 slice widths overflow"))?;
if width == 0 || total % width != 0 {
return Err(RawError::Corrupt(format!("CR2 slices ({width}) do not divide the frame ({total} samples)")));
}
let height = total / width;
if width > u32::MAX as usize || height > u32::MAX as usize {
return Err(RawError::Limit("CR2 dimensions exceed u32::MAX"));
}
let mut data = Vec::new();
if let Some(frame) = &frame {
data = vec![0u16; total];
@@ -297,7 +306,9 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma
let mut x0 = 0;
for &sw in &widths {
for y in 0..height {
data[y * width + x0..y * width + x0 + sw].copy_from_slice(&frame.data[i..i + sw]);
let row_start = y.checked_mul(width).and_then(|s| s.checked_add(x0)).ok_or(RawError::Limit("CR2 row index overflow"))?;
let row_end = row_start.checked_add(sw).ok_or(RawError::Limit("CR2 row index overflow"))?;
data[row_start..row_end].copy_from_slice(&frame.data[i..i + sw]);
i += sw;
}
x0 += sw;
@@ -312,14 +323,29 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma
let mut active = Rect::new(0, 0, width, height);
let mut crop = Rect::new(0, 0, width, height);
if let Some(si) = mn.as_ref().and_then(|m| m.ifd.u64s(SENSOR_INFO)).filter(|v| v.len() >= 9) {
let (l, tp, r, b) = (si[5] as usize, si[6] as usize, si[7] as usize, si[8] as usize);
if r > l && b > tp && r < width && b < height {
active = Rect::new(l, tp, r - l + 1, b - tp + 1);
// `AspectInfo` is measured from the image area's origin, so it only applies when that area is known.
let image = Rect::new(0, 0, active.width, active.height);
crop = crate::shared::aspect_crop(mn.as_ref().map(|m| &m.ifd), image).unwrap_or(image);
let coords = [si[5], si[6], si[7], si[8]].map(|v| usize::try_from(v).ok());
if let [Some(l), Some(tp), Some(r), Some(b)] = coords
&& r > l
&& b > tp
&& r < width
&& b < height
{
let cw = r - l + 1;
let ch = b - tp + 1;
if cw <= width - l && ch <= height - tp {
active = Rect::new(l, tp, cw, ch);
// `AspectInfo` is measured from the image area's origin, so it only applies when that area is known.
let image = Rect::new(0, 0, active.width, active.height);
crop = crate::shared::aspect_crop(mn.as_ref().map(|m| &m.ifd), image).unwrap_or(image);
}
}
}
if active.width == 0 || active.height == 0 {
active = Rect::new(0, 0, width, height);
}
if crop.width == 0 || crop.height == 0 {
crop = Rect::new(0, 0, active.width, active.height);
}
let color_data = mn.as_ref().and_then(|m| m.ifd.value(COLOR_BALANCE).map(|v| words(v, m.order)));
let kelvin_presets = color_data.as_deref().and_then(kelvin_presets_from_color_data);
let wb = color_data.as_deref().and_then(wb_from_color_balance).or_else(|| wb_from_wb_info(mn.as_ref()?));
@@ -867,4 +893,23 @@ pub(crate) mod tests {
let image = decode_with_note(&[(crate::shared::ASPECT_INFO, 4, aspect)]);
assert_eq!((image.active_area, image.crop), (Rect::new(0, 0, 64, 10), Rect::new(0, 0, 64, 10)));
}
/// Active sensor area dimensions that are missing, zero-sized or inverted fall back to the full sensor frame.
#[test]
fn active_area_fallback_on_missing_or_corrupt_sensor_info() {
let (w, h) = (68, 50);
// Zero-sized: right == left
let si_zero: Vec<u8> = [68u16, 50, 0, 0, 0, 4, 2, 4, 49].iter().flat_map(|v| v.to_le_bytes()).collect();
let img = decode_sized_with_note(w, h, &[(SENSOR_INFO, 3, si_zero)]);
assert_eq!((img.active_area, img.crop), (Rect::new(0, 0, w, h), Rect::new(0, 0, w, h)));
// Inverted borders: right < left
let si_inv: Vec<u8> = [68u16, 50, 0, 0, 0, 10, 2, 4, 49].iter().flat_map(|v| v.to_le_bytes()).collect();
let img = decode_sized_with_note(w, h, &[(SENSOR_INFO, 3, si_inv)]);
assert_eq!((img.active_area, img.crop), (Rect::new(0, 0, w, h), Rect::new(0, 0, w, h)));
// Without SensorInfo: falls back to full sensor frame
let img = decode_sized_with_note(w, h, &[]);
assert_eq!((img.active_area, img.crop), (Rect::new(0, 0, w, h), Rect::new(0, 0, w, h)));
}
}
+21 -3
View File
@@ -89,6 +89,9 @@ impl Layout {
}
let rows = samples / row;
let (width, height) = (row / mcu * 2, rows * vertical);
if width == 0 || height == 0 || width > u32::MAX as usize || height > u32::MAX as usize {
return Err(RawError::Limit("sRAW dimensions exceed u32::MAX"));
}
if width.checked_mul(height).and_then(|p| p.checked_mul(3)).is_none_or(|s| s > limits.samples()) {
return Err(RawError::Limit("sRAW image too large"));
}
@@ -347,13 +350,28 @@ pub(super) fn decode(bytes: &[u8], tiff: &Tiff, raw: &Ifd, mode: Mode, limits: &
let mn =
tiff.exif().and_then(|e| e.get(t::MAKER_NOTE)).and_then(|e| makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make));
let (w, h) = (layout.width, layout.height);
if w > u32::MAX as usize || h > u32::MAX as usize {
return Err(RawError::Limit("sRAW dimensions exceed u32::MAX"));
}
let mut active = Rect::new(0, 0, w, h);
if let Some(si) = mn.as_ref().and_then(|m| m.ifd.u64s(SENSOR_INFO)).filter(|v| v.len() >= 9) {
let (l, tp, r, b) = (si[5] as usize, si[6] as usize, si[7] as usize, si[8] as usize);
if r > l && b > tp && r < w && b < h {
active = Rect::new(l, tp, r - l + 1, b - tp + 1);
let coords = [si[5], si[6], si[7], si[8]].map(|v| usize::try_from(v).ok());
if let [Some(l), Some(tp), Some(r), Some(b)] = coords
&& r > l
&& b > tp
&& r < w
&& b < h
{
let cw = r - l + 1;
let ch = b - tp + 1;
if cw <= w - l && ch <= h - tp {
active = Rect::new(l, tp, cw, ch);
}
}
}
if active.width == 0 || active.height == 0 {
active = Rect::new(0, 0, w, h);
}
let colour_data = mn.as_ref().and_then(|m| m.ifd.value(COLOR_BALANCE).map(|v| words(v, m.order)));
let black_counts = colour_data.as_deref().and_then(colour_data_black);
// 1.0 = a CFA CR2 of the same body at full 14-bit scale; see LUMA_GAIN
+73 -20
View File
@@ -371,30 +371,18 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f
let (full_w, full_h) = if std::ptr::eq(pixels, raw) {
(w, h)
} else {
(raw.u64(t::IMAGE_WIDTH).unwrap_or(0) as usize, raw.u64(t::IMAGE_LENGTH).unwrap_or(0) as usize)
(
raw.u64(t::IMAGE_WIDTH).and_then(|v| usize::try_from(v).ok()).unwrap_or(0),
raw.u64(t::IMAGE_LENGTH).and_then(|v| usize::try_from(v).ok()).unwrap_or(0),
)
};
if full_w == 0 || full_h == 0 {
return Err(RawError::Corrupt("raw image IFD without a size".into()));
}
let active_area = match raw.u64s(t::ACTIVE_AREA).as_deref() {
Some([top, left, bottom, right]) if bottom > top && right > left && (*bottom as usize) <= full_h && (*right as usize) <= full_w => {
Rect::new(*left as usize, *top as usize, (*right - *left) as usize, (*bottom - *top) as usize)
}
_ => Rect::new(0, 0, full_w, full_h),
};
let (crop, default_crop_adjusted) = default_crop(raw, active_area, full_w, full_h);
let (active_area, crop) = if (full_w, full_h) == (w, h) {
(active_area, crop)
} else {
let (sx, sy) = (w as f64 / full_w as f64, h as f64 / full_h as f64);
let scale = |r: Rect| {
let (x, y) = ((r.x as f64 * sx).round() as usize, (r.y as f64 * sy).round() as usize);
let (x1, y1) = (((r.x + r.width) as f64 * sx).round() as usize, ((r.y + r.height) as f64 * sy).round() as usize);
Rect::new(x, y, x1.saturating_sub(x).max(1), y1.saturating_sub(y).max(1))
};
let area = scale(active_area).clipped(w, h);
(area, scale(crop).clipped(area.width, area.height))
};
if w > u32::MAX as usize || h > u32::MAX as usize || full_w > u32::MAX as usize || full_h > u32::MAX as usize {
return Err(RawError::Limit("DNG dimensions exceed u32::MAX"));
}
let (active_area, crop, default_crop_adjusted) = active_area_and_crop(raw, w, h, full_w, full_h);
let mut assumed_cfa = false;
let cfa = if info.photometric == photometric::CFA {
@@ -557,6 +545,49 @@ fn extend_understated_strip(bytes: &[u8], info: &mut ImageInfo, raw: &Ifd) {
}
}
fn active_area_and_crop(raw: &Ifd, w: usize, h: usize, full_w: usize, full_h: usize) -> (Rect, Rect, bool) {
let active_area = match raw.u64s(t::ACTIVE_AREA).as_deref() {
Some(&[top, left, bottom, right]) => {
let coords = [top, left, bottom, right].map(|v| usize::try_from(v).ok());
match coords {
[Some(top), Some(left), Some(bottom), Some(right)]
if bottom > top && right > left && top <= full_h && left <= full_w && bottom <= full_h && right <= full_w =>
{
Rect::new(left, top, right - left, bottom - top)
}
_ => Rect::new(0, 0, full_w, full_h),
}
}
_ => Rect::new(0, 0, full_w, full_h),
};
let active_area = if active_area.width == 0 || active_area.height == 0 { Rect::new(0, 0, full_w, full_h) } else { active_area };
let (crop, mut default_crop_adjusted) = default_crop(raw, active_area, full_w, full_h);
if (full_w, full_h) == (w, h) {
(active_area, crop, default_crop_adjusted)
} else {
let (sx, sy) = (w as f64 / full_w as f64, h as f64 / full_h as f64);
let scale = |r: Rect| {
let (x, y) = ((r.x as f64 * sx).round() as usize, (r.y as f64 * sy).round() as usize);
let (x1, y1) = (((r.x + r.width) as f64 * sx).round() as usize, ((r.y + r.height) as f64 * sy).round() as usize);
Rect::new(x, y, x1.saturating_sub(x).max(1), y1.saturating_sub(y).max(1))
};
let mut area = scale(active_area).clipped(w, h);
let area_fell_back = area.width == 0 || area.height == 0;
if area_fell_back {
area = Rect::new(0, 0, w, h);
}
let scaled_crop = scale(crop);
let mut c = if area_fell_back { Rect::new(0, 0, area.width, area.height) } else { scaled_crop.clipped(area.width, area.height) };
if c.width == 0 || c.height == 0 {
c = Rect::new(0, 0, area.width, area.height);
}
if (raw.contains(t::DEFAULT_CROP_ORIGIN) || raw.contains(t::DEFAULT_CROP_SIZE)) && (area_fell_back || c != scaled_crop) {
default_crop_adjusted = true;
}
(area, c, default_crop_adjusted)
}
}
/// The default crop is relative to ActiveArea. DNG 1.7.1 defines independent
/// defaults: origin (0, 0), size ImageWidth/ImageLength. An unusable optional crop
/// preserves the entire active image. Valid partly overlapping rectangles retain the
@@ -720,6 +751,28 @@ mod tests {
let mut hostile = RawData::U16(image);
assert!(deinterleave(&mut hostile, 8, 6, 1, 1 << 20, 1).is_err());
}
#[test]
fn scaled_active_area_fallback_resets_crop_to_full_replacement_area() {
use craft_tiff::Entry;
let raw = Ifd { entries: vec![Entry { tag: t::ACTIVE_AREA, offset: 0, value: Value::Long(vec![63, 63, 64, 64]) }], ..Default::default() };
let (area, crop, adjusted) = active_area_and_crop(&raw, 8, 8, 64, 64);
assert_eq!(area, Rect::new(0, 0, 8, 8));
assert_eq!(crop, Rect::new(0, 0, 8, 8));
assert!(!adjusted);
let mut entries = vec![
Entry { tag: t::ACTIVE_AREA, offset: 0, value: Value::Long(vec![63, 63, 64, 64]) },
Entry { tag: t::DEFAULT_CROP_ORIGIN, offset: 0, value: Value::Rational(vec![(0, 1), (0, 1)]) },
Entry { tag: t::DEFAULT_CROP_SIZE, offset: 0, value: Value::Rational(vec![(1, 1), (1, 1)]) },
];
entries.sort_by_key(|e| e.tag);
let explicit_crop_raw = Ifd { entries, ..Default::default() };
let (area, crop, adjusted) = active_area_and_crop(&explicit_crop_raw, 8, 8, 64, 64);
assert_eq!(area, Rect::new(0, 0, 8, 8));
assert_eq!(crop, Rect::new(0, 0, 8, 8));
assert!(adjusted);
}
}
#[cfg(all(test, feature = "hasselblad"))]
+5 -2
View File
@@ -206,6 +206,9 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma
let ifd0 = tiff.ifds.first().ok_or_else(|| RawError::Corrupt("TIFF without IFDs".into()))?;
let info = ifd0.image()?;
let (w, h) = (info.width as usize, info.height as usize);
if w > u32::MAX as usize || h > u32::MAX as usize {
return Err(RawError::Limit("ORF dimensions exceed u32::MAX"));
}
let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= limits.samples()).ok_or(RawError::Limit("image too large"))?;
// A partial TIFF directory is damage, not evidence of an unsupported compressed layout.
// Do not infer packing from an absent strip table or from clipped sensor bytes.
@@ -233,7 +236,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma
(d, 16, true)
} else if is_block16(w, n, total, chunks.len()) {
let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("ORF strip outside file".into()))?;
let stride = w / 10 * 16;
let stride = (w / 10).checked_mul(16).filter(|&s| s > 0).ok_or_else(|| RawError::Corrupt("bad ORF row stride".into()))?;
if src.len() as u64 != total || src.len() / stride != h {
return Err(RawError::Corrupt("ORF strip shorter than its rows".into()));
}
@@ -257,7 +260,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma
// the depth is fixed here, so a header-only probe needs the samples only when the file doesn't state its
// colour-filter layout
let d = if mode == Mode::Full || stated.is_none() {
let stride = src.len() / h;
let stride = src.len().checked_div(h).filter(|&s| s > 0).ok_or_else(|| RawError::Corrupt("bad ORF row stride".into()))?;
let mut d = vec![0u16; n];
d.par_chunks_mut(w).enumerate().for_each(|(y, row)| unpack_row_le32_msb(&src[y * stride..(y + 1) * stride], 12, row));
d
+6 -2
View File
@@ -410,9 +410,13 @@ fn preview_covering(bytes: &[u8], min_edge: Option<u32>, jpeg_only: bool) -> Opt
.or(largest)
.map(|s| if is_jxl(s) { s.to_vec() } else { trim_eoi(s).to_vec() });
// a TIFF raw whose preview no tag points to: one we can't decode (Leaf MOS), or Epson ERF (in its maker note)
// ORF capability must not remove the scan fallback for unsupported modes and damaged preview pointers.
// Container capability must not remove the scan fallback for unsupported modes and damaged preview pointers.
let best = best.or_else(|| {
format.filter(|f| !f.is_supported() || matches!(f, crate::RawFormat::Erf | crate::RawFormat::Orf)).and_then(|_| scan_for_jpeg(bytes))
format
.filter(|f| {
!f.is_supported() || matches!(f, crate::RawFormat::Erf | crate::RawFormat::Orf | crate::RawFormat::Cr2 | crate::RawFormat::Dng)
})
.and_then(|_| scan_for_jpeg(bytes))
});
// Hasselblad 3FR / FFF carry no JPEG, only uncompressed RGB images: one wrapped as a baseline TIFF
#[cfg(feature = "hasselblad")]
+43
View File
@@ -974,3 +974,46 @@ fn supported_orf_keeps_unreferenced_jpeg_fallback() {
assert_eq!(embedded_preview(&file).as_deref(), Some(jpeg.as_slice()));
assert_eq!(embedded_preview_covering(&file, 1).as_deref(), Some(jpeg.as_slice()));
}
#[cfg(feature = "cr2")]
/// CR2 capability reporting must not disable preview scanning when preview tags are missing or damaged.
#[test]
fn supported_cr2_keeps_unreferenced_jpeg_fallback() {
let mut ifd = IfdBuilder::new();
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![64]));
ifd.set(t::IMAGE_LENGTH, Value::Long(vec![64]));
ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![16]));
ifd.set(t::COMPRESSION, Value::Short(vec![1]));
let raw_tiff = TiffWriter::default().write(&[ifd]).unwrap();
let mut file = Vec::new();
file.extend_from_slice(b"II*\0\x10\0\0\0CR\x02\0\0\0\0\0");
file.extend_from_slice(&raw_tiff[8..]);
let jpeg = scan_jpeg(3, 900);
file.extend_from_slice(&jpeg);
let format = crate::probe(&file).unwrap();
assert_eq!(format, crate::RawFormat::Cr2);
assert!(format.is_supported());
assert_eq!(embedded_preview(&file).as_deref(), Some(jpeg.as_slice()));
assert_eq!(embedded_preview_covering(&file, 1).as_deref(), Some(jpeg.as_slice()));
}
#[cfg(feature = "dng")]
/// DNG capability reporting must not disable preview scanning when preview tags are missing or damaged.
#[test]
fn supported_dng_keeps_unreferenced_jpeg_fallback() {
let mut ifd = IfdBuilder::new();
ifd.set(t::DNG_VERSION, Value::Byte(vec![1, 4, 0, 0]));
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![64]));
ifd.set(t::IMAGE_LENGTH, Value::Long(vec![64]));
ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![16]));
ifd.set(t::COMPRESSION, Value::Short(vec![1]));
ifd.set_image(ImageData::Strips { rows_per_strip: 64, strips: vec![vec![0; 16]] });
let mut file = TiffWriter::default().write(&[ifd]).unwrap();
let jpeg = scan_jpeg(3, 900);
file.extend_from_slice(&jpeg);
let format = crate::probe(&file).unwrap();
assert_eq!(format, crate::RawFormat::Dng);
assert!(format.is_supported());
assert_eq!(embedded_preview(&file).as_deref(), Some(jpeg.as_slice()));
assert_eq!(embedded_preview_covering(&file, 1).as_deref(), Some(jpeg.as_slice()));
}