asset-io 0.4.0

Streaming, container-agnostic access to media file structure and metadata (JUMBF, XMP)
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
// 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) or
    /// [continues](Self::c2pa_box_continues) a box, 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()
                        || self.c2pa_box_continues(structure, id, s)
                })
            });
        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())
    }

    /// Whether `element` of `segment` is the rest of the box before it, so
    /// [`Structure::c2pa_boxes`] lists both as one box. Called before
    /// [`c2pa_box_name`](Self::c2pa_box_name). The default is `false`. A
    /// container that splits one box into several segments overrides it: GIF
    /// stores each data sub-block of an application extension as a segment.
    fn c2pa_box_continues(
        &self,
        _structure: &Structure,
        _segment: SegmentId,
        _element: &Segment,
    ) -> bool {
        false
    }

    /// 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())),
        }
    }
}