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

172 lines
5.8 KiB
Rust

//! PNG at the chunk level: kept chunks are copied byte for byte (with their CRCs).
use crate::{Ctx, Group, MetaError, exif_items, text, xmp};
pub(crate) const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
const MAX_CHUNKS: usize = 1_000_000;
/// Chunks that carry metadata and are dropped.
const DROPPED: [&[u8; 4]; 5] = [b"eXIf", b"tEXt", b"zTXt", b"iTXt", b"tIME"];
struct Chunk {
kind: [u8; 4],
/// From the length field to the end of the CRC.
span: (usize, usize),
data: (usize, usize),
}
#[derive(Default)]
struct Parsed {
chunks: Vec<Chunk>,
/// The position after IEND, if there is one.
iend_end: Option<usize>,
error: Option<MetaError>,
}
fn parse(b: &[u8]) -> Parsed {
let mut p = Parsed::default();
let mut pos = SIGNATURE.len();
while pos < b.len() {
if p.chunks.len() >= MAX_CHUNKS {
p.error = Some(MetaError::Damaged("it has too many chunks".into()));
break;
}
let (Some(len), Some(kind)) = (text::be32(b, pos), b.get(pos + 4..pos + 8)) else {
p.error = Some(MetaError::truncated());
break;
};
if len > 0x7FFF_FFFF {
p.error = Some(MetaError::Damaged("a chunk has an impossible length".into()));
break;
}
let data_start = pos + 8;
let Some(end) = data_start.checked_add(len as usize).and_then(|e| e.checked_add(4)).filter(|&e| e <= b.len())
else {
p.error = Some(MetaError::truncated());
break;
};
let kind = [kind[0], kind[1], kind[2], kind[3]];
p.chunks.push(Chunk { kind, span: (pos, end), data: (data_start, end - 4) });
pos = end;
if &kind == b"IEND" {
p.iend_end = Some(end);
break;
}
}
if p.error.is_none() && p.iend_end.is_none() {
p.error = Some(MetaError::truncated());
}
p
}
pub(crate) fn read(b: &[u8], ctx: &mut Ctx) -> Result<(), MetaError> {
let parsed = parse(b);
for c in &parsed.chunks {
let data = b.get(c.data.0..c.data.1).unwrap_or(&[]);
match &c.kind {
b"eXIf" => {
let raw = if data.starts_with(b"Exif\0\0") { &data[6..] } else { data };
exif_items::read_block(raw, ctx);
}
b"tEXt" => {
let (key, value) = split_nul(data);
let key = text::latin1(key);
ctx.push(text_group(&key), key_label(&key), text::latin1(value));
}
b"zTXt" => {
let (key, value) = split_nul(data);
let key = text::latin1(key);
let value = format!("compressed text, {}", crate::bytes_label(value.len().saturating_sub(1)));
ctx.push(text_group(&key), key_label(&key), value);
}
b"iTXt" => read_itxt(data, ctx),
b"tIME" if data.len() >= 7 => {
let year = u16::from_be_bytes([data[0], data[1]]);
let value =
format!("{year:04}-{:02}-{:02} {:02}:{:02}:{:02}", data[2], data[3], data[4], data[5], data[6]);
ctx.push(Group::Dates, "Last modified", value);
}
b"tIME" => ctx.push(Group::Dates, "Last modified", "(damaged)"),
_ => {}
}
}
if let Some(end) = parsed.iend_end
&& b.len() > end
{
ctx.push(Group::Other, "Data after the end of the image", crate::bytes_label(b.len() - end));
}
if let Some(e) = parsed.error {
if parsed.chunks.is_empty() {
return Err(e);
}
ctx.warn(format!("{e} Only part of it could be read."));
}
Ok(())
}
fn read_itxt(data: &[u8], ctx: &mut Ctx) {
let (key, rest) = split_nul(data);
let key = text::latin1(key);
let (Some(&compressed), Some(_method)) = (rest.first(), rest.get(1)) else {
ctx.push(text_group(&key), key_label(&key), "(damaged)");
return;
};
let rest = rest.get(2..).unwrap_or(&[]);
let (_lang, rest) = split_nul(rest);
let (_translated, value) = split_nul(rest);
if key == "XML:com.adobe.xmp" {
if compressed == 0 {
xmp::read_packet(value, Group::Xmp, "XMP packet", ctx);
} else {
ctx.push(Group::Xmp, "XMP packet (compressed)", crate::bytes_label(value.len()));
}
return;
}
let shown = if compressed == 0 {
String::from_utf8_lossy(value).into_owned()
} else {
format!("compressed text, {}", crate::bytes_label(value.len()))
};
ctx.push(text_group(&key), key_label(&key), shown);
}
fn split_nul(b: &[u8]) -> (&[u8], &[u8]) {
match b.iter().position(|&c| c == 0) {
Some(i) => (&b[..i], &b[i + 1..]),
None => (b, &[]),
}
}
fn key_label(key: &str) -> String {
if key.is_empty() { "Text".into() } else { key.to_string() }
}
fn text_group(key: &str) -> Group {
match key.to_ascii_lowercase().as_str() {
"author" | "copyright" | "artist" => Group::Author,
"software" => Group::Software,
"source" => Group::Camera,
"creation time" | "date" => Group::Dates,
"title" | "description" | "comment" | "disclaimer" | "warning" => Group::Comment,
"xml:com.adobe.xmp" | "raw profile type xmp" => Group::Xmp,
"raw profile type exif" | "raw profile type app1" => Group::Exif,
"raw profile type iptc" | "raw profile type 8bim" => Group::Iptc,
_ => Group::Other,
}
}
pub(crate) fn strip(b: &[u8]) -> Result<Vec<u8>, MetaError> {
let parsed = parse(b);
if let Some(e) = parsed.error {
return Err(e);
}
let mut out = Vec::with_capacity(b.len());
out.extend_from_slice(&SIGNATURE);
for c in &parsed.chunks {
if !DROPPED.contains(&&c.kind) {
out.extend_from_slice(&b[c.span.0..c.span.1]);
}
}
Ok(out)
}