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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
// 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.

//! PDF on the structure model: bounded discovery of the catalog's XMP and C2PA
//! stores, without loading the document.
//!
//! This is not a general PDF parser, renderer, sanitizer or C2PA validator. It follows
//! classic tables, cross-reference streams and `/Prev` chains from the final
//! `startxref`, and resolves the current catalog's `/Metadata` and document-level
//! `/AF` C2PA association (compressed object streams are decoded on demand). A stream
//! is a segment holding its payload as it is in the file; the segments between are
//! [`Other`](crate::SegmentKind::Other) bytes, so the structure tiles the file and a
//! hash can skip exactly a store.
//!
//! The XMP metadata stream is an [`ItemKind::Xmp`] item and
//! the C2PA store an [`ItemKind::C2pa`] item, each in its own
//! [`Metadata`](crate::SegmentKind::Metadata) segment. A Flate-compressed store is an
//! item whose bytes are the encoded ones, with a
//! [`Zlib`](crate::TransferEncoding::Zlib) transfer encoding;
//! [`Structure::xmp`](crate::Structure::xmp),
//! [`Structure::c2pa_store`](crate::Structure::c2pa_store) and
//! [`Structure::read_content`](crate::Structure::read_content) decode them. See
//! below for the rules and the limits.
#![doc = include_str!("README.md")]

mod flate;
mod lexer;
mod write;

use std::{
    borrow::Cow,
    collections::{BTreeMap, BTreeSet},
    sync::Arc,
};

use flate::Decode;
use lexer::{
    invalid, required, unsigned, whitespace, Dictionary, Lex, Lexer, Reference, Stop, Value,
    MAX_DEPTH, MAX_SYNTAX_BYTES,
};

use crate::{
    container_api,
    container_api::{
        BoxFuture, ContainerHandler, FormatSpec, Io, ItemInfo, MetadataUpdate, PlanBuilder,
        StructureBuilder, WritePlan, MAX_SEGMENT_SIZE,
    },
    labels,
    transfer::inflate,
    ByteRange, Error, Item, ItemKind, Name, Result, Role, SegmentId, SegmentKind, Structure,
    TransferEncoding, Updates,
};

const MAX_ENTRIES: usize = 1_000_000;
const MAX_CLASSIC_ENTRIES: usize = 100_000;
const MAX_REVISIONS: usize = 128;
const MAX_OBJECTS: usize = 4096;
const MAX_STRUCTURAL_STREAM: usize = 8 * 1024 * 1024;
const MAX_DECODE_WORK: usize = 32 * 1024 * 1024;
const MAX_XREF_STORAGE: usize = 16 * 1024 * 1024;
const MAX_OBJECT_STREAM_ENTRIES: u64 = 100_000;
/// The final `startxref` and `%%EOF` must be this close to the end.
const TAIL: u64 = 1024;
/// `%PDF-1.x` and a line end.
const HEADER_LEN: u64 = 9;

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

/// The PDF handler.
pub fn handler() -> Arc<dyn ContainerHandler> {
    Arc::new(PdfHandler)
}

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

/// What a structure keeps for this handler.
#[derive(Clone, Debug)]
struct PdfState {
    /// Whether the document can be edited, and what an edit needs to know.
    edit: write::State,
}

impl PdfState {
    fn of(structure: &Structure) -> Result<&PdfState> {
        container_api::attachment::<PdfState>(structure)
            .ok_or_else(|| invalid("structure was not parsed by the PDF handler"))
    }
}

impl ContainerHandler for PdfHandler {
    /// The payload of the active revision's store stream. The stores of earlier
    /// revisions are part of the document as it was signed then, so they stay
    /// hashed, and only the active store can be excluded.
    fn c2pa_data_hash_exclusions(
        &self,
        structure: &Structure,
        item: &crate::Item,
    ) -> Result<Vec<crate::ByteRange>> {
        if item.label() == Some(labels::SUPERSEDED) {
            return Err(invalid(
                "only the active PDF revision's C2PA store is excluded from a data hash",
            ));
        }
        item.extents()
            .map(|extent| Ok(structure.segment(extent.segment())?.range()))
            .collect()
    }

    fn id(&self) -> &'static str {
        ID
    }

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

    fn detect(&self, header: &[u8]) -> bool {
        header.len() >= HEADER_LEN as usize
            && &header[..5] == b"%PDF-"
            && ((header[5] == b'1' && header[6] == b'.' && matches!(header[7], b'0'..=b'7'))
                || &header[5..8] == b"2.0")
            && matches!(header[8], b'\r' | b'\n')
    }

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

    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 {
            let mut io = io;
            let c2pa = c2pa_write(src_structure, &mut io, updates).await?;
            plan(src_structure, io.len(), updates, c2pa)
        })
    }

    fn check_patch(&self, structure: &Structure, item: &Item, len: usize) -> Result<()> {
        let state = PdfState::of(structure)?;
        if let Some(refusal) = state.edit.refusal() {
            return Err(refusal);
        }
        if *item.transfer() != TransferEncoding::Identity {
            return Err(Error::UnsupportedFeature(
                "cannot patch compressed PDF metadata in place",
            ));
        }
        if len as u64 != item.len() {
            return Err(invalid(
                "PDF in-place updates require exact-length payloads",
            ));
        }
        Ok(())
    }
}

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

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

// ---------------------------------------------------------------------------
// Cross-reference data
// ---------------------------------------------------------------------------

struct Object {
    value: Value,
    /// Where the stream data starts, if the object is a stream.
    stream: Option<u64>,
}

#[derive(Clone, Copy)]
enum Entry {
    Free,
    Normal { offset: u64, generation: u16 },
    Compressed { container: u32, index: u32 },
}

