asset-io 0.8.1

Streaming, container-agnostic access to media file structure and metadata (JUMBF, XMP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
// Copyright 2026 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.

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

//! PNG on the structure model.
//!
//! Each chunk is one segment: `length(4) type(4) [iTXt prefix]` is the header,
//! the chunk data is the payload, and the CRC is the trailer. The `caBX` chunk is
//! an [`ItemKind::C2pa`] item, `eXIf` an [`ItemKind::Exif`] item and an XMP `iTXt`
//! chunk an [`ItemKind::Xmp`] item, each in a [`Metadata`](SegmentKind::Metadata)
//! segment; `IDAT` chunks are [`MediaData`](SegmentKind::MediaData). A compressed
//! XMP `iTXt` (method 0) is an XMP item whose bytes are the compressed text, with a
//! [`Zlib`](TransferEncoding::Zlib) transfer encoding. New XMP is written
//! uncompressed.

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

use crate::{
    container_api::{
        BoxFuture, ContainerHandler, Crc32, Existing, FormatSpec, Io, ItemInfo, MetadataSlot,
        PlanBuilder, ReadWriteSeek, StructureBuilder, WritePlan,
    },
    Error, ItemKind, Name, Result, Segment, SegmentId, SegmentKind, Structure, TransferEncoding,
    Updates,
};

const SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
const ITXT: [u8; 4] = *b"iTXt";
const CABX: [u8; 4] = *b"caBX";
const IEND: [u8; 4] = *b"IEND";
const IDAT: [u8; 4] = *b"IDAT";
const FCTL: [u8; 4] = *b"fcTL";
const EXIF: [u8; 4] = *b"eXIf";

/// `keyword NUL`, compression flag, compression method, empty language tag NUL,
/// empty translated keyword NUL.
const XMP_PREFIX_LEN: usize = 22;
const XMP_ITXT_PREFIX: &[u8; XMP_PREFIX_LEN] = b"XML:com.adobe.xmp\0\0\0\0\0";
const XMP_KEYWORD: &[u8] = b"XML:com.adobe.xmp\0";

/// Largest legal chunk data length (PNG spec: 2^31 - 1).
const MAX_CHUNK_LEN: u64 = 0x7fff_ffff;

/// How much of an iTXt chunk to look at when deciding whether it holds XMP.
const PEEK: usize = 256;

/// Length of the iTXt prefix if this chunk's data begins an uncompressed XMP
/// iTXt; `None` otherwise.
fn xmp_prefix_len(buf: &[u8]) -> Option<(usize, TransferEncoding)> {
    if buf.len() < XMP_KEYWORD.len() + 2 || &buf[..XMP_KEYWORD.len()] != XMP_KEYWORD {
        return None;
    }
    let mut i = XMP_KEYWORD.len();
    // Compression flag and method: 0 is plain text, 1 with method 0 is zlib.
    let transfer = match (buf[i], buf[i + 1]) {
        (0, _) => TransferEncoding::Identity,
        (1, 0) => TransferEncoding::Zlib {
            png_predictor_columns: None,
        },
        _ => return None,
    };
    i += 2;
    i += buf[i..].iter().position(|&b| b == 0)? + 1; // language tag
    i += buf[i..].iter().position(|&b| b == 0)? + 1; // translated keyword
    Some((i, transfer))
}

/// The PNG container handler.
#[derive(Debug, Clone, Copy, Default)]
pub struct PngHandler;

/// The shared PNG handler.
pub fn handler() -> Arc<dyn ContainerHandler> {
    Arc::new(PngHandler)
}

/// The PNG container's [`ContainerHandler::id`].
pub const ID: &str = "png";

impl ContainerHandler for PngHandler {
    fn id(&self) -> &'static str {
        ID
    }

    fn formats(&self) -> &[FormatSpec] {
        const F: &[FormatSpec] = &[FormatSpec::new("image/png", "png")];
        F
    }

    fn detect(&self, header: &[u8]) -> bool {
        header.starts_with(SIGNATURE)
    }

    fn parse_async(self: Arc<Self>, io: Io) -> BoxFuture<'static, Result<Structure>> {
        Box::pin(parse_with(self, io))
    }

    // A PNG write needs nothing from the source to be planned.
    fn write_plan_async<'f, 'a: 'f>(
        &'f self,
        src_structure: &'f Structure,
        _io: Io,
        updates: &'a Updates,
    ) -> BoxFuture<'f, Result<WritePlan<'a>>> {
        Box::pin(async move { plan(src_structure, updates) })
    }

    fn compose(&self, kind: ItemKind, data: &[u8]) -> Result<Vec<u8>> {
        let op = match kind {
            ItemKind::C2pa => new_chunk(kind, CABX, &[], data)?,
            ItemKind::Xmp => new_chunk(kind, ITXT, XMP_ITXT_PREFIX, data)?,
            _ => return Err(Error::UnsupportedFormat),
        };
        let Op::New {
            ty,
            prefix,
            payload,
            ..
        } = op
        else {
            return Err(Error::UnsupportedFormat);
        };
        let mut out = Vec::with_capacity(12 + prefix.len() + payload.len());
        let (hdr, n) = chunk_header(&ty, prefix, payload.len());
        out.extend_from_slice(&hdr[..n]);
        out.extend_from_slice(payload);
        out.extend_from_slice(&chunk_crc(&ty, prefix, payload));
        Ok(out)
    }

    fn fix_trailer(
        &self,
        mut out: &mut dyn ReadWriteSeek,
        structure: &Structure,
        segment: SegmentId,
    ) -> Result<()> {
        fix_crc(&mut out, structure.segment(segment)?)
    }
}

