asset_io/lib.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//! A portable, dynamically extensible container model for media assets.
15//!
16//! `asset-io` provides one abstract model for reading, inspecting and updating a
17//! wide variety of image, audio, video and document formats, including JPEG, PNG,
18//! ISO BMFF (HEIF, AVIF, MP4), RIFF (WebP, WAV, AVI), TIFF, SVG and PDF. Applications
19//! work with common structures and metadata items rather than format-specific
20//! parsers and writers.
21//!
22//! Container support is dynamically extensible: applications register built-in
23//! or third-party handlers with [`HandlerRegistry`] at runtime. Handler authors
24//! use [`container_api`] to add formats without changing the client API.
25//!
26//! The core is portable and independent of any async runtime. The same handler
27//! implementation runs with blocking streams, async adapters or caller-driven
28//! I/O. It is designed for high performance: updates stream the output in a single
29//! pass with bounded buffers, copying unchanged media without loading the whole
30//! asset into memory. [`Sink`]s observe tagged bytes during reads and writes,
31//! allowing callers to hash output without a second pass.
32//!
33//! Used by [c2pa-rs](https://github.com/contentauth/c2pa-rs) for media-container
34//! access, `asset-io` separates container mechanics from manifest interpretation,
35//! hashing and signing.
36//!
37//! A [`Structure`] describes a file as an ordered tiling of [`Segment`]s, each
38//! split into header, payload and trailer, plus [`Item`]s: logical units such as
39//! XMP, JUMBF, EXIF or an embedded file, assembled from [`Extent`]s. It carries
40//! geometry only: no data, and no hashing or signing rules. Callers decide what
41//! each byte range means.
42//!
43//! # Glossary
44//!
45//! - **Asset**: a complete byte stream. Assets are recursive: an asset can contain
46//! embedded assets. The [`Asset`] type pairs one with its parsed structure.
47//! - **Structure**: the parsed description of an asset ([`Structure`]): its
48//! segments, items and sub-assets, and the handler that parsed it. It is
49//! geometry only and holds no bytes, so its reads take the stream as an
50//! argument; an [`Asset`] holds the stream for them. A planned structure
51//! ([`Structure::plan`]) describes an output before it is written.
52//! - **Container**: a structural family (ISO BMFF, JPEG, RIFF). **Format**: a media
53//! type within one (HEIC and MP4 are both ISO BMFF).
54//! - **Handler**: implements a container's specifications
55//! ([`ContainerHandler`](container_api::ContainerHandler)).
56//! - **Range**: an offset and a length ([`ByteRange`]).
57//! - **Segment**: a unit of the asset's tiling. Segments are ordered, do not
58//! overlap and cover every byte; a segment is what a writer copies, replaces or
59//! moves. Its [`SegmentKind`] gives its dominant purpose: `Preamble` (the leading
60//! bytes that identify the format; "signature" is avoided, as C2PA uses it for
61//! cryptographic signatures), `Metadata`, `MediaData` (coded media of any type)
62//! or `Other`. Items, not segment kinds, say what bytes belong to.
63//! - **Role**: within a segment, framing ([`Role::Header`], [`Role::Trailer`])
64//! versus content ([`Role::Payload`]). "Header" always means framing.
65//! - **Region**: a segment, a role and a range: the view a hasher takes
66//! ([`Region`]).
67//! - **Element**: a native unit of the container (box, chunk, marker segment, PDF
68//! object, IFD). [`Structure::elements`] is the finest tiling by elements.
69//! - **Box**: a container-defined grouping of elements, with a name, range and
70//! metadata ranges ([`BoxInfo`], [`Structure::boxes`]). Unnamed bytes are kept
71//! without a name. This view does not apply C2PA-specific names or restrictions.
72//! - **Node**: an element and its position in the container's tree
73//! ([`Node`], [`Structure::walk`]).
74//! - **Item**: a logical unit the format defines, with an [`ItemKind`] (the
75//! specification that defines it), an [`ItemCategory`] derived from the kind
76//! (metadata or asset) and an [`Encoding`] (its serialization).
77//! - **Transfer encoding**: how the bytes a container stores for an item wrap its
78//! content, such as SVG's base64, a PDF `FlateDecode` (zlib) stream or a HEIF
79//! `content_encoding` ([`TransferEncoding`], [`Item::transfer`]). It is distinct
80//! from the [`Encoding`], which is the serialization of the content itself. The
81//! core always identifies it; decoders are optional features (`flate`,
82//! `brotli`). [`Structure::read_item`] returns the
83//! stored bytes (what a hash covers); [`Structure::read_content`] the content.
84//! - **Extent**: one contiguous run of an item's bytes. An item may be
85//! multi-extent; "fragment" is reserved for fragmented ISO BMFF.
86//! - **Identifiers**: native names, kept exactly: FourCCs, markers, UUIDs, JUMBF
87//! types, URIs, media types and container labels ([`Name`],
88//! [`Item::native_type`], [`Item::native_id`]).
89//! - **Relation**: a reference from one item to another that keeps its native type
90//! (HEIF `thmb`, `auxl`, `cdsc`, `dimg`); [`RelationKind`] gives common names.
91//! - **Sub-asset**: a contiguous, top-level embedded asset, such as each image of a
92//! Multi-Picture Format file ([`SubAsset`]).
93//! - **Embedded asset**: an item the format declares to be a file of a media type
94//! ([`ItemKind::EmbeddedAsset`]). Items whose bytes the format does not type are
95//! [`ItemKind::Other`]; [`Structure::scan_embedded`] also finds those that turn out
96//! to be files.
97//!
98//! # Layering
99//!
100//! 1. Account for every byte: segments always tile the asset.
101//! 2. Expose the structure the format's own specifications define, including
102//! companion specifications (EXIF/TIFF, MPF, JPEG XT, the HEIF item model), and
103//! preserve native identifiers.
104//! 3. Never interpret content that is portable across formats (C2PA manifests, XMP
105//! schemas, IPTC vocabularies). That belongs to optional higher-level helpers
106//! built on this API. Where such content is placed in each container is
107//! container knowledge, and is here.
108//!
109//! # Design principles
110//!
111//! - **Container agnostic**: one API for every format. Format knowledge lives in a
112//! [`ContainerHandler`](container_api::ContainerHandler); callers never test
113//! which format they have.
114//! - **Streaming**: a file is parsed and written in one pass, in bounded memory.
115//! - **Safe on hostile input**: every length is checked, resources are capped,
116//! and errors are returned rather than guessed around.
117//! - **Pluggable**: [`HandlerRegistry`] finds handlers by format string or by
118//! content, and callers can register their own.
119//!
120//! # Containers and features
121//!
122//! Each built-in container is a Cargo feature (`jpeg`, `png`, `bmff`, `riff`,
123//! `svg`, `pdf`, `tiff`, `c2pa`, `gif`, `id3`, or `all-formats`) and a module under
124//! [`containers`]. No container is enabled by default.
125//! [`HandlerRegistry::builtin`] holds the handlers of the enabled features, and
126//! handlers from other crates are registered at runtime. Without any container
127//! feature, the crate is the API a handler crate builds on, and nothing more.
128//!
129//! # API namespaces
130//!
131//! The root exposes the client model, [`HandlerRegistry`], [`Asset`],
132//! [`Structure`], [`Updates`] and [`Sink`], including C2PA geometry and exact
133//! patching. Handler authors use [`container_api`] for handler traits, builders,
134//! metadata-update decisions and container utilities. Built-in factories and
135//! typed options remain under [`containers`].
136//!
137//! Advanced clients use [`plan`] for declarative write plans, [`execute`] for
138//! caller-driven execution, [`io`] for async reads and [`task`] for read requests
139//! and blocking or caller-driven task execution. The `*_async`, planning and
140//! task methods on [`Structure`] still compose these APIs; no runtime is required.
141//! [`HandlerRegistry::handler`] and [`HandlerRegistry::handlers`] retain handler
142//! lookup and composition, including custom use of
143//! [`ContainerHandler::compose`](container_api::ContainerHandler::compose).
144//!
145//! # Example
146//!
147//! ```no_run
148//! use asset_io::{Asset, ItemKind, NullSink, Updates};
149//!
150//! # fn main() -> asset_io::Result<()> {
151//! // Enable the `jpeg` feature for this example.
152//! let asset = Asset::open(std::fs::File::open("image.jpg")?, None)?;
153//!
154//! // Read a metadata item, which may have extents in several segments.
155//! if let Some(jumbf) = asset.item(ItemKind::C2pa)? {
156//! let bytes = asset.read_item(jumbf)?;
157//! println!("JUMBF: {} bytes", bytes.len());
158//! }
159//!
160//! // Write a copy with changes. Every output byte also goes to a sink, tagged
161//! // with its segment and role, so it can be hashed without a second pass.
162//! let mut out = std::fs::File::create("out.jpg")?;
163//! let updates = Updates::new()
164//! .set_xmp(b"<x:xmpmeta/>".to_vec())
165//! .remove_c2pa();
166//! asset.write(&mut out, &updates, &mut NullSink)?;
167//! # Ok(())
168//! # }
169//! ```
170//!
171//! [`Asset`] holds the source; [`Structure`] is the I/O-free description it
172//! wraps, whose methods take the source as an argument. Async and caller-driven
173//! code uses [`Structure::parse_task`] and the `*_async` methods directly.
174
175#![cfg_attr(docsrs, feature(doc_cfg))]
176
177mod asset;
178pub mod container_api;
179pub mod containers;
180mod crc;
181mod embedded;
182mod error;
183pub mod execute;
184mod handler;
185pub mod io;
186mod item;
187pub mod jumbf;
188#[cfg(feature = "memory-mapped")]
189mod mapped;
190mod parse;
191pub mod plan;
192mod plan_builder;
193mod range;
194mod registry;
195mod segment;
196mod sink;
197mod structure;
198pub mod task;
199pub mod testing;
200mod thumbnail;
201#[cfg(feature = "exif")]
202mod tiff;
203#[cfg(feature = "tokio")]
204#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
205pub mod tokio;
206pub mod transfer;
207mod updates;
208mod walk;
209#[cfg(feature = "xmp")]
210mod xmp;
211
212pub use asset::Asset;
213pub use embedded::{EmbeddedAsset, EmbeddedReader, ScanLimits};
214pub use error::{Error, Result};
215pub use item::{Encoding, Extent, Item, ItemCategory, ItemKind, Relation, RelationKind};
216#[cfg(feature = "memory-mapped")]
217pub use mapped::MappedFile;
218pub use range::ByteRange;
219pub use registry::HandlerRegistry;
220pub use segment::{labels, Name, Role, Segment, SegmentKind};
221pub use sink::{Chunk, NullSink, Sink};
222pub use structure::{BoxInfo, C2paPatch, Region, SegmentId, Structure, SubAsset};
223pub use thumbnail::Thumbnail;
224#[cfg(feature = "exif")]
225pub use tiff::ExifInfo;
226pub use transfer::TransferEncoding;
227pub use updates::Updates;
228pub use walk::Node;
229#[cfg(feature = "xmp")]
230pub use xmp::MiniXmp;