exiftool-rs 0.7.4

Read, write, and edit metadata in 93 file formats — a pure Rust reimplementation of ExifTool 13.59 with tag-name and value parity across the test corpus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! IPTC (International Press Telecommunications Council) metadata reader.
//!
//! Reads IPTC-IIM (Information Interchange Model) records, commonly found
//! in JPEG APP13 Photoshop segments. Mirrors ExifTool's IPTC.pm.

use crate::error::Result;
use crate::tag::{Tag, TagGroup, TagId};
use crate::tags::iptc as iptc_tags;
use crate::value::Value;

/// Family-1 group of an IPTC directory sitting where the format says it should
/// (`JPEG-APP13-Photoshop-IPTC`, `TIFF-IFD0-IPTC`, …), and of every IPTC block
/// in a format that has no standard location at all (PDF, MIFF, …).
const STANDARD_GROUP1: &str = "IPTC";

/// Family-1 group of an IPTC directory found in an unexpected place inside a
/// format that *does* define a standard one. ExifTool's `ProcessIPTC` counts
/// those and appends the count + 1 to the group name, so the first is `IPTC2`.
/// We only ever see one per file, so the counter is not modelled.
const NONSTANDARD_GROUP1: &str = "IPTC2";

/// IPTC metadata reader.
pub struct IptcReader;

impl IptcReader {
    /// Parse IPTC data from a raw byte slice.
    ///
    /// IPTC-IIM format: sequences of records, each:
    ///   - 1 byte:  tag marker (0x1C)
    ///   - 1 byte:  record number
    ///   - 1 byte:  dataset number
    ///   - 2 bytes: data length (big-endian), or extended if >= 0x8000
    ///   - N bytes: data
    ///
    /// Pre-scan IPTC data for CodedCharacterSet (record 1, dataset 90).
    /// Returns true if UTF-8 is indicated (ESC %G = bytes 0x1B 0x25 0x47).
    fn detect_iptc_charset(data: &[u8]) -> bool {
        let mut pos = 0;
        while pos + 5 <= data.len() {
            if data[pos] != 0x1C {
                pos += 1;
                continue;
            }
            let record = data[pos + 1];
            let dataset = data[pos + 2];
            let length = u16::from_be_bytes([data[pos + 3], data[pos + 4]]) as usize;
            pos += 5;
            if length >= 0x8000 {
                break;
            }
            if pos + length > data.len() {
                break;
            }
            if record == 1 && dataset == 90 {
                let val = &data[pos..pos + length];
                // ESC %G = UTF-8
                return val.windows(3).any(|w| w == [0x1B, 0x25, 0x47]);
            }
            pos += length;
        }
        false
    }

    /// Read an IPTC directory found at the format's standard location.
    pub fn read(data: &[u8]) -> Result<Vec<Tag>> {
        Self::read_in_group(data, STANDARD_GROUP1)
    }

    /// Read an IPTC directory found somewhere ExifTool does not expect one — a
    /// JPEG trailer, a maker note — which lands in its own numbered family-1
    /// group. See [`NONSTANDARD_GROUP1`].
    pub fn read_nonstandard(data: &[u8]) -> Result<Vec<Tag>> {
        Self::read_in_group(data, NONSTANDARD_GROUP1)
    }