/// Parse a PNG into a validated structure.
#[cfg(test)]
fn parse<R: Read + Seek>(src: &mut R) -> Result<Structure> {
    handler().parse(src)
}

async fn parse_with(handler: Arc<dyn ContainerHandler>, mut io: Io) -> Result<Structure> {
    let total = io.len();
    if total < SIGNATURE.len() as u64 + 12 {
        return Err(Error::InvalidFormat("PNG too small".into()));
    }
    let mut r = io.reader(0);
    if &r.array::<8>().await? != SIGNATURE {
        return Err(Error::InvalidFormat("Not a PNG file".into()));
    }

    let mut b = StructureBuilder::new(handler, "image/png", total);
    // Named PNGh so a hasher listing every box sees the preamble as the first one.
    b.push_span(SegmentKind::Preamble, Name::FourCC(*b"PNGh"), 8, 0, 0)?;

    let mut offset = 8u64;
    let mut found_iend = false;
    while !found_iend {
        let remaining = total - offset;
        if remaining < 12 {
            return Err(Error::InvalidFormat("PNG truncated: missing IEND".into()));
        }
        r.seek(offset);
        let hdr = r.array::<8>().await?;
        let len = u32::from_be_bytes([hdr[0], hdr[1], hdr[2], hdr[3]]) as u64;
        let ty = [hdr[4], hdr[5], hdr[6], hdr[7]];
        if len > MAX_CHUNK_LEN {
            return Err(Error::invalid_segment(
                offset,
                format!("chunk length too large: {len}"),
            ));
        }
        let chunk_len = 12 + len;
        if chunk_len > remaining {
            return Err(Error::invalid_segment(
                offset,
                "chunk extends past end of file",
            ));
        }

        let mut prefix = 0u64;
        let mut transfer = TransferEncoding::Identity;
        let item = match ty {
            CABX => Some(ItemKind::C2pa),
            EXIF => Some(ItemKind::Exif),
            ITXT => {
                let n = len.min(PEEK as u64) as usize;
                xmp_prefix_len(r.take(n).await?).map(|(p, t)| {
                    prefix = p as u64;
                    transfer = t;
                    ItemKind::Xmp
                })
            }
            _ => None,
        };

        let (name, header_len, payload_len) = (Name::FourCC(ty), 8 + prefix as u32, len - prefix);
        match item {
            Some(kind) => {
                let info = item_info(kind).transfer(transfer);
                b.push_item(
                    SegmentKind::Metadata,
                    name,
                    header_len,
                    payload_len,
                    4,
                    info,
                )?;
            }
            None => {
                let kind = if ty == IDAT {
                    SegmentKind::MediaData
                } else {
                    SegmentKind::Other
                };
                b.push_span(kind, name, header_len, payload_len, 4)?;
            }
        }

        offset += chunk_len;
        found_iend = ty == IEND;
    }

    // The chunks through IEND are the structure; anything after is data beyond it.
    b.end_boxes()?;
    b.push_tail()?;
    b.finish()
}