enum Xrefs {
    Classic(BTreeMap<u32, Entry>),
    Stream {
        ranges: Vec<(u32, u32)>,
        widths: [usize; 3],
        data: Vec<u8>,
    },
}

impl Xrefs {
    fn entry(&self, id: u32) -> Result<Option<Entry>> {
        match self {
            Self::Classic(entries) => Ok(entries.get(&id).copied()),
            Self::Stream {
                ranges,
                widths,
                data,
            } => {
                let mut index = 0usize;
                for &(start, count) in ranges {
                    if id >= start && id - start < count {
                        index += (id - start) as usize;
                        let row = &data[index * widths.iter().sum::<usize>()..];
                        let mut position = 0;
                        let mut fields = [0u64; 3];
                        for (i, &width) in widths.iter().enumerate() {
                            fields[i] = if i == 0 && width == 0 { 1 } else { 0 };
                            for &byte in &row[position..position + width] {
                                fields[i] = (fields[i] << 8) | u64::from(byte);
                            }
                            position += width;
                        }
                        return Ok(Some(match fields[0] {
                            0 => Entry::Free,
                            1 => Entry::Normal {
                                offset: fields[1],
                                generation: u16::try_from(fields[2])
                                    .map_err(|_| invalid("generation overflow"))?,
                            },
                            2 => Entry::Compressed {
                                container: u32::try_from(fields[1])
                                    .map_err(|_| invalid("object stream number overflow"))?,
                                index: u32::try_from(fields[2])
                                    .map_err(|_| invalid("object stream index overflow"))?,
                            },
                            _ => return Err(invalid("unknown cross-reference entry type")),
                        }));
                    }
                    index += count as usize;
                }
                Ok(None)
            }
        }
    }
}

struct ObjectStream {
    id: u32,
    data: Vec<u8>,
    objects: Vec<(u32, usize)>,
    first: usize,
}

/// What the catalog's metadata entries say.
struct CatalogMetadata {
    catalog: Dictionary,
    associated: Vec<Value>,
    active: Option<BTreeSet<Reference>>,
    ranges: Vec<(ByteRange, ItemKind, Option<Decode>)>,
}

// ---------------------------------------------------------------------------
// The parser
// ---------------------------------------------------------------------------

/// Reads objects through an [`Io`], a window at a time. The syntax itself is parsed by
/// [`Lexer`] over bytes in memory; this holds the budgets and the cross-reference
/// chain and decides which bytes to read.
struct Parser<'io> {
    io: &'io mut Io,
    size: u64,
    budget: u64,
    nodes: usize,
    objects: usize,
    xrefs: Vec<Xrefs>,
    /// The `Root` each revision's trailer names, parallel to `xrefs` (newest first).
    roots: Vec<Option<Reference>>,
    /// How many of the newest revisions to look past: objects are found as the
    /// document was at the revision `skip` back.
    skip: usize,
    decoding_left: usize,
    resolving: BTreeSet<Reference>,
    object_stream: Option<ObjectStream>,
    trailer: Dictionary,
    next_id: u32,
}

impl<'io> Parser<'io> {
    fn new(io: &'io mut Io, size: u64) -> Self {
        Self {
            io,
            size,
            budget: MAX_SYNTAX_BYTES,
            nodes: 0,
            objects: 0,
            xrefs: Vec::new(),
            roots: Vec::new(),
            skip: 0,
            decoding_left: MAX_DECODE_WORK,
            resolving: BTreeSet::new(),
            object_stream: None,
            trailer: Dictionary::new(),
            next_id: 0,
        }
    }

