raves_metadata 0.0.4

A library to parse metadata from media 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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! A parser generic over HEIC, AVIF, and other formats with identical
//! structure.
//!
//! Here's a nice resource explaining the file structure:
//!
//! <https://github.com/spacestation93/heif_howto>

use std::{collections::HashMap, fmt::Write as _, sync::Arc};

use parking_lot::RwLock;
use winnow::{Parser as _, binary::be_u32, combinator::peek, error::EmptyError};

use crate::{
    MaybeParsedExif, MaybeParsedXmp, MetadataProviderRaw,
    providers::shared::{
        bmff::{
            BoxHeader, BoxType,
            ftyp::FtypBox,
            heif::{
                iinf::{FullBox, ItemInfoBox, ItemInfoEntry},
                iloc::{ConstructionMethod, ItemExtent, ItemLocationBox, ItemLocationEntry},
                pitm::PrimaryItemBox,
            },
        },
        desc,
    },
};

mod iinf;
mod iloc;
mod pitm;
mod search;

/// A HEIF-like file.
#[derive(Clone, Debug)]
pub struct HeifLike {
    exif: Arc<RwLock<Option<MaybeParsedExif>>>,
    xmp: Arc<RwLock<Option<MaybeParsedXmp>>>,
}

impl HeifLike {
    pub fn parse(
        input: &mut &[u8],
        supported_ftyp_entries: &[[u8; 4]],
    ) -> Result<HeifLike, HeifLikeConstructionError> {
        parse_heif_like(input, supported_ftyp_entries)
    }

    /// Helper associated function called by other HEIF-likes to parse the
    /// magic number.
    pub fn parse_magic_number(input: &[u8], supported_ftyp_entries: &[[u8; 4]]) -> bool {
        let mut input = input;

        // grab the `ftyp` box, which must be the first in the file.
        let Some(ftyp) = FtypBox::new(&mut input) else {
            log::trace!("No `ftyp` box.");
            return false;
        };

        // ensure the brand is correct
        if !supported_ftyp_entries.contains(&ftyp.major_brand)
            && !ftyp
                .compatible_brands
                .iter()
                .any(|c| supported_ftyp_entries.contains(c))
        {
            return false;
        }

        true
    }
}

impl MetadataProviderRaw for HeifLike {
    fn exif_raw(&self) -> Arc<RwLock<Option<MaybeParsedExif>>> {
        Arc::clone(&self.exif)
    }

    fn xmp_raw(&self) -> Arc<RwLock<Option<MaybeParsedXmp>>> {
        Arc::clone(&self.xmp)
    }
}

