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

250 lines
8.7 KiB
Rust

//! JPEG at the segment level: the image data (tables, frame header, scans) is copied byte for byte.
use crate::{Ctx, Group, MetaError, exif_items, iptc, text, xmp};
const EXIF_SIG: &[u8] = b"Exif\0";
const XMP_SIG: &[u8] = b"http://ns.adobe.com/xap/1.0/\0";
const XMP_EXT_SIG: &[u8] = b"http://ns.adobe.com/xmp/extension/\0";
const ICC_SIG: &[u8] = b"ICC_PROFILE\0";
const JFIF_SIG: &[u8] = b"JFIF\0";
const ADOBE_SIG: &[u8] = b"Adobe";
/// A file with more segments than this is refused (each costs a few bytes of memory).
const MAX_SEGMENTS: usize = 100_000;
struct Segment {
marker: u8,
/// The whole segment in the file, from its 0xFF to the end of its payload (and, for SOS, its scan data).
span: (usize, usize),
/// The payload after the two length bytes (empty for markers without one).
payload: (usize, usize),
}
#[derive(Default)]
struct Parsed {
segments: Vec<Segment>,
/// The position just after the end-of-image marker, if there is one.
eoi_end: Option<usize>,
/// A segment header runs past the end of the file.
truncated: bool,
/// Something other than a marker where a marker must be, or too many segments.
damaged: Option<&'static str>,
}
fn parse(b: &[u8]) -> Parsed {
let mut p = Parsed::default();
let len = b.len();
let mut pos = 2;
loop {
if p.segments.len() >= MAX_SEGMENTS {
p.damaged = Some("it has too many segments");
break;
}
if pos >= len {
p.truncated = true;
break;
}
if b[pos] != 0xFF {
p.damaged = Some("a segment does not start where it should");
break;
}
let start = pos;
while pos < len && b[pos] == 0xFF {
pos += 1;
}
let Some(&marker) = b.get(pos) else {
p.truncated = true;
break;
};
pos += 1;
match marker {
0xD9 => {
p.eoi_end = Some(pos);
break;
}
0x01 | 0xD0..=0xD7 => p.segments.push(Segment { marker, span: (start, pos), payload: (pos, pos) }),
0x00 | 0xD8 => {
p.damaged = Some("a segment marker is invalid");
break;
}
_ => {
let Some(seg_len) = text::be16(b, pos) else {
p.truncated = true;
break;
};
let seg_len = usize::from(seg_len);
if seg_len < 2 {
p.damaged = Some("a segment length is invalid");
break;
}
let end = pos + seg_len;
if end > len {
p.truncated = true;
break;
}
let payload = (pos + 2, end);
pos = end;
if marker == 0xDA {
pos = scan_end(b, pos);
}
p.segments.push(Segment { marker, span: (start, pos), payload });
if pos >= len {
// The scan data runs to the end: a file cut off inside the image data. Kept as it is.
break;
}
}
}
}
p
}
/// The end of entropy-coded data: the next 0xFF that starts a marker other than a restart marker.
fn scan_end(b: &[u8], mut i: usize) -> usize {
while i + 1 < b.len() {
if b[i] == 0xFF {
match b[i + 1] {
0x00 | 0xD0..=0xD7 => {
i += 2;
continue;
}
0xFF => {
i += 1;
continue;
}
_ => return i,
}
}
i += 1;
}
b.len()
}
fn payload<'a>(b: &'a [u8], s: &Segment) -> &'a [u8] {
b.get(s.payload.0..s.payload.1).unwrap_or(&[])
}
/// The raw EXIF (TIFF header onwards) of an APP1 Exif payload.
fn exif_raw(p: &[u8]) -> Option<&[u8]> {
if p.starts_with(EXIF_SIG) { p.get(6..) } else { None }
}
pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> {
let parsed = parse(b);
for s in &parsed.segments {
let p = payload(b, s);
match s.marker {
0xE0 if p.starts_with(JFIF_SIG) => {
if p.get(12).copied().unwrap_or(0) != 0 && p.get(13).copied().unwrap_or(0) != 0 {
ctx.push(Group::Other, "JFIF thumbnail", crate::bytes_label(p.len().saturating_sub(14)));
}
}
0xE1 if p.starts_with(EXIF_SIG) => {
exif_items::read_block(exif_raw(p).unwrap_or(&[]), ctx);
}
0xE1 if p.starts_with(XMP_SIG) => xmp::read_packet(&p[XMP_SIG.len()..], Group::Xmp, "XMP packet", ctx),
0xE1 if p.starts_with(XMP_EXT_SIG) => {
ctx.push(Group::Xmp, "Extended XMP part", crate::bytes_label(p.len()))
}
0xE2 if p.starts_with(ICC_SIG) => {}
0xE2 if p.starts_with(b"MPF\0") => {
ctx.push(Group::Other, "Multi-picture index (MPF)", crate::bytes_label(p.len()))
}
0xED if p.starts_with(iptc::PHOTOSHOP_SIGNATURE) => iptc::read_photoshop(p, ctx),
0xEE if p.starts_with(ADOBE_SIG) => {}
0xE0..=0xEF => {
let n = s.marker - 0xE0;
let id = block_id(p);
let name = if id.is_empty() { format!("APP{n} block") } else { format!("APP{n} block ({id})") };
ctx.push(Group::Other, name, crate::bytes_label(p.len()));
}
0xFE => ctx.push(Group::Comment, "Comment", text::lossy(p)),
_ => {}
}
}
if let Some(end) = parsed.eoi_end
&& b.len() > end
{
ctx.push(Group::Other, "Data after the end of the image", crate::bytes_label(b.len() - end));
}
if parsed.truncated {
ctx.warn("The file ends too early (truncated); only part of it could be read.");
}
if let Some(why) = parsed.damaged {
ctx.warn(format!("The file is damaged ({why}); only part of it could be read."));
}
Ok(())
}
/// The printable ASCII name at the start of an APPn payload, e.g. "Ducky".
fn block_id(p: &[u8]) -> String {
p.iter().take(24).take_while(|c| c.is_ascii_graphic() || **c == b' ').map(|&c| c as char).collect()
}
pub(crate) fn strip(b: &[u8]) -> Result<Vec<u8>, MetaError> {
let parsed = parse(b);
if parsed.truncated {
return Err(MetaError::truncated());
}
if let Some(why) = parsed.damaged {
return Err(MetaError::Damaged(why.into()));
}
// The orientation of the first EXIF block, if it can be read; a damaged block gives none.
let orientation = parsed
.segments
.iter()
.filter(|s| s.marker == 0xE1)
.find_map(|s| exif_raw(payload(b, s)))
.and_then(|raw| exif_items::read_block(raw, &mut Ctx::default()))
.filter(|&o| o != 1);
let mut out = Vec::with_capacity(b.len());
out.extend_from_slice(&[0xFF, 0xD8]);
let mut orientation_pending = orientation;
for s in &parsed.segments {
let p = payload(b, s);
let is_jfif = s.marker == 0xE0 && p.starts_with(JFIF_SIG);
let keep = match s.marker {
0xE2 => p.starts_with(ICC_SIG),
0xEE => p.starts_with(ADOBE_SIG),
0xE0 => is_jfif,
0xE1 | 0xE3..=0xED | 0xEF | 0xFE => false,
_ => true,
};
if !keep {
continue;
}
// The orientation block goes after JFIF (which must come first) and before everything else kept.
if !is_jfif && let Some(o) = orientation_pending.take() {
out.extend_from_slice(&orientation_segment(o));
}
if is_jfif && p.len() > 14 {
// Rewrite without the thumbnail: version, units and density stay.
out.extend_from_slice(&[0xFF, 0xE0, 0x00, 16]);
out.extend_from_slice(&p[..12]);
out.extend_from_slice(&[0, 0]);
} else {
out.extend_from_slice(&b[s.span.0..s.span.1]);
}
}
if let Some(o) = orientation_pending {
out.extend_from_slice(&orientation_segment(o));
}
if parsed.eoi_end.is_some() {
out.extend_from_slice(&[0xFF, 0xD9]);
}
Ok(out)
}
/// A minimal APP1 Exif segment holding only the Orientation tag (big-endian TIFF, one IFD, one entry).
fn orientation_segment(o: u16) -> Vec<u8> {
let mut s = Vec::with_capacity(36);
s.extend_from_slice(&[0xFF, 0xE1, 0x00, 34]);
s.extend_from_slice(b"Exif\0\0");
s.extend_from_slice(b"MM\0\x2A\0\0\0\x08");
s.extend_from_slice(&[0x00, 0x01]);
s.extend_from_slice(&[0x01, 0x12, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01]);
s.extend_from_slice(&o.to_be_bytes());
s.extend_from_slice(&[0, 0]);
s.extend_from_slice(&[0, 0, 0, 0]);
s
}