    fn read_in_group(data: &[u8], group1: &str) -> Result<Vec<Tag>> {
        let mut tags = Vec::new();
        let is_utf8 = Self::detect_iptc_charset(data);
        let mut pos = 0;

        while pos + 5 <= data.len() {
            // Check for IPTC tag marker
            if data[pos] != 0x1C {
                // Skip non-IPTC data
                pos += 1;
                continue;
            }

            let record = data[pos + 1];
            let dataset = data[pos + 2];
            let length = u16::from_be_bytes([data[pos + 3], data[pos + 4]]) as usize;

            pos += 5;

            // Extended dataset length (bit 15 set means the length field itself
            // gives the number of bytes in an extended length that follows)
            if length >= 0x8000 {
                // Skip extended length datasets for now
                break;
            }

            if pos + length > data.len() {
                break;
            }

            let value_data = &data[pos..pos + length];
            pos += length;

            // Only handle Envelope (record 1) and Application (record 2); the
            // rest carry no tags we surface. The record does NOT select the
            // family-1 group: ExifTool names it after the IPTC *directory*, so
            // both records share the group passed in by the caller.
            if !matches!(record, 1 | 2) {
                continue;
            }

            // Check for PhotoMechanic SoftEdit fields BEFORE string decoding
            // (These are int32s, not strings, so must be decoded as binary)
            if record == 2 && (209..=222).contains(&dataset) {
                // Decode as binary (int32s)
                let bin_value = Value::Binary(value_data.to_vec());
                if let Some((pm_name, pm_print)) = lookup_photomechanic(dataset, &bin_value) {
                    tags.push(Tag {
                        id: TagId::Numeric(((record as u16) << 8) | dataset as u16),
                        name: pm_name.clone(),
                        description: pm_name,
                        group: TagGroup {
                            family0: "PhotoMechanic".to_string(),
                            family1: "PhotoMechanic".to_string(),
                            family2: "Image".to_string(),
                            family3: "Main".into(),
                        },
                        raw_value: bin_value,
                        print_value: pm_print,
                        priority: 0,
                    });
                    continue;
                }
            }

            let value = if iptc_tags::is_string_tag(record, dataset) {
                let s = if is_utf8 {
                    crate::encoding::decode_utf8_or_latin1(value_data).to_string()
                } else {
                    crate::encoding::decode_latin1(value_data)
                };
                Value::String(s.trim_end_matches('\0').to_string())
            } else if length <= 2 {
                match length {
                    1 => Value::U8(value_data[0]),
                    2 => Value::U16(u16::from_be_bytes([value_data[0], value_data[1]])),
                    _ => Value::Binary(value_data.to_vec()),
                }
            } else {
                Value::Binary(value_data.to_vec())
            };

            let tag_info = iptc_tags::lookup(record, dataset);
            let (name, description) = match tag_info {
                Some(info) => (info.name.to_string(), info.description.to_string()),
                None => {
                    // Suppress unknown IPTC records (don't emit IPTC:N:N format)
                    continue;
                }
            };

            let base = value.to_display_string();
            let print_value = iptc_print_conv(record, dataset, &base).unwrap_or(base);

            // Repeatable datasets (Keywords, SupplementalCategories, ...) appear
            // multiple times; ExifTool combines them into one comma-joined list.
            let id_num = ((record as u16) << 8) | dataset as u16;
            if let Some(existing) = tags
                .iter_mut()
                .find(|t| matches!(t.id, TagId::Numeric(n) if n == id_num))
            {
                let prev = std::mem::replace(&mut existing.raw_value, Value::U8(0));
                let mut items = match prev {
                    Value::List(v) => v,
                    single => vec![single],
                };
                items.push(value);
                existing.print_value = items
                    .iter()
                    .map(|v| v.to_display_string())
                    .collect::<Vec<_>>()
                    .join(", ");
                existing.raw_value = Value::List(items);
                continue;
            }

            tags.push(Tag {
                id: TagId::Numeric(id_num),
                name,
                description,
                group: TagGroup {
                    family0: "IPTC".to_string(),
                    family1: group1.to_string(),
                    family2: "Other".to_string(),
                    family3: "Main".into(),
                },
                raw_value: value,
                print_value,
                priority: 0,
            });
        }

        Ok(tags)
    }
}