fn parse_heif_like<'input>(
    input: &mut &'input [u8],
    supported_ftyp_entries: &[[u8; 4]],
) -> Result<HeifLike, HeifLikeConstructionError> {
    // save the "original" input so we can use it later when parsing w/
    // offsets.
    //
    // required since MPEG-21 ("items") require parsing w/ this style, which
    // includes HEIF files...
    let original_input: &'input [u8] = input;

    // grab the `ftyp` box, which must be the first in the file.
    let ftyp: FtypBox = FtypBox::new(input).ok_or_else(|| {
        log::error!(
            "The `ftyp` box was not found. It may not be the first \
            box in the file."
        );
        HeifLikeConstructionError::NoFtypBox
    })?;
    log::trace!("found ftyp box! major brand: {:?}", ftyp.major_brand);

    // ensure the brand is correct
    if !supported_ftyp_entries.contains(&ftyp.major_brand)
        && !ftyp
            .compatible_brands
            .iter()
            .any(|c| supported_ftyp_entries.contains(c))
    {
        log::error!("Not a HEIF-like file. Returning error.");
        return Err(HeifLikeConstructionError::NotAHeifLike {
            major_brand: ftyp.major_brand,
        });
    }

    // try to grab the `meta` box.
    //
    // if we don't find one, then the media probably doesn't have metadata.
    log::trace!("Looking for meta boxes...");
    let mut meta_box_list: Vec<(FullBox, &[u8])> = search::find_meta_boxes(input);

    // ensure we've just got one
    let mut meta_box: (FullBox, &[u8]) = match meta_box_list.len() {
        // zero metadata boxes?
        //
        // then we've got no metadata. ez pz for this library
        0 => {
            log::debug!(
                "The `meta` box had no children. \
                No metadata to find, so returning!"
            );
            return Ok(HeifLike {
                exif: Arc::new(const { RwLock::new(None) }),
                xmp: Arc::new(const { RwLock::new(None) }),
            });
        }

        // ah, perfect.
        //
        // let's steal the box
        1 => meta_box_list.remove(0),

        // more than one metabox isn't currently supported.
        //
        // print + return an error
        other => {
            log::error!(
                "Multiple `meta` boxes detected! This structure isn't \
                currently supported. Please create an issue and upload your \
                image if you encounter this error. \
                expected `1` meta box, but found `{other}`..!"
            );
            return Err(HeifLikeConstructionError::MultipleMetaBoxes { n: other as u32 });
        }
    };
    log::trace!("Found one meta box.");
    let meta_blob = &mut meta_box.1;

    // try to find the `ItemInfoBox` and `ItemLocationBox`.
    //
    // - `ItemInfoBox` contains info about what items will be present
    // - `ItemLocationBox` says where things will be in the file
    // - `PrimaryItemBox` notes which item is the "primary" one
    // - `ItemDataBox` contains metadata, if `construction_method` specifies
    let mut maybe_item_info: Option<ItemInfoBox> = None;
    let mut maybe_item_location: Option<ItemLocationBox> = None;
    let mut maybe_item_data: Option<&[u8]> = None;
    let mut maybe_primary_item: Option<PrimaryItemBox> = None;
    while !meta_blob.is_empty() {
        if maybe_item_info.is_some() && maybe_item_location.is_some() {
            break;
        }

        // parse next box (without consuming its data)
        let box_header: BoxHeader = match peek(BoxHeader::new).parse_next(meta_blob) {
            Ok(bh) => bh,
            Err(e) => {
                log::warn!("Failed to parse box header! err: {e}");
                break;
            }
        };

        match box_header.box_type {
            // ItemInfoBox (`iinf`)
            ty if ty == BoxType::Id(*b"iinf") => {
                maybe_item_info = Some(
                    ItemInfoBox::new
                        .parse_next(meta_blob)
                        .inspect_err(|e| {
                            log::error!("Failed to parse `ItemInfoBox` inside `MetaBox`. err: {e}")
                        })
                        .map_err(|_| HeifLikeConstructionError::CantParseItemInfoBox)?,
                );
            }

            // ItemLocationBox (`iloc`)
            ty if ty == BoxType::Id(*b"iloc") => {
                maybe_item_location = Some(
                    ItemLocationBox::new
                        .parse_next(meta_blob)
                        .inspect_err(|e| {
                            log::error!(
                                "Failed to parse `ItemLocationBox` inside `MetaBox`. err: {e}"
                            )
                        })
                        .map_err(|_| HeifLikeConstructionError::CantParseItemLocationBox)?,
                );
            }

            // ItemDataBox (`idat`)
            ty if ty == BoxType::Id(*b"idat") => {
                if let Some(blob) = BoxHeader::new
                    .context(desc("item data box header"))
                    .parse_next(meta_blob)
                    .ok()
                    .and_then(|header: BoxHeader| header.payload(input))
                {
                    maybe_item_data = Some(blob);
                } else {
                    log::error!("Failed to build `idat`.");
                };
            }

            // PrimaryItemBox (`pitm`)
            ty if ty == BoxType::Id(*b"pitm") => {
                maybe_primary_item = Some(
                    PrimaryItemBox::new
                        .parse_next(meta_blob)
                        .inspect_err(|e| {
                            log::error!(
                                "Failed to parse `PrimaryItemBox` inside `MetaBox`. err: {e}"
                            )
                        })
                        .map_err(|_| HeifLikeConstructionError::CantParsePrimaryItemBox)?,
                );
            }

            unsupported_box_type => {
                log::trace!("Skipping unsupported box type: `{unsupported_box_type:?}`");

                // skip it
                _ = BoxHeader::new
                    .parse_next(meta_blob)
                    .ok()
                    .and_then(|header| header.eat_payload(meta_blob));
            }
        }
    }
    log::trace!("Item info found? {}", maybe_item_info.is_some());
    log::trace!("Item location found? {}", maybe_item_location.is_some());
    log::trace!("Item data found? {}", maybe_item_data.is_some());
    log::trace!("Primary item found? {}", maybe_primary_item.is_some());

    // ensure we have item info
    let Some(item_info) = maybe_item_info else {
        log::debug!(
            "No item info detected, so there can't be any metadata. \
            Returning blank metadata."
        );
        return Ok(HeifLike {
            exif: Arc::new(const { RwLock::new(None) }),
            xmp: Arc::new(const { RwLock::new(None) }),
        });
    };

    //  loc info
    let Some(item_location) = maybe_item_location else {
        log::debug!(
            "No item locations detected, so we can't find any metadata. \
            Returning blank metadata."
        );
        return Ok(HeifLike {
            exif: Arc::new(const { RwLock::new(None) }),
            xmp: Arc::new(const { RwLock::new(None) }),
        });
    };

    let metadata_blobs = find_metadata(
        original_input,
        item_info,
        item_location,
        maybe_item_data,
        maybe_primary_item,
    )
    .inspect_err(|e| log::error!("Failed to parse final metadata blobs. err: {e}"))
    .inspect(|t| {
        log::trace!("Found Exif? {}", t.exif.is_some());
        log::trace!("Found XMP? {}", t.xmp.is_some());
    })?;

    Ok(HeifLike {
        exif: Arc::new(RwLock::new(
            metadata_blobs
                .exif
                .map(|raw| MaybeParsedExif::Raw(raw.to_vec())),
        )),
        xmp: Arc::new(RwLock::new(
            metadata_blobs
                .xmp
                .map(|raw| MaybeParsedXmp::Raw(raw.to_vec())),
        )),
    })
}

