exiftool-rs 0.5.0

Read, write, and edit metadata in 93 file formats — a pure Rust reimplementation of ExifTool 13.53 with 100% tag name parity (194/194 test files)
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
//! DjVu file format reader.
//!
//! Parses IFF-based DjVu files to extract metadata.
//! Mirrors ExifTool's DjVu.pm.

use crate::error::{Error, Result};
use crate::metadata::XmpReader;
use crate::tag::{Tag, TagGroup, TagId};
use crate::value::Value;

pub fn read_djvu(data: &[u8]) -> Result<Vec<Tag>> {
    if data.len() < 16 || !data.starts_with(b"AT&TFORM") {
        return Err(Error::InvalidData("not a DjVu file".into()));
    }

    let mut tags = Vec::new();
    let form_type = &data[12..16];

    // Determine subfile type
    let subfile_type = match form_type {
        b"DJVU" => "Single-page image",
        b"DJVM" => "Multi-page document",
        b"PM44" => "Color IW44",
        b"BM44" => "Grayscale IW44",
        b"DJVI" => "Shared component",
        b"THUM" => "Thumbnail image",
        _ => "",
    };
    if !subfile_type.is_empty() {
        tags.push(mk(
            "SubfileType",
            "Subfile Type",
            Value::String(subfile_type.into()),
        ));
    }

    // Parse chunks
    let pos = 16;
    parse_chunks(data, pos, data.len(), &mut tags);

    Ok(tags)
}

fn parse_chunks(data: &[u8], mut pos: usize, end: usize, tags: &mut Vec<Tag>) {
    while pos + 8 <= end {
        let chunk_id = &data[pos..pos + 4];
        let chunk_size =
            u32::from_be_bytes([data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]])
                as usize;
        pos += 8;

        let chunk_end = pos + chunk_size;
        if chunk_end > end {
            break;
        }

        let chunk_data = &data[pos..chunk_end];

        match chunk_id {
            b"INFO" => parse_info(chunk_data, tags),
            b"FORM" => {
                // FORM chunk contains a type and nested chunks
                if chunk_data.len() >= 4 {
                    let sub_type = &chunk_data[..4];
                    // SubfileType from form type
                    let subfile_str = match sub_type {
                        b"DJVU" => "Single-page image",
                        b"DJVM" => "Multi-page document",
                        b"PM44" => "Color IW44",
                        b"BM44" => "Grayscale IW44",
                        b"DJVI" => "Shared component",
                        b"THUM" => "Thumbnail image",
                        _ => "",
                    };
                    if !subfile_str.is_empty() {
                        tags.push(mk(
                            "SubfileType",
                            "Subfile Type",
                            Value::String(subfile_str.into()),
                        ));
                    }
                    parse_chunks(data, pos + 4, chunk_end, tags);
                }
            }
            b"ANTa" => parse_ant(chunk_data, tags),
            b"ANTz" => {
                // BZZ compressed annotation - decompress and parse
                if let Some(decompressed) = super::bzz::decode(chunk_data) {
                    parse_ant(&decompressed, tags);
                }
            }
            b"INCL" => {
                // Included file ID
                let id = crate::encoding::decode_utf8_or_latin1(chunk_data)
                    .trim_end_matches('\0')
                    .to_string();
                if !id.is_empty() {
                    tags.push(mk("IncludedFileID", "Included File ID", Value::String(id)));
                }
            }
            b"NDIR" => {
                // Bundled multi-page document directory - skip
            }
            _ => {}
        }

        pos = chunk_end;
        if chunk_size % 2 != 0 {
            pos += 1;
        }
    }
}