/// What a PNG metadata item is.
fn item_info(kind: ItemKind) -> ItemInfo {
    match kind {
        ItemKind::Xmp => ItemInfo::xmp(),
        ItemKind::C2pa => ItemInfo::c2pa(),
        _ => ItemInfo::exif(),
    }
}

/// One planned output chunk.
enum Op<'a> {
    /// Copy a source segment unchanged.
    Copy(SegmentId),
    /// Emit a new chunk holding an item of `kind`.
    New {
        kind: ItemKind,
        ty: [u8; 4],
        prefix: &'static [u8],
        payload: &'a [u8],
    },
}

fn new_chunk<'a>(
    kind: ItemKind,
    ty: [u8; 4],
    prefix: &'static [u8],
    payload: &'a [u8],
) -> Result<Op<'a>> {
    if (prefix.len() as u64).saturating_add(payload.len() as u64) > MAX_CHUNK_LEN {
        return Err(Error::LimitExceeded {
            what: "PNG chunk length",
            limit: MAX_CHUNK_LEN,
        });
    }
    Ok(Op::New {
        kind,
        ty,
        prefix,
        payload,
    })
}

/// Decide what the output contains. This is the single source of truth for
/// both the destination structure and the bytes written.
fn plan<'a>(src: &Structure, updates: &'a Updates) -> Result<WritePlan<'a>> {
    let mut ops: Vec<Op<'a>> = Vec::with_capacity(src.segments().len() + 2);
    let mut xmp = MetadataSlot::new(updates.xmp());
    let mut jumbf = MetadataSlot::new(updates.c2pa());
    let has_jumbf = src.items_of(ItemKind::C2pa).next().is_some();

    for (i, seg) in src.segments().iter().enumerate() {
        let id = SegmentId::from_index(i)?;
        match src.items_in(id).next().map(|e| e.kind()) {
            Some(ItemKind::Xmp) => match xmp.existing() {
                Existing::Keep => ops.push(Op::Copy(id)),
                Existing::Replace(d) => {
                    ops.push(new_chunk(ItemKind::Xmp, ITXT, XMP_ITXT_PREFIX, d)?)
                }
                _ => {}
            },
            Some(ItemKind::C2pa) => match jumbf.existing() {
                Existing::Keep => ops.push(Op::Copy(id)),
                Existing::Replace(d) => ops.push(new_chunk(ItemKind::C2pa, CABX, &[], d)?),
                _ => {}
            },
            _ => {
                // C2PA A.3.2: the caBX chunk should precede the IDAT chunks. Insert
                // before the first IDAT, or before an APNG fcTL that directly
                // precedes it so the frame-control chunk stays with its data.
                // Only when there is nothing to replace: an existing manifest keeps
                // its position (C2PA 11.2.3: an update must not move the store).
                if !has_jumbf && seg.name() == Name::FourCC(IDAT) {
                    if let Some(d) = jumbf.pending() {
                        let op = new_chunk(ItemKind::C2pa, CABX, &[], d)?;
                        let after_fctl = matches!(
                            ops.last(),
                            Some(Op::Copy(p)) if src.segments()[p.index()].name() == Name::FourCC(FCTL)
                        );
                        if after_fctl {
                            let fctl = ops.pop().ok_or(Error::NotFound { what: "fcTL op" })?;
                            ops.push(op);
                            ops.push(fctl);
                        } else {
                            ops.push(op);
                        }
                    }
                }
                if seg.name() == Name::FourCC(IEND) {
                    if let Some(d) = xmp.pending() {
                        ops.push(new_chunk(ItemKind::Xmp, ITXT, XMP_ITXT_PREFIX, d)?);
                    }
                    if let Some(d) = jumbf.pending() {
                        ops.push(new_chunk(ItemKind::C2pa, CABX, &[], d)?);
                    }
                }
                ops.push(Op::Copy(id));
            }
        }
    }

    let mut b = PlanBuilder::new(src);
    for op in ops {
        match op {
            Op::Copy(sid) => {
                b.copy_segment(sid)?;
            }
            Op::New {
                kind,
                ty,
                prefix,
                payload,
            } => {
                let (hdr, n) = chunk_header(&ty, prefix, payload.len());
                let id = b.put_segment(
                    SegmentKind::Metadata,
                    Name::FourCC(ty),
                    hdr[..n].to_vec(),
                    payload,
                    chunk_crc(&ty, prefix, payload).to_vec(),
                )?;
                b.item(item_info(kind), &[id])?;
            }
        }
    }
    b.carry_items(|_| true);
    b.finish()
}