struct FindMetadataReturnValues<'input> {
    exif: Option<&'input [u8]>,
    xmp: Option<&'input [u8]>,
}

#[derive(Clone)]
struct ItemData {
    item_id: u32,
    item_location: ItemLocationEntry,
    item_info: ItemInfoEntry,
}

fn find_metadata<'input>(
    // blobs:
    //
    // 1. original file blob (for file-based indexing)
    // 2. original `meta` blob
    original_file_blob: &'input [u8],

    // data on _what_ will be _where_ in the blobs
    item_info: ItemInfoBox,
    item_location: ItemLocationBox,
    maybe_item_data: Option<&'input [u8]>,
    _maybe_primary_item: Option<PrimaryItemBox>,
) -> Result<FindMetadataReturnValues<'input>, HeifLikeConstructionError> {
    // make an index of what items we've got
    let item_infos_len = item_info.item_infos.len();
    let mut item_infos: HashMap<u32, ItemInfoEntry> = item_info.item_infos.into_iter().fold(
        HashMap::with_capacity(item_infos_len),
        |mut map, item_info_entry| {
            log::debug!(
                "Found item_info with ID: {}, item_type: {:?}",
                item_info_entry.item_id(),
                item_info_entry.item_type()
            );
            map.insert(item_info_entry.item_id(), item_info_entry);
            map
        },
    );
    log::trace!("Num. of items: `{item_infos_len}`");

    // create a list of all items
    let items: Vec<ItemData> = item_location
        .items
        .into_iter()
        .filter_map(|item_location| {
            log::debug!(
                "Processing item_location with ID: {}",
                item_location.item_id
            );
            if let Some(item_info) = item_infos.remove(&item_location.item_id) {
                log::debug!("Successfully matched item ID: {}", item_location.item_id);
                Some(ItemData {
                    item_id: item_location.item_id,
                    item_info,
                    item_location,
                })
            } else {
                log::warn!(
                    "No item_info found for item_location ID: {}",
                    item_location.item_id
                );
                None
            }
        })
        .collect();
    log::debug!("After filtering, we have `{}` items!", items.len());

    // we'll want to find both exif and xmp data
    let mut ret = FindMetadataReturnValues {
        exif: None,
        xmp: None,
    };

    // try to find both exif and xmp in there.
    for (i, item) in items.iter().enumerate() {
        log::debug!(
            "Processing item {}/{}: ID={}, item_type={:?}",
            i + 1,
            items.len(),
            item.item_id,
            item.item_info.item_type()
        );

        // stop looping (so... return) if we've found both
        if ret.exif.is_some() && ret.xmp.is_some() {
            break;
        }

        // based on item's construction method, we'll choose what to do...
        match item.item_location.construction_method {
            // easy!
            //
            // go to this offset and read a box...
            ConstructionMethod::Set0 => {
                log::trace!("Construction method: File offsets (Set0)");

                // update `ret` w/ the parsed item
                update_with_item(&mut ret, item.clone(), original_file_blob)?;
            }

            // oooh. little bit harder.
            //
            // use the `idat` stream above and find it in there
            ConstructionMethod::Idat => {
                log::trace!("Construction method: Item data");

                // ensure we have the item data
                let Some(item_data) = maybe_item_data else {
                    log::warn!("File specified that `idat` should be present, but it wasn't...");
                    continue;
                };

                // update `ret` w/ the parsed item
                update_with_item(&mut ret, item.clone(), item_data)?;
            }

            // not doing this right now, but this is the `extent`-based one.
            //
            // basically, imagine pointers to random items and having to read
            // off those. sounds annoying.
            //
            // if you have a need for this, please submit an issue with a test
            // file you own the rights to (e.g., CC0). I'll implement it! :D
            ConstructionMethod::Item => {
                log::trace!("Construction method: Item");
            }
        }
    }

    Ok(ret)
}

