asset-io 0.3.1

Streaming, container-agnostic access to media file structure and metadata (JUMBF, XMP)
Documentation
// Copyright 2026 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.

// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

//! Pluggable container handlers.
//!
//! A [`ContainerHandler`] teaches asset-io one container format. The built-in
//! containers (under [`containers`](crate::containers)) implement it, and so can a handler registered by a
//! caller (see [`HandlerRegistry`](crate::HandlerRegistry)). A parsed
//! [`Structure`] keeps the handler that produced it, so everything that depends on
//! the container (subdividing scans, box names, patching trailers, rewriting) works
//! on any structure without the caller knowing the format.

use std::{
    borrow::Cow,
    io::{Read, Seek, SeekFrom, Write},
    sync::Arc,
};

use crate::{
    error::{Error, Result},
    io::{BoxFuture, Io},
    item::{Item, ItemKind},
    plan::WritePlan,
    range::ByteRange,
    segment::{Name, Segment},
    sink::Sink,
    structure::{SegmentId, Structure},
    task::block_on,
    walk::Node,
    Updates,
};

/// A readable, seekable stream. Blanket-implemented, so any `Read + Seek` works.
pub trait ReadSeek: Read + Seek {}
impl<T: Read + Seek + ?Sized> ReadSeek for T {}

/// A readable, writable, seekable stream. Blanket-implemented.
pub trait ReadWriteSeek: Read + Write + Seek {}
impl<T: Read + Write + Seek + ?Sized> ReadWriteSeek for T {}

/// How many leading bytes [`ContainerHandler::detect`] is given.
pub const DETECT_LEN: usize = 64;

/// The kind of C2PA hard-binding assertion a container's embedded manifest uses;
/// see [`ContainerHandler::c2pa_hash`]. Creating and checking the assertion is
/// the caller's; this only says which one the container calls for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum C2paHash {
    /// `c2pa.hash.data`: every byte outside the ranges
    /// [`Structure::c2pa_data_hash_exclusions`] returns.
    Data,
    /// `c2pa.hash.boxes`: each box [`Structure::c2pa_boxes`] lists.
    Box,
    /// `c2pa.hash.bmff`: the ISO BMFF box tree, as the C2PA specification
    /// defines it for BMFF.
    Bmff,
}

/// One format a container handler serves: a media type and its file extensions.
///
/// A container that carries several media types (ISO BMFF: HEIC, MP4, M4A...)
/// declares one `FormatSpec` per media type. Format strings are matched ignoring
/// case, surrounding whitespace and a leading dot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct FormatSpec {
    /// The media type, for example `image/jpeg`.
    pub media_type: &'static str,
    /// The preferred file extension, without a dot, for example `jpg`.
    pub extension: &'static str,
    /// Other media types accepted for this format, for example `image/x-webp`.
    pub media_type_aliases: &'static [&'static str],
    /// Other file extensions accepted for this format, for example `jpeg`.
    pub extension_aliases: &'static [&'static str],
}

impl FormatSpec {
    /// A format with one media type and one extension.
    pub const fn new(media_type: &'static str, extension: &'static str) -> Self {
        Self {
            media_type,
            extension,
            media_type_aliases: &[],
            extension_aliases: &[],
        }
    }

    /// Adds media types accepted for this format.
    pub const fn media_type_aliases(mut self, aliases: &'static [&'static str]) -> Self {
        self.media_type_aliases = aliases;
        self
    }

    /// Adds file extensions accepted for this format.
    pub const fn extension_aliases(mut self, aliases: &'static [&'static str]) -> Self {
        self.extension_aliases = aliases;
        self
    }

    /// Every file extension this format accepts, the preferred one first.
    pub fn extensions(&self) -> impl Iterator<Item = &'static str> {
        std::iter::once(self.extension).chain(self.extension_aliases.iter().copied())
    }

    /// Every media type this format accepts, the preferred one first.
    pub fn media_types(&self) -> impl Iterator<Item = &'static str> {
        std::iter::once(self.media_type).chain(self.media_type_aliases.iter().copied())
    }

    /// Every format string (extension or media type) this format accepts.
    pub fn format_strings(&self) -> impl Iterator<Item = &'static str> {
        self.extensions().chain(self.media_types())
    }
}

/// Knowledge of one container format.
///
/// Implementations must be cheap to share (`Send + Sync`) and stateless in
/// practice: one instance serves every asset of its formats.
pub trait ContainerHandler: std::fmt::Debug + Send + Sync {
    /// The container's identity, for example `"jpeg"` or `"bmff"`. Stable and
    /// independent of the format strings the handler serves; two format strings
    /// belong to the same container iff their handlers have the same id.
    fn id(&self) -> &'static str;

    /// The formats this handler serves, each a media type with its extensions.
    fn formats(&self) -> &[FormatSpec];