fn parse_info(data: &[u8], tags: &mut Vec<Tag>) {
    if data.len() < 10 {
        return;
    }
    let width = u16::from_be_bytes([data[0], data[1]]);
    let height = u16::from_be_bytes([data[2], data[3]]);

    // DjVu version: bytes 4 and 5 (minor, major)
    let minor = data[4];
    let major = data[5];
    let version_str = format!("{}.{}", major, minor);

    // Spatial resolution: little-endian uint16 at offset 6
    let dpi = u16::from_le_bytes([data[6], data[7]]);

    // Gamma at offset 8: uint8, value = gamma * 10
    let gamma = data[8] as f64 / 10.0;

    // Orientation at offset 9: lower 3 bits
    let orientation = if data.len() > 9 { data[9] & 0x07 } else { 0 };

    tags.push(mk("ImageWidth", "Image Width", Value::U16(width)));
    tags.push(mk("ImageHeight", "Image Height", Value::U16(height)));
    tags.push(mk(
        "DjVuVersion",
        "DjVu Version",
        Value::String(version_str),
    ));
    tags.push(mk(
        "SpatialResolution",
        "Spatial Resolution",
        Value::U16(dpi),
    ));

    if gamma > 0.0 {
        tags.push(mk("Gamma", "Gamma", Value::String(format!("{:.1}", gamma))));
    }

    let orient_str = match orientation {
        1 => "Horizontal (normal)",
        2 => "Rotate 180",
        5 => "Rotate 90 CW",
        6 => "Rotate 270 CW",
        _ => "Unknown (0)",
    };
    tags.push(mk(
        "Orientation",
        "Orientation",
        Value::String(orient_str.into()),
    ));
}

/// Parse DjVu ANTa annotation chunk (s-expression format)
fn parse_ant(data: &[u8], tags: &mut Vec<Tag>) {
    let text = crate::encoding::decode_utf8_or_latin1(data);
    let text = text.as_str();

    // Look for (metadata ...) block
    if let Some(meta_start) = find_sexpr(text, "metadata") {
        parse_meta_sexpr(&text[meta_start..], tags);
    }

    // Look for (xmp ...) block
    if let Some(xmp_content) = extract_sexpr_value(text, "xmp") {
        if let Ok(xmp_tags) = XmpReader::read(xmp_content.as_bytes()) {
            tags.extend(xmp_tags);
        }
    }

    // Look for (url ...) blocks
    let mut search = text;
    let mut url_start = 0;
    while let Some(pos) = search.find("(url ") {
        let from = url_start + pos;
        if let Some(url) = extract_sexpr_value(&text[from..], "url") {
            tags.push(mk("URL", "URL", Value::String(url)));
        }
        let advance = pos + 5;
        if advance >= search.len() {
            break;
        }
        search = &search[advance..];
        url_start += advance;
    }
}

fn find_sexpr(text: &str, name: &str) -> Option<usize> {
    let search = format!("({}", name);
    let mut pos = 0;
    while let Some(p) = text[pos..].find(&search) {
        let abs = pos + p;
        // Check that after the name comes a space, (, or "
        let after = abs + search.len();
        if after >= text.len()
            || matches!(
                text.as_bytes()[after],
                b' ' | b'\t' | b'\n' | b'\r' | b'"' | b'('
            )
        {
            return Some(abs);
        }
        pos = abs + 1;
    }
    None
}

fn extract_sexpr_value(text: &str, name: &str) -> Option<String> {
    let search = format!("({} ", name);
    if let Some(p) = text.find(&search) {
        let after = p + search.len();
        extract_sexpr_string(&text[after..])
    } else {
        None
    }
}

fn extract_sexpr_string(text: &str) -> Option<String> {
    let text = text.trim_start();
    if let Some(stripped) = text.strip_prefix('"') {
        // Parse quoted string
        let mut result = String::new();
        let mut chars = stripped.chars();
        loop {
            match chars.next() {
                None => break,
                Some('"') => return Some(result),
                Some('\\') => match chars.next() {
                    Some('n') => result.push('\n'),
                    Some('r') => result.push('\r'),
                    Some('t') => result.push('\t'),
                    Some('"') => result.push('"'),
                    Some('\\') => result.push('\\'),
                    Some(c) => {
                        result.push('\\');
                        result.push(c);
                    }
                    None => break,
                },
                Some(c) => result.push(c),
            }
        }
        Some(result)
    } else {
        // Unquoted token - read until whitespace or )
        let end = text
            .find(|c: char| c.is_whitespace() || c == ')')
            .unwrap_or(text.len());
        if end > 0 {
            Some(text[..end].to_string())
        } else {
            None
        }
    }
}

fn parse_meta_sexpr(text: &str, tags: &mut Vec<Tag>) {
    // Find (metadata ...)
    // Parse inner s-expressions as key/value pairs
    // Format: (metadata (key "value") (key "value") ...)
    let search = "(metadata";
    if let Some(p) = text.find(search) {
        let after = p + search.len();
        // skip whitespace after "metadata"
        let inner = &text[after..];
        // Parse each (key "value") pair
        parse_meta_pairs(inner, tags);
    }
}