/// Creates the range we'll use to slice above.
fn make_slice_range(
    item: &ItemData,
    extent: &ItemExtent,
) -> Result<core::ops::Range<usize>, HeifLikeConstructionError> {
    let start: u64 = item
        .item_location
        .base_offset
        .saturating_add(extent.extent_offset);
    let end: u64 = start.saturating_add(extent.extent_length);

    Ok(start
        .try_into()
        .map_err(|_| HeifLikeConstructionError::ParserBugSlicesTooSmall)?
        ..end
            .try_into()
            .map_err(|_| HeifLikeConstructionError::ParserBugSlicesTooSmall)?)
}

/// Updates the metadata return values with the given item.
fn update_with_item<'input>(
    ret: &mut FindMetadataReturnValues<'input>,
    item: ItemData,
    blob: &'input [u8],
) -> Result<(), HeifLikeConstructionError> {
    log::trace!("Updating found metadata w/ item. ID: `#{}`", item.item_id);

    // ensure only one extent present
    let [single_extent] = item.item_location.extents.as_slice() else {
        log::error!("Multiple extents are not currently supported.");
        if cfg!(debug_assertions) {
            panic!("Multiple extents are not currently supported.");
        } else {
            return Ok(());
        }
    };

    // grab our single extent as a blob (via slicing)
    let slice_range = make_slice_range(&item, single_extent)
        .inspect_err(|e| log::error!("Failed to make slice range! err: {e}"))?;
    log::trace!("Slice range: {slice_range:?}");

    let blob: &mut &[u8] = &mut &blob[slice_range];

    // exif
    if item.item_info.item_type() == Some(*b"Exif") {
        let blob_len: usize = blob.len();

        // handle some literal nonsense
        //
        // (some images can omit the required header)
        let first_two_bytes: [u8; 2] = [blob[0], blob[1]];
        let exif_tiff_header_offset = if (first_two_bytes == *b"MM" || first_two_bytes == *b"II")
            && blob_len < u16::from_be_bytes(first_two_bytes).into()
        {
            log::warn!(
                "Malformed Exif header detected. Missing `exif_tiff_header_offset`. \
                Assuming value of zero..."
            );
            0
        } else {
            // parse out the u32 explaining how many bytes to skip
            let Ok::<_, EmptyError>(exif_tiff_header_offset) = be_u32
                .context(desc("exif_tiff_header_offset"))
                .parse_next(blob)
                .map(|off| off as usize)
            else {
                log::error!("Failed to grab `exif_tiff_header_offset` for Exif! Skipping...");
                return Ok(());
            };
            exif_tiff_header_offset
        };

        // check bounds
        log::trace!("`exif_tiff_header_offset` is: `{exif_tiff_header_offset}`");
        if blob_len < exif_tiff_header_offset {
            log::warn!(
                "`exif_tiff_header_offset` was larger than the blob. \
                blob len: `{blob_len}`, \
                offset: `{exif_tiff_header_offset}`",
            );
            if cfg!(debug_assertions) {
                panic!();
            }
        }

        // move to offset (or start from beginning)
        ret.exif = Some(&blob[exif_tiff_header_offset..]);

        log::trace!("Updated w/ Exif!");
        return Ok(());
    }
    log::debug!("passed Exif");

    // xmp (using mime)
    if let Some(mime) = item.item_info.mime()
        && (mime == "application/rdf+xml" || mime == "application/xmp+xml")
    {
        log::trace!("Updated w/ XMP when using MIME!");
        ret.xmp = Some(blob);
        return Ok(());
    }
    log::debug!("passed XMP (MIME)");

    // xmp (when using item)
    if let Some(item_type) = item.item_info.item_type()
        && [b"xif\0", b"XMP ", b"xmp "].contains(&&item_type)
    {
        log::trace!("Updated w/ XMP using item type: {item_type:?}");
        ret.xmp = Some(blob);
        return Ok(());
    }
    log::debug!("passed XMP (item)");

    Ok(())
}