/// Length, type and prefix of a new chunk; returns the bytes and how many are used.
/// The length was bounded by [`new_chunk`].
fn chunk_header(
    ty: &[u8; 4],
    prefix: &[u8],
    payload_len: usize,
) -> ([u8; 8 + XMP_PREFIX_LEN], usize) {
    let data_len = (prefix.len() + payload_len) as u32;
    let mut hdr = [0u8; 8 + XMP_PREFIX_LEN];
    hdr[0..4].copy_from_slice(&data_len.to_be_bytes());
    hdr[4..8].copy_from_slice(ty);
    hdr[8..8 + prefix.len()].copy_from_slice(prefix);
    (hdr, 8 + prefix.len())
}

/// The checksum of a new chunk, which covers its type and data.
fn chunk_crc(ty: &[u8; 4], prefix: &[u8], payload: &[u8]) -> [u8; 4] {
    let mut crc = Crc32::new();
    crc.update(ty);
    crc.update(prefix);
    crc.update(payload);
    crc.finalize().to_be_bytes()
}

/// Recompute and store the CRC of the chunk in `seg` by reading it back from `out`.
pub(crate) fn fix_crc<W: Read + Write + Seek>(out: &mut W, seg: &Segment) -> Result<()> {
    let trailer = seg.trailer();
    if trailer.len() != 4 || seg.header().len() < 8 {
        return Err(Error::invalid_segment(
            seg.range().offset(),
            "not a PNG chunk",
        ));
    }
    // CRC covers type + data: everything after the 4-byte length, before the CRC.
    let start = seg.range().offset() + 4;
    let mut remaining = trailer.offset() - start;
    out.seek(SeekFrom::Start(start))?;
    let mut crc = Crc32::new();
    let mut buf = [0u8; 8192];
    while remaining > 0 {
        let n = remaining.min(buf.len() as u64) as usize;
        out.read_exact(&mut buf[..n])?;
        crc.update(&buf[..n]);
        remaining -= n as u64;
    }
    out.seek(SeekFrom::Start(trailer.offset()))?;
    out.write_all(&crc.finalize().to_be_bytes())?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::*;
    use crate::testing::{c2pa_store_of_len, rewrite, Conformance};

    fn chunk(ty: &[u8; 4], data: &[u8]) -> Vec<u8> {
        let mut v = Vec::new();
        v.extend_from_slice(&(data.len() as u32).to_be_bytes());
        v.extend_from_slice(ty);
        v.extend_from_slice(data);
        let mut c = Crc32::new();
        c.update(ty);
        c.update(data);
        v.extend_from_slice(&c.finalize().to_be_bytes());
        v
    }

    fn sample_png() -> Vec<u8> {
        let mut v = SIGNATURE.to_vec();
        v.extend(chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]));
        v.extend(chunk(b"IDAT", &[1, 2, 3, 4, 5, 6, 7, 8]));
        v.extend(chunk(b"IEND", &[]));
        v
    }

    /// Every chunk's stored CRC matches its contents.
    fn verify_crcs(bytes: &[u8]) {
        let s = parse(&mut Cursor::new(bytes.to_vec())).unwrap();
        for seg in s.segments().iter().skip(1) {
            if seg.trailer().len() != 4 {
                continue;
            }
            let e = seg.range();
            let body = &bytes[(e.offset() + 4) as usize..seg.trailer().offset() as usize];
            let stored = &bytes[seg.trailer().offset() as usize..e.end() as usize];
            let mut c = Crc32::new();
            c.update(body);
            assert_eq!(
                stored,
                &c.finalize().to_be_bytes()[..],
                "bad CRC at {}",
                e.offset()
            );
        }
    }

    /// Chunk type names of the output, in order.
    fn order_after_set(png: &[u8]) -> Vec<String> {
        let updates = Updates::new().set_c2pa(c2pa_store_of_len(64));
        let (_, dest) = rewrite(handler(), png, &updates).unwrap();
        dest.segments()
            .iter()
            .skip(1)
            .map(|g| match g.name() {
                Name::FourCC(t) => String::from_utf8_lossy(&t).into_owned(),
                _ => "?".into(),
            })
            .collect()
    }

    #[test]
    fn new_cabx_precedes_idat() {
        // C2PA A.3.2: caBX should precede the IDAT chunks, not sit before IEND.
        let mut v = SIGNATURE.to_vec();
        v.extend(chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]));
        v.extend(chunk(b"tEXt", b"k\0v"));
        v.extend(chunk(b"IDAT", &[1, 2, 3, 4]));
        v.extend(chunk(b"IDAT", &[5, 6, 7, 8]));
        v.extend(chunk(b"IEND", &[]));
        assert_eq!(
            order_after_set(&v),
            ["IHDR", "tEXt", "caBX", "IDAT", "IDAT", "IEND"]
        );
    }

    fn apng() -> Vec<u8> {
        let mut v = SIGNATURE.to_vec();
        v.extend(chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]));
        v.extend(chunk(b"acTL", &[0, 0, 0, 2, 0, 0, 0, 0]));
        v.extend(chunk(b"fcTL", &[0u8; 26]));
        v.extend(chunk(b"IDAT", &[1, 2, 3, 4]));
        v.extend(chunk(b"IEND", &[]));
        v
    }

    fn with_manifest() -> Vec<u8> {
        let mut v = SIGNATURE.to_vec();
        v.extend(chunk(b"IHDR", &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0]));
        v.extend(chunk(b"IDAT", &[1, 2, 3, 4]));
        v.extend(chunk(b"caBX", &c2pa_store_of_len(48)));
        v.extend(chunk(b"IEND", &[]));
        v
    }

    #[test]
    fn new_cabx_stays_ahead_of_apng_fctl() {
        assert_eq!(
            order_after_set(&apng()),
            ["IHDR", "acTL", "caBX", "fcTL", "IDAT", "IEND"]
        );
    }

    #[test]
    fn existing_cabx_is_replaced_in_place() {
        // Position of an existing manifest is kept; no second one is added.
        assert_eq!(
            order_after_set(&with_manifest()),
            ["IHDR", "IDAT", "caBX", "IEND"]
        );
    }

    #[test]
    fn conforms() {
        let c = Conformance::new(handler()).c2pa(Some(c2pa_store_of_len(64)));
        c.check("plain", &sample_png());
        c.check("with a manifest", &with_manifest());
        c.check("apng", &apng());
    }

    #[test]
    fn rejects_truncated_and_oversized_chunks() {
        let mut png = sample_png();
        png.truncate(png.len() - 5);
        assert!(parse(&mut Cursor::new(png)).is_err());

        let mut bad = SIGNATURE.to_vec();
        bad.extend_from_slice(&0x7fff_fff0u32.to_be_bytes());
        bad.extend_from_slice(b"IDAT");
        bad.extend_from_slice(&[0; 16]);
        assert!(parse(&mut Cursor::new(bad)).is_err());
    }

    #[test]
    fn trailing_bytes_are_kept_in_structure() {
        let mut png = sample_png();
        png.extend_from_slice(b"trailing");
        let s = parse(&mut Cursor::new(png.clone())).unwrap();
        assert_eq!(s.segments().last().unwrap().range().len(), 8);
    }

    #[test]
    fn data_after_iend_is_reported_as_trailing() {
        let clean = sample_png();
        let s = parse(&mut Cursor::new(clean.clone())).unwrap();
        assert_eq!(s.trailing(), None);

        let mut png = clean.clone();
        png.extend_from_slice(b"trailing");
        let s = parse(&mut Cursor::new(png.clone())).unwrap();
        let t = s.trailing().unwrap();
        assert_eq!((t.offset(), t.len()), (clean.len() as u64, 8));

        // An edit moves it with the file, and what was planned is what is written.
        let updates = Updates::new().set_c2pa(vec![0xab; 100]);
        let mut out = Cursor::new(Vec::new());
        let dest = s
            .write(
                &mut Cursor::new(png.clone()),
                &mut out,
                &updates,
                &mut crate::NullSink,
            )
            .unwrap();
        let out = out.into_inner();
        let re = parse(&mut Cursor::new(out.clone())).unwrap();
        assert_eq!(dest.trailing(), re.trailing());
        assert_eq!(
            &out[re.trailing().unwrap().offset() as usize..],
            b"trailing"
        );
    }

    #[test]
    fn new_chunks_have_valid_crcs() {
        let png = sample_png();
        let s = parse(&mut Cursor::new(png.clone())).unwrap();
        let updates = Updates::new()
            .set_c2pa(vec![0xab; 100])
            .set_xmp(b"<x/>".to_vec());
        let mut out = Cursor::new(Vec::new());
        s.write(
            &mut Cursor::new(png),
            &mut out,
            &updates,
            &mut crate::NullSink,
        )
        .unwrap();
        verify_crcs(&out.into_inner());
    }

    #[test]
    fn patch_updates_payload_and_crc() {
        let png = sample_png();
        let s = parse(&mut Cursor::new(png.clone())).unwrap();
        let updates = Updates::new().set_c2pa(vec![0u8; 64]);
        let mut out = Cursor::new(Vec::new());
        let dest = s
            .write(
                &mut Cursor::new(png),
                &mut out,
                &updates,
                &mut crate::NullSink,
            )
            .unwrap();

        let e = dest.require_item(ItemKind::C2pa).unwrap().clone();
        dest.patch(&mut out, &e, b"signed manifest").unwrap();
        let bytes = out.into_inner();
        verify_crcs(&bytes);

        let re = parse(&mut Cursor::new(bytes.clone())).unwrap();
        let e = re.require_item(ItemKind::C2pa).unwrap();
        let data = re.read_item(&mut Cursor::new(bytes), e).unwrap();
        assert_eq!(&data[..15], b"signed manifest");
        assert!(data[15..].iter().all(|&b| b == 0));
        assert_eq!(data.len(), 64);
    }

    #[test]
    fn xmp_round_trip_and_compressed_itxt_is_zlib_xmp() {
        let png = sample_png();
        let s = parse(&mut Cursor::new(png.clone())).unwrap();
        let updates = Updates::new().set_xmp(b"<x/>".to_vec());
        let mut out = Cursor::new(Vec::new());
        s.write(
            &mut Cursor::new(png),
            &mut out,
            &updates,
            &mut crate::NullSink,
        )
        .unwrap();
        let bytes = out.into_inner();
        verify_crcs(&bytes);
        let re = parse(&mut Cursor::new(bytes.clone())).unwrap();
        let e = re.require_item(ItemKind::Xmp).unwrap();
        assert_eq!(re.read_item(&mut Cursor::new(bytes), e).unwrap(), b"<x/>");

        // Same keyword with the compression flag set: XMP stored as zlib, whose
        // item is the compressed text.
        let compressed = |method: u8, text: &[u8]| {
            let mut data = XMP_ITXT_PREFIX.to_vec();
            data[18] = 1;
            data[19] = method;
            data.extend_from_slice(text);
            let mut p = SIGNATURE.to_vec();
            p.extend(chunk(b"iTXt", &data));
            p.extend(chunk(b"IEND", &[]));
            p
        };
        let p = compressed(0, b"zzz");
        let s = parse(&mut Cursor::new(p.clone())).unwrap();
        let e = s.require_item(ItemKind::Xmp).unwrap();
        assert_eq!(
            *e.transfer(),
            TransferEncoding::Zlib {
                png_predictor_columns: None
            }
        );
        assert_eq!(s.read_item(&mut Cursor::new(p.clone()), e).unwrap(), b"zzz");
        // An unknown compression method is not XMP.
        let s = parse(&mut Cursor::new(compressed(1, b"zzz"))).unwrap();
        assert!(s.item(ItemKind::Xmp).unwrap().is_none());

        // Replacing or removing it treats it as any XMP item.
        for (updates, want) in [
            (Updates::new().set_xmp(b"<y/>".to_vec()), Some(&b"<y/>"[..])),
            (Updates::new().remove_xmp(), None),
        ] {
            let s = parse(&mut Cursor::new(p.clone())).unwrap();
            let mut out = Cursor::new(Vec::new());
            s.write(
                &mut Cursor::new(p.clone()),
                &mut out,
                &updates,
                &mut crate::NullSink,
            )
            .unwrap();
            let bytes = out.into_inner();
            verify_crcs(&bytes);
            let re = parse(&mut Cursor::new(bytes.clone())).unwrap();
            assert_eq!(
                re.items_of(ItemKind::Xmp).count(),
                usize::from(want.is_some())
            );
            if let Some(want) = want {
                let e = re.require_item(ItemKind::Xmp).unwrap();
                assert_eq!(*e.transfer(), TransferEncoding::Identity);
                assert_eq!(re.read_item(&mut Cursor::new(bytes), e).unwrap(), want);
            }
        }
    }

    #[cfg(feature = "flate")]
    #[test]
    fn compressed_xmp_reads_as_its_content() {
        let packet = b"<x:xmpmeta>compressed</x:xmpmeta>";
        let mut data = XMP_ITXT_PREFIX.to_vec();
        data[18] = 1;
        data.extend_from_slice(&crate::testing::compress::zlib(packet));
        let mut p = SIGNATURE.to_vec();
        p.extend(chunk(b"iTXt", &data));
        p.extend(chunk(b"IEND", &[]));
        let s = parse(&mut Cursor::new(p.clone())).unwrap();
        let e = s.require_item(ItemKind::Xmp).unwrap();
        assert_eq!(
            s.read_content(&mut Cursor::new(p.clone()), e).unwrap(),
            packet
        );
        assert_eq!(
            s.xmp(&mut Cursor::new(p)).unwrap().as_deref(),
            Some(&packet[..])
        );
    }
}