Skip to main content

asset_io/containers/bmff/
mod.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//! ISO BMFF (MP4, MOV, HEIF, AVIF, ...) on the structure model.
15//!
16//! Segments are the file's top-level boxes. A box's `size`/`type` (and extended
17//! size and `uuid` type) are the header; the rest is the payload; there is no
18//! trailer. Boxes nested inside segments are not segments: [`Structure::walk`]
19//! finds them lazily, reading only box headers.
20//!
21//! `ftyp` is the [`Preamble`](SegmentKind::Preamble) and `mdat` is
22//! [`MediaData`](SegmentKind::MediaData), even when HEIF items lie in it.
23//!
24//! C2PA's content provenance boxes (`uuid` D8FEC3D6-...) are
25//! [`Metadata`](SegmentKind::Metadata) segments holding one item each:
26//! `manifest`, `original` and `update` boxes are [`ItemKind::C2pa`] items
27//! labelled with their purpose, whose payload is the manifest store itself (the
28//! purpose string and the merkle offset field belong to the header). `merkle` boxes
29//! are [`ItemKind::Other`] items labelled `merkle`. An XMP `uuid` box is an
30//! [`ItemKind::Xmp`] item.
31//!
32//! HEIF items found through a file-level `meta` box are items too, with their item
33//! type as [`native_type`](crate::Item::native_type), their `item_ID` as
34//! [`native_id`](crate::Item::native_id) and every `iref` reference from them as
35//! [relations](crate::Item::relations):
36//!
37//! - an `Exif` item is an [`ItemKind::Exif`] item (the TIFF data, after the item's
38//!   offset field);
39//! - a `mime` item of type `application/rdf+xml` is an [`ItemKind::Xmp`] item;
40//! - `jpeg` items and `mime` items with another valid content type declare a media
41//!   type, and are [`ItemKind::EmbeddedAsset`] items;
42//! - `uri ` items, `mime` items without a valid content type, and any other item
43//!   that is the source of a `thmb` reference (a coded image such as `hvc1`) are
44//!   [`ItemKind::Other`] items of unknown encoding. A `uri ` item keeps its URI in
45//!   [`Item::uri`](crate::Item::uri), and a thumbnail its thumbnail relation.
46//!
47//! Their bytes lie in `mdat` or `idat`, so an item can have several extents, and
48//! `Structure::slice_item` and `read_item` work on them as on any other. Items that
49//! cannot be located (external data, unsupported construction methods, extents
50//! outside the file) are left out, and a `meta` box that does not parse does not make
51//! the file an error.
52//!
53//! [`Structure::xmp`] reads the XMP `uuid` box if there is one; otherwise the XMP
54//! item that describes (`cdsc`) the primary item (`pitm`); otherwise the only XMP
55//! item, if there is exactly one.
56//!
57//! Combinations the C2PA specification forbids are errors at parse time: more than
58//! one manifest, original or update store; `original` without `update` or the
59//! reverse; `manifest` together with `update`; a C2PA box without a known purpose.
60//!
61//! # Writing
62//!
63//! `Updates::set_c2pa` writes a `manifest` box: it replaces the existing
64//! `manifest` (or `original`) box in place, or is inserted after `ftyp`. Any
65//! `update` box is dropped, as when a file is re-signed. `remove_c2pa` drops every
66//! C2PA box. XMP follows the same placement rules, and is always written as the
67//! `uuid` box.
68//!
69//! HEIF items, whatever their kind, are carried through a write unchanged:
70//! updates do not edit, add or remove them (an XMP item in `mdat` stays as it is
71//! when the XMP `uuid` box is set or removed).
72//!
73//! [`BmffUpdates::set_merkle`] replaces the `merkle` boxes with new ones, placed right
74//! after the last `mdat`, or, in a fragmented file (one with `moof` boxes), one
75//! immediately before each `moof`, as C2PA requires of a fragment file and of a flat
76//! fragmented file; `remove_merkle` drops them. A file that has them takes a
77//! new manifest only if they are also set or removed, since they belong with the
78//! manifest that describes them. The boxes can be written as placeholders of their
79//! final size and filled in with `Structure::patch_exact` once the media has been
80//! hashed during the write.
81//!
82//! `set_c2pa(store).as_update()` is the same as `set_c2pa` unless the new store begins
83//! with the manifests already in the file, byte for byte. Then those stay as they
84//! are (a `manifest` box becomes `original`; only its purpose changes) and the
85//! rest is written as the `update` box, added at the end of the file or replacing
86//! the existing `update` box. Nothing before it moves.
87//!
88//! Adding, replacing or dropping a box moves the data after it. The absolute file
89//! offsets that point there (`stco`, `co64`, `saio`, `tfhd` base data offset,
90//! `tfra`, `iloc`) are rewritten while the file is copied: the size change is known
91//! before copying starts, so there is one pass. Tables are rewritten through the
92//! copy buffer, so memory does not grow with the size of `moov`; only `iloc`,
93//! which is variable-length, is buffered (capped at 16 MiB). When no box changes
94//! size, nothing is rewritten and `moov` is copied verbatim. `mfro` and `sidx`
95//! hold sizes and relative offsets, which these edits do not change.
96
97mod heif_items;
98
99use std::{borrow::Cow, io::SeekFrom, sync::Arc};
100
101use crate::{
102    container_api,
103    container_api::{
104        block_on, BoxFuture, ContainerHandler, Existing, FormatSpec, Io, ItemInfo, MetadataSlot,
105        MetadataUpdate, OffsetMap, PlanBuilder, ReadSeek, Relocate, StructureBuilder, WritePlan,
106        MAX_SEGMENT_SIZE,
107    },
108    ByteRange, Encoding, Error, Item, ItemKind, Name, Node, Relation, RelationKind, Result, Role,
109    Segment, SegmentId, SegmentKind, Structure, Updates,
110};
111
112/// C2PA content provenance box type, `D8FEC3D6-1B0E-483C-9297-5828877EC481`.
113const C2PA_UUID: [u8; 16] = [
114    0xd8, 0xfe, 0xc3, 0xd6, 0x1b, 0x0e, 0x48, 0x3c, 0x92, 0x97, 0x58, 0x28, 0x87, 0x7e, 0xc4, 0x81,
115];
116/// XMP box type, `BE7ACFCB-97A9-42E8-9C71-999491E3AFAC`.
117const XMP_UUID: [u8; 16] = [
118    0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac,
119];
120
121/// Maximum nesting depth followed by [`walk`](ContainerHandler::walk).
122const MAX_BOX_DEPTH: u32 = 32;
123
124/// Purpose labels of C2PA boxes (see [`labels`](crate::labels)).
125use crate::labels::{MANIFEST, MERKLE, ORIGINAL, UPDATE};
126
127/// What to do with the `merkle` boxes of a file; see [`BmffUpdates`].
128#[derive(Debug, Clone, Default)]
129#[non_exhaustive]
130pub enum MerkleUpdate {
131    /// Keep existing boxes (default)
132    #[default]
133    Keep,
134    /// Remove existing boxes
135    Remove,
136    /// Replace existing boxes with these payloads, one box each
137    Set(Vec<Vec<u8>>),
138}
139
140/// ISO BMFF options for [`Updates`]: what to do with the `merkle` boxes.
141///
142/// Merkle boxes carry proofs for hashed media blocks. Other containers ignore
143/// these options. [`Updates::remove_all`] removes them as well.
144pub trait BmffUpdates: Sized {
145    /// Replace the file's merkle boxes with one box per payload.
146    ///
147    /// The boxes are written immediately after the last `mdat`, and any existing
148    /// merkle boxes are dropped. In a fragmented file, one with `moof` boxes, there
149    /// must be one payload per `moof`, and each box is written immediately before
150    /// its `moof`. All payloads are usually the same length (the C2PA
151    /// specification pads them to one length).
152    ///
153    /// The content usually depends on hashes of the media, which exist only after
154    /// the write. Write zeroed payloads of the final length, hash the media through
155    /// the [`Sink`](crate::Sink) during the write, then fill each box in place with
156    /// [`Structure::patch_exact`](crate::Structure::patch_exact). The boxes are the
157    /// items labelled [`MERKLE`] of kind [`ItemKind::Other`].
158    ///
159    /// A file that has merkle boxes cannot take a new manifest unless the boxes are
160    /// also set or removed, and an update manifest cannot change them.
161    fn set_merkle(self, payloads: Vec<Vec<u8>>) -> Self;
162
163    /// Remove the file's merkle boxes. See [`set_merkle`](Self::set_merkle).
164    fn remove_merkle(self) -> Self;
165
166    /// Keep the file's merkle boxes (explicit, same as default).
167    fn keep_merkle(self) -> Self;
168
169    /// What to do with the merkle boxes.
170    fn merkle(&self) -> &MerkleUpdate;
171}
172
173impl BmffUpdates for Updates {
174    fn set_merkle(self, payloads: Vec<Vec<u8>>) -> Self {
175        self.set_extension(MerkleUpdate::Set(payloads))
176    }
177
178    fn remove_merkle(self) -> Self {
179        self.set_extension(MerkleUpdate::Remove)
180    }
181
182    fn keep_merkle(self) -> Self {
183        self.set_extension(MerkleUpdate::Keep)
184    }
185
186    fn merkle(&self) -> &MerkleUpdate {
187        static KEEP: MerkleUpdate = MerkleUpdate::Keep;
188        static REMOVE: MerkleUpdate = MerkleUpdate::Remove;
189        match self.extension::<MerkleUpdate>() {
190            Some(m) => m,
191            None if self.removes_all() => &REMOVE,
192            None => &KEEP,
193        }
194    }
195}
196
197/// Longest purpose string looked for: longer than any defined purpose.
198const MAX_PURPOSE_LEN: usize = 32;
199
200/// Boxes whose content is a sequence of boxes that C2PA exclusions can address.
201const CONTAINERS: &[[u8; 4]] = &[
202    *b"moov", *b"trak", *b"mdia", *b"minf", *b"stbl", *b"moof", *b"traf", *b"edts", *b"udta",
203    *b"dinf", *b"tref", *b"treg", *b"mvex", *b"mfra", *b"meta", *b"schi",
204];
205
206/// ISO/IEC 14496-12:2022 boxes that begin with version and flags.
207const FULL_BOXES: &[[u8; 4]] = &[
208    *b"pdin", *b"mvhd", *b"tkhd", *b"mdhd", *b"hdlr", *b"nmhd", *b"elng", *b"stsd", *b"stdp",
209    *b"stts", *b"ctts", *b"cslg", *b"stss", *b"stsh", *b"elst", *b"dref", *b"stsz", *b"stz2",
210    *b"stsc", *b"stco", *b"co64", *b"padb", *b"subs", *b"saiz", *b"saio", *b"mehd", *b"trex",
211    *b"mfhd", *b"tfhd", *b"trun", *b"tfra", *b"mfro", *b"tfdt", *b"leva", *b"trep", *b"assp",
212    *b"sbgp", *b"sgpd", *b"csgp", *b"cprt", *b"tsel", *b"kind", *b"meta", *b"xml ", *b"bxml",
213    *b"iloc", *b"pitm", *b"ipro", *b"infe", *b"iinf", *b"iref", *b"ipma", *b"schm", *b"fiin",
214    *b"fpar", *b"fecr", *b"gitn", *b"fire", *b"stri", *b"stsg", *b"stvi", *b"csch", *b"sidx",
215    *b"ssix", *b"prft", *b"srpp", *b"vmhd", *b"smhd", *b"srat", *b"chnl", *b"dmix", *b"txtC",
216    *b"mime", *b"uri ", *b"uriI", *b"hmhd", *b"sthd", *b"vvhd", *b"medc",
217];
218
219const UUID: [u8; 4] = *b"uuid";
220const MDAT: [u8; 4] = *b"mdat";
221const MOOF: [u8; 4] = *b"moof";
222const FTYP: [u8; 4] = *b"ftyp";
223const META: [u8; 4] = *b"meta";
224const HDLR: [u8; 4] = *b"hdlr";
225
226/// The ISO BMFF container handler.
227#[derive(Debug, Clone, Copy, Default)]
228pub struct BmffHandler;
229
230/// The shared BMFF handler.
231pub fn handler() -> Arc<dyn ContainerHandler> {
232    Arc::new(BmffHandler)
233}
234
235/// The ISO BMFF container's [`ContainerHandler::id`].
236pub const ID: &str = "bmff";
237
238impl ContainerHandler for BmffHandler {
239    // C2PA binds ISO BMFF with `c2pa.hash.bmff`, not a data hash.
240    fn c2pa_data_hash_exclusions(
241        &self,
242        _structure: &Structure,
243        _item: &crate::Item,
244    ) -> Result<Vec<crate::ByteRange>> {
245        Err(Error::UnsupportedFeature(
246            "C2PA data-hash exclusions for ISO BMFF",
247        ))
248    }
249
250    fn id(&self) -> &'static str {
251        ID
252    }
253
254    fn formats(&self) -> &[FormatSpec] {
255        const F: &[FormatSpec] = &[
256            FormatSpec::new("video/mp4", "mp4").media_type_aliases(&["application/mp4"]),
257            FormatSpec::new("audio/mp4", "m4a"),
258            FormatSpec::new("video/x-m4v", "m4v"),
259            FormatSpec::new("video/quicktime", "mov"),
260            FormatSpec::new("image/heic", "heic"),
261            FormatSpec::new("image/heif", "heif"),
262            FormatSpec::new("image/avif", "avif"),
263        ];
264        F
265    }
266
267    fn detect(&self, header: &[u8]) -> bool {
268        header.len() >= 12 && header[4..8] == FTYP
269    }
270
271    fn parse_async(self: Arc<Self>, io: Io) -> BoxFuture<'static, Result<Structure>> {
272        Box::pin(parse_with(self, io))
273    }
274
275    fn write_plan_async<'f, 'a: 'f>(
276        &'f self,
277        src_structure: &'f Structure,
278        mut io: Io,
279        updates: &'a Updates,
280    ) -> BoxFuture<'f, Result<WritePlan<'a>>> {
281        Box::pin(async move {
282            let (ops, boxes, map) = plan(src_structure, &mut io, updates).await?;
283            assemble(src_structure, &mut io, ops, &boxes, map, true).await
284        })
285    }
286
287    // The structure does not depend on the offset tables, so planning alone does not
288    // read them.
289    fn plan(
290        &self,
291        src_structure: &Structure,
292        src: &mut dyn ReadSeek,
293        updates: &Updates,
294    ) -> Result<Structure> {
295        block_on(src_structure.total_size(), src, |mut io| async move {
296            let (ops, boxes, map) = plan(src_structure, &mut io, updates).await?;
297            let plan = assemble(src_structure, &mut io, ops, &boxes, map, false).await?;
298            Ok(plan.into_structure())
299        })
300    }
301
302    fn compose(&self, kind: ItemKind, data: &[u8]) -> Result<Vec<u8>> {
303        let op = match kind {
304            ItemKind::C2pa => new_c2pa(data)?,
305            ItemKind::Xmp => new_xmp(data)?,
306            _ => return Err(Error::UnsupportedFormat),
307        };
308        let Op::New {
309            header, payload, ..
310        } = op
311        else {
312            return Err(Error::UnsupportedFormat);
313        };
314        let mut out = header;
315        out.extend_from_slice(&payload);
316        Ok(out)
317    }
318
319    fn read_xmp(&self, structure: &Structure, src: &mut dyn ReadSeek) -> Result<Option<Vec<u8>>> {
320        let mut src = src;
321        match xmp_item(structure)? {
322            Some(e) => structure.read_content(&mut src, e).map(Some),
323            None => Ok(None),
324        }
325    }
326
327    fn walk(
328        &self,
329        _structure: &Structure,
330        src: &mut dyn ReadSeek,
331        f: &mut dyn FnMut(&Node<'_>) -> Result<()>,
332    ) -> Result<()> {
333        let total = src.seek(SeekFrom::End(0))?;
334        block_on(total, src, |mut io| async move {
335            walk(&mut io, 0, total, f).await
336        })
337    }
338}
339
340/// Parse the top-level boxes of a BMFF file into a validated structure.
341#[cfg(test)]
342fn parse<R: std::io::Read + std::io::Seek>(src: &mut R) -> Result<Structure> {
343    handler().parse(src)
344}
345
346#[derive(Debug, Clone, Copy)]
347struct BoxHeader {
348    /// Whole box, clamped as described on [`read_header`].
349    size: u64,
350    /// 8, or 16 with an extended size.
351    header_len: u32,
352    ty: [u8; 4],
353}
354
355/// Read the box header at `at`, inside a region ending at `end` (`at < end`).
356///
357/// - `Ok(None)`: fewer than 8 bytes remain; some files carry trailing bytes.
358/// - size 0 means the box runs to `end`.
359/// - a box larger than the region is an error, except `mdat`, which is clamped to
360///   the region (truncated media files are common and still hashable).
361async fn read_header(io: &mut Io, at: u64, end: u64) -> Result<Option<BoxHeader>> {
362    let remaining = end - at;
363    if remaining < 8 {
364        return Ok(None);
365    }
366    let mut h = [0u8; 8];
367    io.read_at(at, &mut h).await?;
368    let size32 = u32::from_be_bytes([h[0], h[1], h[2], h[3]]);
369    let ty = [h[4], h[5], h[6], h[7]];
370    let (mut size, header_len) = match size32 {
371        0 => (remaining, 8u32),
372        1 => {
373            if remaining < 16 {
374                return Err(Error::invalid_segment(at, "extended box size truncated"));
375            }
376            let mut l = [0u8; 8];
377            io.read_at(at + 8, &mut l).await?;
378            (u64::from_be_bytes(l), 16u32)
379        }
380        n => (n as u64, 8u32),
381    };
382    if size < header_len as u64 {
383        return Err(Error::invalid_segment(
384            at,
385            "box size smaller than its header",
386        ));
387    }
388    if size > remaining {
389        if ty == MDAT {
390            size = remaining;
391        } else {
392            return Err(Error::invalid_segment(at, "box extends past its container"));
393        }
394    }
395    Ok(Some(BoxHeader {
396        size,
397        header_len,
398        ty,
399    }))
400}
401
402fn is_container(ty: &[u8; 4]) -> bool {
403    CONTAINERS.contains(ty)
404}
405
406fn is_full_box(ty: &[u8; 4]) -> bool {
407    FULL_BOXES.contains(ty)
408}
409
410/// QuickTime writes `meta` without version and flags; its first child is `hdlr`.
411async fn meta_lacks_full_box_header(io: &mut Io, content: u64, box_end: u64) -> bool {
412    if box_end - content < 8 {
413        return false;
414    }
415    let mut b = [0u8; 8];
416    io.read_at(content, &mut b).await.is_ok() && b[4..8] == HDLR[..]
417}
418
419/// One level of boxes being walked: where the next box is, where the level ends, and
420/// how much of the path belongs to the levels above.
421#[derive(Clone, Copy)]
422struct Level {
423    at: u64,
424    end: u64,
425    mark: usize,
426}
427
428/// Visit the boxes in `[start, end)` and the boxes nested in the containers among
429/// them, in file order, a parent before its children. Reads only box headers (and
430/// the few bytes after one that say what it is).
431async fn walk<F>(io: &mut Io, start: u64, end: u64, f: &mut F) -> Result<()>
432where
433    F: FnMut(&Node<'_>) -> Result<()> + ?Sized,
434{
435    let mut path = String::new();
436    let mut levels = vec![Level {
437        at: start,
438        end,
439        mark: 0,
440    }];
441    while let Some(&Level { at, end, mark }) = levels.last() {
442        let depth = levels.len() as u32;
443        let Some(h) = (if at < end {
444            read_header(io, at, end).await?
445        } else {
446            None
447        }) else {
448            // The level is done: no more boxes, or only trailing bytes too short
449            // to be one.
450            path.truncate(mark);
451            levels.pop();
452            continue;
453        };
454        let box_end = at + h.size; // read_header guarantees <= end
455        let mut content = at + h.header_len as u64;
456        let mut user_type = None;
457        let mut full = is_full_box(&h.ty);
458
459        if h.ty == UUID {
460            if box_end - content < 16 {
461                return Err(Error::invalid_segment(
462                    at,
463                    "uuid box too small for its type",
464                ));
465            }
466            let mut u = [0u8; 16];
467            io.read_at(content, &mut u).await?;
468            content += 16;
469            full = u == C2PA_UUID;
470            user_type = Some(u);
471        } else if h.ty == META && full && meta_lacks_full_box_header(io, content, box_end).await {
472            full = false;
473        }
474        let header_len = (content - at) as u32;
475
476        let (mut version, mut flags) = (None, None);
477        if full {
478            if box_end - content < 4 {
479                return Err(Error::invalid_segment(
480                    at,
481                    "FullBox too small for version and flags",
482                ));
483            }
484            let mut vf = [0u8; 4];
485            io.read_at(content, &mut vf).await?;
486            content += 4;
487            version = Some(vf[0]);
488            flags = Some(u32::from_be_bytes([0, vf[1], vf[2], vf[3]]));
489        }
490
491        let here = path.len();
492        path.push('/');
493        path.push_str(&String::from_utf8_lossy(&h.ty));
494        let mut node = Node::new(
495            &path,
496            Name::FourCC(h.ty),
497            crate::ByteRange::new(at, h.size)?,
498            header_len,
499            depth,
500        );
501        node.version = version;
502        node.flags = flags;
503        node.user_type = user_type;
504        f(&node)?;
505        if let Some(level) = levels.last_mut() {
506            level.at = box_end;
507        }
508        if is_container(&h.ty) && content < box_end {
509            if depth + 1 > MAX_BOX_DEPTH {
510                return Err(Error::LimitExceeded {
511                    what: "box nesting depth",
512                    limit: MAX_BOX_DEPTH as u64,
513                });
514            }
515            levels.push(Level {
516                at: content,
517                end: box_end,
518                mark: here,
519            });
520        } else {
521            path.truncate(here);
522        }
523    }
524    Ok(())
525}
526
527/// Media type implied by the major brand of a leading `ftyp` box.
528async fn media_type(io: &mut Io, total: u64) -> Result<&'static str> {
529    let Some(h) = read_header(io, 0, total).await? else {
530        return Ok("video/mp4");
531    };
532    if h.ty != FTYP || h.size < h.header_len as u64 + 4 {
533        return Ok("video/mp4");
534    }
535    let mut brand = [0u8; 4];
536    io.read_at(h.header_len as u64, &mut brand).await?;
537    Ok(match &brand {
538        b"avif" | b"avis" => "image/avif",
539        b"heic" | b"heix" | b"hevc" | b"hevx" => "image/heic",
540        b"mif1" | b"msf1" => "image/heif",
541        b"qt  " => "video/quicktime",
542        b"M4A " => "audio/mp4",
543        b"M4V " | b"M4VH" | b"M4VP" => "video/x-m4v",
544        _ => "video/mp4",
545    })
546}
547
548/// What a top-level box is, from its header and the first bytes of its content.
549struct Classified {
550    kind: SegmentKind,
551    /// Header length including any `uuid` type and C2PA fields.
552    header_len: u32,
553    item: Option<BoxItem>,
554}
555
556/// The item a top-level `uuid` box holds.
557#[derive(Debug, Clone, Copy, PartialEq, Eq)]
558enum BoxItem {
559    /// A C2PA box with this purpose; `merkle` boxes are not JUMBF.
560    C2pa(&'static str),
561    Xmp,
562}
563
564impl BoxItem {
565    fn info(self) -> ItemInfo {
566        match self {
567            BoxItem::C2pa(MERKLE) => {
568                ItemInfo::new(ItemKind::Other, Encoding::Unknown).label(MERKLE)
569            }
570            BoxItem::C2pa(label) => ItemInfo::c2pa().label(label),
571            BoxItem::Xmp => ItemInfo::xmp(),
572        }
573    }
574
575    /// The box item of a source item: one with no HEIF item id, labelled with a C2PA
576    /// purpose or holding XMP.
577    fn of(item: &Item) -> Option<Self> {
578        if item.native_id().is_some() {
579            return None;
580        }
581        match (
582            item.label().and_then(|l| purpose_label(l.as_bytes())),
583            item.kind(),
584        ) {
585            (Some(label), ItemKind::C2pa | ItemKind::Other) => Some(BoxItem::C2pa(label)),
586            (None, ItemKind::Xmp) => Some(BoxItem::Xmp),
587            _ => None,
588        }
589    }
590}
591
592/// The primary item of a HEIF file (`pitm`), kept with its structure.
593#[derive(Debug, Clone, Copy)]
594struct HeifPrimary(u64);
595
596/// The XMP that [`Structure::xmp`] reads; see the module documentation.
597fn xmp_item(s: &Structure) -> Result<Option<&Item>> {
598    let mut boxes = s
599        .items_of(ItemKind::Xmp)
600        .filter(|e| e.native_id().is_none());
601    if let Some(first) = boxes.next() {
602        let extra = boxes.count();
603        if extra > 0 {
604            return Err(Error::Ambiguous {
605                what: ItemKind::Xmp.as_str(),
606                count: extra + 1,
607            });
608        }
609        return Ok(Some(first));
610    }
611    let items: Vec<&Item> = s.items_of(ItemKind::Xmp).collect();
612    if let Some(HeifPrimary(primary)) = container_api::attachment::<HeifPrimary>(s) {
613        let describes = |e: &&Item| {
614            e.relations()
615                .iter()
616                .any(|r| r.kind() == RelationKind::Describes && r.target() == *primary)
617        };
618        if let Some(e) = items.iter().copied().find(describes) {
619            return Ok(Some(e));
620        }
621    }
622    Ok(match items[..] {
623        [one] => Some(one),
624        _ => None,
625    })
626}
627
628fn purpose_label(p: &[u8]) -> Option<&'static str> {
629    match p {
630        b"manifest" => Some(MANIFEST),
631        b"original" => Some(ORIGINAL),
632        b"update" => Some(UPDATE),
633        b"merkle" => Some(MERKLE),
634        _ => None,
635    }
636}
637
638async fn classify(io: &mut Io, at: u64, h: &BoxHeader) -> Result<Classified> {
639    let plain = |kind| Classified {
640        kind,
641        header_len: h.header_len,
642        item: None,
643    };
644    match h.ty {
645        FTYP => return Ok(plain(SegmentKind::Preamble)),
646        MDAT => return Ok(plain(SegmentKind::MediaData)),
647        UUID => {}
648        _ => return Ok(plain(SegmentKind::Other)),
649    }
650
651    let box_end = at + h.size;
652    let body = at + h.header_len as u64;
653    if box_end - body < 16 {
654        return Err(Error::invalid_segment(
655            at,
656            "uuid box too small for its type",
657        ));
658    }
659    let mut u = [0u8; 16];
660    io.read_at(body, &mut u).await?;
661    let after_uuid = body + 16;
662    if u == XMP_UUID {
663        return Ok(Classified {
664            kind: SegmentKind::Metadata,
665            header_len: h.header_len + 16,
666            item: Some(BoxItem::Xmp),
667        });
668    }
669    if u != C2PA_UUID {
670        return Ok(Classified {
671            kind: SegmentKind::Other,
672            header_len: h.header_len + 16,
673            item: None,
674        });
675    }
676
677    // FullBox version and flags, then the NUL-terminated purpose.
678    let purpose_at = after_uuid + 4;
679    if purpose_at >= box_end {
680        return Err(Error::invalid_segment(at, "C2PA box has no purpose"));
681    }
682    let n = (box_end - purpose_at).min(MAX_PURPOSE_LEN as u64 + 1) as usize;
683    let mut buf = [0u8; MAX_PURPOSE_LEN + 1];
684    io.read_at(purpose_at, &mut buf[..n]).await?;
685    let nul = buf[..n].iter().position(|&b| b == 0).ok_or_else(|| {
686        Error::invalid_segment(at, "C2PA box purpose is unterminated or too long")
687    })?;
688    let label = purpose_label(&buf[..nul])
689        .ok_or_else(|| Error::invalid_segment(at, "unknown C2PA box purpose"))?;
690
691    let mut header_len = (purpose_at - at) + nul as u64 + 1;
692    if label != MERKLE {
693        // 8-byte offset of the first merkle box, then the manifest store.
694        header_len += 8;
695        if at + header_len > box_end {
696            return Err(Error::invalid_segment(
697                at,
698                "C2PA box too small for its merkle offset",
699            ));
700        }
701    }
702    Ok(Classified {
703        kind: SegmentKind::Metadata,
704        header_len: u32::try_from(header_len)
705            .map_err(|_| Error::invalid_segment(at, "header too long"))?,
706        item: Some(BoxItem::C2pa(label)),
707    })
708}
709
710#[derive(Default)]
711struct StoreCounts {
712    manifest: u32,
713    original: u32,
714    update: u32,
715}
716
717impl StoreCounts {
718    fn add(&mut self, label: &str) {
719        match label {
720            MANIFEST => self.manifest += 1,
721            ORIGINAL => self.original += 1,
722            UPDATE => self.update += 1,
723            _ => {}
724        }
725    }
726
727    /// C2PA 2.x, A.5 and 11.2: one manifest store, or one original/update pair.
728    fn check(&self) -> Result<()> {
729        let err = |m: &str| Err(Error::InvalidFormat(m.into()));
730        if self.manifest > 1 || self.original > 1 || self.update > 1 {
731            return err("more than one C2PA manifest store box of the same purpose");
732        }
733        if self.original != self.update {
734            return err("C2PA original and update boxes must appear together");
735        }
736        if self.manifest > 0 && self.update > 0 {
737            return err("C2PA manifest box cannot be combined with an update box");
738        }
739        Ok(())
740    }
741}
742
743async fn parse_with(handler: Arc<dyn ContainerHandler>, mut io: Io) -> Result<Structure> {
744    let io = &mut io;
745    let total = io.len();
746    if total < 8 {
747        return Err(Error::InvalidFormat("BMFF too small".into()));
748    }
749    let mut b = StructureBuilder::new(handler, media_type(io, total).await?, total);
750    let mut counts = StoreCounts::default();
751    // Top-level segments in order (for placing item data), and file-level `meta`
752    // boxes (where HEIF items are listed).
753    let mut placed: Vec<(SegmentId, u64, u64)> = Vec::new();
754    let mut metas: Vec<(u64, u64)> = Vec::new();
755
756    let mut at = 0u64;
757    while at < total {
758        let Some(h) = read_header(io, at, total).await? else {
759            // Fewer than 8 bytes cannot be a box: keep them as unnamed trailing data.
760            b.push_tail()?;
761            break;
762        };
763        let c = classify(io, at, &h).await?;
764        let id = b.push_span(
765            c.kind,
766            Name::FourCC(h.ty),
767            c.header_len,
768            h.size - c.header_len as u64,
769            0,
770        )?;
771        placed.push((id, at, h.size));
772        if h.ty == META {
773            let content = at + c.header_len as u64;
774            let end = at + h.size;
775            let body = if meta_lacks_full_box_header(io, content, end).await {
776                content
777            } else {
778                content + 4
779            };
780            if body <= end {
781                metas.push((body, end));
782            }
783        }
784        if let Some(item) = c.item {
785            if let BoxItem::C2pa(label) = item {
786                counts.add(label);
787            }
788            b.item_of_segments(item.info(), &[id])?;
789        }
790        at += h.size;
791    }
792    counts.check()?;
793    let mut primary = None;
794    for (body, end) in metas {
795        // Items are optional metadata: a `meta` box that cannot be read as HEIF
796        // items does not make the file unreadable.
797        let Ok(items) = read_items(io, body, end).await else {
798            continue;
799        };
800        primary = primary.or(items.primary);
801        for f in &items.found {
802            add_item(&mut b, io, &placed, f).await?;
803        }
804    }
805    if let Some(p) = primary {
806        b.attach(HeifPrimary(p.into()));
807    }
808    b.finish()
809}
810
811/// Largest `meta` box read to look for items.
812const MAX_META_BOX: u64 = 16 << 20;
813
814async fn read_items(io: &mut Io, body: u64, end: u64) -> Result<heif_items::Items> {
815    let len = end - body;
816    if len > MAX_META_BOX {
817        return Err(Error::LimitExceeded {
818            what: "meta box",
819            limit: MAX_META_BOX,
820        });
821    }
822    let buf = io.read_vec(body, len as usize).await?;
823    heif_items::find(&buf, body)
824}
825
826/// The pieces of `[offset, offset + len)` in each top-level segment it crosses,
827/// or `None` if it leaves the file or crosses too many.
828fn split_over_segments(
829    placed: &[(SegmentId, u64, u64)],
830    mut offset: u64,
831    mut len: u64,
832) -> Result<Option<Vec<(SegmentId, ByteRange)>>> {
833    const MAX_PARTS: usize = 4096;
834    let mut parts = Vec::new();
835    while len > 0 {
836        let i = placed.partition_point(|p| p.1 <= offset);
837        let Some(&(id, start, size)) = i.checked_sub(1).and_then(|i| placed.get(i)) else {
838            return Ok(None);
839        };
840        if offset >= start + size || parts.len() >= MAX_PARTS {
841            return Ok(None);
842        }
843        let take = len.min(start + size - offset);
844        parts.push((id, ByteRange::new(offset, take)?));
845        offset += take;
846        len -= take;
847    }
848    Ok(Some(parts))
849}
850
851/// Add one HEIF item. An item that cannot be located in the file is skipped.
852async fn add_item(
853    b: &mut StructureBuilder,
854    io: &mut Io,
855    placed: &[(SegmentId, u64, u64)],
856    f: &heif_items::Found,
857) -> Result<()> {
858    let mut extents = f.extents.clone();
859    if f.kind == heif_items::Kind::Exif {
860        // The item starts with the offset of the TIFF header from the end of that
861        // field; the item is the TIFF data.
862        let (at, len) = extents[0];
863        let mut h = [0u8; 4];
864        if len < 4 || io.read_at(at, &mut h).await.is_err() {
865            return Ok(());
866        }
867        let skip = 4u64.saturating_add(u32::from_be_bytes(h) as u64);
868        extents = heif_items::skip_bytes(&extents, skip);
869    }
870    let mut parts = Vec::new();
871    for (at, len) in extents {
872        match split_over_segments(placed, at, len)? {
873            Some(p) => parts.extend(p),
874            None => return Ok(()),
875        }
876    }
877    if parts.is_empty() {
878        return Ok(());
879    }
880    let mut info = match f.kind {
881        heif_items::Kind::Exif => ItemInfo::exif(),
882        heif_items::Kind::Xmp => ItemInfo::xmp(),
883        heif_items::Kind::Asset => ItemInfo::new(ItemKind::EmbeddedAsset, Encoding::Asset),
884        heif_items::Kind::Opaque => ItemInfo::new(ItemKind::Other, Encoding::Unknown),
885    }
886    .native_type(Name::FourCC(f.item_type))
887    .native_id(f.item_id.into())
888    .transfer(f.transfer.clone());
889    if let Some(m) = &f.media_type {
890        info = info.media_type(m.clone());
891    }
892    if let Some(u) = &f.uri {
893        info = info.uri(u.clone());
894    }
895    for &(ty, to) in &f.refs {
896        info = info.relation(Relation::new(ty, to.into()));
897    }
898    b.item(info, &parts)
899}
900
901// ---------------------------------------------------------------------------
902// Writing
903// ---------------------------------------------------------------------------
904
905/// Most offset-bearing boxes collected from one top-level box.
906const MAX_PATCHES: usize = 1 << 20;
907/// Largest box (`iloc`) read into memory to rewrite.
908const MAX_IN_MEMORY_BOX: u64 = 16 << 20;
909
910/// A run of source bytes that is rewritten while copying.
911#[derive(Debug)]
912enum Patch {
913    /// `count` fixed-size entries, each with one absolute offset.
914    Table {
915        start: u64,
916        count: u64,
917        stride: u32,
918        field_off: u32,
919        width: u8,
920    },
921    /// Replacement bytes of the same length.
922    Bytes { at: u64, data: Vec<u8> },
923}
924
925impl Patch {
926    fn start(&self) -> u64 {
927        match self {
928            Patch::Table { start, .. } => *start,
929            Patch::Bytes { at, .. } => *at,
930        }
931    }
932
933    fn len(&self) -> u64 {
934        match self {
935            // Bounded when the patch is built.
936            Patch::Table { count, stride, .. } => count * *stride as u64,
937            Patch::Bytes { data, .. } => data.len() as u64,
938        }
939    }
940}
941
942/// Boxes of these types can contain offset-bearing boxes.
943fn may_hold_offsets(name: Name) -> bool {
944    matches!(name, Name::FourCC(t) if t == *b"moov" || t == *b"moof" || t == *b"mfra" || t == *b"meta")
945}
946
947#[derive(Debug, Clone, Copy)]
948enum Table {
949    Stco,
950    Co64,
951    Saio,
952    Iloc,
953    Tfhd,
954    Tfra,
955}
956
957#[derive(Debug, Clone, Copy)]
958struct Candidate {
959    table: Table,
960    end: u64,
961    /// First byte after the FullBox version and flags.
962    content: u64,
963    version: u8,
964    flags: u32,
965}
966
967async fn read_u32_at(io: &mut Io, at: u64) -> Result<u32> {
968    let mut b = [0u8; 4];
969    io.read_at(at, &mut b).await?;
970    Ok(u32::from_be_bytes(b))
971}
972
973/// Find the offset-bearing boxes inside one top-level box by reading box headers,
974/// then read just their table headers.
975async fn collect_patches(io: &mut Io, seg: &Segment, map: &OffsetMap) -> Result<Vec<Patch>> {
976    let mut cands: Vec<Candidate> = Vec::new();
977    let ext = seg.range();
978    walk(io, ext.offset(), ext.end(), &mut |n: &Node<'_>| {
979        let table = match n.path {
980            "/moov/trak/mdia/minf/stbl/stco" => Table::Stco,
981            "/moov/trak/mdia/minf/stbl/co64" => Table::Co64,
982            "/moov/trak/mdia/minf/stbl/saio" => Table::Saio,
983            "/meta/iloc" => Table::Iloc,
984            "/moof/traf/tfhd" => Table::Tfhd,
985            "/mfra/tfra" => Table::Tfra,
986            _ => return Ok(()),
987        };
988        if cands.len() >= MAX_PATCHES {
989            return Err(Error::LimitExceeded {
990                what: "offset tables in one box",
991                limit: MAX_PATCHES as u64,
992            });
993        }
994        let (Some(version), Some(flags)) = (n.version, n.flags) else {
995            return Err(Error::invalid_segment(
996                n.range.offset(),
997                "offset table is not a FullBox",
998            ));
999        };
1000        cands.push(Candidate {
1001            table,
1002            end: n.range.end(),
1003            content: n.range.offset() + n.header_len as u64 + 4,
1004            version,
1005            flags,
1006        });
1007        Ok(())
1008    })
1009    .await?;
1010
1011    let mut patches = Vec::with_capacity(cands.len());
1012    for c in cands {
1013        if let Some(p) = build_patch(io, &c, map).await? {
1014            patches.push(p);
1015        }
1016    }
1017    patches.sort_by_key(Patch::start);
1018    for w in patches.windows(2) {
1019        if w[0].start().saturating_add(w[0].len()) > w[1].start() {
1020            return Err(Error::invalid_segment(
1021                w[1].start(),
1022                "overlapping offset tables",
1023            ));
1024        }
1025    }
1026    Ok(patches)
1027}
1028
1029/// A table of `count` entries of `stride` bytes at `start` must fit before `end`.
1030fn table(
1031    start: u64,
1032    count: u64,
1033    stride: u32,
1034    field_off: u32,
1035    width: u8,
1036    end: u64,
1037) -> Result<Option<Patch>> {
1038    let len = count
1039        .checked_mul(stride as u64)
1040        .and_then(|l| start.checked_add(l))
1041        .filter(|&e| e <= end)
1042        .ok_or_else(|| Error::invalid_segment(start, "offset table extends past its box"))?;
1043    debug_assert!(len >= start);
1044    Ok(Some(Patch::Table {
1045        start,
1046        count,
1047        stride,
1048        field_off,
1049        width,
1050    }))
1051}
1052
1053async fn build_patch(io: &mut Io, c: &Candidate, map: &OffsetMap) -> Result<Option<Patch>> {
1054    let room = |need: u64| -> Result<()> {
1055        if c.end.saturating_sub(c.content) < need {
1056            return Err(Error::invalid_segment(
1057                c.content,
1058                "offset table box is truncated",
1059            ));
1060        }
1061        Ok(())
1062    };
1063    match c.table {
1064        Table::Stco | Table::Co64 => {
1065            room(4)?;
1066            let w: u8 = if matches!(c.table, Table::Stco) { 4 } else { 8 };
1067            let count = read_u32_at(io, c.content).await? as u64;
1068            table(c.content + 4, count, w as u32, 0, w, c.end)
1069        }
1070        Table::Saio => {
1071            let skip = if c.flags & 1 == 1 { 8 } else { 0 };
1072            room(skip + 4)?;
1073            let count = read_u32_at(io, c.content + skip).await? as u64;
1074            let w: u8 = if c.version == 0 { 4 } else { 8 };
1075            table(c.content + skip + 4, count, w as u32, 0, w, c.end)
1076        }
1077        Table::Tfhd => {
1078            if c.flags & 1 == 0 {
1079                return Ok(None); // no base data offset
1080            }
1081            room(12)?; // track id, base data offset
1082            table(c.content + 4, 1, 8, 0, 8, c.end)
1083        }
1084        Table::Tfra => {
1085            room(12)?;
1086            let info = read_u32_at(io, c.content + 4).await?;
1087            let count = read_u32_at(io, c.content + 8).await? as u64;
1088            let w: u32 = if c.version == 1 { 8 } else { 4 };
1089            let sizes = ((info >> 4) & 3) + ((info >> 2) & 3) + (info & 3) + 3;
1090            table(c.content + 12, count, 2 * w + sizes, w, w as u8, c.end)
1091        }
1092        Table::Iloc => {
1093            let len = c.end.saturating_sub(c.content);
1094            if len > MAX_IN_MEMORY_BOX {
1095                return Err(Error::LimitExceeded {
1096                    what: "iloc box size",
1097                    limit: MAX_IN_MEMORY_BOX,
1098                });
1099            }
1100            let mut data = io.read_vec(c.content, len as usize).await?;
1101            adjust_iloc(&mut data, c.version, map)?;
1102            Ok(Some(Patch::Bytes {
1103                at: c.content,
1104                data,
1105            }))
1106        }
1107    }
1108}
1109
1110fn put_uint(dst: &mut [u8], v: u64) -> Result<()> {
1111    let range = || Error::InvalidFormat("offset adjustment does not fit its field".into());
1112    match dst.len() {
1113        4 => dst.copy_from_slice(&u32::try_from(v).map_err(|_| range())?.to_be_bytes()),
1114        8 => dst.copy_from_slice(&v.to_be_bytes()),
1115        _ => return Err(range()),
1116    }
1117    Ok(())
1118}
1119
1120fn get_uint(src: &[u8]) -> u64 {
1121    src.iter().fold(0u64, |a, &b| (a << 8) | b as u64)
1122}
1123
1124/// Rewrite file offsets in an `iloc` body (after version and flags), in place.
1125/// With a base offset, the base moves and the extents stay relative to it;
1126/// without one, the extent offsets are absolute and move. Items that are not
1127/// file-offset constructed are left alone.
1128fn adjust_iloc(b: &mut [u8], version: u8, map: &OffsetMap) -> Result<()> {
1129    if version > 2 {
1130        return Err(Error::InvalidFormat("unknown iloc version".into()));
1131    }
1132    // `next(n, b)` advances over `n` bytes and returns where they start.
1133    let mut pos = 0usize;
1134    let mut next = |n: usize, b: &[u8]| -> Result<usize> {
1135        let s = pos;
1136        pos = s
1137            .checked_add(n)
1138            .filter(|&e| e <= b.len())
1139            .ok_or_else(|| Error::invalid_segment(0, "iloc box is truncated"))?;
1140        Ok(s)
1141    };
1142
1143    let s = next(2, b)?;
1144    let (a, b1) = (b[s], b[s + 1]);
1145    let offset_size = (a >> 4) as usize;
1146    let length_size = (a & 15) as usize;
1147    let base_size = (b1 >> 4) as usize;
1148    let index_size = if version >= 1 { (b1 & 15) as usize } else { 0 };
1149    for sz in [offset_size, length_size, base_size, index_size] {
1150        if !matches!(sz, 0 | 4 | 8) {
1151            return Err(Error::InvalidFormat("unsupported iloc field size".into()));
1152        }
1153    }
1154    let item_count = if version < 2 {
1155        let s = next(2, b)?;
1156        get_uint(&b[s..s + 2])
1157    } else {
1158        let s = next(4, b)?;
1159        get_uint(&b[s..s + 4])
1160    };
1161    for _ in 0..item_count {
1162        next(if version < 2 { 2 } else { 4 }, b)?; // item id
1163        let construction = if version >= 1 {
1164            let s = next(2, b)?;
1165            b[s + 1] & 0x0f
1166        } else {
1167            0
1168        };
1169        next(2, b)?; // data reference index
1170        let base_at = next(base_size, b)?;
1171        let base = get_uint(&b[base_at..base_at + base_size]);
1172        let s = next(2, b)?;
1173        let extent_count = get_uint(&b[s..s + 2]);
1174        if construction == 0 && base_size > 0 && base != 0 {
1175            let v = map.apply(base)?;
1176            put_uint(&mut b[base_at..base_at + base_size], v)?;
1177        }
1178        for _ in 0..extent_count {
1179            next(index_size, b)?;
1180            let at = next(offset_size, b)?;
1181            if construction == 0 && (base_size == 0 || base == 0) && offset_size > 0 {
1182                let v = get_uint(&b[at..at + offset_size]);
1183                if v != 0 {
1184                    let v = map.apply(v)?;
1185                    put_uint(&mut b[at..at + offset_size], v)?;
1186                }
1187            }
1188            next(length_size, b)?;
1189        }
1190    }
1191    Ok(())
1192}
1193
1194/// Size and type, then `prefix`, for a box whose payload is `payload_len` bytes.
1195fn box_header(ty: &[u8; 4], prefix: &[u8], payload_len: u64) -> Result<Vec<u8>> {
1196    let too_big = || Error::LimitExceeded {
1197        what: "box size",
1198        limit: u64::MAX,
1199    };
1200    let inner = (prefix.len() as u64)
1201        .checked_add(payload_len)
1202        .ok_or_else(too_big)?;
1203    let mut h = Vec::with_capacity(16 + prefix.len());
1204    match u32::try_from(inner.checked_add(8).ok_or_else(too_big)?) {
1205        Ok(size) => {
1206            h.extend_from_slice(&size.to_be_bytes());
1207            h.extend_from_slice(ty);
1208        }
1209        Err(_) => {
1210            let size = inner.checked_add(16).ok_or_else(too_big)?;
1211            h.extend_from_slice(&1u32.to_be_bytes());
1212            h.extend_from_slice(ty);
1213            h.extend_from_slice(&size.to_be_bytes());
1214        }
1215    }
1216    h.extend_from_slice(prefix);
1217    Ok(h)
1218}
1219
1220/// Header of a C2PA box up to the manifest store: the merkle offset is written
1221/// as 0, as merkle boxes are not produced.
1222fn c2pa_box_header(purpose: &str, payload_len: u64) -> Result<Vec<u8>> {
1223    let mut prefix = C2PA_UUID.to_vec();
1224    prefix.extend_from_slice(&[0u8; 4]); // version and flags
1225    prefix.extend_from_slice(purpose.as_bytes());
1226    prefix.push(0);
1227    prefix.extend_from_slice(&[0u8; 8]); // offset of the first merkle box
1228    box_header(&UUID, &prefix, payload_len)
1229}
1230
1231fn xmp_box_header(payload_len: u64) -> Result<Vec<u8>> {
1232    box_header(&UUID, &XMP_UUID, payload_len)
1233}
1234
1235enum Op<'a> {
1236    /// Copy a source segment unchanged.
1237    Copy(SegmentId),
1238    /// Copy a source segment, rewriting the offsets inside it.
1239    Scan(SegmentId),
1240    /// Copy a C2PA box with its purpose changed to another of the same length.
1241    Relabel {
1242        id: SegmentId,
1243        from: &'static str,
1244        to: &'static str,
1245    },
1246    /// Emit a new box holding `item`.
1247    New {
1248        item: BoxItem,
1249        header: Vec<u8>,
1250        payload: Cow<'a, [u8]>,
1251    },
1252}
1253
1254/// Record that the region ending at `old_end` changed from `old_len` to `new_len`
1255/// bytes. Regions at the end of the file move nothing.
1256fn note(map: &mut OffsetMap, total: u64, old_end: u64, new_len: u64, old_len: u64) -> Result<()> {
1257    if old_end >= total {
1258        return Ok(());
1259    }
1260    let delta = i64::try_from(new_len as i128 - old_len as i128)
1261        .map_err(|_| Error::InvalidFormat("box size change out of range".into()))?;
1262    map.add(old_end, delta);
1263    Ok(())
1264}
1265
1266fn new_c2pa(d: &[u8]) -> Result<Op<'_>> {
1267    new_store_box(MANIFEST, Cow::Borrowed(d))
1268}
1269
1270fn new_store_box<'a>(purpose: &'static str, d: Cow<'a, [u8]>) -> Result<Op<'a>> {
1271    Ok(Op::New {
1272        item: BoxItem::C2pa(purpose),
1273        header: c2pa_box_header(purpose, d.len() as u64)?,
1274        payload: d,
1275    })
1276}
1277
1278/// A merkle box: C2PA type, version and flags, the purpose, then the payload
1279/// (no merkle offset field, unlike the store boxes).
1280fn new_merkle(d: &[u8]) -> Result<Op<'_>> {
1281    let mut prefix = C2PA_UUID.to_vec();
1282    prefix.extend_from_slice(&[0u8; 4]);
1283    prefix.extend_from_slice(MERKLE.as_bytes());
1284    prefix.push(0);
1285    Ok(Op::New {
1286        item: BoxItem::C2pa(MERKLE),
1287        header: box_header(&UUID, &prefix, d.len() as u64)?,
1288        payload: Cow::Borrowed(d),
1289    })
1290}
1291
1292fn new_xmp(d: &[u8]) -> Result<Op<'_>> {
1293    Ok(Op::New {
1294        item: BoxItem::Xmp,
1295        header: xmp_box_header(d.len() as u64)?,
1296        payload: Cow::Borrowed(d),
1297    })
1298}
1299
1300/// The bytes of `item`, its extents joined, read through `io`.
1301async fn read_item(src: &Structure, io: &mut Io, item: &Item) -> Result<Vec<u8>> {
1302    let mut out = Vec::new();
1303    for part in item.extents() {
1304        let r = part.range();
1305        if r.end() > src.total_size() {
1306            return Err(Error::invalid_segment(
1307                r.offset(),
1308                "range outside the asset",
1309            ));
1310        }
1311        if (out.len() as u64).saturating_add(r.len()) > MAX_SEGMENT_SIZE {
1312            return Err(Error::LimitExceeded {
1313                what: "read size",
1314                limit: MAX_SEGMENT_SIZE,
1315            });
1316        }
1317        out.extend(io.read_vec(r.offset(), r.len() as usize).await?);
1318    }
1319    Ok(out)
1320}
1321
1322fn op_len(op: &Op<'_>, src: &Structure) -> Result<u64> {
1323    Ok(match op {
1324        Op::Copy(id) | Op::Scan(id) | Op::Relabel { id, .. } => src.segment(*id)?.range().len(),
1325        Op::New {
1326            header, payload, ..
1327        } => header.len() as u64 + payload.len() as u64,
1328    })
1329}
1330
1331/// Decide what the output contains: the single source of truth for both the
1332/// destination structure and the bytes written.
1333async fn plan<'a>(
1334    src: &Structure,
1335    io: &mut Io,
1336    updates: &'a Updates,
1337) -> Result<(Vec<Op<'a>>, Vec<Option<BoxItem>>, OffsetMap)> {
1338    let segs = src.segments();
1339    // The item each top-level `uuid` box holds, from the items.
1340    let mut boxes: Vec<Option<BoxItem>> = vec![None; segs.len()];
1341    for e in src.items() {
1342        if let (Some(item), Some(p)) = (BoxItem::of(e), e.extents().next()) {
1343            boxes[p.segment().index()] = Some(item);
1344        }
1345    }
1346    let labels: Vec<Option<&'static str>> = boxes
1347        .iter()
1348        .map(|b| match b {
1349            Some(BoxItem::C2pa(l)) => Some(*l),
1350            _ => None,
1351        })
1352        .collect();
1353    let has_store = labels
1354        .iter()
1355        .any(|l| matches!(l, Some(MANIFEST) | Some(ORIGINAL)));
1356    let has_xmp = boxes.contains(&Some(BoxItem::Xmp));
1357
1358    // An update manifest: the new store begins with the store already in the file,
1359    // so that store is left as it is (as the original) and only what follows it is
1360    // written, as the update. Anything else is written as a whole.
1361    let frozen = src
1362        .items_labelled(ItemKind::C2pa, MANIFEST)
1363        .next()
1364        .or_else(|| src.items_labelled(ItemKind::C2pa, ORIGINAL).next());
1365    let mut addition: Option<Vec<u8>> = match (updates.c2pa(), updates.is_c2pa_update(), frozen) {
1366        (MetadataUpdate::Set(full), true, Some(e)) => {
1367            let existing = read_item(src, io, e).await?;
1368            crate::jumbf::addition_to(&existing, full)?
1369        }
1370        _ => None,
1371    };
1372    let update_mode = addition.is_some();
1373
1374    let merkle_kept = matches!(updates.merkle(), MerkleUpdate::Keep);
1375    if update_mode && !merkle_kept {
1376        return Err(Error::InvalidFormat(
1377            "an update manifest cannot change merkle boxes".into(),
1378        ));
1379    }
1380    if matches!(updates.c2pa(), MetadataUpdate::Set(_))
1381        && !update_mode
1382        && merkle_kept
1383        && labels.contains(&Some(MERKLE))
1384    {
1385        return Err(Error::InvalidFormat(
1386            "a file with merkle boxes needs them set or removed to take a new manifest".into(),
1387        ));
1388    }
1389    // Merkle boxes go right after the last mdat, or in a fragmented file right
1390    // before each moof.
1391    let last_mdat = segs.iter().rposition(|s| s.name() == Name::FourCC(MDAT));
1392    let moofs: Vec<usize> = segs
1393        .iter()
1394        .enumerate()
1395        .filter(|(_, s)| s.name() == Name::FourCC(MOOF))
1396        .map(|(i, _)| i)
1397        .collect();
1398    let fragmented = !moofs.is_empty();
1399    if let MerkleUpdate::Set(boxes) = updates.merkle() {
1400        if fragmented {
1401            if boxes.len() != moofs.len() {
1402                return Err(Error::InvalidFormat(format!(
1403                    "{} merkle boxes for {} moof boxes: one goes before each",
1404                    boxes.len(),
1405                    moofs.len()
1406                )));
1407            }
1408        } else if last_mdat.is_none() {
1409            return Err(Error::InvalidFormat(
1410                "BMFF has no mdat box to place merkle boxes after".into(),
1411            ));
1412        }
1413    }
1414
1415    let total = src.total_size();
1416    let mut map = OffsetMap::default();
1417    let mut ops: Vec<Op<'a>> = Vec::with_capacity(segs.len() + 2);
1418    let mut store = MetadataSlot::new(updates.c2pa());
1419    let mut xmp = MetadataSlot::new(updates.xmp());
1420    let mut ftyp_seen = false;
1421
1422    for (i, seg) in segs.iter().enumerate() {
1423        let id = SegmentId::from_index(i)?;
1424        let (old_len, end) = (seg.range().len(), seg.range().end());
1425        // A fragmented file's merkle box goes in front of its moof.
1426        if let (true, MerkleUpdate::Set(boxes)) = (fragmented, updates.merkle()) {
1427            if let Some(n) = moofs.iter().position(|&moof| moof == i) {
1428                let op = new_merkle(&boxes[n])?;
1429                note(&mut map, total, seg.range().offset(), op_len(&op, src)?, 0)?;
1430                ops.push(op);
1431            }
1432        }
1433        match labels[i] {
1434            Some(MERKLE) => match updates.merkle() {
1435                MerkleUpdate::Keep => ops.push(Op::Copy(id)),
1436                _ => note(&mut map, total, end, 0, old_len)?,
1437            },
1438            // The first update: the store becomes the original, unchanged but for
1439            // its purpose, and the update is added after everything.
1440            Some(MANIFEST) if update_mode => ops.push(Op::Relabel {
1441                id,
1442                from: MANIFEST,
1443                to: ORIGINAL,
1444            }),
1445            Some(ORIGINAL) if update_mode => ops.push(Op::Copy(id)),
1446            // Later updates replace the update store: it holds all of them.
1447            Some(UPDATE) if update_mode => {
1448                let add = addition.take().ok_or(Error::NotFound {
1449                    what: "update store",
1450                })?;
1451                let op = new_store_box(UPDATE, Cow::Owned(add))?;
1452                note(&mut map, total, end, op_len(&op, src)?, old_len)?;
1453                ops.push(op);
1454            }
1455            Some(MANIFEST) | Some(ORIGINAL) => match store.existing() {
1456                Existing::Keep => ops.push(Op::Copy(id)),
1457                Existing::Replace(d) => {
1458                    let op = new_c2pa(d)?;
1459                    note(&mut map, total, end, op_len(&op, src)?, old_len)?;
1460                    ops.push(op);
1461                }
1462                _ => note(&mut map, total, end, 0, old_len)?,
1463            },
1464            // An update box does not survive a new manifest.
1465            Some(UPDATE) => match updates.c2pa() {
1466                MetadataUpdate::Keep => ops.push(Op::Copy(id)),
1467                _ => note(&mut map, total, end, 0, old_len)?,
1468            },
1469            _ if boxes[i] == Some(BoxItem::Xmp) => match xmp.existing() {
1470                Existing::Keep => ops.push(Op::Copy(id)),
1471                Existing::Replace(d) => {
1472                    let op = new_xmp(d)?;
1473                    note(&mut map, total, end, op_len(&op, src)?, old_len)?;
1474                    ops.push(op);
1475                }
1476                _ => note(&mut map, total, end, 0, old_len)?,
1477            },
1478            _ => {
1479                ops.push(Op::Copy(id));
1480                if !ftyp_seen && seg.name() == Name::FourCC(FTYP) {
1481                    ftyp_seen = true;
1482                    if !has_store {
1483                        if let Some(d) = store.pending() {
1484                            let op = new_c2pa(d)?;
1485                            note(&mut map, total, end, op_len(&op, src)?, 0)?;
1486                            ops.push(op);
1487                        }
1488                    }
1489                    if !has_xmp {
1490                        if let Some(d) = xmp.pending() {
1491                            let op = new_xmp(d)?;
1492                            note(&mut map, total, end, op_len(&op, src)?, 0)?;
1493                            ops.push(op);
1494                        }
1495                    }
1496                }
1497            }
1498        }
1499        if let (false, Some(i2), MerkleUpdate::Set(boxes)) =
1500            (fragmented, last_mdat, updates.merkle())
1501        {
1502            if i2 == i {
1503                let mut added = 0u64;
1504                for d in boxes {
1505                    let op = new_merkle(d)?;
1506                    added = added
1507                        .checked_add(op_len(&op, src)?)
1508                        .ok_or(Error::LimitExceeded {
1509                            what: "output size",
1510                            limit: u64::MAX,
1511                        })?;
1512                    ops.push(op);
1513                }
1514                note(&mut map, total, end, added, 0)?;
1515            }
1516        }
1517    }
1518    if let Some(add) = addition.take() {
1519        // No update store existed: add one after everything else, so nothing that
1520        // exists moves.
1521        ops.push(new_store_box(UPDATE, Cow::Owned(add))?);
1522    }
1523    if (!update_mode && store.is_pending()) || xmp.is_pending() {
1524        return Err(Error::InvalidFormat(
1525            "BMFF has no ftyp box to insert metadata after".into(),
1526        ));
1527    }
1528
1529    // Now that every edit is known, mark the boxes whose offsets must move.
1530    if !map.is_identity() {
1531        for op in ops.iter_mut() {
1532            if let Op::Copy(id) = *op {
1533                if may_hold_offsets(src.segment(id)?.name()) {
1534                    *op = Op::Scan(id);
1535                }
1536            }
1537        }
1538    }
1539
1540    Ok((ops, boxes, map))
1541}
1542
1543/// A box whose size field is 0 runs to the end of the file, so only the last box of
1544/// the source can be one. If the write puts anything after it, it needs a size of
1545/// its own, or it would swallow what follows. Returns that box and its size.
1546async fn open_ended_box(
1547    src: &Structure,
1548    io: &mut Io,
1549    ops: &[Op<'_>],
1550) -> Result<Option<(SegmentId, u32)>> {
1551    let Some(last) = src.segments().len().checked_sub(1) else {
1552        return Ok(None);
1553    };
1554    let at = ops.iter().position(|op| {
1555        matches!(op, Op::Copy(id) | Op::Scan(id) | Op::Relabel { id, .. } if id.index() == last)
1556    });
1557    if !at.is_some_and(|at| at + 1 < ops.len()) {
1558        return Ok(None);
1559    }
1560    let id = SegmentId::from_index(last)?;
1561    let seg = src.segment(id)?;
1562    let mut size = [0u8; 4];
1563    io.read_at(seg.header().offset(), &mut size).await?;
1564    if size != [0; 4] {
1565        return Ok(None);
1566    }
1567    let size = u32::try_from(seg.range().len()).map_err(|_| Error::LimitExceeded {
1568        what: "size of a box that no longer runs to the end of the file",
1569        limit: u32::MAX as u64,
1570    })?;
1571    Ok(Some((id, size)))
1572}
1573
1574/// The header of `seg` with `size` as its size field.
1575fn put_size(b: &mut PlanBuilder<'_, '_>, id: SegmentId, seg: &Segment, size: u32) -> Result<()> {
1576    let header = seg.header();
1577    b.put(id, Role::Header, size.to_be_bytes().to_vec());
1578    b.copy(id, Role::Header, header.sub(4, header.len() - 4)?);
1579    Ok(())
1580}
1581
1582/// The plan that writes `ops`: the output structure and, unless `with_steps` is
1583/// false, the steps. Reads the source for what the steps need to know: the offset
1584/// tables to rewrite and the header of a relabelled box.
1585async fn assemble<'a>(
1586    src: &Structure,
1587    io: &mut Io,
1588    ops: Vec<Op<'a>>,
1589    boxes: &[Option<BoxItem>],
1590    map: OffsetMap,
1591    with_steps: bool,
1592) -> Result<WritePlan<'a>> {
1593    let map = Arc::new(map);
1594    let mut b = PlanBuilder::new(src);
1595    if let Some(primary) = container_api::attachment::<HeifPrimary>(src) {
1596        b.attach(*primary);
1597    }
1598    let open_ended = if with_steps {
1599        open_ended_box(src, io, &ops).await?
1600    } else {
1601        None
1602    };
1603    for op in ops {
1604        let (id, item) = match op {
1605            Op::Copy(sid) => {
1606                let s = src.segment(sid)?;
1607                let id = match open_ended.filter(|(open, _)| *open == sid) {
1608                    Some((_, size)) => {
1609                        let id = b.shape_like(sid)?;
1610                        put_size(&mut b, id, s, size)?;
1611                        b.copy(id, Role::Payload, s.payload());
1612                        id
1613                    }
1614                    None => b.copy_segment(sid)?,
1615                };
1616                (id, boxes[sid.index()])
1617            }
1618            Op::Scan(sid) => {
1619                let seg = src.segment(sid)?;
1620                let id = b.shape_like(sid)?;
1621                if with_steps {
1622                    let mut patches = collect_patches(io, seg, &map).await?;
1623                    for (role, range) in seg.regions() {
1624                        match open_ended.filter(|(open, _)| *open == sid) {
1625                            Some((_, size)) if role == Role::Header => {
1626                                put_size(&mut b, id, seg, size)?
1627                            }
1628                            _ => patched_steps(&mut b, id, role, range, &mut patches, &map)?,
1629                        }
1630                    }
1631                }
1632                (id, boxes[sid.index()])
1633            }
1634            Op::Relabel { id: sid, from, to } => {
1635                let seg = src.segment(sid)?;
1636                let id = b.shape_like(sid)?;
1637                if with_steps {
1638                    let header = seg.header();
1639                    // [size, type] [uuid 16] [version, flags 4] [purpose NUL] [merkle offset 8]
1640                    let fixed = 16 + 4 + from.len() + 1 + 8;
1641                    let prefix = (header.len() as usize)
1642                        .checked_sub(fixed)
1643                        .filter(|p| *p == 8 || *p == 16)
1644                        .ok_or_else(|| {
1645                            Error::invalid_segment(header.offset(), "unexpected C2PA box header")
1646                        })?;
1647                    let mut h = vec![0u8; header.len() as usize];
1648                    io.read_at(header.offset(), &mut h).await?;
1649                    let at = prefix + 16 + 4;
1650                    if &h[at..at + from.len()] != from.as_bytes() || h[at + from.len()] != 0 {
1651                        return Err(Error::invalid_segment(
1652                            header.offset(),
1653                            "C2PA box purpose is not what was parsed",
1654                        ));
1655                    }
1656                    h[at..at + to.len()].copy_from_slice(to.as_bytes());
1657                    if let Some((_, size)) = open_ended.filter(|(open, _)| *open == sid) {
1658                        h[..4].copy_from_slice(&size.to_be_bytes());
1659                    }
1660                    b.put(id, Role::Header, h);
1661                    b.copy(id, Role::Payload, seg.payload());
1662                }
1663                (id, Some(BoxItem::C2pa(to)))
1664            }
1665            Op::New {
1666                item,
1667                header,
1668                payload,
1669            } => (
1670                b.put_segment(
1671                    SegmentKind::Metadata,
1672                    Name::FourCC(UUID),
1673                    header,
1674                    payload,
1675                    &[][..],
1676                )?,
1677                Some(item),
1678            ),
1679        };
1680        if let Some(item) = item {
1681            b.item(item.info(), &[id])?;
1682        }
1683    }
1684    // HEIF items are bytes inside boxes that are copied as they are, so they
1685    // follow the boxes to wherever those land.
1686    b.carry_items(|e| e.native_id().is_some());
1687    b.finish()
1688}
1689
1690/// Append the steps that copy `range`, rewriting the patches inside it. `patches`
1691/// are sorted and disjoint; those outside `range` are skipped.
1692fn patched_steps(
1693    plan: &mut PlanBuilder<'_, '_>,
1694    dest: SegmentId,
1695    role: Role,
1696    range: ByteRange,
1697    patches: &mut [Patch],
1698    map: &Arc<OffsetMap>,
1699) -> Result<()> {
1700    let mut cur = range.offset();
1701    for p in patches {
1702        let (start, len) = (p.start(), p.len());
1703        if start < range.offset() || start.saturating_add(len) > range.end() {
1704            continue;
1705        }
1706        plan.copy(dest, role, ByteRange::new(cur, start - cur)?);
1707        match p {
1708            Patch::Bytes { data, .. } => {
1709                plan.put(dest, role, std::mem::take(data));
1710            }
1711            Patch::Table {
1712                stride,
1713                field_off,
1714                width,
1715                ..
1716            } => {
1717                let rule = Relocate::new(map.clone(), *stride, *field_off, *width)
1718                    .map_err(|_| Error::invalid_segment(start, "invalid offset table geometry"))?;
1719                plan.relocate(dest, role, ByteRange::new(start, len)?, rule);
1720            }
1721        }
1722        cur = start + len;
1723    }
1724    plan.copy(dest, role, ByteRange::new(cur, range.end() - cur)?);
1725    Ok(())
1726}
1727
1728#[cfg(test)]
1729mod tests {
1730    use std::io::Cursor;
1731
1732    use super::*;
1733    use crate::{testing::c2pa_store, TransferEncoding};
1734
1735    fn boxed(ty: &[u8; 4], body: &[u8]) -> Vec<u8> {
1736        let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
1737        v.extend_from_slice(ty);
1738        v.extend_from_slice(body);
1739        v
1740    }
1741
1742    fn c2pa_box(purpose: &str, tail: &[u8]) -> Vec<u8> {
1743        let mut body = C2PA_UUID.to_vec();
1744        body.extend_from_slice(&[0, 0, 0, 0]);
1745        body.extend_from_slice(purpose.as_bytes());
1746        body.push(0);
1747        if purpose != MERKLE {
1748            body.extend_from_slice(&[0u8; 8]);
1749        }
1750        body.extend_from_slice(tail);
1751        boxed(b"uuid", &body)
1752    }
1753
1754    fn ftyp() -> Vec<u8> {
1755        boxed(b"ftyp", b"isom\0\0\0\0isom")
1756    }
1757
1758    fn file(parts: &[Vec<u8>]) -> Vec<u8> {
1759        parts.concat()
1760    }
1761
1762    fn walk_paths(s: &Structure, data: &[u8]) -> Vec<(String, u64, u64)> {
1763        let mut out = Vec::new();
1764        s.walk(&mut Cursor::new(data), |n| {
1765            out.push((n.path.to_string(), n.range.offset(), n.range.len()));
1766            Ok(())
1767        })
1768        .unwrap();
1769        out
1770    }
1771
1772    #[test]
1773    fn tiles_and_labels_c2pa_boxes() {
1774        let data = file(&[
1775            ftyp(),
1776            c2pa_box(MANIFEST, b"STORE"),
1777            boxed(b"moov", &boxed(b"free", b"")),
1778            boxed(b"mdat", b"media"),
1779        ]);
1780        let s = parse(&mut Cursor::new(&data)).unwrap();
1781        assert_eq!(s.media_type(), "video/mp4");
1782        let covered: u64 = s.regions().map(|r| r.range.len()).sum();
1783        assert_eq!(covered, data.len() as u64);
1784
1785        let e = s.items_labelled(ItemKind::C2pa, MANIFEST).next().unwrap();
1786        assert_eq!(s.read_item(&mut Cursor::new(&data), e).unwrap(), b"STORE");
1787        assert!(s.items_labelled(ItemKind::C2pa, UPDATE).next().is_none());
1788    }
1789
1790    #[test]
1791    fn walk_reports_nested_paths() {
1792        let trak = boxed(b"trak", &boxed(b"mdia", &boxed(b"hdlr", &[0u8; 8])));
1793        let data = file(&[ftyp(), boxed(b"moov", &trak), boxed(b"mdat", b"x")]);
1794        let s = parse(&mut Cursor::new(&data)).unwrap();
1795        let w = walk_paths(&s, &data);
1796        let paths: Vec<_> = w.iter().map(|(p, _, _)| p.as_str()).collect();
1797        assert_eq!(
1798            paths,
1799            [
1800                "/ftyp",
1801                "/moov",
1802                "/moov/trak",
1803                "/moov/trak/mdia",
1804                "/moov/trak/mdia/hdlr",
1805                "/mdat"
1806            ]
1807        );
1808        // hdlr is a FullBox: version and flags are reported, not part of header_len.
1809        let mut seen = false;
1810        s.walk(&mut Cursor::new(&data), |n| {
1811            if n.path.ends_with("hdlr") {
1812                assert_eq!((n.version, n.flags, n.header_len), (Some(0), Some(0), 8));
1813                seen = true;
1814            }
1815            Ok(())
1816        })
1817        .unwrap();
1818        assert!(seen);
1819    }
1820
1821    #[test]
1822    fn quicktime_meta_without_full_box_header() {
1823        let meta = boxed(b"meta", &boxed(b"hdlr", &[0u8; 8]));
1824        let data = file(&[ftyp(), boxed(b"moov", &boxed(b"udta", &meta))]);
1825        let s = parse(&mut Cursor::new(&data)).unwrap();
1826        let w = walk_paths(&s, &data);
1827        assert!(w.iter().any(|(p, _, _)| p == "/moov/udta/meta/hdlr"));
1828    }
1829
1830    #[test]
1831    fn mdat_overrun_is_clamped_others_are_errors() {
1832        let mut mdat = boxed(b"mdat", b"abcdef");
1833        mdat[3] = 200; // size larger than the file
1834        let data = file(&[ftyp(), mdat]);
1835        let s = parse(&mut Cursor::new(&data)).unwrap();
1836        assert_eq!(s.total_size(), data.len() as u64);
1837
1838        let mut moov = boxed(b"moov", b"");
1839        moov[3] = 200;
1840        assert!(parse(&mut Cursor::new(file(&[ftyp(), moov]))).is_err());
1841    }
1842
1843    #[test]
1844    fn size_zero_runs_to_end_and_large_size_is_read() {
1845        let mut mdat = boxed(b"mdat", b"abc");
1846        mdat[..4].copy_from_slice(&0u32.to_be_bytes());
1847        let data = file(&[ftyp(), mdat]);
1848        parse(&mut Cursor::new(&data)).unwrap();
1849
1850        let mut large = 1u32.to_be_bytes().to_vec();
1851        large.extend_from_slice(b"free");
1852        large.extend_from_slice(&20u64.to_be_bytes());
1853        large.extend_from_slice(b"1234");
1854        let data = file(&[ftyp(), large]);
1855        let s = parse(&mut Cursor::new(&data)).unwrap();
1856        let free = &s.segments()[1];
1857        assert_eq!((free.header().len(), free.payload().len()), (16, 4));
1858    }
1859
1860    #[test]
1861    fn trailing_bytes_become_unnamed_data() {
1862        let data = file(&[ftyp(), vec![1, 2, 3]]);
1863        let s = parse(&mut Cursor::new(&data)).unwrap();
1864        assert!(s.segments().last().unwrap().name().is_none());
1865    }
1866
1867    #[test]
1868    fn hostile_headers_are_rejected() {
1869        for bad_size in [2u32, 7] {
1870            let mut b = boxed(b"free", b"");
1871            b[..4].copy_from_slice(&bad_size.to_be_bytes());
1872            assert!(parse(&mut Cursor::new(file(&[ftyp(), b]))).is_err());
1873        }
1874        // Extended size smaller than its own header.
1875        let mut large = 1u32.to_be_bytes().to_vec();
1876        large.extend_from_slice(b"free");
1877        large.extend_from_slice(&4u64.to_be_bytes());
1878        assert!(parse(&mut Cursor::new(file(&[ftyp(), large]))).is_err());
1879        // uuid box too short to hold its type.
1880        assert!(parse(&mut Cursor::new(file(&[ftyp(), boxed(b"uuid", &[0u8; 4])]))).is_err());
1881        // Nesting past the limit.
1882        let mut nested = boxed(b"free", b"");
1883        for _ in 0..MAX_BOX_DEPTH + 1 {
1884            nested = boxed(b"trak", &nested);
1885        }
1886        let data = file(&[ftyp(), nested]);
1887        let s = parse(&mut Cursor::new(&data)).unwrap();
1888        assert!(s.walk(&mut Cursor::new(&data), |_| Ok(())).is_err());
1889    }
1890
1891    #[test]
1892    fn c2pa_box_rules() {
1893        let parse_of = |parts: &[Vec<u8>]| parse(&mut Cursor::new(file(parts)));
1894        let (m, o, u, k) = (
1895            c2pa_box(MANIFEST, b"A"),
1896            c2pa_box(ORIGINAL, b"B"),
1897            c2pa_box(UPDATE, b"C"),
1898            c2pa_box(MERKLE, b"D"),
1899        );
1900        assert!(parse_of(&[ftyp(), m.clone(), k.clone()]).is_ok());
1901        assert!(parse_of(&[ftyp(), o.clone(), u.clone()]).is_ok());
1902        assert!(parse_of(&[ftyp(), m.clone(), m.clone()]).is_err());
1903        assert!(parse_of(&[ftyp(), u.clone(), u.clone(), o.clone()]).is_err());
1904        assert!(parse_of(&[ftyp(), o]).is_err());
1905        assert!(parse_of(&[ftyp(), u.clone()]).is_err());
1906        assert!(parse_of(&[ftyp(), m, u]).is_err());
1907        assert!(parse_of(&[ftyp(), c2pa_box("bogus", b"")]).is_err());
1908
1909        // No NUL within the purpose limit.
1910        let mut body = C2PA_UUID.to_vec();
1911        body.extend_from_slice(&[0u8; 4]);
1912        body.extend_from_slice(&[b'a'; 64]);
1913        assert!(parse_of(&[ftyp(), boxed(b"uuid", &body)]).is_err());
1914    }
1915
1916    #[test]
1917    fn xmp_uuid_box_is_an_item() {
1918        let mut body = XMP_UUID.to_vec();
1919        body.extend_from_slice(b"<xmp/>");
1920        let data = file(&[ftyp(), boxed(b"uuid", &body)]);
1921        let s = parse(&mut Cursor::new(&data)).unwrap();
1922        let e = s.require_item(ItemKind::Xmp).unwrap();
1923        assert_eq!(s.read_item(&mut Cursor::new(&data), e).unwrap(), b"<xmp/>");
1924        assert_eq!(
1925            (e.encoding(), e.label(), e.native_id()),
1926            (Encoding::Xml, None, None)
1927        );
1928        assert_eq!(s.segments()[1].kind(), SegmentKind::Metadata);
1929    }
1930
1931    #[test]
1932    fn media_type_follows_brand() {
1933        let data = file(&[boxed(b"ftyp", b"avif\0\0\0\0avif")]);
1934        assert_eq!(
1935            parse(&mut Cursor::new(&data)).unwrap().media_type(),
1936            "image/avif"
1937        );
1938    }
1939
1940    // ---- writing ----
1941
1942    use crate::{testing::Conformance, Chunk, NullSink};
1943
1944    fn full(ty: &[u8; 4], version: u8, flags: u32, body: &[u8]) -> Vec<u8> {
1945        let mut b = vec![version];
1946        b.extend_from_slice(&flags.to_be_bytes()[1..]);
1947        b.extend_from_slice(body);
1948        boxed(ty, &b)
1949    }
1950
1951    fn moov_with(stco: &[u8]) -> Vec<u8> {
1952        boxed(
1953            b"moov",
1954            &boxed(
1955                b"trak",
1956                &boxed(b"mdia", &boxed(b"minf", &boxed(b"stbl", stco))),
1957            ),
1958        )
1959    }
1960
1961    /// `ftyp`, `before`, a `moov` whose one chunk offset points at the media,
1962    /// `mdat` holding `MEDIA`, then `tail`. Returns the file and the true offset
1963    /// of the media.
1964    fn media_file(before: &[Vec<u8>], tail: &[Vec<u8>], entry: Option<u32>) -> (Vec<u8>, u32) {
1965        let build = |e: u32| {
1966            let mut body = 1u32.to_be_bytes().to_vec();
1967            body.extend_from_slice(&e.to_be_bytes());
1968            let mut parts = vec![ftyp()];
1969            parts.extend_from_slice(before);
1970            parts.push(moov_with(&full(b"stco", 0, 0, &body)));
1971            parts.push(boxed(b"mdat", b"MEDIA"));
1972            parts.extend_from_slice(tail);
1973            file(&parts)
1974        };
1975        let probe = build(0);
1976        let tail_len: usize = tail.iter().map(Vec::len).sum();
1977        let media = (probe.len() - tail_len - 5) as u32;
1978        (build(entry.unwrap_or(media)), media)
1979    }
1980
1981    fn rewrite(src: &[u8], u: &Updates) -> Result<Vec<u8>> {
1982        Ok(crate::testing::rewrite(handler(), src, u)?.0)
1983    }
1984
1985    fn find(bytes: &[u8], path: &str) -> (u64, u64, u32) {
1986        let s = parse(&mut Cursor::new(bytes)).unwrap();
1987        let mut hit = None;
1988        s.walk(&mut Cursor::new(bytes), |n| {
1989            if n.path == path && hit.is_none() {
1990                hit = Some((n.range.offset(), n.range.len(), n.header_len));
1991            }
1992            Ok(())
1993        })
1994        .unwrap();
1995        hit.unwrap_or_else(|| panic!("{path} not found"))
1996    }
1997
1998    fn be32(b: &[u8], at: u64) -> u32 {
1999        u32::from_be_bytes(b[at as usize..at as usize + 4].try_into().unwrap())
2000    }
2001
2002    fn stco_entry(b: &[u8]) -> u32 {
2003        let (off, _, hl) = find(b, "/moov/trak/mdia/minf/stbl/stco");
2004        be32(b, off + hl as u64 + 4 + 4)
2005    }
2006
2007    fn media_at(b: &[u8], at: u32) -> bool {
2008        b.get(at as usize..at as usize + 5) == Some(b"MEDIA")
2009    }
2010
2011    #[test]
2012    fn conforms() {
2013        let c = Conformance::new(handler())
2014            .c2pa(Some(crate::testing::c2pa_store_of_len(64)))
2015            .updates("merkle", Updates::new().set_merkle(vec![vec![0u8; 8]; 2]))
2016            .updates(
2017                "manifest and no merkle",
2018                Updates::new().set_c2pa(b"STORE".to_vec()).remove_merkle(),
2019            );
2020        c.check("plain", &media_file(&[], &[], None).0);
2021        c.check(
2022            "with a manifest",
2023            &media_file(&[c2pa_box(MANIFEST, b"A")], &[], None).0,
2024        );
2025        c.check(
2026            "with a manifest and merkle boxes",
2027            &media_file(&[c2pa_box(MANIFEST, b"A")], &[c2pa_box(MERKLE, b"M")], None).0,
2028        );
2029        c.check("fragmented", &fragmented());
2030        c.check("heif", &heif(EXIF_ITEM, THUMB));
2031    }
2032
2033    #[test]
2034    fn manifest_is_inserted_after_ftyp_and_offsets_follow() {
2035        let (f, e0) = media_file(&[], &[], None);
2036        let out = rewrite(&f, &Updates::new().set_c2pa(b"STORE".to_vec())).unwrap();
2037        let s = parse(&mut Cursor::new(&out)).unwrap();
2038        assert_eq!(s.segments()[1].name(), Name::FourCC(UUID));
2039        let e = s.items_labelled(ItemKind::C2pa, MANIFEST).next().unwrap();
2040        assert_eq!(s.read_item(&mut Cursor::new(&out), e).unwrap(), b"STORE");
2041        let added = (out.len() - f.len()) as u32;
2042        assert_eq!(added, 8 + 16 + 4 + 9 + 8 + 5);
2043        assert_eq!(stco_entry(&out), e0 + added);
2044        assert!(media_at(&out, stco_entry(&out)));
2045    }
2046
2047    #[test]
2048    fn replacing_in_place_tracks_size_changes() {
2049        let (f, e0) = media_file(&[], &[], None);
2050        let one = rewrite(&f, &Updates::new().set_c2pa(b"STORE".to_vec())).unwrap();
2051
2052        // Smaller: offsets shrink with it, position is kept.
2053        let smaller = rewrite(&one, &Updates::new().set_c2pa(b"ST".to_vec())).unwrap();
2054        assert_eq!(smaller.len(), one.len() - 3);
2055        assert_eq!(stco_entry(&smaller), e0 + 47);
2056        assert!(media_at(&smaller, stco_entry(&smaller)));
2057
2058        // Same size: only the payload differs and nothing is rewritten.
2059        let same = rewrite(&one, &Updates::new().set_c2pa(b"STORX".to_vec())).unwrap();
2060        assert_eq!(same.len(), one.len());
2061        assert_eq!(stco_entry(&same), stco_entry(&one));
2062        let diff: Vec<_> = (0..one.len()).filter(|&i| one[i] != same[i]).collect();
2063        assert_eq!(diff.len(), 1);
2064
2065        // Removing restores the original file.
2066        assert_eq!(rewrite(&one, &Updates::new().remove_c2pa()).unwrap(), f);
2067    }
2068
2069    #[test]
2070    fn re_signing_drops_the_update_box() {
2071        let (f, e0) = media_file(&[c2pa_box(ORIGINAL, b"A")], &[c2pa_box(UPDATE, b"U")], None);
2072        let out = rewrite(&f, &Updates::new().set_c2pa(b"NEW".to_vec())).unwrap();
2073        let s = parse(&mut Cursor::new(&out)).unwrap();
2074        assert_eq!(s.items_labelled(ItemKind::C2pa, UPDATE).count(), 0);
2075        assert_eq!(s.items_labelled(ItemKind::C2pa, ORIGINAL).count(), 0);
2076        assert_eq!(s.items_labelled(ItemKind::C2pa, MANIFEST).count(), 1);
2077        // "NEW" is two bytes longer than "A" in a box of the same shape.
2078        assert_eq!(stco_entry(&out), e0 + 2);
2079        assert!(media_at(&out, stco_entry(&out)));
2080    }
2081
2082    #[test]
2083    fn a_new_manifest_needs_a_decision_about_merkle_boxes() {
2084        let (m1, m2) = (b"m1: 1".to_vec(), b"m2: 2".to_vec());
2085        let first = c2pa_store(&[&m1]);
2086        let (f, _) = media_file(
2087            &[c2pa_box(MANIFEST, &first)],
2088            &[c2pa_box(MERKLE, b"D")],
2089            None,
2090        );
2091        assert_eq!(rewrite(&f, &Updates::new()).unwrap(), f);
2092        assert!(rewrite(&f, &Updates::new().set_c2pa(b"B".to_vec())).is_err());
2093        let removed = rewrite(&f, &Updates::new().set_c2pa(b"B".to_vec()).remove_merkle()).unwrap();
2094        let s = parse(&mut Cursor::new(&removed)).unwrap();
2095        assert_eq!(s.items_labelled(ItemKind::Other, MERKLE).count(), 0);
2096
2097        // An update manifest leaves the merkle boxes alone, and cannot change them.
2098        let extended = c2pa_store(&[&m1, &m2]);
2099        let keep = rewrite(&f, &Updates::new().set_c2pa(extended.clone()).as_update()).unwrap();
2100        let s = parse(&mut Cursor::new(&keep)).unwrap();
2101        assert_eq!(merkle_payloads(&s, &keep), vec![b"D".to_vec()]);
2102        let u = Updates::new()
2103            .set_c2pa(extended)
2104            .as_update()
2105            .remove_merkle();
2106        assert!(rewrite(&f, &u).is_err());
2107    }
2108
2109    fn merkle_payloads(s: &Structure, data: &[u8]) -> Vec<Vec<u8>> {
2110        s.items_labelled(ItemKind::Other, MERKLE)
2111            .map(|e| s.read_item(&mut Cursor::new(data), e).unwrap())
2112            .collect()
2113    }
2114
2115    #[test]
2116    fn merkle_boxes_follow_the_last_mdat_and_are_filled_in_place() {
2117        let (f, e0) = media_file(&[], &[boxed(b"free", b"zz")], None);
2118        let out = rewrite(&f, &Updates::new().set_merkle(vec![vec![0u8; 12]; 3])).unwrap();
2119        let s = parse(&mut Cursor::new(&out)).unwrap();
2120
2121        // Three boxes directly after mdat, before the trailing box; nothing before
2122        // them moved.
2123        let (mdat_at, mdat_len, _) = find(&out, "/mdat");
2124        let first = s.items_labelled(ItemKind::Other, MERKLE).next().unwrap();
2125        let seg = s
2126            .segment(first.extents().next().unwrap().segment())
2127            .unwrap();
2128        assert_eq!(seg.range().offset(), mdat_at + mdat_len);
2129        assert_eq!(merkle_payloads(&s, &out).len(), 3);
2130        assert_eq!(stco_entry(&out), e0);
2131        assert_eq!(out.len(), f.len() + 3 * (8 + 16 + 4 + 7 + 12));
2132
2133        // Fill each box in place, as after hashing the media.
2134        let mut cur = Cursor::new(out.clone());
2135        for (i, e) in s.items_labelled(ItemKind::Other, MERKLE).enumerate() {
2136            s.patch_exact(&mut cur, e, &[i as u8 + 1; 12]).unwrap();
2137        }
2138        let filled = cur.into_inner();
2139        assert_eq!(filled.len(), out.len());
2140        let s2 = parse(&mut Cursor::new(&filled)).unwrap();
2141        assert_eq!(
2142            merkle_payloads(&s2, &filled),
2143            vec![vec![1u8; 12], vec![2; 12], vec![3; 12]]
2144        );
2145
2146        // Setting again replaces; removing restores the original file.
2147        let two = rewrite(&filled, &Updates::new().set_merkle(vec![vec![9u8; 4]; 2])).unwrap();
2148        assert_eq!(
2149            merkle_payloads(&parse(&mut Cursor::new(&two)).unwrap(), &two).len(),
2150            2
2151        );
2152        assert_eq!(
2153            rewrite(&filled, &Updates::new().remove_merkle()).unwrap(),
2154            f
2155        );
2156        // Keep is the default.
2157        assert_eq!(rewrite(&filled, &Updates::new()).unwrap(), filled);
2158    }
2159
2160    /// The intended flow: placeholders of final size, media hashed (here: summed)
2161    /// as it streams past in the same pass, boxes filled in afterwards.
2162    #[test]
2163    fn media_seen_by_the_sink_can_fill_the_merkle_boxes() {
2164        struct Sum {
2165            mdat: Vec<usize>,
2166            sum: u64,
2167            seen: u64,
2168        }
2169        impl crate::Sink for Sum {
2170            fn begin(&mut self, structure: &Structure) -> Result<()> {
2171                self.mdat = structure
2172                    .segments()
2173                    .iter()
2174                    .enumerate()
2175                    .filter(|(_, s)| s.name() == Name::FourCC(MDAT))
2176                    .map(|(i, _)| i)
2177                    .collect();
2178                Ok(())
2179            }
2180
2181            fn chunk(&mut self, c: Chunk<'_>) -> Result<()> {
2182                if c.role == Role::Payload && self.mdat.contains(&c.segment.index()) {
2183                    self.sum += c.data.iter().map(|&b| b as u64).sum::<u64>();
2184                    self.seen += c.data.len() as u64;
2185                }
2186                Ok(())
2187            }
2188        }
2189
2190        let (f, _) = media_file(&[], &[], None);
2191        let src = parse(&mut Cursor::new(&f)).unwrap();
2192        let mut out = Cursor::new(Vec::new());
2193        let mut sink = Sum {
2194            mdat: vec![],
2195            sum: 0,
2196            seen: 0,
2197        };
2198        let u = Updates::new().set_merkle(vec![vec![0u8; 8]]);
2199        let dest = container_api::handler(&src)
2200            .write(&src, &mut Cursor::new(&f), &mut out, &u, &mut sink)
2201            .unwrap();
2202        assert_eq!(sink.seen, 5);
2203        assert_eq!(sink.sum, b"MEDIA".iter().map(|&b| b as u64).sum::<u64>());
2204
2205        let e = dest.items_labelled(ItemKind::Other, MERKLE).next().unwrap();
2206        dest.patch_exact(&mut out, e, &sink.sum.to_be_bytes())
2207            .unwrap();
2208        let bytes = out.into_inner();
2209        let s = parse(&mut Cursor::new(&bytes)).unwrap();
2210        assert_eq!(
2211            merkle_payloads(&s, &bytes),
2212            vec![sink.sum.to_be_bytes().to_vec()]
2213        );
2214    }
2215
2216    #[test]
2217    fn merkle_and_manifest_together_keep_offsets_right() {
2218        let (f, e0) = media_file(&[], &[], None);
2219        let u = Updates::new()
2220            .set_c2pa(b"STORE".to_vec())
2221            .set_merkle(vec![vec![7u8; 6]; 2]);
2222        let out = rewrite(&f, &u).unwrap();
2223        let s = parse(&mut Cursor::new(&out)).unwrap();
2224        assert_eq!(merkle_payloads(&s, &out), vec![vec![7u8; 6]; 2]);
2225        // The manifest goes in front of the media and moves it; merkle boxes behind
2226        // the media do not.
2227        let added = (8 + 16 + 4 + 9 + 8 + 5) as u32;
2228        assert_eq!(stco_entry(&out), e0 + added);
2229        assert!(media_at(&out, stco_entry(&out)));
2230    }
2231
2232    #[test]
2233    fn a_box_that_ran_to_the_end_gets_its_size_when_something_follows_it() {
2234        // The last box, with a size of 0 (to the end of the file), then merkle boxes
2235        // after it: without a size of its own it would swallow them.
2236        let mut mdat = boxed(b"mdat", b"MEDIA");
2237        mdat[..4].copy_from_slice(&0u32.to_be_bytes());
2238        let f = file(&[ftyp(), mdat]);
2239        let out = rewrite(&f, &Updates::new().set_merkle(vec![vec![0u8; 8]])).unwrap();
2240        let s = parse(&mut Cursor::new(&out)).unwrap();
2241        let sizes: Vec<_> = s.segments().iter().map(|g| g.range().len()).collect();
2242        assert_eq!(sizes[1], 13); // the mdat, now sized: 8 + "MEDIA"
2243        assert_eq!(s.segments().len(), 3);
2244        assert_eq!(&out[ftyp().len() + 4..][..4], b"mdat");
2245        assert_eq!(be32(&out, ftyp().len() as u64), 13);
2246
2247        // Nothing after it: the header is left as it was.
2248        let kept = rewrite(&f, &Updates::new()).unwrap();
2249        assert_eq!(kept, f);
2250        let manifest_first = rewrite(&f, &Updates::new().set_c2pa(b"STORE".to_vec())).unwrap();
2251        let at = ftyp().len() + manifest_first.len() - f.len();
2252        assert_eq!(be32(&manifest_first, at as u64), 0);
2253    }
2254
2255    #[test]
2256    fn a_first_box_that_ran_to_the_end_is_sized_before_a_box_is_added() {
2257        // Found by fuzzing: an ftyp of size 0 followed by an inserted XMP box.
2258        let mut f = ftyp();
2259        f[..4].copy_from_slice(&0u32.to_be_bytes());
2260        let out = rewrite(&f, &Updates::new().set_xmp(b"<x/>".to_vec())).unwrap();
2261        assert_eq!(be32(&out, 0), f.len() as u32);
2262        assert_eq!(parse(&mut Cursor::new(&out)).unwrap().segments().len(), 2);
2263    }
2264
2265    #[test]
2266    fn merkle_option_defaults_and_remove_all() {
2267        assert!(matches!(Updates::new().merkle(), MerkleUpdate::Keep));
2268        assert!(matches!(
2269            Updates::remove_all().merkle(),
2270            MerkleUpdate::Remove
2271        ));
2272        // An explicit choice beats remove_all.
2273        assert!(matches!(
2274            Updates::remove_all().keep_merkle().merkle(),
2275            MerkleUpdate::Keep
2276        ));
2277
2278        // remove_all drops the merkle boxes a file has.
2279        let (f, _) = media_file(&[], &[], None);
2280        let with = rewrite(&f, &Updates::new().set_merkle(vec![vec![1u8; 4]])).unwrap();
2281        let s = parse(&mut Cursor::new(&with)).unwrap();
2282        assert_eq!(merkle_payloads(&s, &with).len(), 1);
2283        let out = rewrite(&with, &Updates::remove_all()).unwrap();
2284        let s = parse(&mut Cursor::new(&out)).unwrap();
2285        assert!(merkle_payloads(&s, &out).is_empty());
2286    }
2287
2288    #[test]
2289    fn offset_tables_are_a_relocation_step_not_a_copy() {
2290        let (f, _) = media_file(&[], &[], None);
2291        let s = parse(&mut Cursor::new(&f)).unwrap();
2292        let u = Updates::new().set_c2pa(b"STORE".to_vec());
2293        let plan = s.write_plan(&mut Cursor::new(&f), &u).unwrap();
2294        crate::plan::validate(&plan, f.len() as u64).unwrap();
2295        let tables: Vec<_> = plan
2296            .steps()
2297            .iter()
2298            .filter(|st| matches!(st, container_api::Step::Relocate { .. }))
2299            .collect();
2300        assert_eq!(tables.len(), 1);
2301        // Planning the structure alone does not read the tables.
2302        let structure = s.plan(&mut Cursor::new(&f), &u).unwrap();
2303        assert_eq!(structure.total_size(), plan.structure().total_size());
2304    }
2305
2306    #[test]
2307    fn merkle_boxes_need_an_mdat() {
2308        let f = file(&[ftyp()]);
2309        assert!(rewrite(&f, &Updates::new().set_merkle(vec![vec![0u8; 4]])).is_err());
2310        // Removing from a file without any is fine.
2311        assert_eq!(rewrite(&f, &Updates::new().remove_merkle()).unwrap(), f);
2312    }
2313
2314    #[test]
2315    fn xmp_is_inserted_replaced_and_removed() {
2316        let (f, e0) = media_file(&[], &[], None);
2317        let out = rewrite(&f, &Updates::new().set_xmp(b"<x/>".to_vec())).unwrap();
2318        let s = parse(&mut Cursor::new(&out)).unwrap();
2319        let e = s.require_item(ItemKind::Xmp).unwrap();
2320        assert_eq!(s.read_item(&mut Cursor::new(&out), e).unwrap(), b"<x/>");
2321        assert_eq!(stco_entry(&out), e0 + 8 + 16 + 4);
2322        assert!(media_at(&out, stco_entry(&out)));
2323        assert_eq!(rewrite(&out, &Updates::new().remove_xmp()).unwrap(), f);
2324
2325        // Both at once, manifest first.
2326        let both = rewrite(
2327            &f,
2328            &Updates::new()
2329                .set_c2pa(b"S".to_vec())
2330                .set_xmp(b"<x/>".to_vec()),
2331        )
2332        .unwrap();
2333        let s = parse(&mut Cursor::new(&both)).unwrap();
2334        let held = |i| {
2335            s.items_in(SegmentId::from_index(i).unwrap())
2336                .next()
2337                .unwrap()
2338        };
2339        assert_eq!(s.segments()[1].kind(), SegmentKind::Metadata);
2340        assert_eq!(held(1).kind(), ItemKind::C2pa);
2341        assert_eq!(held(2).kind(), ItemKind::Xmp);
2342        assert!(media_at(&both, stco_entry(&both)));
2343    }
2344
2345    #[test]
2346    fn no_ftyp_means_nowhere_to_insert() {
2347        let f = file(&[boxed(b"free", b"")]);
2348        assert!(rewrite(&f, &Updates::new().set_c2pa(b"S".to_vec())).is_err());
2349        assert_eq!(rewrite(&f, &Updates::new()).unwrap(), f);
2350    }
2351
2352    #[test]
2353    fn offsets_that_cannot_move_are_errors() {
2354        // 32-bit chunk offset that would pass 4 GiB.
2355        let (f, _) = media_file(&[], &[], Some(0xffff_fff8));
2356        assert!(rewrite(&f, &Updates::new().set_c2pa(b"S".to_vec())).is_err());
2357
2358        // A table claiming more entries than its box holds.
2359        let mut body = 0xffff_ffffu32.to_be_bytes().to_vec();
2360        body.extend_from_slice(&[0u8; 4]);
2361        let f = file(&[
2362            ftyp(),
2363            moov_with(&full(b"stco", 0, 0, &body)),
2364            boxed(b"mdat", b"MEDIA"),
2365        ]);
2366        assert!(rewrite(&f, &Updates::new().set_c2pa(b"S".to_vec())).is_err());
2367    }
2368
2369    fn payload_of(bytes: &[u8], label: &str) -> Option<Vec<u8>> {
2370        let s = parse(&mut Cursor::new(bytes)).unwrap();
2371        let found = s
2372            .items_labelled(ItemKind::C2pa, label)
2373            .next()
2374            .map(|e| s.read_item(&mut Cursor::new(bytes), e).unwrap());
2375        found
2376    }
2377
2378    #[test]
2379    fn an_update_keeps_the_manifest_as_original_and_adds_an_update_box() {
2380        let (m1, m2) = (b"m1: 1".to_vec(), b"m2: 2".to_vec());
2381        let first = c2pa_store(&[&m1]);
2382        let (f, e0) = media_file(&[c2pa_box(MANIFEST, &first)], &[], None);
2383        let out = rewrite(
2384            &f,
2385            &Updates::new().set_c2pa(c2pa_store(&[&m1, &m2])).as_update(),
2386        )
2387        .unwrap();
2388
2389        // Everything is as it was, but for the purpose and the box at the end.
2390        let mut expect = f.clone();
2391        let at = expect.windows(9).position(|w| w == b"manifest\0").unwrap();
2392        expect[at..at + 8].copy_from_slice(b"original");
2393        expect.extend_from_slice(&c2pa_box(UPDATE, &c2pa_store(&[&m2])));
2394        assert_eq!(out, expect);
2395
2396        assert_eq!(payload_of(&out, ORIGINAL).unwrap(), first);
2397        assert!(payload_of(&out, MANIFEST).is_none());
2398        assert_eq!(stco_entry(&out), e0);
2399    }
2400
2401    #[test]
2402    fn signing_an_update_fills_the_placeholder_of_the_update_store() {
2403        let (m1, m2) = (b"m1: 1".to_vec(), b"m2: 2".to_vec());
2404        let (f, _) = media_file(
2405            &[
2406                c2pa_box(ORIGINAL, &c2pa_store(&[&m1])),
2407                c2pa_box(UPDATE, &c2pa_store(&[&m2])),
2408            ],
2409            &[],
2410            None,
2411        );
2412        let s = parse(&mut Cursor::new(&f)).unwrap();
2413        let signed = c2pa_store(&[&m1, b"m2: x"]);
2414        let mut out = Cursor::new(f.clone());
2415        s.patch_c2pa_store(&mut out, &signed).unwrap();
2416        let out = out.into_inner();
2417        assert_eq!(payload_of(&out, UPDATE).unwrap(), c2pa_store(&[b"m2: x"]));
2418        assert_eq!(payload_of(&out, ORIGINAL).unwrap(), c2pa_store(&[&m1]));
2419
2420        // The original cannot change.
2421        let mut untouched = Cursor::new(f.clone());
2422        let changed = c2pa_store(&[b"m1: x", &m2]);
2423        assert!(matches!(
2424            s.patch_c2pa_store(&mut untouched, &changed),
2425            Err(Error::UnsupportedFeature(_))
2426        ));
2427        assert_eq!(untouched.into_inner(), f);
2428    }
2429
2430    #[test]
2431    fn later_updates_replace_the_update_store() {
2432        let (m1, m2, m3) = (b"m1: 1".to_vec(), b"m2: 2".to_vec(), b"m3: 3".to_vec());
2433        for before_moov in [false, true] {
2434            let update = c2pa_box(UPDATE, &c2pa_store(&[&m2]));
2435            let original = c2pa_box(ORIGINAL, &c2pa_store(&[&m1]));
2436            let (f, _) = if before_moov {
2437                media_file(&[original, update], &[], None)
2438            } else {
2439                media_file(&[original], &[update], None)
2440            };
2441            let full = c2pa_store(&[&m1, &m2, &m3]);
2442            let out = rewrite(&f, &Updates::new().set_c2pa(full).as_update()).unwrap();
2443            assert_eq!(payload_of(&out, UPDATE).unwrap(), c2pa_store(&[&m2, &m3]));
2444            assert_eq!(payload_of(&out, ORIGINAL).unwrap(), c2pa_store(&[&m1]));
2445            // An update box ahead of the media moves it; the offsets follow.
2446            assert!(
2447                media_at(&out, stco_entry(&out)),
2448                "before_moov={before_moov}"
2449            );
2450
2451            // A manifest being signed replaces its placeholder in the update store.
2452            let m3b = b"m3: three, signed".to_vec();
2453            let full = c2pa_store(&[&m1, &m2, &m3b]);
2454            let again = rewrite(&out, &Updates::new().set_c2pa(full).as_update()).unwrap();
2455            assert_eq!(
2456                payload_of(&again, UPDATE).unwrap(),
2457                c2pa_store(&[&m2, &m3b])
2458            );
2459            assert!(media_at(&again, stco_entry(&again)));
2460        }
2461    }
2462
2463    #[test]
2464    fn an_update_that_is_not_an_extension_is_written_as_a_whole() {
2465        let (m1, m2, m3) = (b"m1: 1".to_vec(), b"m2: 2".to_vec(), b"m3: 3".to_vec());
2466
2467        // Nothing to update.
2468        let (clean, _) = media_file(&[], &[], None);
2469        let full = c2pa_store(&[&m1]);
2470        let out = rewrite(&clean, &Updates::new().set_c2pa(full.clone()).as_update()).unwrap();
2471        assert_eq!(payload_of(&out, MANIFEST).unwrap(), full);
2472
2473        // The existing manifests changed (redaction): the whole store is written,
2474        // and the old update store is gone.
2475        let (f, _) = media_file(
2476            &[
2477                c2pa_box(ORIGINAL, &c2pa_store(&[&m1])),
2478                c2pa_box(UPDATE, &c2pa_store(&[&m2])),
2479            ],
2480            &[],
2481            None,
2482        );
2483        let edited = c2pa_store(&[b"m1: redacted", &m2, &m3]);
2484        let out = rewrite(&f, &Updates::new().set_c2pa(edited.clone()).as_update()).unwrap();
2485        assert_eq!(payload_of(&out, MANIFEST).unwrap(), edited);
2486        assert!(payload_of(&out, ORIGINAL).is_none());
2487        assert!(payload_of(&out, UPDATE).is_none());
2488        assert!(media_at(&out, stco_entry(&out)));
2489
2490        // Set after update clears the hint.
2491        let (f, _) = media_file(&[c2pa_box(MANIFEST, &c2pa_store(&[&m1]))], &[], None);
2492        let extended = c2pa_store(&[&m1, b"m9: 9"]);
2493        let plain = Updates::new().set_c2pa(extended.clone());
2494        let out = rewrite(&f, &plain).unwrap();
2495        assert!(payload_of(&out, ORIGINAL).is_none());
2496        assert_eq!(payload_of(&out, MANIFEST).unwrap(), extended);
2497        // Without the hint a pure extension is a standard manifest, not an update;
2498        // a later set_c2pa also clears it.
2499        let cleared = Updates::new()
2500            .set_c2pa(extended.clone())
2501            .as_update()
2502            .set_c2pa(extended.clone());
2503        let out = rewrite(&f, &cleared).unwrap();
2504        assert!(payload_of(&out, ORIGINAL).is_none());
2505    }
2506
2507    const EXIF_ITEM: &[u8] = b"\0\0\0\x06Exif\0\0II*\0\x08\0\0\0";
2508    const TIFF: &[u8] = b"II*\0\x08\0\0\0";
2509    const THUMB: &[u8] = b"THUMBNAIL-BYTES";
2510
2511    /// `ftyp`, a `meta` listing a HEVC item, an EXIF item and a JPEG thumbnail of
2512    /// the first, then an `mdat` holding the data of the last two.
2513    fn heif(exif: &[u8], thumb: &[u8]) -> Vec<u8> {
2514        heif_with(exif, thumb, heif_items::build::infe(3, b"jpeg"))
2515    }
2516
2517    /// [`heif`] with a chosen `infe` (item 3) for the thumbnail.
2518    fn heif_with(exif: &[u8], thumb: &[u8], thumb_infe: Vec<u8>) -> Vec<u8> {
2519        use heif_items::build::{iinf, iloc0, infe, meta, thmb};
2520        let build = |e_at: u32, t_at: u32| {
2521            let body = meta(&[
2522                iinf(&[infe(1, b"hvc1"), infe(2, b"Exif"), thumb_infe.clone()]),
2523                thmb(3, 1),
2524                iloc0(&[
2525                    (2, &[(e_at, exif.len() as u32)]),
2526                    (3, &[(t_at, thumb.len() as u32)]),
2527                ]),
2528            ]);
2529            let mut p = vec![0u8; 4]; // version and flags
2530            p.extend_from_slice(&body);
2531            file(&[
2532                ftyp(),
2533                boxed(b"meta", &p),
2534                boxed(b"mdat", &[exif, thumb].concat()),
2535            ])
2536        };
2537        let data_at = (build(0, 0).len() - exif.len() - thumb.len()) as u32;
2538        build(data_at, data_at + exif.len() as u32)
2539    }
2540
2541    /// The first item of `kind`: its native type and its bytes.
2542    fn item(s: &Structure, bytes: &[u8], kind: ItemKind) -> Option<(Option<Name>, Vec<u8>)> {
2543        let e = s.items_of(kind).next()?;
2544        Some((
2545            e.native_type(),
2546            s.read_item(&mut Cursor::new(bytes), e).unwrap(),
2547        ))
2548    }
2549
2550    /// The item with a thumbnail relation.
2551    fn thumb(s: &Structure) -> Option<&Item> {
2552        s.items().find(|e| {
2553            e.relations()
2554                .iter()
2555                .any(|r| r.kind() == RelationKind::Thumbnail)
2556        })
2557    }
2558
2559    #[test]
2560    fn heif_exif_and_thumbnail_items_are_items() {
2561        let f = heif(EXIF_ITEM, THUMB);
2562        let s = parse(&mut Cursor::new(&f)).unwrap();
2563        // The EXIF item starts at the TIFF header, after the offset field and
2564        // the bytes it skips.
2565        assert_eq!(
2566            item(&s, &f, ItemKind::Exif),
2567            Some((Some(Name::FourCC(*b"Exif")), TIFF.to_vec()))
2568        );
2569        let exif = s.require_item(ItemKind::Exif).unwrap();
2570        assert_eq!(
2571            (exif.encoding(), exif.native_id(), exif.label()),
2572            (Encoding::Tiff, Some(2), None)
2573        );
2574        // A `jpeg` thumbnail is a file, with the native reference kept.
2575        assert_eq!(
2576            item(&s, &f, ItemKind::EmbeddedAsset),
2577            Some((Some(Name::FourCC(*b"jpeg")), THUMB.to_vec()))
2578        );
2579        let t = thumb(&s).unwrap();
2580        assert_eq!(t.kind(), ItemKind::EmbeddedAsset);
2581        assert_eq!(t.encoding(), Encoding::Asset);
2582        assert_eq!(t.native_id(), Some(3));
2583        assert_eq!(t.relations(), &[Relation::new(*b"thmb", 1)]);
2584        let t = s.embedded_thumbnail(&mut Cursor::new(&f)).unwrap().unwrap();
2585        assert_eq!(
2586            (t.data.as_slice(), t.media_type()),
2587            (THUMB, Some("image/jpeg"))
2588        );
2589        // Still a tiling, and the C2PA rules are not disturbed.
2590        let covered: u64 = s.regions().map(|r| r.range.len()).sum();
2591        assert_eq!(covered, f.len() as u64);
2592        assert_eq!(rewrite(&f, &Updates::new()).unwrap(), f);
2593    }
2594
2595    #[test]
2596    fn thumbnail_media_types_follow_the_item() {
2597        use heif_items::build::{infe, infe_mime};
2598        let media = |thumb_infe: Vec<u8>, write: bool| {
2599            let f = heif_with(TIFF, THUMB, thumb_infe);
2600            let s = parse(&mut Cursor::new(&f)).unwrap();
2601            let (s, f) = if write {
2602                // The media type is carried through a write that moves the item.
2603                let out = rewrite(&f, &Updates::new().set_c2pa(b"STORE".to_vec())).unwrap();
2604                (parse(&mut Cursor::new(&out)).unwrap(), out)
2605            } else {
2606                (s, f)
2607            };
2608            let t = s.embedded_thumbnail(&mut Cursor::new(&f)).unwrap().unwrap();
2609            assert_eq!(t.data, THUMB);
2610            let e = thumb(&s).unwrap();
2611            assert_eq!(e.media_type(), t.media_type());
2612            // Files of a declared media type are embedded assets; a coded bitstream
2613            // or a `mime` item with no valid type is not.
2614            let coded = e.media_type().is_none();
2615            assert_eq!(
2616                (e.kind(), e.encoding()),
2617                if coded {
2618                    (ItemKind::Other, Encoding::Unknown)
2619                } else {
2620                    (ItemKind::EmbeddedAsset, Encoding::Asset)
2621                }
2622            );
2623            assert_eq!(s.embedded_assets().count(), usize::from(!coded));
2624            t.media_type().map(str::to_owned)
2625        };
2626        for write in [false, true] {
2627            assert_eq!(
2628                media(infe(3, b"jpeg"), write).as_deref(),
2629                Some("image/jpeg")
2630            );
2631            assert_eq!(
2632                media(infe_mime(3, b"image/png"), write).as_deref(),
2633                Some("image/png")
2634            );
2635            // A coded item is a bitstream, not a file, so it has no media type.
2636            assert_eq!(media(infe(3, b"av01"), write), None);
2637            assert_eq!(media(infe_mime(3, b"nonsense"), write), None);
2638        }
2639    }
2640
2641    #[test]
2642    fn items_follow_their_boxes_through_a_write() {
2643        let f = heif(EXIF_ITEM, THUMB);
2644        let s = parse(&mut Cursor::new(&f)).unwrap();
2645        let mut out = Cursor::new(Vec::new());
2646        let dest = container_api::handler(&s)
2647            .write(
2648                &s,
2649                &mut Cursor::new(&f),
2650                &mut out,
2651                &Updates::new().set_c2pa(b"STORE".to_vec()),
2652                &mut NullSink,
2653            )
2654            .unwrap();
2655        let out = out.into_inner();
2656        assert!(out.len() > f.len());
2657
2658        // The structure returned describes the items where they now are ...
2659        for (kind, want) in [(ItemKind::Exif, TIFF), (ItemKind::EmbeddedAsset, THUMB)] {
2660            assert_eq!(item(&dest, &out, kind).unwrap().1, want);
2661        }
2662        // ... as does parsing the output: the offsets in iloc moved with the data.
2663        let again = parse(&mut Cursor::new(&out)).unwrap();
2664        assert_eq!(
2665            item(&again, &out, ItemKind::Exif),
2666            item(&dest, &out, ItemKind::Exif)
2667        );
2668        assert_eq!(
2669            item(&again, &out, ItemKind::EmbeddedAsset),
2670            item(&dest, &out, ItemKind::EmbeddedAsset)
2671        );
2672        // Native identifiers and relations are carried too.
2673        assert_eq!(
2674            container_api::item_info(thumb(&dest).unwrap()),
2675            container_api::item_info(thumb(&again).unwrap())
2676        );
2677    }
2678
2679    #[test]
2680    fn bad_items_and_bad_meta_do_not_fail_the_file() {
2681        // A TIFF offset that runs past the item.
2682        let bad_offset = heif(b"\xFF\xFF\xFF\xFFExif\0\0II*\0", THUMB);
2683        let s = parse(&mut Cursor::new(&bad_offset)).unwrap();
2684        assert!(s.items_of(ItemKind::Exif).next().is_none());
2685        assert!(thumb(&s).is_some());
2686
2687        // A meta box that is not HEIF items at all.
2688        let junk = file(&[
2689            ftyp(),
2690            boxed(b"meta", &[0, 0, 0, 0, 0xde, 0xad, 0xbe, 0xef, 1, 2, 3]),
2691            boxed(b"mdat", b"x"),
2692        ]);
2693        let s = parse(&mut Cursor::new(&junk)).unwrap();
2694        assert!(s.items_of(ItemKind::Exif).next().is_none());
2695        assert!(s
2696            .embedded_thumbnail(&mut Cursor::new(&junk))
2697            .unwrap()
2698            .is_none());
2699    }
2700
2701    /// `ftyp`, a `meta` with `children` and an `iloc` for `items`, whose data lies in
2702    /// the `mdat` that follows in order, then `tail`.
2703    fn heif_file(children: &[Vec<u8>], items: &[(u16, &[u8])], tail: &[Vec<u8>]) -> Vec<u8> {
2704        use heif_items::build::{iloc0, meta};
2705        let build = |at: u32| {
2706            let mut next = at;
2707            let locs: Vec<(u16, [(u32, u32); 1])> = items
2708                .iter()
2709                .map(|(id, d)| {
2710                    let loc = (*id, [(next, d.len() as u32)]);
2711                    next += d.len() as u32;
2712                    loc
2713                })
2714                .collect();
2715            let locs: Vec<(u16, &[(u32, u32)])> =
2716                locs.iter().map(|(id, e)| (*id, &e[..])).collect();
2717            let mut body = children.to_vec();
2718            body.push(iloc0(&locs));
2719            let mut p = vec![0u8; 4]; // version and flags
2720            p.extend_from_slice(&meta(&body));
2721            let data: Vec<u8> = items.iter().flat_map(|(_, d)| d.to_vec()).collect();
2722            let mut parts = vec![ftyp(), boxed(b"meta", &p), boxed(b"mdat", &data)];
2723            parts.extend_from_slice(tail);
2724            file(&parts)
2725        };
2726        let tail_len: usize = tail.iter().map(Vec::len).sum();
2727        let data_len: usize = items.iter().map(|(_, d)| d.len()).sum();
2728        build((build(0).len() - tail_len - data_len) as u32)
2729    }
2730
2731    const PRIMARY_XMP: &[u8] = b"<x:xmpmeta>primary</x:xmpmeta>";
2732    const THUMB_XMP: &[u8] = b"<x:xmpmeta>thumb</x:xmpmeta>";
2733
2734    /// A HEIF whose primary item is 1, with an EXIF item, a coded thumbnail, two XMP
2735    /// items (5 describes the primary, 4 the thumbnail), an auxiliary PNG and a URI
2736    /// item. With `primary` false there is no `pitm`.
2737    fn heif_with_relations(primary: bool, tail: &[Vec<u8>]) -> Vec<u8> {
2738        use heif_items::build::{iinf, infe, infe_mime, infe_uri, iref, pitm};
2739        let mut children = Vec::new();
2740        if primary {
2741            children.push(pitm(1));
2742        }
2743        children.push(iinf(&[
2744            infe(1, b"hvc1"),
2745            infe(2, b"Exif"),
2746            infe(3, b"hvc1"),
2747            infe_mime(4, b"application/rdf+xml"),
2748            infe_mime(5, b"application/rdf+xml"),
2749            infe_mime(6, b"image/png"),
2750            infe_uri(7, "urn:example:depth"),
2751        ]));
2752        children.push(iref(&[
2753            (b"cdsc", 2, &[1]),
2754            (b"thmb", 3, &[1]),
2755            (b"cdsc", 4, &[3]),
2756            (b"cdsc", 5, &[1]),
2757            (b"auxl", 6, &[1]),
2758        ]));
2759        heif_file(
2760            &children,
2761            &[
2762                (1, b"PRIMARY-CODED"),
2763                (2, EXIF_ITEM),
2764                (3, b"THUMB-CODED"),
2765                (4, THUMB_XMP),
2766                (5, PRIMARY_XMP),
2767                (6, b"PNG-BYTES"),
2768                (7, b"URI-BYTES"),
2769            ],
2770            tail,
2771        )
2772    }
2773
2774    fn by_id(s: &Structure, id: u64) -> &Item {
2775        s.items().find(|e| e.native_id() == Some(id)).unwrap()
2776    }
2777
2778    #[test]
2779    fn heif_items_keep_native_types_ids_and_relations() {
2780        let f = heif_with_relations(true, &[]);
2781        let s = parse(&mut Cursor::new(&f)).unwrap();
2782        let summary: Vec<_> = s
2783            .items()
2784            .map(|e| {
2785                (
2786                    e.native_id().unwrap(),
2787                    e.kind(),
2788                    e.encoding(),
2789                    e.native_type().unwrap(),
2790                    e.relations()
2791                        .iter()
2792                        .map(|r| (r.kind(), r.target()))
2793                        .collect::<Vec<_>>(),
2794                )
2795            })
2796            .collect();
2797        use RelationKind::*;
2798        assert_eq!(
2799            summary,
2800            vec![
2801                (
2802                    2,
2803                    ItemKind::Exif,
2804                    Encoding::Tiff,
2805                    Name::FourCC(*b"Exif"),
2806                    vec![(Describes, 1)]
2807                ),
2808                (
2809                    3,
2810                    ItemKind::Other,
2811                    Encoding::Unknown,
2812                    Name::FourCC(*b"hvc1"),
2813                    vec![(Thumbnail, 1)]
2814                ),
2815                (
2816                    4,
2817                    ItemKind::Xmp,
2818                    Encoding::Xml,
2819                    Name::FourCC(*b"mime"),
2820                    vec![(Describes, 3)]
2821                ),
2822                (
2823                    5,
2824                    ItemKind::Xmp,
2825                    Encoding::Xml,
2826                    Name::FourCC(*b"mime"),
2827                    vec![(Describes, 1)]
2828                ),
2829                (
2830                    6,
2831                    ItemKind::EmbeddedAsset,
2832                    Encoding::Asset,
2833                    Name::FourCC(*b"mime"),
2834                    vec![(Auxiliary, 1)]
2835                ),
2836                (
2837                    7,
2838                    ItemKind::Other,
2839                    Encoding::Unknown,
2840                    Name::FourCC(*b"uri "),
2841                    vec![]
2842                ),
2843            ]
2844        );
2845        assert_eq!(by_id(&s, 6).relations()[0].native(), *b"auxl");
2846        assert_eq!(by_id(&s, 4).media_type(), Some("application/rdf+xml"));
2847        assert!(s.items().all(|e| e.label().is_none()));
2848
2849        // A URI item keeps its URI apart from its label and has no media type.
2850        let uri = by_id(&s, 7);
2851        assert_eq!(uri.uri(), Some("urn:example:depth"));
2852        assert_eq!(uri.media_type(), None);
2853        assert_eq!(
2854            (uri.kind(), uri.encoding()),
2855            (ItemKind::Other, Encoding::Unknown)
2856        );
2857        let assets: Vec<_> = s.embedded_assets().map(|e| e.native_id()).collect();
2858        assert_eq!(assets, vec![Some(6)]);
2859
2860        // The coded thumbnail is not an embedded asset, but it is the thumbnail.
2861        let t = s.embedded_thumbnail(&mut Cursor::new(&f)).unwrap().unwrap();
2862        assert_eq!(
2863            (t.data.as_slice(), t.media_type()),
2864            (&b"THUMB-CODED"[..], None)
2865        );
2866
2867        // The XMP is the item that describes the primary item.
2868        assert_eq!(
2869            s.xmp(&mut Cursor::new(&f)).unwrap().as_deref(),
2870            Some(PRIMARY_XMP)
2871        );
2872        assert!(matches!(
2873            s.item(ItemKind::Xmp),
2874            Err(Error::Ambiguous { count: 2, .. })
2875        ));
2876    }
2877
2878    /// A HEIF whose primary item (1) is described by one XMP item stored with
2879    /// `content_encoding` `encoding`.
2880    fn heif_with_encoded_xmp(encoding: &[u8], stored: &[u8]) -> Vec<u8> {
2881        use heif_items::build::{iinf, infe, infe_mime_encoded, iref, pitm};
2882        heif_file(
2883            &[
2884                pitm(1),
2885                iinf(&[
2886                    infe(1, b"hvc1"),
2887                    infe_mime_encoded(5, b"application/rdf+xml", encoding),
2888                ]),
2889                iref(&[(b"cdsc", 5, &[1])]),
2890            ],
2891            &[(5, stored)],
2892            &[],
2893        )
2894    }
2895
2896    #[cfg(feature = "flate")]
2897    #[test]
2898    fn compressed_xmp_items_are_decoded() {
2899        use crate::testing::compress::{raw_deflate, zlib};
2900        // libheif writes zlib data labelled `deflate` in one path; both decode.
2901        for stored in [raw_deflate(PRIMARY_XMP), zlib(PRIMARY_XMP)] {
2902            let f = heif_with_encoded_xmp(b"deflate", &stored);
2903            let s = parse(&mut Cursor::new(&f)).unwrap();
2904            let e = s.require_item(ItemKind::Xmp).unwrap();
2905            assert_eq!(*e.transfer(), TransferEncoding::Deflate);
2906            assert_eq!(s.read_item(&mut Cursor::new(&f), e).unwrap(), stored);
2907            assert_eq!(
2908                s.xmp(&mut Cursor::new(&f)).unwrap().as_deref(),
2909                Some(PRIMARY_XMP)
2910            );
2911        }
2912    }
2913
2914    #[test]
2915    fn brotli_xmp_items_are_identified_and_need_the_feature() {
2916        let stored = crate::testing::brotli_stored(PRIMARY_XMP);
2917        let f = heif_with_encoded_xmp(b"br", &stored);
2918        let s = parse(&mut Cursor::new(&f)).unwrap();
2919        let e = s.require_item(ItemKind::Xmp).unwrap();
2920        assert_eq!(*e.transfer(), TransferEncoding::Brotli);
2921        // The stored bytes are always readable.
2922        assert_eq!(s.read_item(&mut Cursor::new(&f), e).unwrap(), stored);
2923        let xmp = s.xmp(&mut Cursor::new(&f));
2924        #[cfg(feature = "brotli")]
2925        assert_eq!(xmp.unwrap().as_deref(), Some(PRIMARY_XMP));
2926        #[cfg(not(feature = "brotli"))]
2927        assert!(matches!(xmp, Err(Error::UnsupportedFeature(_))));
2928    }
2929
2930    #[test]
2931    fn heif_xmp_precedence() {
2932        // Without a primary item, two XMP items are not a choice to guess.
2933        let f = heif_with_relations(false, &[]);
2934        let s = parse(&mut Cursor::new(&f)).unwrap();
2935        assert_eq!(s.xmp(&mut Cursor::new(&f)).unwrap(), None);
2936
2937        // A single XMP item is the XMP, whatever it describes.
2938        use heif_items::build::{iinf, infe, infe_mime, iref, pitm};
2939        let one = heif_file(
2940            &[
2941                pitm(1),
2942                iinf(&[infe(1, b"hvc1"), infe_mime(4, b"application/rdf+xml")]),
2943                iref(&[(b"cdsc", 4, &[9])]),
2944            ],
2945            &[(4, THUMB_XMP)],
2946            &[],
2947        );
2948        let s = parse(&mut Cursor::new(&one)).unwrap();
2949        assert_eq!(
2950            s.xmp(&mut Cursor::new(&one)).unwrap().as_deref(),
2951            Some(THUMB_XMP)
2952        );
2953
2954        // An XMP uuid box comes first.
2955        let mut body = XMP_UUID.to_vec();
2956        body.extend_from_slice(b"<box/>");
2957        let with_box = heif_with_relations(true, &[boxed(b"uuid", &body)]);
2958        let s = parse(&mut Cursor::new(&with_box)).unwrap();
2959        assert_eq!(s.items_of(ItemKind::Xmp).count(), 3);
2960        assert_eq!(
2961            s.xmp(&mut Cursor::new(&with_box)).unwrap().as_deref(),
2962            Some(&b"<box/>"[..])
2963        );
2964    }
2965
2966    #[test]
2967    fn xmp_is_written_as_the_box_and_heif_items_are_carried() {
2968        let f = heif_with_relations(true, &[]);
2969        let src = parse(&mut Cursor::new(&f)).unwrap();
2970        for updates in [
2971            Updates::new().set_xmp(b"<new/>".to_vec()),
2972            Updates::new().remove_xmp(),
2973            Updates::new().set_c2pa(b"STORE".to_vec()),
2974        ] {
2975            let out = rewrite(&f, &updates).unwrap();
2976            let s = parse(&mut Cursor::new(&out)).unwrap();
2977            // Every HEIF item survives with the same identity and bytes.
2978            for e in src.items() {
2979                let id = e.native_id().unwrap();
2980                assert_eq!(
2981                    container_api::item_info(by_id(&s, id)),
2982                    container_api::item_info(e)
2983                );
2984                assert_eq!(
2985                    s.read_item(&mut Cursor::new(&out), by_id(&s, id)).unwrap(),
2986                    src.read_item(&mut Cursor::new(&f), e).unwrap()
2987                );
2988            }
2989            let want: &[u8] = match updates.xmp() {
2990                MetadataUpdate::Set(d) => d,
2991                _ => PRIMARY_XMP,
2992            };
2993            assert_eq!(
2994                s.xmp(&mut Cursor::new(&out)).unwrap().as_deref(),
2995                Some(want)
2996            );
2997            // The structure the write returned agrees, primary item included.
2998            let planned = src.plan(&mut Cursor::new(&f), &updates).unwrap();
2999            assert_eq!(
3000                planned.xmp(&mut Cursor::new(&out)).unwrap().as_deref(),
3001                Some(want)
3002            );
3003        }
3004    }
3005
3006    #[test]
3007    fn item_data_is_split_where_it_crosses_boxes() {
3008        let a = SegmentId::from_index(0).unwrap();
3009        let b = SegmentId::from_index(1).unwrap();
3010        let placed = [(a, 0u64, 10u64), (b, 10, 10)];
3011        let parts = split_over_segments(&placed, 6, 8).unwrap().unwrap();
3012        assert_eq!(
3013            parts,
3014            vec![
3015                (a, ByteRange::new(6, 4).unwrap()),
3016                (b, ByteRange::new(10, 4).unwrap())
3017            ]
3018        );
3019        // Past the end of the file: not placed.
3020        assert!(split_over_segments(&placed, 18, 5).unwrap().is_none());
3021        assert!(split_over_segments(&placed, 25, 1).unwrap().is_none());
3022    }
3023
3024    #[test]
3025    fn iloc_offsets_follow() {
3026        let build = |v: u32| {
3027            let mut iloc = vec![0x44, 0x00];
3028            iloc.extend_from_slice(&1u16.to_be_bytes()); // items
3029            iloc.extend_from_slice(&1u16.to_be_bytes()); // id
3030            iloc.extend_from_slice(&0u16.to_be_bytes()); // data reference
3031            iloc.extend_from_slice(&1u16.to_be_bytes()); // extents
3032            iloc.extend_from_slice(&v.to_be_bytes());
3033            iloc.extend_from_slice(&5u32.to_be_bytes());
3034            let mut meta = vec![0u8; 4];
3035            meta.extend_from_slice(&full(b"iloc", 0, 0, &iloc));
3036            file(&[ftyp(), boxed(b"meta", &meta), boxed(b"mdat", b"MEDIA")])
3037        };
3038        let media = (build(0).len() - 5) as u32;
3039        let f = build(media);
3040        let out = rewrite(&f, &Updates::new().set_c2pa(b"STORE".to_vec())).unwrap();
3041        let (off, _, hl) = find(&out, "/meta/iloc");
3042        let v = be32(&out, off + hl as u64 + 4 + 10);
3043        assert_eq!(v, media + 50);
3044        assert!(media_at(&out, v));
3045    }
3046
3047    /// A movie fragment and a fragment-random-access box that both record where
3048    /// the `moof` is, which is `FRAGMENT_BASE`.
3049    const FRAGMENT_BASE: u64 = 20;
3050
3051    fn fragmented() -> Vec<u8> {
3052        let base = FRAGMENT_BASE; // the moof starts right after ftyp
3053        let mut tfhd = 1u32.to_be_bytes().to_vec();
3054        tfhd.extend_from_slice(&base.to_be_bytes());
3055        let moof = boxed(b"moof", &boxed(b"traf", &full(b"tfhd", 0, 1, &tfhd)));
3056        let mut tfra = 1u32.to_be_bytes().to_vec(); // track
3057        tfra.extend_from_slice(&0u32.to_be_bytes()); // entry field sizes
3058        tfra.extend_from_slice(&1u32.to_be_bytes()); // entries
3059        tfra.extend_from_slice(&0u32.to_be_bytes()); // time
3060        tfra.extend_from_slice(&(base as u32).to_be_bytes()); // moof offset
3061        tfra.extend_from_slice(&[1, 1, 1]);
3062        let mfra = boxed(b"mfra", &full(b"tfra", 0, 0, &tfra));
3063        file(&[ftyp(), moof, boxed(b"mdat", b"MEDIA"), mfra])
3064    }
3065
3066    #[test]
3067    fn fragment_offsets_follow() {
3068        let base = FRAGMENT_BASE;
3069        let f = fragmented();
3070
3071        let out = rewrite(&f, &Updates::new().set_c2pa(b"STORE".to_vec())).unwrap();
3072        let moof_at = find(&out, "/moof").0;
3073        assert_eq!(moof_at, base + 50);
3074        let (off, _, hl) = find(&out, "/moof/traf/tfhd");
3075        let b = u64::from_be_bytes(
3076            out[(off + hl as u64 + 4 + 4) as usize..][..8]
3077                .try_into()
3078                .unwrap(),
3079        );
3080        assert_eq!(b, moof_at);
3081        let (off, _, hl) = find(&out, "/mfra/tfra");
3082        assert_eq!(be32(&out, off + hl as u64 + 4 + 12 + 4) as u64, moof_at);
3083    }
3084
3085    fn moof_at(base: u64) -> Vec<u8> {
3086        let mut tfhd = 1u32.to_be_bytes().to_vec();
3087        tfhd.extend_from_slice(&base.to_be_bytes());
3088        boxed(b"moof", &boxed(b"traf", &full(b"tfhd", 0, 1, &tfhd)))
3089    }
3090
3091    /// A flat fragmented file of two `moof`/`mdat` pairs, each `moof` recording its
3092    /// own offset.
3093    fn two_fragments() -> Vec<u8> {
3094        let pair = moof_at(0).len() as u64 + boxed(b"mdat", b"MEDIA").len() as u64;
3095        file(&[
3096            ftyp(),
3097            moof_at(FRAGMENT_BASE),
3098            boxed(b"mdat", b"MEDIA"),
3099            moof_at(FRAGMENT_BASE + pair),
3100            boxed(b"mdat", b"MEDIA"),
3101        ])
3102    }
3103
3104    /// The end of each merkle box, the offset of each `moof` and the base data
3105    /// offset each `moof`'s `tfhd` records.
3106    fn merkle_ends_moofs_and_bases(out: &[u8]) -> (Vec<u64>, Vec<u64>, Vec<u64>) {
3107        let s = parse(&mut Cursor::new(out)).unwrap();
3108        let ends = s
3109            .items_labelled(ItemKind::Other, MERKLE)
3110            .map(|e| {
3111                s.segment(e.extents().next().unwrap().segment())
3112                    .unwrap()
3113                    .range()
3114                    .end()
3115            })
3116            .collect();
3117        let walked = walk_paths(&s, out);
3118        let at = |path: &str| -> Vec<u64> {
3119            walked
3120                .iter()
3121                .filter(|(p, _, _)| p == path)
3122                .map(|&(_, offset, _)| offset)
3123                .collect()
3124        };
3125        let bases = at("/moof/traf/tfhd")
3126            .into_iter()
3127            .map(|off| u64::from_be_bytes(out[(off + 16) as usize..][..8].try_into().unwrap()))
3128            .collect();
3129        (ends, at("/moof"), bases)
3130    }
3131
3132    #[test]
3133    fn a_merkle_box_precedes_the_moof_of_a_fragment() {
3134        let out = rewrite(
3135            &fragmented(),
3136            &Updates::new().set_merkle(vec![vec![7u8; 6]]),
3137        )
3138        .unwrap();
3139        let s = parse(&mut Cursor::new(&out)).unwrap();
3140        assert_eq!(merkle_payloads(&s, &out), vec![vec![7u8; 6]]);
3141        let (ends, moofs, bases) = merkle_ends_moofs_and_bases(&out);
3142        // Right before the moof, which has moved, as everything that records it.
3143        assert_eq!(ends, moofs);
3144        assert!(moofs[0] > FRAGMENT_BASE);
3145        assert_eq!(bases, moofs);
3146        let (off, _, hl) = find(&out, "/mfra/tfra");
3147        assert_eq!(be32(&out, off + hl as u64 + 4 + 12 + 4) as u64, moofs[0]);
3148    }
3149
3150    #[test]
3151    fn a_merkle_box_precedes_each_moof_of_a_flat_fragmented_file() {
3152        let out = rewrite(
3153            &two_fragments(),
3154            &Updates::new().set_merkle(vec![vec![1u8; 4], vec![2u8; 4]]),
3155        )
3156        .unwrap();
3157        let s = parse(&mut Cursor::new(&out)).unwrap();
3158        assert_eq!(merkle_payloads(&s, &out), vec![vec![1u8; 4], vec![2u8; 4]]);
3159        let (ends, moofs, bases) = merkle_ends_moofs_and_bases(&out);
3160        assert_eq!(ends, moofs);
3161        assert_eq!(moofs.len(), 2);
3162        assert_eq!(bases, moofs);
3163    }
3164
3165    #[test]
3166    fn fragmented_merkle_boxes_need_one_payload_per_moof() {
3167        for payloads in [vec![], vec![vec![0u8; 4]], vec![vec![0u8; 4]; 3]] {
3168            let n = payloads.len();
3169            let result = rewrite(&two_fragments(), &Updates::new().set_merkle(payloads));
3170            assert!(result.is_err(), "{n} payloads for two moof boxes");
3171        }
3172    }
3173
3174    #[test]
3175    fn fragmented_merkle_boxes_are_replaced_and_removed_in_place() {
3176        let first = rewrite(
3177            &two_fragments(),
3178            &Updates::new().set_merkle(vec![vec![1u8; 4], vec![2u8; 4]]),
3179        )
3180        .unwrap();
3181        // A new set replaces the old, of a different size, and stays in front.
3182        let second = rewrite(
3183            &first,
3184            &Updates::new().set_merkle(vec![vec![3u8; 9], vec![4u8; 9]]),
3185        )
3186        .unwrap();
3187        let s = parse(&mut Cursor::new(&second)).unwrap();
3188        assert_eq!(
3189            merkle_payloads(&s, &second),
3190            vec![vec![3u8; 9], vec![4u8; 9]]
3191        );
3192        let (ends, moofs, bases) = merkle_ends_moofs_and_bases(&second);
3193        assert_eq!((&ends, &bases), (&moofs, &moofs));
3194
3195        let removed = rewrite(&second, &Updates::new().remove_merkle()).unwrap();
3196        assert_eq!(removed, two_fragments());
3197    }
3198
3199    #[test]
3200    fn a_manifest_and_fragment_merkle_boxes_keep_offsets_right() {
3201        let out = rewrite(
3202            &two_fragments(),
3203            &Updates::new()
3204                .set_c2pa(b"STORE".to_vec())
3205                .set_merkle(vec![vec![1u8; 4], vec![2u8; 4]]),
3206        )
3207        .unwrap();
3208        let (ends, moofs, bases) = merkle_ends_moofs_and_bases(&out);
3209        assert_eq!((&ends, &bases), (&moofs, &moofs));
3210        let s = parse(&mut Cursor::new(&out)).unwrap();
3211        assert!(s.c2pa_item().unwrap().is_some());
3212    }
3213}