    /// Run `f` over the file from `offset`, with a window that grows until `f` has all
    /// the bytes it needs. `f` may run more than once, so it must not keep state.
    async fn lex<T>(&mut self, offset: u64, f: impl Fn(&mut Lexer<'_>) -> Lex<T>) -> Result<T> {
        if offset > self.size {
            return Err(invalid("offset outside file"));
        }
        let remaining = self.size - offset;
        let mut want = 4096u64;
        loop {
            let len = remaining.min(want);
            let data = self.io.read_vec(offset, len as usize).await?;
            let mut lexer = Lexer::new(&data, offset, len == remaining, self.budget, self.nodes);
            match f(&mut lexer) {
                Ok(value) => {
                    self.budget = lexer.budget;
                    self.nodes = lexer.nodes;
                    return Ok(value);
                }
                Err(Stop::Fail(e)) => return Err(e),
                Err(Stop::More) => {
                    if want >= MAX_SYNTAX_BYTES {
                        return Err(invalid("syntax work limit exceeded"));
                    }
                    want = (want * 4).min(MAX_SYNTAX_BYTES);
                }
            }
        }
    }

    /// Read the cross-reference chain from `offset`, returning the document's root.
    async fn xrefs(&mut self, mut offset: u64) -> Result<Reference> {
        let mut root = None;
        let mut entry_count = 0usize;
        let mut classic_count = 0usize;
        let mut storage = 0usize;
        let mut visited = BTreeSet::new();
        for _ in 0..MAX_REVISIONS {
            if !visited.insert(offset) {
                return Err(invalid("cyclic Prev chain"));
            }
            let file_size = self.size;
            let (entries_so_far, classic_so_far) = (entry_count, classic_count);
            let classic = self
                .lex(offset, |lx| {
                    if lx.token()? != b"xref" {
                        return Ok(None);
                    }
                    let (mut entry_count, mut classic_count) = (entries_so_far, classic_so_far);
                    let mut entries = BTreeMap::new();
                    loop {
                        lx.skip_space()?;
                        if lx.peek()? == Some(b't') {
                            break;
                        }
                        let first = lx.number()?;
                        let count = lx.number()?;
                        let count = usize::try_from(count)
                            .map_err(|_| Stop::Fail(invalid("xref count overflow")))?;
                        entry_count = entry_count
                            .checked_add(count)
                            .filter(|n| *n <= MAX_ENTRIES)
                            .ok_or_else(|| {
                                Stop::Fail(invalid("cross-reference entry limit exceeded"))
                            })?;
                        // Classic tables have much higher per-entry overhead than
                        // compact streams.
                        classic_count = classic_count
                            .checked_add(count)
                            .filter(|n| *n <= MAX_CLASSIC_ENTRIES)
                            .ok_or_else(|| {
                                Stop::Fail(invalid("classic cross-reference entry limit exceeded"))
                            })?;
                        let end = first
                            .checked_add(count as u64)
                            .filter(|end| *end <= u64::from(u32::MAX))
                            .ok_or_else(|| Stop::Fail(invalid("xref object number overflow")))?;
                        for id in first..end {
                            let object_offset = lx.number()?;
                            let generation = u16::try_from(lx.number()?)
                                .map_err(|_| Stop::Fail(invalid("generation overflow")))?;
                            let entry = match lx.token()?.as_slice() {
                                b"n" if object_offset < file_size => Entry::Normal {
                                    offset: object_offset,
                                    generation,
                                },
                                b"f" => Entry::Free,
                                _ => {
                                    return Err(Stop::Fail(invalid("invalid xref entry or offset")))
                                }
                            };
                            if entries.insert(id as u32, entry).is_some() {
                                return Err(Stop::Fail(invalid("overlapping xref subsections")));
                            }
                        }
                    }
                    lx.expect(b"trailer")?;
                    let highest = entries.last_key_value().map(|(&id, _)| id);
                    let trailer = lx.value(0)?.dictionary()?;
                    Ok(Some((
                        trailer,
                        Xrefs::Classic(entries),
                        highest,
                        entry_count,
                        classic_count,
                    )))
                })
                .await?;
            let (mut trailer, section, highest) = match classic {
                Some((trailer, section, highest, entries, classic_entries)) => {
                    entry_count = entries;
                    classic_count = classic_entries;
                    (trailer, section, highest)
                }
                None => {
                    let object = self.raw_object(offset, None).await?;
                    let mut dict = object.value.dictionary()?;
                    if !required(&mut dict, b"Type")?.is_name(b"XRef") {
                        return Err(invalid(
                            "startxref does not reference a cross-reference table",
                        ));
                    }
                    let size = required(&mut dict, b"Size")?.integer()?;
                    if size > u64::from(u32::MAX) {
                        return Err(invalid("invalid trailer Size"));
                    }
                    let Value::Array(w) = required(&mut dict, b"W")? else {
                        return Err(invalid("invalid xref widths"));
                    };
                    if w.len() != 3 {
                        return Err(invalid("xref requires three field widths"));
                    }
                    let mut widths = [0usize; 3];
                    for (target, value) in widths.iter_mut().zip(w) {
                        let width = value.integer()?;
                        if width > 8 {
                            return Err(invalid("xref field width exceeds 8 bytes"));
                        }
                        *target = width as usize;
                    }
                    let row_size: usize = widths.iter().sum();
                    if row_size == 0 {
                        return Err(invalid("empty xref rows"));
                    }
                    let indices = match dict.remove(b"Index".as_slice()) {
                        Some(Value::Array(indices)) => indices,
                        None => vec![Value::Integer(0), Value::Integer(size)],
                        _ => return Err(invalid("invalid xref Index")),
                    };
                    if indices.len() % 2 != 0 {
                        return Err(invalid("odd xref Index length"));
                    }
                    let mut ranges = Vec::new();
                    let mut end = 0;
                    let mut rows = 0usize;
                    let mut indices = indices.into_iter();
                    while let Some(first) = indices.next() {
                        let first = first.integer()?;
                        let count = indices
                            .next()
                            .ok_or_else(|| invalid("missing xref count"))?
                            .integer()?;
                        let next = first
                            .checked_add(count)
                            .filter(|n| *n <= size)
                            .ok_or_else(|| invalid("xref Index outside Size"))?;
                        if first < end {
                            return Err(invalid("unordered or overlapping xref Index"));
                        }
                        end = next;
                        rows = rows
                            .checked_add(
                                usize::try_from(count)
                                    .map_err(|_| invalid("xref count overflow"))?,
                            )
                            .filter(|n| *n <= MAX_ENTRIES)
                            .ok_or_else(|| invalid("cross-reference entry limit exceeded"))?;
                        ranges.push((first as u32, count as u32));
                    }
                    entry_count = entry_count
                        .checked_add(rows)
                        .filter(|n| *n <= MAX_ENTRIES)
                        .ok_or_else(|| invalid("cross-reference entry limit exceeded"))?;
                    let decoded_size = rows
                        .checked_mul(row_size)
                        .filter(|n| *n <= MAX_STRUCTURAL_STREAM)
                        .ok_or_else(|| invalid("xref decoded size limit exceeded"))?;
                    let decode = Decode::from_dictionary(&mut dict)?;
                    let expected = if let Some(config) = decode.filter(|c| c.predictor != 1) {
                        if decoded_size % config.columns as usize != 0 {
                            return Err(invalid("xref predictor row mismatch"));
                        }
                        decoded_size
                            .checked_add(decoded_size / config.columns as usize)
                            .ok_or_else(|| invalid("xref predictor size overflow"))?
                    } else {
                        decoded_size
                    };
                    let data = self
                        .structural_stream(object.stream, &mut dict, decode, Some(expected))
                        .await?;
                    if data.len() != decoded_size {
                        return Err(invalid("xref decoded length mismatch"));
                    }
                    storage = storage
                        .checked_add(data.len())
                        .filter(|n| *n <= MAX_XREF_STORAGE)
                        .ok_or_else(|| invalid("xref storage limit exceeded"))?;
                    dict.insert(b"Size".to_vec(), Value::Integer(size));
                    let highest = ranges
                        .last()
                        .and_then(|&(first, count)| count.checked_sub(1).map(|n| first + n));
                    (
                        dict,
                        Xrefs::Stream {
                            ranges,
                            widths,
                            data,
                        },
                        highest,
                    )
                }
            };
            let size = required(&mut trailer, b"Size")?.integer()?;
            if size > u64::from(u32::MAX) || highest.is_some_and(|id| u64::from(id) >= size) {
                return Err(invalid("invalid trailer Size"));
            }
            self.next_id = self.next_id.max(size as u32);
            if self.xrefs.is_empty() {
                self.trailer = trailer.clone();
            } else {
                for key in [b"Info".as_slice(), b"ID"] {
                    if let Some(value) = trailer.get(key) {
                        self.trailer
                            .entry(key.to_vec())
                            .or_insert_with(|| value.clone());
                    }
                }
            }
            if trailer
                .get(b"Encrypt".as_slice())
                .is_some_and(|v| !matches!(v, Value::Null))
            {
                return Err(Error::UnsupportedFeature("encrypted PDF"));
            }
            if trailer.contains_key(b"XRefStm".as_slice()) {
                return Err(Error::UnsupportedFeature(
                    "PDF hybrid cross-reference streams",
                ));
            }
            let mut this_root = None;
            if let Some(value) = trailer.remove(b"Root".as_slice()) {
                let Value::Reference(reference) = value else {
                    return Err(invalid("Root must be indirect"));
                };
                this_root = Some(reference);
                if root.is_none() {
                    root = Some(reference);
                }
            }
            self.xrefs.push(section);
            self.roots.push(this_root);
            match trailer.remove(b"Prev".as_slice()) {
                None => return root.ok_or_else(|| invalid("missing document Root")),
                Some(value) => {
                    offset = value.integer()?;
                }
            }
        }
        Err(invalid("revision limit exceeded"))
    }

    /// Resolve an indirect reference to its object. Boxed because an object stream is
    /// itself an object (the recursion is bounded by [`MAX_DEPTH`]).
    fn object(&mut self, reference: Reference) -> BoxFuture<'_, Result<Object>> {
        Box::pin(async move {
            self.objects += 1;
            if self.objects > MAX_OBJECTS {
                return Err(invalid("object resolution limit exceeded"));
            }
            if self.resolving.len() >= MAX_DEPTH || !self.resolving.insert(reference) {
                return Err(invalid("cyclic or excessively nested object resolution"));
            }
            let result = match self.entry(reference.0) {
                Ok(Entry::Normal { offset, generation }) if generation == reference.1 => {
                    self.raw_object(offset, Some(reference)).await
                }
                Ok(Entry::Compressed { container, index }) if reference.1 == 0 => {
                    self.compressed_object(reference.0, container, index).await
                }
                Ok(_) => Err(invalid("stale or free object reference")),
                Err(e) => Err(e),
            };
            self.resolving.remove(&reference);
            result
        })
    }

