226 lines
7.6 KiB
Rust
226 lines
7.6 KiB
Rust
//! EXIF (a TIFF-structured block) to report items, through kamadak-exif.
|
|
|
|
use exif::{Context, Exif, Field, In, Reader, Tag, Value};
|
|
|
|
use crate::{Ctx, Group, guarded};
|
|
|
|
/// Lists the fields of a raw EXIF block (starting at the TIFF header) and returns the Orientation (1..=8) if one
|
|
/// could be read. Damage becomes a warning, never an error.
|
|
pub(crate) fn read_block(raw: &[u8], ctx: &mut Ctx) -> Option<u16> {
|
|
ctx.push(Group::Exif, "EXIF block", crate::bytes_label(raw.len()));
|
|
let parsed = guarded(|| {
|
|
let mut reader = Reader::new();
|
|
reader.continue_on_error(true);
|
|
match reader.read_raw(raw.to_vec()) {
|
|
Ok(exif) => Ok((exif, false)),
|
|
Err(e) => e.distill_partial_result(|_| {}).map(|exif| (exif, true)),
|
|
}
|
|
});
|
|
let exif = match parsed {
|
|
Some(Ok((exif, partial))) => {
|
|
if partial {
|
|
ctx.warn("Part of the EXIF data is damaged; what could be read is listed. All of it is removed.");
|
|
}
|
|
exif
|
|
}
|
|
Some(Err(_)) | None => {
|
|
ctx.warn("The EXIF data is damaged and could not be read. It is removed all the same.");
|
|
return None;
|
|
}
|
|
};
|
|
list(&exif, ctx)
|
|
}
|
|
|
|
/// Lists an already parsed EXIF (also used for TIFF files, whose own tags are EXIF-structured).
|
|
pub(crate) fn list(exif: &Exif, ctx: &mut Ctx) -> Option<u16> {
|
|
let mut orientation = None;
|
|
let mut lat = None;
|
|
let mut lon = None;
|
|
let mut make = None;
|
|
let mut model = None;
|
|
let mut thumbnail = false;
|
|
let mut rest: Vec<(Group, String, String)> = Vec::new();
|
|
|
|
for field in exif.fields() {
|
|
if field.ifd_num != In::PRIMARY {
|
|
thumbnail = true;
|
|
continue;
|
|
}
|
|
let tag = field.tag;
|
|
if is_structural(tag) {
|
|
continue;
|
|
}
|
|
match tag {
|
|
Tag::Orientation => {
|
|
orientation =
|
|
field.value.get_uint(0).and_then(|v| u16::try_from(v).ok()).filter(|v| (1..=8).contains(v))
|
|
}
|
|
Tag::GPSLatitude => lat = dms(&field.value),
|
|
Tag::GPSLongitude => lon = dms(&field.value),
|
|
Tag::Make => make = ascii(&field.value),
|
|
Tag::Model => model = ascii(&field.value),
|
|
_ => {}
|
|
}
|
|
rest.push((group_of(tag), tag.to_string(), value_text(field, exif)));
|
|
}
|
|
|
|
let negative = |ref_tag: Tag, neg: u8| {
|
|
exif.get_field(ref_tag, In::PRIMARY)
|
|
.and_then(|f| ascii(&f.value))
|
|
.is_some_and(|s| s.as_bytes().first().is_some_and(|c| c.eq_ignore_ascii_case(&neg)))
|
|
};
|
|
if let (Some(la), Some(lo)) = (lat, lon) {
|
|
let (ns, ew) = (
|
|
if negative(Tag::GPSLatitudeRef, b'S') { "S" } else { "N" },
|
|
if negative(Tag::GPSLongitudeRef, b'W') { "W" } else { "E" },
|
|
);
|
|
ctx.push(Group::Gps, "Location", format!("{} {ns}, {} {ew}", coord(la), coord(lo)));
|
|
}
|
|
let camera = match (make.as_deref(), model.as_deref()) {
|
|
(Some(ma), Some(mo)) if mo.to_lowercase().starts_with(&ma.to_lowercase()) => Some(mo.to_string()),
|
|
(Some(ma), Some(mo)) => Some(format!("{ma} {mo}")),
|
|
(Some(x), None) | (None, Some(x)) => Some(x.to_string()),
|
|
(None, None) => None,
|
|
};
|
|
if let Some(c) = camera.filter(|c| !c.is_empty()) {
|
|
ctx.push(Group::Camera, "Camera", c);
|
|
}
|
|
for (g, name, value) in rest {
|
|
ctx.push(g, name, value);
|
|
}
|
|
if thumbnail {
|
|
ctx.push(Group::Exif, "Embedded thumbnail", "yes (a small copy of the picture)");
|
|
}
|
|
orientation
|
|
}
|
|
|
|
fn group_of(tag: Tag) -> Group {
|
|
match tag.context() {
|
|
Context::Gps => return Group::Gps,
|
|
Context::Tiff | Context::Exif => {}
|
|
_ => return Group::Exif,
|
|
}
|
|
match tag {
|
|
Tag::Make | Tag::Model | Tag::BodySerialNumber | Tag::LensSpecification | Tag::LensMake | Tag::LensModel => {
|
|
Group::Camera
|
|
}
|
|
Tag::LensSerialNumber => Group::Camera,
|
|
Tag::Artist | Tag::Copyright | Tag::CameraOwnerName => Group::Author,
|
|
Tag::Software => Group::Software,
|
|
Tag::DateTime
|
|
| Tag::DateTimeOriginal
|
|
| Tag::DateTimeDigitized
|
|
| Tag::OffsetTime
|
|
| Tag::OffsetTimeOriginal
|
|
| Tag::OffsetTimeDigitized
|
|
| Tag::SubSecTime
|
|
| Tag::SubSecTimeOriginal
|
|
| Tag::SubSecTimeDigitized => Group::Dates,
|
|
Tag::UserComment | Tag::ImageDescription => Group::Comment,
|
|
_ => match (tag.context(), tag.number()) {
|
|
// HostComputer, ProcessingSoftware
|
|
(Context::Tiff, 0x013C | 0x000B) => Group::Software,
|
|
// XPTitle, XPComment, XPAuthor, XPKeywords, XPSubject (Windows)
|
|
(Context::Tiff, 0x9C9B..=0x9C9F) => Group::Comment,
|
|
_ => Group::Exif,
|
|
},
|
|
}
|
|
}
|
|
|
|
/// Tags that describe the pixel layout, not the picture's story; not listed.
|
|
fn is_structural(tag: Tag) -> bool {
|
|
if tag.context() != Context::Tiff {
|
|
return false;
|
|
}
|
|
matches!(
|
|
tag.number(),
|
|
0x00FE..=0x0103
|
|
| 0x0106
|
|
| 0x0107
|
|
| 0x010A
|
|
| 0x0111
|
|
| 0x0115..=0x011C
|
|
| 0x0128
|
|
| 0x013D..=0x0140
|
|
| 0x0142..=0x0145
|
|
| 0x014A
|
|
| 0x0152
|
|
| 0x0153
|
|
| 0x0201
|
|
| 0x0202
|
|
| 0x0211..=0x0214
|
|
| 0x8769
|
|
| 0x8773
|
|
| 0x8825
|
|
| 0xA005
|
|
)
|
|
}
|
|
|
|
fn value_text(field: &Field, exif: &Exif) -> String {
|
|
match &field.value {
|
|
Value::Ascii(_) => ascii(&field.value).unwrap_or_default(),
|
|
Value::Undefined(v, _) if field.tag == Tag::MakerNote => {
|
|
format!("{} (the camera maker's private data)", crate::bytes_label(v.len()))
|
|
}
|
|
Value::Byte(v) | Value::Undefined(v, _) if v.len() > 64 && !is_text_like(field.tag) => {
|
|
crate::bytes_label(v.len())
|
|
}
|
|
v if value_len(v) > 64 => format!("{} values", value_len(v)),
|
|
_ => guarded(|| field.display_value().with_unit(exif).to_string()).unwrap_or_default(),
|
|
}
|
|
}
|
|
|
|
fn is_text_like(tag: Tag) -> bool {
|
|
tag == Tag::UserComment || (tag.context() == Context::Tiff && (0x9C9B..=0x9C9F).contains(&tag.number()))
|
|
}
|
|
|
|
fn value_len(v: &Value) -> usize {
|
|
match v {
|
|
Value::Byte(x) | Value::Undefined(x, _) => x.len(),
|
|
Value::Ascii(x) => x.len(),
|
|
Value::Short(x) => x.len(),
|
|
Value::Long(x) => x.len(),
|
|
Value::Rational(x) => x.len(),
|
|
Value::SByte(x) => x.len(),
|
|
Value::SShort(x) => x.len(),
|
|
Value::SLong(x) => x.len(),
|
|
Value::SRational(x) => x.len(),
|
|
Value::Float(x) => x.len(),
|
|
Value::Double(x) => x.len(),
|
|
Value::Unknown(..) => 0,
|
|
}
|
|
}
|
|
|
|
fn ascii(v: &Value) -> Option<String> {
|
|
match v {
|
|
Value::Ascii(parts) => {
|
|
let s: Vec<String> =
|
|
parts.iter().map(|p| crate::text::lossy(p).trim().to_string()).filter(|p| !p.is_empty()).collect();
|
|
Some(s.join("; "))
|
|
}
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Degrees, minutes, seconds as rationals to decimal degrees.
|
|
fn dms(v: &Value) -> Option<f64> {
|
|
let Value::Rational(parts) = v else { return None };
|
|
if parts.is_empty() {
|
|
return None;
|
|
}
|
|
let mut deg = 0.0;
|
|
for (r, scale) in parts.iter().zip([1.0, 60.0, 3600.0]) {
|
|
if r.denom == 0 {
|
|
return None;
|
|
}
|
|
deg += f64::from(r.num) / f64::from(r.denom) / scale;
|
|
}
|
|
(deg.is_finite() && deg <= 180.0).then_some(deg)
|
|
}
|
|
|
|
fn coord(v: f64) -> String {
|
|
let s = format!("{v:.5}");
|
|
let s = s.trim_end_matches('0').trim_end_matches('.');
|
|
s.to_string()
|
|
}
|