fn parse_meta_pairs(text: &str, tags: &mut Vec<Tag>) {
    let mut pos = 0;
    let bytes = text.as_bytes();

    while pos < bytes.len() {
        // Skip whitespace
        while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
            pos += 1;
        }
        if pos >= bytes.len() {
            break;
        }
        if bytes[pos] == b')' {
            break; // End of metadata block
        }
        if bytes[pos] != b'(' {
            pos += 1;
            continue;
        }
        pos += 1; // skip '('

        // Read key
        let key_start = pos;
        while pos < bytes.len() && !bytes[pos].is_ascii_whitespace() && bytes[pos] != b')' {
            pos += 1;
        }
        let key = &text[key_start..pos];
        if key.is_empty() {
            continue;
        }

        // Skip whitespace
        while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
            pos += 1;
        }

        // Read value (could be quoted or unquoted)
        if pos >= bytes.len() {
            break;
        }

        let value = if bytes[pos] == b'"' {
            pos += 1;
            let mut s = String::new();
            loop {
                if pos >= bytes.len() {
                    break;
                }
                if bytes[pos] == b'"' {
                    pos += 1;
                    break;
                }
                if bytes[pos] == b'\\' && pos + 1 < bytes.len() {
                    pos += 1;
                    match bytes[pos] {
                        b'n' => s.push('\n'),
                        b'r' => s.push('\r'),
                        b't' => s.push('\t'),
                        b'"' => s.push('"'),
                        b'\\' => s.push('\\'),
                        c => {
                            s.push('\\');
                            s.push(c as char);
                        }
                    }
                } else {
                    s.push(bytes[pos] as char);
                }
                pos += 1;
            }
            s
        } else {
            let vstart = pos;
            while pos < bytes.len() && bytes[pos] != b')' && !bytes[pos].is_ascii_whitespace() {
                pos += 1;
            }
            text[vstart..pos].to_string()
        };

        // Skip to closing ')'
        while pos < bytes.len() && bytes[pos] != b')' {
            pos += 1;
        }
        if pos < bytes.len() {
            pos += 1; // skip ')'
        }

        // Map key to tag name
        let tag_name = djvu_meta_tag_name(key);
        if !value.is_empty() && !tag_name.is_empty() {
            tags.push(mk(&tag_name, &tag_name, Value::String(value)));
        }
    }
}

fn djvu_meta_tag_name(key: &str) -> String {
    match key {
        "author" => "Author".into(),
        "title" => "Title".into(),
        "subject" => "Subject".into(),
        "keywords" => "Keywords".into(),
        "creator" | "Creator" => "Creator".into(),
        "producer" | "Producer" => "Producer".into(),
        "CreationDate" => "CreateDate".into(),
        "ModDate" => "ModifyDate".into(),
        "note" => "Note".into(),
        "notes" | "Notes" => "Notes".into(),
        "annote" => "Annotation".into(),
        "year" => "Year".into(),
        "publisher" => "Publisher".into(),
        "journal" => "Journal".into(),
        "booktitle" => "BookTitle".into(),
        "url" => "URL".into(),
        "description" | "Description" => "Description".into(),
        "rights" | "Rights" => "Rights".into(),
        "Trapped" => "Trapped".into(),
        "CreatorTool" => "CreatorTool".into(),
        // PDF-style tags (capitalized)
        "Title" => "Title".into(),
        "Author" => "Author".into(),
        "Subject" => "Subject".into(),
        "Keywords" => "Keywords".into(),
        "ModifyDate" => "ModifyDate".into(),
        "CreateDate" => "CreateDate".into(),
        // Fallback: capitalize first letter
        s => {
            let mut chars = s.chars();
            match chars.next() {
                None => String::new(),
                Some(c) => c.to_uppercase().to_string() + chars.as_str(),
            }
        }
    }
}

fn mk(name: &str, description: &str, value: Value) -> Tag {
    let pv = value.to_display_string();
    Tag {
        id: TagId::Text(name.to_string()),
        name: name.to_string(),
        description: description.to_string(),
        group: TagGroup {
            family0: "DjVu".into(),
            family1: "DjVu".into(),
            family2: "Image".into(),
        },
        raw_value: value,
        print_value: pv,
        priority: 0,
    }
}