    fn entry(&self, id: u32) -> Result<Entry> {
        for section in &self.xrefs[self.skip..] {
            if let Some(entry) = section.entry(id)? {
                return Ok(entry);
            }
        }
        Err(invalid("unresolved object"))
    }

    async fn raw_object(&mut self, offset: u64, reference: Option<Reference>) -> Result<Object> {
        self.lex(offset, |lx| {
            let number = lx.number()?;
            let generation = lx.number()?;
            if reference.is_some_and(|r| number != u64::from(r.0) || generation != u64::from(r.1)) {
                return Err(Stop::Fail(invalid("xref/object identity mismatch")));
            }
            lx.expect(b"obj")?;
            let value = lx.value(0)?;
            let ending = lx.token()?;
            let stream = if ending == b"stream" {
                if !matches!(value, Value::Dictionary(_)) {
                    return Err(Stop::Fail(invalid("stream without dictionary")));
                }
                match lx.byte()? {
                    b'\n' => {}
                    b'\r' => {
                        if lx.peek()? == Some(b'\n') {
                            lx.byte()?;
                        }
                    }
                    _ => {
                        return Err(Stop::Fail(invalid("stream keyword requires newline")));
                    }
                }
                Some(lx.offset())
            } else if ending == b"endobj" {
                None
            } else {
                return Err(Stop::Fail(invalid("missing endobj")));
            };
            Ok(Object { value, stream })
        })
        .await
    }

    /// Where the stream's data is, checked against the file and its `endstream`.
    async fn stream_range(
        &mut self,
        offset: Option<u64>,
        dict: &mut Dictionary,
        direct_length: bool,
    ) -> Result<ByteRange> {
        let offset = offset.ok_or_else(|| invalid("expected stream"))?;
        let value = required(dict, b"Length")?;
        let length = if direct_length {
            value.integer()?
        } else {
            self.resolve(value).await?.integer()?
        };
        let end = offset
            .checked_add(length)
            .filter(|end| *end < self.size)
            .ok_or_else(|| invalid("stream length outside file"))?;
        self.lex(end, |lx| {
            lx.expect(b"endstream")?;
            lx.expect(b"endobj")
        })
        .await?;
        ByteRange::new(offset, length)
    }

