Skip to main content

asset_io/
item.rs

1// Copyright 2026 Adobe. All rights reserved.
2// This file is licensed to you under the Apache License,
3// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4// or the MIT license (http://opensource.org/licenses/MIT),
5// at your option.
6
7// Unless required by applicable law or agreed to in writing,
8// this software is distributed on an "AS IS" BASIS, WITHOUT
9// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
10// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
11// specific language governing permissions and limitations under
12// each license.
13
14//! Items: logical units defined by a format, assembled from extents.
15
16use std::borrow::Cow;
17
18use crate::{range::ByteRange, segment::Name, structure::SegmentId, transfer::TransferEncoding};
19
20/// The specification that defines an [`Item`].
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22#[non_exhaustive]
23pub enum ItemKind {
24    /// XMP (ISO 16684-1).
25    Xmp,
26    /// EXIF, whose data is TIFF.
27    Exif,
28    /// A C2PA manifest store, whose data is JUMBF. Where the container reserves an
29    /// element for it (PNG `caBX`, the ISO BMFF C2PA box), that element is the item;
30    /// where the container carries JUMBF of any type (JPEG APP11), the superbox type
31    /// tells. Other JUMBF is [`Other`](Self::Other) with [`Encoding::Jumbf`].
32    C2pa,
33    /// A self-contained file stored inside the asset, or a reference to one.
34    EmbeddedAsset,
35    /// Anything else the container exposes; see its [encoding](Item::encoding)
36    /// and native identifiers.
37    Other,
38}
39
40impl ItemKind {
41    /// A string for this kind: `"xmp"`, `"exif"`, `"c2pa"`, `"embedded_asset"`,
42    /// `"other"`.
43    pub fn as_str(&self) -> &'static str {
44        match self {
45            Self::Xmp => "xmp",
46            Self::Exif => "exif",
47            Self::C2pa => "c2pa",
48            Self::EmbeddedAsset => "embedded_asset",
49            Self::Other => "other",
50        }
51    }
52
53    /// Whether items of this kind are metadata or assets.
54    pub fn category(&self) -> ItemCategory {
55        match self {
56            Self::Xmp | Self::Exif | Self::C2pa => ItemCategory::Metadata,
57            Self::EmbeddedAsset => ItemCategory::Asset,
58            Self::Other => ItemCategory::Other,
59        }
60    }
61}
62
63impl std::fmt::Display for ItemKind {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        f.write_str(self.as_str())
66    }
67}
68
69/// Broad category of an [`ItemKind`].
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71#[non_exhaustive]
72pub enum ItemCategory {
73    /// Data about the asset.
74    Metadata,
75    /// A file in its own right.
76    Asset,
77    /// Neither, or unknown.
78    Other,
79}
80
81impl ItemCategory {
82    /// `"metadata"`, `"asset"` or `"other"`.
83    pub fn as_str(&self) -> &'static str {
84        match self {
85            Self::Metadata => "metadata",
86            Self::Asset => "asset",
87            Self::Other => "other",
88        }
89    }
90}
91
92impl std::fmt::Display for ItemCategory {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.write_str(self.as_str())
95    }
96}
97
98/// How an item's bytes are serialized.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100#[non_exhaustive]
101pub enum Encoding {
102    /// XML (XMP is RDF/XML).
103    Xml,
104    /// TIFF structure (EXIF is always TIFF).
105    Tiff,
106    /// A JUMBF superbox tree.
107    Jumbf,
108    /// Plain ISO BMFF boxes that are not JUMBF superboxes.
109    IsoBmff,
110    /// A self-contained file; its media type, when known, is [`Item::media_type`].
111    Asset,
112    /// Not known to the container.
113    Unknown,
114}
115
116impl Encoding {
117    /// `"xml"`, `"tiff"`, `"jumbf"`, `"iso_bmff"`, `"asset"` or `"unknown"`.
118    pub fn as_str(&self) -> &'static str {
119        match self {
120            Self::Xml => "xml",
121            Self::Tiff => "tiff",
122            Self::Jumbf => "jumbf",
123            Self::IsoBmff => "iso_bmff",
124            Self::Asset => "asset",
125            Self::Unknown => "unknown",
126        }
127    }
128}
129
130impl std::fmt::Display for Encoding {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        f.write_str(self.as_str())
133    }
134}
135
136/// A common name for a native item reference type.
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
138#[non_exhaustive]
139pub enum RelationKind {
140    /// The item is a thumbnail of the target (HEIF `thmb`).
141    Thumbnail,
142    /// The item is an auxiliary image of the target, such as alpha or depth
143    /// (HEIF `auxl`).
144    Auxiliary,
145    /// The item describes the target, as metadata does (HEIF `cdsc`).
146    Describes,
147    /// The item is derived from the target (HEIF `dimg`).
148    Derived,
149    /// Any other reference type; see [`Relation::native`].
150    Other,
151}
152
153impl RelationKind {
154    /// The kind of a HEIF `iref` reference type.
155    pub fn from_native(native: [u8; 4]) -> Self {
156        match &native {
157            b"thmb" => Self::Thumbnail,
158            b"auxl" => Self::Auxiliary,
159            b"cdsc" => Self::Describes,
160            b"dimg" => Self::Derived,
161            _ => Self::Other,
162        }
163    }
164
165    /// `"thumbnail"`, `"auxiliary"`, `"describes"`, `"derived"` or `"other"`.
166    pub fn as_str(&self) -> &'static str {
167        match self {
168            Self::Thumbnail => "thumbnail",
169            Self::Auxiliary => "auxiliary",
170            Self::Describes => "describes",
171            Self::Derived => "derived",
172            Self::Other => "other",
173        }
174    }
175}
176
177/// A reference from one item to another, keeping its native type.
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
179pub struct Relation {
180    kind: RelationKind,
181    native: [u8; 4],
182    target: u64,
183}
184
185impl Relation {
186    /// A reference of native type `native` (for example `thmb`) to the item whose
187    /// [native id](Item::native_id) is `target`.
188    pub fn new(native: [u8; 4], target: u64) -> Self {
189        Self {
190            kind: RelationKind::from_native(native),
191            native,
192            target,
193        }
194    }
195
196    /// The common name of the reference type.
197    pub fn kind(&self) -> RelationKind {
198        self.kind
199    }
200
201    /// The reference type as the format writes it.
202    pub fn native(&self) -> [u8; 4] {
203        self.native
204    }
205
206    /// The [native id](Item::native_id) of the referenced item.
207    pub fn target(&self) -> u64 {
208        self.target
209    }
210}
211
212/// What an item is, apart from where its bytes are. Used to declare items with
213/// [`StructureBuilder::item`](crate::container_api::StructureBuilder::item) and
214/// [`PlanBuilder::item`](crate::container_api::PlanBuilder::item); see [`Item`] for each field.
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct ItemInfo {
217    kind: ItemKind,
218    encoding: Encoding,
219    transfer: TransferEncoding,
220    label: Option<Cow<'static, str>>,
221    media_type: Option<Cow<'static, str>>,
222    jumbf_type: Option<[u8; 16]>,
223    native_type: Option<Name>,
224    native_id: Option<u64>,
225    uri: Option<Cow<'static, str>>,
226    relations: Vec<Relation>,
227}
228
229impl ItemInfo {
230    /// An item of `kind` serialized as `encoding`, with nothing else known.
231    pub fn new(kind: ItemKind, encoding: Encoding) -> Self {
232        Self {
233            kind,
234            encoding,
235            transfer: TransferEncoding::Identity,
236            label: None,
237            media_type: None,
238            jumbf_type: None,
239            native_type: None,
240            native_id: None,
241            uri: None,
242            relations: Vec::new(),
243        }
244    }
245
246    /// An XMP packet.
247    pub fn xmp() -> Self {
248        Self::new(ItemKind::Xmp, Encoding::Xml)
249    }
250
251    /// EXIF (TIFF) data.
252    pub fn exif() -> Self {
253        Self::new(ItemKind::Exif, Encoding::Tiff)
254    }
255
256    /// A C2PA manifest store (JUMBF).
257    pub fn c2pa() -> Self {
258        Self::new(ItemKind::C2pa, Encoding::Jumbf)
259    }
260
261    /// Set the [transfer encoding](Item::transfer).
262    pub fn transfer(mut self, transfer: TransferEncoding) -> Self {
263        self.transfer = transfer;
264        self
265    }
266
267    /// A JUMBF item, other than a C2PA store, whose superbox type has not been
268    /// recorded.
269    pub(crate) fn lacks_jumbf_type(&self) -> bool {
270        self.kind == ItemKind::Other
271            && self.encoding == Encoding::Jumbf
272            && self.jumbf_type.is_none()
273    }
274
275    pub(crate) fn transfer_encoding(&self) -> &TransferEncoding {
276        &self.transfer
277    }
278
279    /// Set the [label](Item::label).
280    pub fn label(mut self, label: impl Into<Cow<'static, str>>) -> Self {
281        self.label = Some(label.into());
282        self
283    }
284
285    /// Set the [media type](Item::media_type).
286    pub fn media_type(mut self, media_type: impl Into<Cow<'static, str>>) -> Self {
287        self.media_type = Some(media_type.into());
288        self
289    }
290
291    /// Set or clear the [JUMBF type](Item::jumbf_type).
292    pub fn jumbf_type(mut self, jumbf_type: Option<[u8; 16]>) -> Self {
293        self.jumbf_type = jumbf_type;
294        self
295    }
296
297    /// Set the [native type](Item::native_type).
298    pub fn native_type(mut self, native_type: Name) -> Self {
299        self.native_type = Some(native_type);
300        self
301    }
302
303    /// Set the [native id](Item::native_id).
304    pub fn native_id(mut self, native_id: u64) -> Self {
305        self.native_id = Some(native_id);
306        self
307    }
308
309    /// Set the [URI](Item::uri).
310    pub fn uri(mut self, uri: impl Into<Cow<'static, str>>) -> Self {
311        self.uri = Some(uri.into());
312        self
313    }
314
315    /// Add a [relation](Item::relations).
316    pub fn relation(mut self, relation: Relation) -> Self {
317        self.relations.push(relation);
318        self
319    }
320}
321
322/// One contiguous run of an [`Item`]'s bytes, and the segment holding it.
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324pub struct Extent {
325    pub(crate) range: ByteRange,
326    pub(crate) segment: SegmentId,
327}
328
329impl Extent {
330    /// The bytes.
331    pub fn range(&self) -> ByteRange {
332        self.range
333    }
334
335    /// The segment that contains them.
336    pub fn segment(&self) -> SegmentId {
337        self.segment
338    }
339}
340
341/// A logical unit defined by the format (XMP, JUMBF, EXIF, an embedded file, ...),
342/// assembled from one or more extents.
343///
344/// Extents are payload-only: framing that repeats per extent (JPEG XT headers, PNG
345/// chunk headers) is not included. The common single-extent case does not allocate.
346#[derive(Debug, Clone)]
347pub struct Item {
348    pub(crate) info: ItemInfo,
349    pub(crate) first: Extent,
350    pub(crate) rest: Vec<Extent>,
351}
352
353impl Item {
354    /// The specification that defines the item.
355    pub fn kind(&self) -> ItemKind {
356        self.info.kind
357    }
358
359    /// How its bytes are serialized.
360    pub fn encoding(&self) -> Encoding {
361        self.info.encoding
362    }
363
364    /// How the stored bytes wrap the content: [`Identity`](TransferEncoding::Identity)
365    /// unless the container stores the item as base64 text (SVG) or compressed
366    /// (PDF streams, PNG `iTXt`, HEIF `mime` items). [`Structure::read_item`](crate::Structure::read_item) returns the stored
367    /// bytes; [`Structure::read_content`](crate::Structure::read_content) the content.
368    pub fn transfer(&self) -> &TransferEncoding {
369        &self.info.transfer
370    }
371
372    /// Everything known about the item apart from its extents.
373    pub(crate) fn info(&self) -> &ItemInfo {
374        &self.info
375    }
376
377    /// Container-defined role of the item among others of its kind, for example
378    /// the purpose of a BMFF C2PA box (`manifest`, `update`, `merkle`; see
379    /// [`labels`](crate::labels)). `None` if the container does not distinguish
380    /// them.
381    pub fn label(&self) -> Option<&str> {
382        self.info.label.as_deref()
383    }
384
385    /// Media type of the item's data, when the container records one: for example
386    /// `image/jpeg` for a HEIF `jpeg` item, or the content type of a HEIF `mime`
387    /// item. `None` when the container does not say, as with
388    /// [`SubAsset::media_type`](crate::SubAsset::media_type).
389    pub fn media_type(&self) -> Option<&str> {
390        self.info.media_type.as_deref()
391    }
392
393    /// The type of a JUMBF superbox, from its description box, when the container
394    /// recorded it while parsing: containers that carry JUMBF of any type (JPEG)
395    /// do, to tell a [C2PA](ItemKind::C2pa) store from [other](ItemKind::Other)
396    /// JUMBF. `None` for items that are not JUMBF, for containers that reserve an
397    /// element for the C2PA store (PNG `caBX`, the BMFF C2PA box), and for data that
398    /// is not a superbox.
399    pub fn jumbf_type(&self) -> Option<[u8; 16]> {
400        self.info.jumbf_type
401    }
402
403    /// The item's type as the format names it, for example a HEIF item type
404    /// (`jpeg`, `mime`, `uri `, `hvc1`, `Exif`).
405    pub fn native_type(&self) -> Option<Name> {
406        self.info.native_type
407    }
408
409    /// The item's identifier in the format, for example a HEIF `item_ID`. The
410    /// [target](Relation::target) of a relation is one of these.
411    pub fn native_id(&self) -> Option<u64> {
412        self.info.native_id
413    }
414
415    /// The URI that identifies the item's type, for a HEIF `uri ` item. It is an
416    /// identifier only and is never fetched.
417    pub fn uri(&self) -> Option<&str> {
418        self.info.uri.as_deref()
419    }
420
421    /// References from this item to others, as the format records them.
422    pub fn relations(&self) -> &[Relation] {
423        &self.info.relations
424    }
425
426    /// Extents in logical order.
427    pub fn extents(&self) -> impl Iterator<Item = &Extent> {
428        std::iter::once(&self.first).chain(self.rest.iter())
429    }
430
431    /// Number of extents.
432    pub fn extent_count(&self) -> usize {
433        1 + self.rest.len()
434    }
435
436    /// Total bytes across all extents (saturating).
437    pub fn len(&self) -> u64 {
438        self.extents()
439            .fold(0u64, |acc, p| acc.saturating_add(p.range.len()))
440    }
441
442    /// True if all extents are empty.
443    pub fn is_empty(&self) -> bool {
444        self.len() == 0
445    }
446
447    /// Whether any extent lies in segment `id`.
448    pub fn is_in(&self, id: SegmentId) -> bool {
449        self.extents().any(|e| e.segment == id)
450    }
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456
457    #[test]
458    fn kinds_map_to_categories_and_strings() {
459        assert_eq!(ItemKind::Xmp.category(), ItemCategory::Metadata);
460        assert_eq!(ItemKind::C2pa.category(), ItemCategory::Metadata);
461        assert_eq!(ItemKind::C2pa.as_str(), "c2pa");
462        assert_eq!(ItemInfo::c2pa().encoding, Encoding::Jumbf);
463        assert_eq!(ItemKind::Exif.category(), ItemCategory::Metadata);
464        assert_eq!(ItemKind::EmbeddedAsset.category(), ItemCategory::Asset);
465        assert_eq!(ItemKind::Other.category(), ItemCategory::Other);
466        assert_eq!(ItemKind::EmbeddedAsset.as_str(), "embedded_asset");
467        assert_eq!(Encoding::IsoBmff.as_str(), "iso_bmff");
468        assert_eq!(ItemInfo::exif().encoding, Encoding::Tiff);
469    }
470
471    #[test]
472    fn relations_keep_their_native_type() {
473        for (native, kind) in [
474            (*b"thmb", RelationKind::Thumbnail),
475            (*b"auxl", RelationKind::Auxiliary),
476            (*b"cdsc", RelationKind::Describes),
477            (*b"dimg", RelationKind::Derived),
478            (*b"base", RelationKind::Other),
479        ] {
480            let r = Relation::new(native, 7);
481            assert_eq!((r.kind(), r.native(), r.target()), (kind, native, 7));
482        }
483    }
484}