/// IPTC PrintConv for the Application Record (record 2): date reformatting and
/// the Urgency labels, matching ExifTool.
/// Convert an IPTC time "HHMMSS[±HHMM]" to ExifTool's "HH:MM:SS[±HH:MM]".
fn convert_iptc_time(s: &str) -> Option<String> {
    let b = s.as_bytes();
    if b.len() < 6 || !b[0..6].iter().all(|c| c.is_ascii_digit()) {
        return None;
    }
    let mut out = format!("{}:{}:{}", &s[0..2], &s[2..4], &s[4..6]);
    let tz = &s[6..];
    if !tz.is_empty() {
        let tb = tz.as_bytes();
        if tb.len() == 5
            && (tb[0] == b'+' || tb[0] == b'-')
            && tb[1..].iter().all(|c| c.is_ascii_digit())
        {
            out.push_str(&format!("{}{}:{}", &tz[0..1], &tz[1..3], &tz[3..5]));
        } else {
            return None;
        }
    }
    Some(out)
}

fn iptc_print_conv(record: u8, dataset: u8, s: &str) -> Option<String> {
    if record != 2 {
        return None;
    }
    let s = s.trim();
    match dataset {
        // ObjectPreviewFileFormat (200): %fileFormat enum; unrecognized -> "Unknown (val)".
        200 => {
            let name = match s {
                "0" => Some("No ObjectData"),
                "1" => Some("IPTC-NAA Digital Newsphoto Parameter Record"),
                "2" => Some("IPTC7901 Recommended Message Format"),
                "3" => Some("Tagged Image File Format (Adobe/Aldus Image data)"),
                "4" => Some("Illustrator (Adobe Graphics data)"),
                "5" => Some("AppleSingle (Apple Computer Inc)"),
                _ => None,
            };
            Some(
                name.map(|n| n.to_string())
                    .unwrap_or_else(|| format!("Unknown ({})", s)),
            )
        }
        // DateCreated (55), DigitizationDate (62): YYYYMMDD -> YYYY:MM:DD
        55 | 62 if s.len() == 8 && s.bytes().all(|b| b.is_ascii_digit()) => {
            Some(format!("{}:{}:{}", &s[0..4], &s[4..6], &s[6..8]))
        }
        // TimeCreated (60), DigitalCreationTime (63): HHMMSS[±HHMM] -> HH:MM:SS[±HH:MM]
        60 | 63 => convert_iptc_time(s),
        // Urgency (10)
        10 => Some(
            match s {
                "0" => "0 (reserved)",
                "1" => "1 (most urgent)",
                "5" => "5 (normal urgency)",
                "8" => "8 (least urgent)",
                _ => return None,
            }
            .to_string(),
        ),
        // Prefs (221): IPTC.pm:655 rewrites the first " N: N: N:S" run into the
        // labelled form "Tagged:N, ColorClass:N, Rating:N, FrameNum:S". The
        // substitution is applied once; text that doesn't match is returned as-is.
        221 => Some(prefs_print_conv(s)),
        // ObjectCycle (75): PrintConv { a, p, b }, unmatched → "Unknown ($val)".
        75 => Some(match s {
            "a" => "Morning".to_string(),
            "p" => "Evening".to_string(),
            "b" => "Both Morning and Evening".to_string(),
            other => format!("Unknown ({})", other),
        }),
        _ => None,
    }
}

/// Perl PrintConv for IPTC Prefs (record 2 dataset 221, IPTC.pm:655):
///   `s[\s*(\d+):\s*(\d+):\s*(\d+):\s*(\S*)][Tagged:$1, ColorClass:$2, Rating:$3, FrameNum:$4]`
/// applied once. `\S*` is greedy but stops at whitespace, so FrameNum captures
/// the remaining non-space token (e.g. a negative "-00001").
fn prefs_print_conv(s: &str) -> String {
    let b = s.as_bytes();
    // Scan for the leftmost match of the regex.
    for start in 0..b.len() {
        let mut i = start;
        // \s*
        while i < b.len() && b[i].is_ascii_whitespace() {
            i += 1;
        }
        let mut nums: [&str; 3] = [""; 3];
        let mut ok = true;
        for num in &mut nums {
            let d0 = i;
            while i < b.len() && b[i].is_ascii_digit() {
                i += 1;
            }
            if i == d0 || i >= b.len() || b[i] != b':' {
                ok = false;
                break;
            }
            *num = &s[d0..i];
            i += 1; // consume ':'
                    // \s* before the next field
            while i < b.len() && b[i].is_ascii_whitespace() {
                i += 1;
            }
        }
        if !ok {
            continue;
        }
        // (\S*) — the FrameNum token: every following non-whitespace char.
        let f0 = i;
        while i < b.len() && !b[i].is_ascii_whitespace() {
            i += 1;
        }
        let frame = &s[f0..i];
        return format!(
            "{}Tagged:{}, ColorClass:{}, Rating:{}, FrameNum:{}{}",
            &s[..start],
            nums[0],
            nums[1],
            nums[2],
            frame,
            &s[i..]
        );
    }
    s.to_string()
}