    /// A stream the parser itself needs (cross-reference or object stream), decoded
    /// within the structural budgets.
    async fn structural_stream(
        &mut self,
        offset: Option<u64>,
        dict: &mut Dictionary,
        decode: Option<Decode>,
        expected: Option<usize>,
    ) -> Result<Vec<u8>> {
        let range = self.stream_range(offset, dict, expected.is_some()).await?;
        let encoded =
            usize::try_from(range.len()).map_err(|_| invalid("stream length overflow"))?;
        if encoded > MAX_STRUCTURAL_STREAM || encoded > self.decoding_left {
            return Err(invalid(
                "encoded structural stream size/work limit exceeded",
            ));
        }
        self.decoding_left -= encoded;
        let limit = MAX_STRUCTURAL_STREAM.min(self.decoding_left);
        let limit = expected.map_or(limit, |size| size.min(limit));
        let raw = self.io.read_vec(range.offset(), encoded).await?;
        if let Some(config) = decode {
            let data = inflate(&raw, limit, expected)?;
            self.decoding_left -= data.len();
            config.undo_predictor(data)
        } else {
            if encoded > limit {
                return Err(invalid("decoded structural stream work limit exceeded"));
            }
            self.decoding_left -= raw.len();
            Ok(raw)
        }
    }

    async fn compressed_object(&mut self, id: u32, container: u32, index: u32) -> Result<Object> {
        if self
            .object_stream
            .as_ref()
            .is_none_or(|stream| stream.id != container)
        {
            if !matches!(self.entry(container)?, Entry::Normal { .. }) {
                return Err(invalid("object stream container is not an ordinary object"));
            }
            let object = self.object((container, 0)).await?;
            let mut dict = object.value.dictionary()?;
            if !required(&mut dict, b"Type")?.is_name(b"ObjStm") {
                return Err(invalid("compressed object container is not ObjStm"));
            }
            let count = required(&mut dict, b"N")?.integer()?;
            let first = required(&mut dict, b"First")?.integer()?;
            if count > MAX_OBJECT_STREAM_ENTRIES {
                return Err(invalid("object stream entry limit exceeded"));
            }
            let decode = Decode::from_dictionary(&mut dict)?;
            let data = self
                .structural_stream(object.stream, &mut dict, decode, None)
                .await?;
            let first = usize::try_from(first)
                .ok()
                .filter(|n| *n <= data.len())
                .ok_or_else(|| invalid("object stream First outside payload"))?;
            let mut lexer = Lexer::new(&data[..first], 0, true, self.budget, self.nodes);
            let mut objects = Vec::new();
            let mut ids = BTreeSet::new();
            let header = (|| -> Lex<()> {
                for _ in 0..count {
                    let object_id = u32::try_from(lexer.number()?)
                        .map_err(|_| Stop::Fail(invalid("object number overflow")))?;
                    let offset = usize::try_from(lexer.number()?)
                        .map_err(|_| Stop::Fail(invalid("object offset overflow")))?;
                    if offset >= data.len() - first
                        || objects
                            .last()
                            .is_some_and(|&(_, previous)| offset <= previous)
                        || !ids.insert(object_id)
                    {
                        return Err(Stop::Fail(invalid(
                            "invalid object stream offsets or duplicate objects",
                        )));
                    }
                    objects.push((object_id, offset));
                }
                lexer.skip_space()
            })();
            finish(header)?;
            if lexer.at != first {
                return Err(invalid("object stream header length mismatch"));
            }
            self.budget = lexer.budget;
            self.object_stream = Some(ObjectStream {
                id: container,
                data,
                objects,
                first,
            });
        }
        let stream = self
            .object_stream
            .as_ref()
            .ok_or_else(|| invalid("missing object stream"))?;
        let &(object_id, start) = stream
            .objects
            .get(index as usize)
            .ok_or_else(|| invalid("compressed object index outside stream"))?;
        if id != object_id {
            return Err(invalid("compressed object identity mismatch"));
        }
        let end = stream
            .objects
            .get(index as usize + 1)
            .map(|&(_, offset)| offset)
            .unwrap_or(stream.data.len() - stream.first);
        let slice = &stream.data[stream.first + start..stream.first + end];
        let mut lexer = Lexer::new(slice, 0, true, self.budget, self.nodes);
        let value = finish(lexer.value(0).and_then(|value| {
            lexer.skip_space()?;
            Ok(value)
        }))?;
        if lexer.at != slice.len() {
            return Err(invalid("trailing syntax in compressed object"));
        }
        self.budget = lexer.budget;
        self.nodes = lexer.nodes;
        Ok(Object {
            value,
            stream: None,
        })
    }

    async fn resolve(&mut self, mut value: Value) -> Result<Value> {
        let mut seen = BTreeSet::new();
        loop {
            let Value::Reference(reference) = value else {
                return Ok(value);
            };
            if seen.len() == MAX_DEPTH {
                return Err(invalid("indirect reference depth limit exceeded"));
            }
            if !seen.insert(reference) {
                return Err(invalid("cyclic indirect reference"));
            }
            let object = self.object(reference).await?;
            if object.stream.is_some() {
                return Err(invalid("unexpected stream reference"));
            }
            value = object.value;
        }
    }

    /// A metadata stream of the catalog: where its data is and how it is encoded.
    async fn stream(
        &mut self,
        value: Value,
        kind: ItemKind,
    ) -> Result<(ByteRange, Option<Decode>)> {
        let Value::Reference(reference) = value else {
            return Err(invalid("stream must be indirect"));
        };
        let object = self.object(reference).await?;
        let mut dict = object.value.dictionary()?;
        let expected_type: &[u8] = if kind == ItemKind::Xmp {
            b"Metadata"
        } else {
            b"EmbeddedFile"
        };
        match dict.remove(b"Type".as_slice()) {
            Some(value) if !value.is_name(expected_type) => {
                return Err(invalid("unexpected metadata stream type"));
            }
            None if kind == ItemKind::Xmp => {
                return Err(invalid("missing metadata stream type"));
            }
            _ => {}
        }
        if kind == ItemKind::Xmp && !required(&mut dict, b"Subtype")?.is_name(b"XML") {
            return Err(invalid("XMP stream must have XML subtype"));
        }
        let decode = Decode::from_dictionary(&mut dict)?;
        let range = self.stream_range(object.stream, &mut dict, false).await?;
        if range.len() > MAX_SEGMENT_SIZE {
            return Err(invalid("metadata stream exceeds 256 MiB limit"));
        }
        Ok((range, decode))
    }