#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum HeifLikeConstructionError {
    /// All HEIF-like files must provide `ftyp` box as soon as possible.
    ///
    /// However, this file didn't.
    NoFtypBox,

    /// The `ftyp` box indicated that this isn't a HEIF-like file.
    NotAHeifLike { major_brand: [u8; 4] },

    /// HEIF files are only expected to have one `meta` box, but the given file
    /// had more than one!
    MultipleMetaBoxes { n: u32 },

    /// Failed to parse the `ItemInfoBox`.
    CantParseItemInfoBox,

    /// Failed to parse the `ItemLocationBox`.
    CantParseItemLocationBox,

    /// Failed to parse the `PrimaryItemBox`.
    CantParsePrimaryItemBox,

    /// Multiple extents aren't currently supported.
    ///
    /// They're annoying to implement. If you own the rights to a file and can
    /// include it here for testing, please create an issue and I will
    /// implement multi-extent parsing.
    ParserBugMultipleExtentsNotSupported { extent_ct: u32 },

    /// Rust slices cannot represent giant files on 32-bit systems.
    ///
    /// This is a limitation of the parser. Please make an issue if you see
    /// this pop up.
    ParserBugSlicesTooSmall,
}

impl core::fmt::Display for HeifLikeConstructionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoFtypBox => f.write_str("File did not start with an `ftyp` box."),
            Self::NotAHeifLike { major_brand } => {
                f.write_str("The provided file was not a known HEIF-like. major brand: `")?;
                for c in major_brand {
                    f.write_char(*c as char)?;
                }
                f.write_char('`')
            }
            Self::MultipleMetaBoxes { n } => write!(
                f,
                "HEIF-like file had more than one `meta` box, but this isn't \
                allowed. \
                box ct: `{n}`"
            ),
            Self::CantParseItemInfoBox => f.write_str("Failed to parse `ItemInfoBox`."),
            Self::CantParseItemLocationBox => f.write_str("Failed to parse `ItemLocationBox`."),
            Self::CantParsePrimaryItemBox => f.write_str("Failed to parse `PrimaryItemBox`."),

            Self::ParserBugMultipleExtentsNotSupported { extent_ct } => write!(
                f,
                "This library does not currently support multi-extent parsing. \
                Please see variant docs for more info. \
                num. of extents: `{extent_ct}`"
            ),
            Self::ParserBugSlicesTooSmall => f.write_str(
                "Slice cannot represent this range on your system. \
                Please see variant docs for more info.",
            ),
        }
    }
}

impl core::error::Error for HeifLikeConstructionError {}