    /// The C2PA hard binding an embedded manifest in `structure` should use, or
    /// `None` when asset-io cannot support embedding one. Called by
    /// [`Structure::c2pa_hash`].
    ///
    /// The default is [`C2paHash::Box`] when every element of the container's own
    /// structure has a [`box_name`](Self::box_name), so
    /// [`Structure::c2pa_boxes`] can list it, and [`C2paHash::Data`] otherwise:
    /// for containers without meaningful boxes.
    fn c2pa_hash(&self, structure: &Structure) -> Option<C2paHash> {
        let named = structure.segments()[..structure.box_count()]
            .iter()
            .enumerate()
            .all(|(i, s)| {
                SegmentId::from_index(i)
                    .is_ok_and(|id| self.c2pa_box_name(structure, id, s).is_some())
            });
        Some(if named { C2paHash::Box } else { C2paHash::Data })
    }

    /// The name a C2PA box hash lists `element` of `segment` under, or `None` if it
    /// is not a box. Called by [`Structure::c2pa_boxes`]. The default is
    /// [`box_name`](Self::box_name); a container whose C2PA box names are not its
    /// element names (RIFF lists a `RIFF` or `LIST` chunk under its type)
    /// overrides it.
    fn c2pa_box_name(
        &self,
        _structure: &Structure,
        _segment: SegmentId,
        element: &Segment,
    ) -> Option<Cow<'static, str>> {
        self.box_name(element.name())
    }

    /// The ranges a C2PA data hash (`c2pa.hash.data`) excludes when `item` is the
    /// embedded manifest store. Called by [`Structure::c2pa_data_hash_exclusions`],
    /// which validates and normalizes the ranges.
    ///
    /// The default excludes every segment that carries the item, framing and
    /// trailers included, which is the C2PA rule for containers that store the
    /// manifest in dedicated segments (JPEG APP11, PNG `caBX`). A container with
    /// other rules overrides it; one whose C2PA embedding uses a different binding
    /// returns [`Error::UnsupportedFeature`].
    fn c2pa_data_hash_exclusions(
        &self,
        structure: &Structure,
        item: &Item,
    ) -> Result<Vec<ByteRange>> {
        item.extents()
            .map(|extent| Ok(structure.segment(extent.segment())?.range()))
            .collect()
    }

    /// Whether `header` (the first [`DETECT_LEN`] bytes, or fewer for a short
    /// stream) looks like this container. The default never matches, so the handler
    /// is found only by format string.
    fn detect(&self, _header: &[u8]) -> bool {
        false
    }

    /// Parse the whole structure of an asset, reading it through `io`.
    ///
    /// It is `async` so that the same code can be run by any I/O: see
    /// [`Task`](crate::task::Task). Read with [`Io`], whose reads are `.await`ed;
    /// everything else is ordinary code. [`parse`](Self::parse) and
    /// [`Structure::parse_task`](crate::Structure::parse_task) run it.
    ///
    /// The result must tile the stream (see [`StructureBuilder`](crate::container_api::StructureBuilder))
    /// and must be built with `self` as its handler, which is why this takes the
    /// `Arc`: `StructureBuilder::new(self, ...)`. Return
    /// `Box::pin(async move { ... })`.
    fn parse_async(self: Arc<Self>, io: Io) -> BoxFuture<'static, Result<Structure>>;

    /// Parse the whole structure of an asset from a stream, reading it with
    /// blocking calls. This runs [`parse_async`](Self::parse_async); there is no
    /// need to implement it.
    fn parse(self: Arc<Self>, src: &mut dyn ReadSeek) -> Result<Structure> {
        let total = src.seek(SeekFrom::End(0))?;
        src.seek(SeekFrom::Start(0))?;
        block_on(total, src, |io| self.parse_async(io))
    }

    /// Describe the write of the asset with `updates` applied: the structure of the
    /// output and the steps that produce it. Nothing is written. The source is
    /// read through `io`, which holds the stream `src_structure` was parsed from.
    ///
    /// This is the method to implement for writing; it is `async` for the same
    /// reason as [`parse_async`](Self::parse_async). A handler that cannot write
    /// leaves the default, which reports [`Error::UnsupportedFormat`]. The default
    /// [`write`](Self::write) executes the plan, and the default
    /// [`plan`](Self::plan) returns its structure. A handler that needs nothing
    /// from the source ignores `io`. The default reports
    /// [`Error::UnsupportedFormat`].
    fn write_plan_async<'f, 'a: 'f>(
        &'f self,
        _src_structure: &'f Structure,
        _io: Io,
        _updates: &'a Updates,
    ) -> BoxFuture<'f, Result<WritePlan<'a>>> {
        Box::pin(async { Err(Error::UnsupportedFormat) })
    }

    /// Like [`write_plan_async`](Self::write_plan_async), reading the source from
    /// `src` with blocking calls. This runs that method; there is no need to
    /// implement it.
    fn write_plan<'a>(
        &self,
        src_structure: &Structure,
        src: &mut dyn ReadSeek,
        updates: &'a Updates,
    ) -> Result<WritePlan<'a>> {
        block_on(src_structure.total_size(), src, |io| {
            self.write_plan_async(src_structure, io, updates)
        })
    }

    /// Write the asset with `updates` applied, delivering every output byte to
    /// `sink`, and return the structure of what was written.
    ///
    /// `out` is only written to, from its current position, so a file, a buffer, a
    /// socket or a hashing writer will do.
    ///
    /// The default executes [`write_plan`](Self::write_plan). Override it only to
    /// write some other way, such as a container whose output cannot be described
    /// ahead of time.
    fn write(
        &self,
        src_structure: &Structure,
        src: &mut dyn ReadSeek,
        out: &mut dyn Write,
        updates: &Updates,
        sink: &mut dyn Sink,
    ) -> Result<Structure> {
        let plan = self.write_plan(src_structure, src, updates)?;
        plan.execute(src, out, sink)?;
        Ok(plan.into_structure())
    }

    /// The structure [`write`](Self::write) would produce for `updates`, without
    /// writing anything. `src` must be the stream `src_structure` was parsed from;
    /// handlers that need nothing from it ignore it.
    ///
    /// Called through [`Structure::plan`](crate::Structure::plan). The default is
    /// the structure of [`write_plan`](Self::write_plan). Implementations must return
    /// exactly what `write` does.
    fn plan(
        &self,
        src_structure: &Structure,
        src: &mut dyn ReadSeek,
        updates: &Updates,
    ) -> Result<Structure> {
        Ok(self
            .write_plan(src_structure, src, updates)?
            .into_structure())
    }

    /// The asset's XMP packet, or `None` if it has none. Called through
    /// [`Structure::xmp`](crate::Structure::xmp).
    ///
    /// The default reads the single XMP item, decoded. Containers that split XMP over
    /// several elements and must reassemble it (JPEG extended XMP) override this.
    fn read_xmp(&self, structure: &Structure, src: &mut dyn ReadSeek) -> Result<Option<Vec<u8>>> {
        let mut src = src;
        match structure.item(ItemKind::Xmp)? {
            Some(e) => structure.read_content(&mut src, e).map(Some),
            None => Ok(None),
        }
    }

    /// The container's own encoding of one metadata item: the bytes
    /// [`write`](Self::write) would insert for an item of `kind` holding `data`,
    /// framing included.
    /// For JPEG that is the APP11 segments of a JUMBF, for PNG the whole `caBX`
    /// chunk with its checksum, for ISO BMFF the whole C2PA `uuid` box.
    ///
    /// This is for callers that insert the data into an asset themselves and have
    /// to match what a writer produces. Callers that use [`write`](Self::write) never
    /// need it. The default reports [`Error::UnsupportedFormat`]; a container for
    /// which the item is stored as it is returns `data` unchanged.
    fn compose(&self, _kind: ItemKind, _data: &[u8]) -> Result<Vec<u8>> {
        Err(Error::UnsupportedFormat)
    }

    /// Whether `item`'s bytes may be overwritten in place with `len` bytes (see
    /// [`Structure::patch`](crate::Structure::patch)). The default allows it, as long as
    /// the bytes fit. A container that cannot take a short payload, or an edit at all
    /// (a compressed stream, a signed document), refuses here. `len` is the length
    /// of what would be stored, after the item's
    /// [transfer encoding](crate::Item::transfer).
    fn check_patch(&self, _structure: &Structure, _item: &Item, _len: usize) -> Result<()> {
        Ok(())
    }

    /// Visit the container's element hierarchy in file order, parents before
    /// children. Called through [`Structure::walk`](crate::Structure::walk).
    ///
    /// The default reports each segment as a top-level node. Containers that nest
    /// elements inside segments override it and read only what they need.
    fn walk(
        &self,
        structure: &Structure,
        _src: &mut dyn ReadSeek,
        f: &mut dyn FnMut(&Node<'_>) -> Result<()>,
    ) -> Result<()> {
        let mut path = String::new();
        for seg in structure.segments() {
            path.clear();
            path.push('/');
            if let Some(n) = self.box_name(seg.name()) {
                path.push_str(&n);
            }
            f(&Node {
                path: &path,
                name: seg.name(),
                range: seg.range(),
                header_len: seg.header().len() as u32,
                depth: 1,
                version: None,
                flags: None,
                user_type: None,
            })?;
        }
        Ok(())
    }

    /// Repair a checksum or similar that covers a segment whose payload was just
    /// patched in place. The default does nothing.
    fn fix_trailer(
        &self,
        _out: &mut dyn ReadWriteSeek,
        _structure: &Structure,
        _segment: SegmentId,
    ) -> Result<()> {
        Ok(())
    }

    /// The name a box-based hash lists for `name`, or `None` if the element is not
    /// a box. The default covers four character codes and numeric ids; override it
    /// for names with other text, such as JPEG marker symbols.
    fn box_name(&self, name: Name) -> Option<Cow<'static, str>> {
        match name {
            Name::None => None,
            Name::FourCC(cc) => Some(Cow::Owned(String::from_utf8_lossy(&cc).into_owned())),
            Name::Id(n) => Some(Cow::Owned(n.to_string())),
            Name::Marker(_) => Some(Cow::Owned(name.to_string())),
        }
    }
}