    /// The current catalog's XMP stream and document-level C2PA store.
    async fn metadata(&mut self, root: Reference) -> Result<CatalogMetadata> {
        let catalog_value = self.resolve(Value::Reference(root)).await?;
        let catalog = catalog_value.dictionary()?;
        if !catalog
            .get(b"Type".as_slice())
            .is_some_and(|value| value.is_name(b"Catalog"))
        {
            return Err(invalid("Root is not a Catalog"));
        }
        let mut ranges = Vec::new();
        let mut active = Some(BTreeSet::new());
        if let Some(value) = catalog.get(b"Metadata".as_slice()).cloned() {
            if !matches!(value, Value::Null) {
                let (range, decode) = self.stream(value, ItemKind::Xmp).await?;
                ranges.push((range, ItemKind::Xmp, decode));
            }
        }
        let associated = self.associated(&catalog).await?;
        let stores = self.stores(&associated, &mut active).await?;
        if stores.len() > 1 {
            return Err(invalid("multiple document-level C2PA manifests"));
        }
        ranges.extend(
            stores
                .into_iter()
                .map(|(range, decode)| (range, ItemKind::C2pa, decode)),
        );
        Ok(CatalogMetadata {
            catalog,
            associated,
            active,
            ranges,
        })
    }

    /// The catalog's `/AF` entries.
    async fn associated(&mut self, catalog: &Dictionary) -> Result<Vec<Value>> {
        let Some(value) = catalog.get(b"AF".as_slice()).cloned() else {
            return Ok(Vec::new());
        };
        Ok(match self.resolve(value.clone()).await? {
            Value::Array(values) => values,
            Value::Null => Vec::new(),
            Value::Dictionary(_) => vec![value],
            _ => return Err(invalid("invalid Catalog AF")),
        })
    }

    /// The C2PA stores among associated files, in order. `active` collects the file
    /// specifications, or is `None` once one is not an indirect reference.
    async fn stores(
        &mut self,
        values: &[Value],
        active: &mut Option<BTreeSet<Reference>>,
    ) -> Result<Vec<(ByteRange, Option<Decode>)>> {
        let mut stores = Vec::new();
        for value in values {
            let mut spec = self.resolve(value.clone()).await?.dictionary()?;
            let Some(relationship) = spec.remove(b"AFRelationship".as_slice()) else {
                continue;
            };
            let relationship = self.resolve(relationship).await?;
            if !matches!(relationship, Value::Name(_)) {
                return Err(invalid("AFRelationship must be a name"));
            }
            if !relationship.is_name(b"C2PA_Manifest") {
                continue;
            }
            match value {
                Value::Reference(reference) => {
                    if let Some(active) = active {
                        active.insert(*reference);
                    }
                }
                _ => *active = None,
            }
            if let Some(subtype) = spec.remove(b"Subtype".as_slice()) {
                if !subtype.is_name(b"application/c2pa") {
                    return Err(invalid("C2PA file specification has wrong subtype"));
                }
            }
            let ef_value = required(&mut spec, b"EF")?;
            let mut ef = self.resolve(ef_value).await?.dictionary()?;
            let stream = match (ef.remove(b"F".as_slice()), ef.remove(b"UF".as_slice())) {
                (Some(Value::Reference(f)), Some(Value::Reference(uf))) if f == uf => {
                    Value::Reference(f)
                }
                (Some(_), Some(_)) => return Err(invalid("conflicting embedded file references")),
                (Some(value), None) | (None, Some(value)) => value,
                (None, None) => return Err(invalid("missing C2PA embedded file")),
            };
            stores.push(self.stream(stream, ItemKind::C2pa).await?);
        }
        Ok(stores)
    }

    /// The C2PA stores of the revisions before the latest, other than the one at
    /// `active`. C2PA reads the stores of all revisions as one, so these come before
    /// the latest revision's store.
    ///
    /// The walk goes back from the latest revision and ends at one whose catalog
    /// lists no store: the store was removed there, and what came before is not
    /// part of what follows. A revision that adds more than one store has none of
    /// them counted, and a revision that cannot be read is passed over; neither
    /// fails the document.
    async fn earlier_stores(&mut self, active: u64) -> Result<Vec<(ByteRange, Option<Decode>)>> {
        let mut found = Vec::new();
        let mut seen = BTreeSet::from([active]);
        for index in 1..self.xrefs.len() {
            let Some(root) = self.roots[index] else {
                continue;
            };
            self.skip = index;
            self.object_stream = None;
            let result = self.revision_stores(root).await;
            self.skip = 0;
            self.object_stream = None;
            let mut stores = match result {
                Ok(stores) => stores,
                Err(Error::InvalidFormat(_) | Error::UnsupportedFeature(_)) => continue,
                Err(error) => return Err(error),
            };
            // An empty stream holds nothing.
            stores.retain(|(range, _)| !range.is_empty());
            if stores.is_empty() {
                break;
            }
            let mut added = stores
                .into_iter()
                .filter(|(range, _)| !seen.contains(&range.offset()));
            if let (Some(store), None) = (added.next(), added.next()) {
                seen.insert(store.0.offset());
                found.push(store);
            }
        }
        Ok(found)
    }

    /// The C2PA stores the catalog `root` lists, as the document was at the revision
    /// `skip` back.
    async fn revision_stores(
        &mut self,
        root: Reference,
    ) -> Result<Vec<(ByteRange, Option<Decode>)>> {
        let catalog = self.resolve(Value::Reference(root)).await?.dictionary()?;
        if !catalog
            .get(b"Type".as_slice())
            .is_some_and(|value| value.is_name(b"Catalog"))
        {
            return Err(invalid("Root is not a Catalog"));
        }
        let values = self.associated(&catalog).await?;
        self.stores(&values, &mut None).await
    }
}