/// Look up a PhotoMechanic SoftEdit field (IPTC record 2, dataset 209-239).
/// Returns (tag_name, print_value) or None if unknown.
fn lookup_photomechanic(dataset: u8, value: &Value) -> Option<(String, String)> {
    // PhotoMechanic fields are FORMAT='int32s' - 4 bytes big-endian signed int
    let int_val = if let Value::Binary(ref b) = value {
        if b.len() == 4 {
            i32::from_be_bytes([b[0], b[1], b[2], b[3]])
        } else {
            return None;
        }
    } else {
        return None;
    };

    let color_classes = [
        "0 (None)",
        "1 (Winner)",
        "2 (Winner alt)",
        "3 (Superior)",
        "4 (Superior alt)",
        "5 (Typical)",
        "6 (Typical alt)",
        "7 (Extras)",
        "8 (Trash)",
    ];

    match dataset {
        209 => Some((
            "RawCropLeft".to_string(),
            format!("{:.3}%", int_val as f64 / 655.36),
        )),
        210 => Some((
            "RawCropTop".to_string(),
            format!("{:.3}%", int_val as f64 / 655.36),
        )),
        211 => Some((
            "RawCropRight".to_string(),
            format!("{:.3}%", int_val as f64 / 655.36),
        )),
        212 => Some((
            "RawCropBottom".to_string(),
            format!("{:.3}%", int_val as f64 / 655.36),
        )),
        213 => Some(("ConstrainedCropWidth".to_string(), int_val.to_string())),
        214 => Some(("ConstrainedCropHeight".to_string(), int_val.to_string())),
        215 => Some(("FrameNum".to_string(), int_val.to_string())),
        216 => {
            let rot = match int_val {
                0 => "0",
                1 => "90",
                2 => "180",
                3 => "270",
                _ => "0",
            };
            Some(("Rotation".to_string(), rot.to_string()))
        }
        217 => Some(("CropLeft".to_string(), int_val.to_string())),
        218 => Some(("CropTop".to_string(), int_val.to_string())),
        219 => Some(("CropRight".to_string(), int_val.to_string())),
        220 => Some(("CropBottom".to_string(), int_val.to_string())),
        221 => {
            let v = if int_val == 0 { "No" } else { "Yes" };
            Some(("Tagged".to_string(), v.to_string()))
        }
        222 => {
            let idx = int_val as usize;
            let class = if idx < color_classes.len() {
                color_classes[idx].to_string()
            } else {
                format!("{}", int_val)
            };
            Some(("ColorClass".to_string(), class))
        }
        223 => Some(("Rating".to_string(), int_val.to_string())),
        236 => Some((
            "PreviewCropLeft".to_string(),
            format!("{:.3}%", int_val as f64 / 655.36),
        )),
        237 => Some((
            "PreviewCropTop".to_string(),
            format!("{:.3}%", int_val as f64 / 655.36),
        )),
        238 => Some((
            "PreviewCropRight".to_string(),
            format!("{:.3}%", int_val as f64 / 655.36),
        )),
        239 => Some((
            "PreviewCropBottom".to_string(),
            format!("{:.3}%", int_val as f64 / 655.36),
        )),
        _ => None,
    }
}