Skip to main content

asset_io/
handler.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//! Pluggable container handlers.
15//!
16//! A [`ContainerHandler`] teaches asset-io one container format. The built-in
17//! containers (under [`containers`](crate::containers)) implement it, and so can a handler registered by a
18//! caller (see [`HandlerRegistry`](crate::HandlerRegistry)). A parsed
19//! [`Structure`] keeps the handler that produced it, so everything that depends on
20//! the container (subdividing scans, box names, patching trailers, rewriting) works
21//! on any structure without the caller knowing the format.
22
23use std::{
24    borrow::Cow,
25    io::{Read, Seek, SeekFrom, Write},
26    sync::Arc,
27};
28
29use crate::{
30    error::{Error, Result},
31    io::{BoxFuture, Io},
32    item::{Item, ItemKind},
33    plan::WritePlan,
34    range::ByteRange,
35    segment::{Name, Segment},
36    sink::Sink,
37    structure::{SegmentId, Structure},
38    task::block_on,
39    walk::Node,
40    Updates,
41};
42
43/// A readable, seekable stream. Blanket-implemented, so any `Read + Seek` works.
44pub trait ReadSeek: Read + Seek {}
45impl<T: Read + Seek + ?Sized> ReadSeek for T {}
46
47/// A readable, writable, seekable stream. Blanket-implemented.
48pub trait ReadWriteSeek: Read + Write + Seek {}
49impl<T: Read + Write + Seek + ?Sized> ReadWriteSeek for T {}
50
51/// How many leading bytes [`ContainerHandler::detect`] is given.
52pub const DETECT_LEN: usize = 64;
53
54/// One format a container handler serves: a media type and its file extensions.
55///
56/// A container that carries several media types (ISO BMFF: HEIC, MP4, M4A...)
57/// declares one `FormatSpec` per media type. Format strings are matched ignoring
58/// case, surrounding whitespace and a leading dot.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct FormatSpec {
62    /// The media type, for example `image/jpeg`.
63    pub media_type: &'static str,
64    /// The preferred file extension, without a dot, for example `jpg`.
65    pub extension: &'static str,
66    /// Other media types accepted for this format, for example `image/x-webp`.
67    pub media_type_aliases: &'static [&'static str],
68    /// Other file extensions accepted for this format, for example `jpeg`.
69    pub extension_aliases: &'static [&'static str],
70}
71
72impl FormatSpec {
73    /// A format with one media type and one extension.
74    pub const fn new(media_type: &'static str, extension: &'static str) -> Self {
75        Self {
76            media_type,
77            extension,
78            media_type_aliases: &[],
79            extension_aliases: &[],
80        }
81    }
82
83    /// Adds media types accepted for this format.
84    pub const fn media_type_aliases(mut self, aliases: &'static [&'static str]) -> Self {
85        self.media_type_aliases = aliases;
86        self
87    }
88
89    /// Adds file extensions accepted for this format.
90    pub const fn extension_aliases(mut self, aliases: &'static [&'static str]) -> Self {
91        self.extension_aliases = aliases;
92        self
93    }
94
95    /// Every file extension this format accepts, the preferred one first.
96    pub fn extensions(&self) -> impl Iterator<Item = &'static str> {
97        std::iter::once(self.extension).chain(self.extension_aliases.iter().copied())
98    }
99
100    /// Every media type this format accepts, the preferred one first.
101    pub fn media_types(&self) -> impl Iterator<Item = &'static str> {
102        std::iter::once(self.media_type).chain(self.media_type_aliases.iter().copied())
103    }
104
105    /// Every format string (extension or media type) this format accepts.
106    pub fn format_strings(&self) -> impl Iterator<Item = &'static str> {
107        self.extensions().chain(self.media_types())
108    }
109}
110
111/// Knowledge of one container format.
112///
113/// Implementations must be cheap to share (`Send + Sync`) and stateless in
114/// practice: one instance serves every asset of its formats.
115pub trait ContainerHandler: std::fmt::Debug + Send + Sync {
116    /// The container's identity, for example `"jpeg"` or `"bmff"`. Stable and
117    /// independent of the format strings the handler serves; two format strings
118    /// belong to the same container iff their handlers have the same id.
119    fn id(&self) -> &'static str;
120
121    /// The formats this handler serves, each a media type with its extensions.
122    fn formats(&self) -> &[FormatSpec];
123
124    /// The container-defined box name of `element`, or `None` if it is not a
125    /// named box. Called by [`Structure::box_name`] for inspection and other
126    /// consumers of the container structure, including [`Structure::complete_boxes`].
127    /// The default covers four character codes, numeric ids and hexadecimal
128    /// one-byte marker codes. Override it for names with other text (JPEG marker
129    /// symbols) or names that need parsed context (RIFF form and list types).
130    ///
131    /// `segment` identifies the owning segment in `structure`; `element` may be
132    /// a finer element within it, as reported by [`Structure::elements`].
133    fn box_name(
134        &self,
135        _structure: &Structure,
136        _segment: SegmentId,
137        element: &Segment,
138    ) -> Option<Cow<'static, str>> {
139        match element.name() {
140            Name::None => None,
141            Name::FourCC(cc) => Some(Cow::Owned(String::from_utf8_lossy(&cc).into_owned())),
142            Name::Id(n) => Some(Cow::Owned(n.to_string())),
143            name @ Name::Marker(_) => Some(Cow::Owned(name.to_string())),
144        }
145    }
146
147    /// Whether `element` of `segment` is the rest of the box before it, so
148    /// [`Structure::boxes`] lists both as one box. Called before
149    /// [`box_name`](Self::box_name). The default is `false`. A
150    /// container that splits one box into several segments overrides it: GIF
151    /// stores each data sub-block of an application extension as a segment.
152    fn box_continues(
153        &self,
154        _structure: &Structure,
155        _segment: SegmentId,
156        _element: &Segment,
157    ) -> bool {
158        false
159    }
160
161    /// The ranges a C2PA data hash (`c2pa.hash.data`) excludes when `item` is the
162    /// embedded manifest store. Called by [`Structure::c2pa_data_hash_exclusions`],
163    /// which validates and normalizes the ranges.
164    ///
165    /// The default excludes every segment that carries the item, framing and
166    /// trailers included, which is the C2PA rule for containers that store the
167    /// manifest in dedicated segments (JPEG APP11, PNG `caBX`). A container with
168    /// other rules overrides it; one whose C2PA embedding uses a different binding
169    /// returns [`Error::UnsupportedFeature`].
170    fn c2pa_data_hash_exclusions(
171        &self,
172        structure: &Structure,
173        item: &Item,
174    ) -> Result<Vec<ByteRange>> {
175        item.extents()
176            .map(|extent| Ok(structure.segment(extent.segment())?.range()))
177            .collect()
178    }
179
180    /// Whether `header` (the first [`DETECT_LEN`] bytes, or fewer for a short
181    /// stream) looks like this container. The default never matches, so the handler
182    /// is found only by format string.
183    fn detect(&self, _header: &[u8]) -> bool {
184        false
185    }
186
187    /// Parse the whole structure of an asset, reading it through `io`.
188    ///
189    /// It is `async` so that the same code can be run by any I/O: see
190    /// [`Task`](crate::task::Task). Read with [`Io`], whose reads are `.await`ed;
191    /// everything else is ordinary code. [`parse`](Self::parse) and
192    /// [`Structure::parse_task`](crate::Structure::parse_task) run it.
193    ///
194    /// The result must tile the stream (see [`StructureBuilder`](crate::container_api::StructureBuilder))
195    /// and must be built with `self` as its handler, which is why this takes the
196    /// `Arc`: `StructureBuilder::new(self, ...)`. Return
197    /// `Box::pin(async move { ... })`.
198    fn parse_async(self: Arc<Self>, io: Io) -> BoxFuture<'static, Result<Structure>>;
199
200    /// Parse the whole structure of an asset from a stream, reading it with
201    /// blocking calls. This runs [`parse_async`](Self::parse_async); there is no
202    /// need to implement it.
203    fn parse(self: Arc<Self>, src: &mut dyn ReadSeek) -> Result<Structure> {
204        let total = src.seek(SeekFrom::End(0))?;
205        src.seek(SeekFrom::Start(0))?;
206        block_on(total, src, |io| self.parse_async(io))
207    }
208
209    /// Describe the write of the asset with `updates` applied: the structure of the
210    /// output and the steps that produce it. Nothing is written. The source is
211    /// read through `io`, which holds the stream `src_structure` was parsed from.
212    ///
213    /// This is the method to implement for writing; it is `async` for the same
214    /// reason as [`parse_async`](Self::parse_async). A handler that cannot write
215    /// leaves the default, which reports [`Error::UnsupportedFormat`]. The default
216    /// [`write`](Self::write) executes the plan, and the default
217    /// [`plan`](Self::plan) returns its structure. A handler that needs nothing
218    /// from the source ignores `io`. The default reports
219    /// [`Error::UnsupportedFormat`].
220    fn write_plan_async<'f, 'a: 'f>(
221        &'f self,
222        _src_structure: &'f Structure,
223        _io: Io,
224        _updates: &'a Updates,
225    ) -> BoxFuture<'f, Result<WritePlan<'a>>> {
226        Box::pin(async { Err(Error::UnsupportedFormat) })
227    }
228
229    /// Like [`write_plan_async`](Self::write_plan_async), reading the source from
230    /// `src` with blocking calls. This runs that method; there is no need to
231    /// implement it.
232    fn write_plan<'a>(
233        &self,
234        src_structure: &Structure,
235        src: &mut dyn ReadSeek,
236        updates: &'a Updates,
237    ) -> Result<WritePlan<'a>> {
238        block_on(src_structure.total_size(), src, |io| {
239            self.write_plan_async(src_structure, io, updates)
240        })
241    }
242
243    /// Write the asset with `updates` applied, delivering every output byte to
244    /// `sink`, and return the structure of what was written.
245    ///
246    /// `out` is only written to, from its current position, so a file, a buffer, a
247    /// socket or a hashing writer will do.
248    ///
249    /// The default executes [`write_plan`](Self::write_plan). Override it only to
250    /// write some other way, such as a container whose output cannot be described
251    /// ahead of time.
252    fn write(
253        &self,
254        src_structure: &Structure,
255        src: &mut dyn ReadSeek,
256        out: &mut dyn Write,
257        updates: &Updates,
258        sink: &mut dyn Sink,
259    ) -> Result<Structure> {
260        let plan = self.write_plan(src_structure, src, updates)?;
261        crate::plan::check_updates_placed(&plan, updates)?;
262        plan.execute(src, out, sink)?;
263        Ok(plan.into_structure())
264    }
265
266    /// The structure [`write`](Self::write) would produce for `updates`, without
267    /// writing anything. `src` must be the stream `src_structure` was parsed from;
268    /// handlers that need nothing from it ignore it.
269    ///
270    /// Called through [`Structure::plan`](crate::Structure::plan). The default is
271    /// the structure of [`write_plan`](Self::write_plan). Implementations must return
272    /// exactly what `write` does.
273    fn plan(
274        &self,
275        src_structure: &Structure,
276        src: &mut dyn ReadSeek,
277        updates: &Updates,
278    ) -> Result<Structure> {
279        Ok(self
280            .write_plan(src_structure, src, updates)?
281            .into_structure())
282    }
283
284    /// The asset's XMP packet, or `None` if it has none. Called through
285    /// [`Structure::xmp`](crate::Structure::xmp).
286    ///
287    /// The default reads the single XMP item, decoded. Containers that split XMP over
288    /// several elements and must reassemble it (JPEG extended XMP) override this.
289    fn read_xmp(&self, structure: &Structure, src: &mut dyn ReadSeek) -> Result<Option<Vec<u8>>> {
290        let mut src = src;
291        match structure.item(ItemKind::Xmp)? {
292            Some(e) => structure.read_content(&mut src, e).map(Some),
293            None => Ok(None),
294        }
295    }
296
297    /// The container's own encoding of one metadata item: the bytes
298    /// [`write`](Self::write) would insert for an item of `kind` holding `data`,
299    /// framing included.
300    /// For JPEG that is the APP11 segments of a JUMBF, for PNG the whole `caBX`
301    /// chunk with its checksum, for ISO BMFF the whole C2PA `uuid` box.
302    ///
303    /// This is for callers that insert the data into an asset themselves and have
304    /// to match what a writer produces. Callers that use [`write`](Self::write) never
305    /// need it. The default reports [`Error::UnsupportedFormat`]; a container for
306    /// which the item is stored as it is returns `data` unchanged.
307    fn compose(&self, _kind: ItemKind, _data: &[u8]) -> Result<Vec<u8>> {
308        Err(Error::UnsupportedFormat)
309    }
310
311    /// Whether `item`'s bytes may be overwritten in place with `len` bytes (see
312    /// [`Structure::patch`](crate::Structure::patch)). The default allows it, as long as
313    /// the bytes fit. A container that cannot take a short payload, or an edit at all
314    /// (a compressed stream, a signed document), refuses here. `len` is the length
315    /// of what would be stored, after the item's
316    /// [transfer encoding](crate::Item::transfer).
317    fn check_patch(&self, _structure: &Structure, _item: &Item, _len: usize) -> Result<()> {
318        Ok(())
319    }
320
321    /// Visit the container's element hierarchy in file order, parents before
322    /// children. Called through [`Structure::walk`](crate::Structure::walk).
323    ///
324    /// The default reports each segment as a top-level node. Containers that nest
325    /// elements inside segments override it and read only what they need.
326    fn walk(
327        &self,
328        structure: &Structure,
329        _src: &mut dyn ReadSeek,
330        f: &mut dyn FnMut(&Node<'_>) -> Result<()>,
331    ) -> Result<()> {
332        let mut path = String::new();
333        for (i, seg) in structure.segments().iter().enumerate() {
334            path.clear();
335            path.push('/');
336            if let Some(n) = self.box_name(structure, SegmentId::from_index(i)?, seg) {
337                path.push_str(&n);
338            }
339            f(&Node {
340                path: &path,
341                name: seg.name(),
342                range: seg.range(),
343                header_len: seg.header().len() as u32,
344                depth: 1,
345                version: None,
346                flags: None,
347                user_type: None,
348            })?;
349        }
350        Ok(())
351    }
352
353    /// Repair a checksum or similar that covers a segment whose payload was just
354    /// patched in place. The default does nothing.
355    fn fix_trailer(
356        &self,
357        _out: &mut dyn ReadWriteSeek,
358        _structure: &Structure,
359        _segment: SegmentId,
360    ) -> Result<()> {
361        Ok(())
362    }
363}