/// A result from a lexer over bytes that are all there: running out is an error.
fn finish<T>(result: Lex<T>) -> Result<T> {
    match result {
        Ok(v) => Ok(v),
        Err(Stop::Fail(e)) => Err(e),
        Err(Stop::More) => Err(invalid("unexpected end of data")),
    }
}

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

async fn parse_with(handler: Arc<dyn ContainerHandler>, mut io: Io) -> Result<Structure> {
    let size = io.len();
    if size < HEADER_LEN {
        return Err(invalid("invalid header"));
    }
    let mut header = [0u8; HEADER_LEN as usize];
    io.read_at(0, &mut header).await?;
    if !PdfHandler.detect(&header) {
        return Err(invalid("invalid header"));
    }
    let offset = startxref(&mut io, size).await?;

    let mut parser = Parser::new(&mut io, size);
    let root = parser.xrefs(offset).await?;
    let found = parser.metadata(root).await?;
    let edit = write::context(
        &mut parser,
        root,
        offset,
        found.catalog,
        found.associated,
        found.active,
    )
    .await?;
    let mut ranges: Vec<_> = found
        .ranges
        .into_iter()
        .map(|(range, kind, decode)| (range, kind, decode, false))
        .collect();
    // A removed store stays removed: earlier ones count only beside a current one,
    // and an empty stream holds nothing.
    let current = ranges
        .iter()
        .find(|r| r.1 == ItemKind::C2pa && !r.0.is_empty())
        .map(|r| r.0);
    if let Some(active) = current {
        for (range, decode) in parser.earlier_stores(active.offset()).await? {
            ranges.push((range, ItemKind::C2pa, decode, true));
        }
    }
    ranges.sort_by_key(|(range, _, _, _)| range.offset());

    let mut b = StructureBuilder::new(handler, "application/pdf", size);
    b.push_span(SegmentKind::Preamble, Name::None, HEADER_LEN as u32, 0, 0)?;
    let mut end = HEADER_LEN;
    let state = PdfState { edit };
    for (range, kind, decode, superseded) in ranges {
        // An empty stream holds nothing to expose.
        if range.is_empty() {
            continue;
        }
        if range.offset() < end {
            return Err(invalid("overlapping metadata streams"));
        }
        if range.offset() > end {
            b.push_span(SegmentKind::Other, Name::None, 0, range.offset() - end, 0)?;
        }
        let transfer = decode.map_or(TransferEncoding::Identity, Decode::transfer);
        let mut info = item_info(kind).transfer(transfer);
        // The bytes of an earlier revision are ordinary data to a hash of the file.
        let mut segment = SegmentKind::Metadata;
        if superseded {
            info = info.label(labels::SUPERSEDED);
            segment = SegmentKind::Other;
        }
        b.push_item(segment, Name::None, 0, range.len(), 0, info)?;
        end = range.end();
    }
    if end < size {
        b.push_span(SegmentKind::Other, Name::None, 0, size - end, 0)?;
    }
    b.attach(state);
    b.finish()
}

// ---------------------------------------------------------------------------
// Writing
// ---------------------------------------------------------------------------

/// Part of a run of text between the segments: kept source bytes or new ones.
enum Text<'a> {
    Copy(ByteRange),
    Put(Cow<'a, [u8]>),
}

/// Emit the run as one segment of other bytes, which is how parsing the output sees
/// them: whatever lies between the metadata streams.
fn flush<'a>(b: &mut PlanBuilder<'_, 'a>, run: &mut Vec<Text<'a>>) -> Result<()> {
    let len: u64 = run
        .iter()
        .map(|t| match t {
            Text::Copy(r) => r.len(),
            Text::Put(d) => d.len() as u64,
        })
        .sum();
    if len == 0 {
        run.clear();
        return Ok(());
    }
    let id = b.shape(SegmentKind::Other, Name::None, 0, len, 0)?;
    for piece in run.drain(..) {
        match piece {
            Text::Copy(r) if !r.is_empty() => {
                b.copy(id, Role::Payload, r);
            }
            Text::Put(d) if !d.is_empty() => {
                b.put(id, Role::Payload, d);
            }
            _ => {}
        }
    }
    Ok(())
}

/// What a revision holds of the C2PA store `updates` asks for.
///
/// C2PA reads the stores of a PDF's revisions as one, so a revision holds only the
/// manifests it adds, never the earlier ones again. A new store is therefore the
/// store the file already has, extended: its addition is written. One that adds
/// nothing, does not extend the existing store, or is not JUMBF so cannot be
/// compared with it, is refused, since the only way to write it would be to repeat
/// the earlier manifests. An existing store that is not JUMBF has no manifests to
/// repeat, so the new store is written as it is.
async fn c2pa_write<'a>(
    src: &Structure,
    io: &mut Io,
    updates: &'a Updates,
) -> Result<write::C2pa<'a>> {
    let full = match updates.c2pa() {
        MetadataUpdate::Keep => return Ok(write::C2pa::Keep),
        MetadataUpdate::Remove => return Ok(write::C2pa::Remove),
        MetadataUpdate::Set(full) => full,
    };
    let Some(existing) = src.c2pa_store_async(io).await? else {
        return Ok(write::C2pa::Set(Cow::Borrowed(full.as_slice())));
    };
    if *full == existing {
        return Err(Error::UnsupportedFeature(
            "the PDF C2PA store has no manifests the file does not already have",
        ));
    }
    // Comparing the store with itself fails exactly when its manifests cannot be
    // told apart, and then there is nothing earlier to repeat.
    if crate::jumbf::addition_to(&existing, &existing).is_err() {
        return Ok(write::C2pa::Set(Cow::Borrowed(full.as_slice())));
    }
    match crate::jumbf::addition_to(&existing, full) {
        Ok(Some(delta)) => Ok(write::C2pa::Set(Cow::Owned(delta))),
        _ => Err(Error::UnsupportedFeature(
            "a new PDF C2PA store must extend the existing store: earlier manifests cannot be rewritten or repeated",
        )),
    }
}

