Files
Pictor-public/crates/meta/src/tiff.rs
T

76 lines
3.3 KiB
Rust

//! TIFF: tags read through kamadak-exif (a TIFF file is itself EXIF-structured); stripping decodes the pixels and
//! writes a fresh, uncompressed TIFF with only the layout tags, through the `image` crate.
use std::io::Cursor;
use crate::{Ctx, Limits, MetaError, exif_items, guarded, text};
/// Whether the first IFD links to a second one (a multi-page TIFF, or one with a thumbnail page).
fn has_second_ifd(b: &[u8]) -> Option<bool> {
let le = b.starts_with(b"II");
let u16_at = |at: usize| -> Option<u16> {
let s = b.get(at..at.checked_add(2)?)?;
Some(if le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) })
};
let u32_at = |at: usize| -> Option<u32> { if le { text::le32(b, at) } else { text::be32(b, at) } };
let ifd = u32_at(4)? as usize;
let count = usize::from(u16_at(ifd)?);
let next_at = ifd.checked_add(2)?.checked_add(count.checked_mul(12)?)?;
Some(u32_at(next_at)? != 0)
}
pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> {
if has_second_ifd(b) == Some(true) {
ctx.warn("This TIFF has more than one page; removing metadata works on single-page TIFF files only.");
}
let parsed = guarded(|| {
let mut reader = exif::Reader::new();
reader.continue_on_error(true);
match reader.read_raw(b.to_vec()) {
Ok(exif) => Ok((exif, false)),
Err(e) => e.distill_partial_result(|_| {}).map(|exif| (exif, true)),
}
});
match parsed {
Some(Ok((exif, partial))) => {
if partial {
ctx.warn("Part of the TIFF tags are damaged; what could be read is listed.");
}
exif_items::list(&exif, ctx);
Ok(())
}
Some(Err(_)) | None => Err(MetaError::Damaged("its TIFF tags cannot be read".into())),
}
}
pub(crate) fn strip(b: &[u8], limits: &Limits) -> Result<Vec<u8>, MetaError> {
match has_second_ifd(b) {
Some(true) => return Err(MetaError::Unsupported("multi-page TIFF files".into())),
Some(false) => {}
None => return Err(MetaError::Damaged("its TIFF structure cannot be read".into())),
}
let decoded = guarded(|| {
let mut reader = image::ImageReader::with_format(Cursor::new(b), image::ImageFormat::Tiff);
let mut l = image::Limits::default();
l.max_alloc = Some(limits.max_decoded_bytes);
reader.limits(l);
reader.decode()
})
.ok_or_else(|| MetaError::Damaged("the image data cannot be decoded".into()))?;
let img = decoded.map_err(|e| match e {
image::ImageError::Limits(_) => MetaError::TooBig("it needs more memory than allowed".into()),
image::ImageError::Unsupported(_) => MetaError::Unsupported("this kind of TIFF image".into()),
_ => MetaError::Damaged("the image data cannot be decoded".into()),
})?;
let mut out = Cursor::new(Vec::new());
guarded(|| img.write_to(&mut out, image::ImageFormat::Tiff))
.ok_or_else(|| MetaError::Write("the TIFF encoder failed".into()))?
.map_err(|e| match e {
image::ImageError::Unsupported(_) => {
MetaError::Unsupported("this kind of TIFF image (pixel format)".into())
}
other => MetaError::Write(other.to_string()),
})?;
Ok(out.into_inner())
}