/// A write is the whole source, unchanged, then an appended revision. In the output,
/// a metadata stream the catalog no longer points at is just bytes, so those are
/// merged into the text around them, as parsing the output sees it. The exception
/// is a C2PA store, when the revision gives another: earlier stores are still
/// read, as `superseded` items.
fn plan<'a>(
    src: &Structure,
    source_len: u64,
    updates: &'a Updates,
    c2pa: write::C2pa<'a>,
) -> Result<WritePlan<'a>> {
    if source_len != src.total_size() {
        return Err(invalid("source size changed since parsing"));
    }
    let state = PdfState::of(src)?;
    let segments = src.segments();
    let mut b = PlanBuilder::new(src);
    let noop = matches!(updates.xmp(), MetadataUpdate::Keep) && matches!(c2pa, write::C2pa::Keep);
    if noop {
        for i in 0..segments.len() {
            b.copy_segment(SegmentId::from_index(i)?)?;
        }
        b.carry_items(|_| true);
        b.attach(state.clone());
        return b.finish();
    }
    if let Some(refusal) = state.edit.refusal() {
        return Err(refusal);
    }
    let write::State::Ready(context) = &state.edit else {
        return Err(invalid("missing editable PDF context"));
    };
    let revision = write::revision(context, src.total_size(), updates, &c2pa)?;

    let keeps = |kind: ItemKind| {
        if kind == ItemKind::Xmp {
            matches!(updates.xmp(), MetadataUpdate::Keep)
        } else {
            matches!(c2pa, write::C2pa::Keep)
        }
    };
    // With a new store, the earlier ones are read before it. An empty one is nothing.
    let supersedes = matches!(&c2pa, write::C2pa::Set(data) if !data.is_empty());
    let mut run: Vec<Text<'a>> = Vec::new();
    for (i, seg) in segments.iter().enumerate() {
        let id = SegmentId::from_index(i)?;
        if seg.kind() == SegmentKind::Preamble {
            b.copy_segment(id)?;
            continue;
        }
        match src.items_in(id).next() {
            Some(item) if item.kind() == ItemKind::C2pa && supersedes => {
                flush(&mut b, &mut run)?;
                let earlier = b.shape(SegmentKind::Other, Name::None, 0, seg.range().len(), 0)?;
                b.copy(earlier, Role::Payload, seg.range());
                b.item(item.info().clone().label(labels::SUPERSEDED), &[earlier])?;
            }
            Some(item)
                if matches!(item.kind(), ItemKind::Xmp | ItemKind::C2pa) && keeps(item.kind()) =>
            {
                flush(&mut b, &mut run)?;
                b.copy_segment(id)?;
            }
            _ => run.push(Text::Copy(seg.range())),
        }
    }
    for piece in revision.pieces {
        match piece {
            write::Piece::Syntax(bytes) => run.push(Text::Put(Cow::Owned(bytes))),
            write::Piece::Stream(kind) => {
                let data: Cow<'a, [u8]> = match (kind, &c2pa) {
                    (ItemKind::C2pa, write::C2pa::Set(data)) => data.clone(),
                    (ItemKind::Xmp, _) => match updates.xmp() {
                        MetadataUpdate::Set(data) => Cow::Borrowed(data.as_slice()),
                        _ => return Err(invalid("write plan payload missing")),
                    },
                    _ => return Err(invalid("write plan payload missing")),
                };
                // An empty stream holds nothing to expose.
                if !data.is_empty() {
                    flush(&mut b, &mut run)?;
                    let id =
                        b.put_segment(SegmentKind::Metadata, Name::None, &[][..], data, &[][..])?;
                    b.item(item_info(kind), &[id])?;
                }
            }
        }
    }
    flush(&mut b, &mut run)?;
    b.carry_items(|item| !(supersedes && item.kind() == ItemKind::C2pa));
    b.attach(PdfState {
        edit: write::State::Ready(Arc::new(revision.context)),
    });
    b.finish()
}

/// The offset the final `startxref` gives, which must be in the last [`TAIL`] bytes.
async fn startxref(io: &mut Io, size: u64) -> Result<u64> {
    let tail_size = size.min(TAIL);
    let tail = io.read_vec(size - tail_size, tail_size as usize).await?;
    let tail = tail.trim_ascii_end();
    let tail = tail
        .strip_suffix(b"%%EOF")
        .ok_or_else(|| invalid("missing final EOF marker"))?;
    let start = tail
        .windows(9)
        .rposition(|window| window == b"startxref")
        .ok_or_else(|| invalid("missing startxref in final 1024 bytes"))?;
    let number = &tail[start + 9..];
    if !number.first().is_some_and(|b| whitespace(*b)) {
        return Err(invalid("invalid startxref"));
    }
    unsigned(number.trim_ascii())
}

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

    use super::*;

    #[test]
    fn the_fixture_exposes_its_xmp() {
        let bytes = std::fs::read(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/tests/fixtures/pdf_metadata.pdf"
        ))
        .unwrap();
        let s = parse(&mut Cursor::new(&bytes)).unwrap();
        assert_eq!(s.media_type(), "application/pdf");
        let xmp = s.xmp(&mut Cursor::new(&bytes)).unwrap();
        assert!(xmp.is_some_and(|x| !x.is_empty()));
    }
}