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
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
// 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.

//! JPEG on the structure model.
//!
//! Every marker segment is one [`Segment`]. For a segment with a length field,
//! the header is `FF xx len(2)` plus any signature or JPEG XT prefix, and the
//! payload is the rest. A scan is one `ImageData` segment: header `FF DA len
//! scan-header`, payload the entropy-coded data up to the next marker that is not
//! a restart marker. Progressive files therefore have one such segment per scan,
//! with their DHT/DRI markers as ordinary segments between them. A scan that
//! contains restart markers subdivides at them: the parser records each `RSTn`
//! as it scans, so [`Structure::elements`](crate::Structure::elements)
//! lists the restart intervals without reading the file again.
//!
//! JUMBF is carried in JPEG XT APP11 segments. A manifest larger than one
//! segment spans several; they form a single multi-extent [`Item`](crate::Item)
//! whose extents are the per-segment payloads, so the repeated XT headers are never
//! part of the data and are always visible as headers.
//!
//! JPEG XT also carries plain ISO BMFF `uuid` boxes in APP11 (Apple writes
//! several). They are not JUMBF: each is an [`ItemKind::Other`] item encoded as
//! [`Encoding::IsoBmff`], and JUMBF updates leave them
//! alone. XMP (with any extended XMP) is one [`ItemKind::Xmp`] item and EXIF one
//! [`ItemKind::Exif`] item; all of these live in
//! [`Metadata`](SegmentKind::Metadata) segments.
//!
//! # Multi-Picture Format
//!
//! When another image (`FF D8 FF`) follows an `EOI` directly, the file holds
//! several images, as in a Multi-Picture Format (MPF) file such as Ultra HDR. Each
//! image's markers are listed in order (`SOI`, ..., `EOI`, `SOI`, ..., `EOI`), and
//! [`Structure::subassets`] reports one part per image, plus one for any data after
//! the last image. Only the first image's XMP, EXIF and JUMBF are interpreted as the
//! asset's; later images are left as plain segments. New metadata is inserted into
//! the first image. Bytes that start like an image (`FF D8 FF`) but do not parse as
//! one are trailing data, as they are after a single image.
//!
//! The MPF APP2 segment records each image's size and offset. When an edit changes
//! the size of the first image or moves the block, the recorded values are shifted
//! to match, so the output stays a valid MPF file. The edit is refused rather than
//! writing a stale or ambiguous index when the index is not one that can be edited
//! safely: it must be well formed (one `MPEntry` array, outside the header and the
//! IFD, agreeing with the stated image count), appear once, and record the offset
//! of every image and the size of every image but the first exactly. The first
//! image's size may be recorded short of the image, as in Pixel Ultra HDR files, and
//! is rewritten to the true size; one that claims more than the image is refused.
//! Parsing and copying unchanged never consult it.
//!
//! Not yet ported: EXIF thumbnail location.

use std::{
    borrow::Cow,
    collections::BTreeMap,
    io::{Read, Seek},
    sync::Arc,
};

use crate::{
    container_api::{
        BoxFuture, ContainerHandler, Existing, FormatSpec, Io, ItemInfo, MetadataSlot, PlanBuilder,
        ReadSeek, StructureBuilder, WritePlan, MAX_SEGMENTS,
    },
    ByteRange, Encoding, Error, Extent, ItemKind, Name, Result, Role, Segment, SegmentId,
    SegmentKind, Structure, Updates,
};

const SOI: u8 = 0xd8;
const EOI: u8 = 0xd9;
const SOS: u8 = 0xda;
const APP1: u8 = 0xe1;
const APP2: u8 = 0xe2;
const APP11: u8 = 0xeb;

/// Start of the Multi-Picture Format APP2 payload.
const MPF_SIGNATURE: &[u8] = b"MPF\0";

const XMP_SIGNATURE: &[u8] = b"http://ns.adobe.com/xap/1.0/\0";
const XMP_EXT_SIGNATURE: &[u8] = b"http://ns.adobe.com/xmp/extension/\0";
const EXIF_SIGNATURE: &[u8] = b"Exif\0\0";
/// Common identifier of a JUMBF APP11 packet, and the box type of a JUMBF superbox.
const JP: [u8; 2] = *b"JP";
/// Read size when scanning entropy-coded data for markers.
const SCAN_BUF: usize = 32 * 1024;
const JUMB: [u8; 4] = *b"jumb";

const XMP_SIG_LEN: usize = XMP_SIGNATURE.len();
const EXT_SIG_LEN: usize = XMP_EXT_SIGNATURE.len();
/// Extended XMP prefix after the marker/length: signature, GUID(32), total(4), offset(4).
const EXT_PREFIX_LEN: usize = EXT_SIG_LEN + 32 + 4 + 4;
/// Largest header we ever build: marker/length plus the extended XMP prefix.
const MAX_HEADER: usize = 4 + EXT_PREFIX_LEN;

/// Largest value of a marker's length field.
const MAX_LEN_FIELD: u64 = 0xffff;
/// Largest standard XMP packet one APP1 can carry.
const MAX_STD_XMP: u64 = MAX_LEN_FIELD - 2 - XMP_SIG_LEN as u64;
/// Extended XMP payload per segment.
const EXT_CHUNK: usize = 65533 - EXT_PREFIX_LEN - 2;
/// JUMBF payload per APP11 segment (room for the 16-byte continuation prefix).
const JUMBF_CHUNK: usize = 65533 - 16;
/// JPEG XT box instance number written for new JUMBF.
const XT_EN: u16 = 0x0211;
/// Largest extended XMP we will reassemble.
const MAX_EXT_XMP: u32 = 100 * 1024 * 1024;

/// How much of a segment to look at when classifying it.
const PEEK: usize = 80;

/// A JUMBF box being assembled from APP11 packets: its instance number, the
/// segments so far, and its type once the first packet has been seen.
struct Open {
    en: u16,
    ids: Vec<SegmentId>,
    ty: Option<[u8; 16]>,
}

impl Open {
    /// The item: a C2PA store or other JUMBF, by superbox type, with the box
    /// instance number (En) as its native id.
    fn info(&self) -> ItemInfo {
        crate::jumbf::item_info(self.ty).native_id(u64::from(self.en))
    }
}

/// Generic UUID boxes use the JPEG XT transport without a repeated box header.
#[derive(Default)]
struct UuidBox {
    size: Option<u64>,
    parts: BTreeMap<u32, SegmentId>,
}

enum Class {
    Plain,
    XmpMain,
    XmpExt,
    Exif,
    Jumbf { en: u16, z: u32 },
    JumbfRaw,
    Uuid { en: u16, z: u32, size: Option<u64> },
}

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

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

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

/// ISO/IEC 10918-1 Table B.1 symbol for a marker code.
fn marker_symbol(m: u8) -> Cow<'static, str> {
    match m {
        0x01 => "TEM".into(),
        0xc4 => "DHT".into(),
        0xc8 => "JPG".into(),
        0xcc => "DAC".into(),
        0xc0..=0xcf => Cow::Owned(format!("SOF{}", m - 0xc0)),
        0xd0..=0xd7 => Cow::Owned(format!("RST{}", m - 0xd0)),
        0xd8 => "SOI".into(),
        0xd9 => "EOI".into(),
        0xda => "SOS".into(),
        0xdb => "DQT".into(),
        0xdc => "DNL".into(),
        0xdd => "DRI".into(),
        0xde => "DHP".into(),
        0xdf => "EXP".into(),
        0xe0..=0xef => Cow::Owned(format!("APP{}", m - 0xe0)),
        0xf0..=0xfd => Cow::Owned(format!("JPG{}", m - 0xf0)),
        0xfe => "COM".into(),
        // 0x02..=0xBF are reserved (RES); 0x00 and 0xFF are never markers.
        _ => "RES".into(),
    }
}

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

    fn box_name(
        &self,
        _structure: &Structure,
        _segment: SegmentId,
        element: &Segment,
    ) -> Option<Cow<'static, str>> {
        match element.name() {
            Name::Marker(m) => Some(marker_symbol(m)),
            Name::None => None,
            other => Some(Cow::Owned(other.to_string())),
        }
    }

    fn formats(&self) -> &[FormatSpec] {
        // A Multi-Picture Format file is a JPEG and has no media type of its own.
        const F: &[FormatSpec] =
            &[FormatSpec::new("image/jpeg", "jpg").extension_aliases(&["jpeg", "mpo"])];
        F
    }

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

    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,
        mut io: Io,
        updates: &'a Updates,
    ) -> BoxFuture<'f, Result<WritePlan<'a>>> {
        Box::pin(async move { plan(src_structure, &mut io, updates).await })
    }

    fn compose(&self, kind: ItemKind, data: &[u8]) -> Result<Vec<u8>> {
        compose(kind, data)
    }

    fn read_xmp(
        &self,
        structure: &Structure,
        mut src: &mut dyn ReadSeek,
    ) -> Result<Option<Vec<u8>>> {
        read_xmp(structure, &mut src)
    }
}

/// Parse a JPEG 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 < 4 {
        return Err(Error::InvalidFormat("JPEG too small".into()));
    }
    let mut soi = [0u8; 2];
    io.read_at(0, &mut soi).await?;
    if soi != [0xff, SOI] {
        return Err(Error::InvalidFormat("Not a JPEG file".into()));
    }

    let mut b = StructureBuilder::new(handler, "image/jpeg", total);
    b.push_span(SegmentKind::Preamble, Name::Marker(SOI), 2, 0, 0)?;

    // Only the first image carries the asset's metadata.
    let mut meta = Meta::default();
    let mut offset = scan_image(&mut io, &mut b, total, 2, true, &mut meta).await?;
    // The first image's markers are the structure. Everything after its EOI, later
    // images and trailing data alike, is data beyond the end of it.
    b.end_boxes()?;
    if let Some(ids) = meta.xmp_open.take() {
        b.item_of_segments(ItemInfo::xmp(), &ids)?;
    }
    if let Some(o) = meta.jumbf_open.take() {
        b.item_of_segments(o.info(), &o.ids)?;
    }
    for (en, raw) in meta.uuid_boxes {
        let ids: Vec<_> = raw.parts.into_values().collect();
        let len = ids.iter().try_fold(0u64, |n, &id| {
            Ok::<_, Error>(n + b.segment(id)?.payload().len())
        })?;
        if raw.size != Some(len) {
            return Err(Error::InvalidFormat(
                "JPEG XT UUID box length mismatch".into(),
            ));
        }
        b.item_of_segments(
            ItemInfo::new(ItemKind::Other, Encoding::IsoBmff).native_id(u64::from(en)),
            &ids,
        )?;
    }

    // Another image directly after this one makes a multi-picture file. Later
    // images are listed as segments and left uninterpreted. Bytes that start like an
    // image but are not one are trailing data, as they are in a single-image file:
    // the structure is rolled back to the end of the last good image.
    let mut multi = false;
    while total - offset >= 4 && next_is_image(&mut io, offset).await? {
        b.begin_subasset(Some("image/jpeg".into()))?;
        match scan_image(&mut io, &mut b, total, offset, false, &mut Meta::default()).await {
            Ok(end) => {
                offset = end;
                multi = true;
            }
            Err(e) if is_malformed(&e) => {
                offset = b.rollback_subasset()?;
                break;
            }
            Err(e) => return Err(e),
        }
    }

    if offset < total {
        if multi {
            b.begin_subasset(None)?;
        }
        b.push_tail()?;
    }
    b.finish()
}

/// Whether `e` says the bytes are not a well-formed image, as opposed to a failure
/// to read them, which must not be mistaken for trailing data.
fn is_malformed(e: &Error) -> bool {
    match e {
        Error::InvalidFormat(_) | Error::InvalidSegment { .. } | Error::LimitExceeded { .. } => {
            true
        }
        Error::Io(io) => io.kind() == std::io::ErrorKind::UnexpectedEof,
        _ => false,
    }
}

/// Metadata being assembled while the primary image is scanned.
#[derive(Default)]
struct Meta {
    xmp_open: Option<Vec<SegmentId>>,
    jumbf_open: Option<Open>,
    /// End offset of the last segment added to `jumbf_open`. C2PA A.3.1 requires the
    /// APP11 segments of one manifest to be sequential and contiguous.
    jumbf_end: u64,
    uuid_boxes: BTreeMap<u16, UuidBox>,
}

/// List the markers of one image, from `offset` through its `EOI`, and return the
/// offset after it. Only the primary image's metadata is interpreted.
async fn scan_image(
    io: &mut Io,
    b: &mut StructureBuilder,
    total: u64,
    mut offset: u64,
    primary: bool,
    meta: &mut Meta,
) -> Result<u64> {
    let Meta {
        xmp_open,
        jumbf_open,
        jumbf_end,
        uuid_boxes,
    } = meta;
    loop {
        if total - offset < 2 {
            return Err(Error::InvalidFormat("JPEG truncated: missing EOI".into()));
        }
        let mut r = io.reader(offset);

        // A marker is FF xx, optionally preceded by FF fill bytes.
        let first = r.u8().await?;
        if first != 0xff {
            return Err(Error::invalid_segment(
                offset,
                format!("expected marker prefix 0xFF, found 0x{first:02X}"),
            ));
        }
        let mut fill = 0u64;
        let marker = loop {
            let m = r.u8().await?;
            if m == 0xff {
                fill += 1;
            } else {
                break m;
            }
        };
        if marker == 0x00 {
            return Err(Error::invalid_segment(
                offset,
                "stuffed byte outside entropy-coded data",
            ));
        }
        if fill > 0 {
            b.push_span(SegmentKind::Other, Name::None, 0, fill, 0)?;
        }
        let mstart = offset + fill;

        // Markers without a length field.
        match marker {
            EOI => {
                b.push_span(SegmentKind::Other, Name::Marker(EOI), 2, 0, 0)?;
                return Ok(mstart + 2);
            }
            0x01 | 0xd0..=0xd7 | SOI => {
                b.push_span(SegmentKind::Other, Name::Marker(marker), 2, 0, 0)?;
                offset = mstart + 2;
                continue;
            }
            _ => {}
        }

        let len = r.u16_be().await? as u64;
        if len < 2 {
            return Err(Error::invalid_segment(mstart, "marker length < 2"));
        }
        let seg_total = 2 + len;
        if mstart + seg_total > total {
            return Err(Error::invalid_segment(
                mstart,
                "segment extends past end of file",
            ));
        }
        let data_len = len - 2;

        if marker == SOS {
            let data_start = mstart + seg_total;
            // The entropy-coded data is read in large windows, straight from the
            // window of `io`, and scanned in place.
            let mut entropy = Entropy::default();
            let mut restarts = Vec::new();
            let mut at = data_start;
            let stop = 'scan: loop {
                if at >= total {
                    return Err(Error::InvalidFormat("EOI marker not found".into()));
                }
                let held = io.fetch_with(at, 1, SCAN_BUF).await?;
                let chunk = &held[..held.len().min((total - at) as usize)];
                let mut idx = 0;
                while let Some(event) = entropy.next_in(chunk, at, &mut idx) {
                    match event {
                        Event::Rst(at, m) => {
                            if restarts.len() >= MAX_SEGMENTS {
                                return Err(Error::LimitExceeded {
                                    what: "segment count",
                                    limit: MAX_SEGMENTS as u64,
                                });
                            }
                            restarts.push((at, m));
                        }
                        Event::Marker(found) => break 'scan found,
                    }
                }
                at += chunk.len() as u64;
            };
            let id = b.push_span(
                SegmentKind::MediaData,
                Name::Marker(SOS),
                seg_total as u32,
                stop - data_start,
                0,
            )?;
            for (at, m) in restarts {
                b.split(id, at, 2, Name::Marker(m))?;
            }
            // The marker that ended the scan (DHT, SOS, EOI, ...) is handled by the
            // main loop, so later scans and metadata after the first scan are seen.
            offset = stop;
            continue;
        }

        let mut kind = SegmentKind::Other;
        let mut hdr_extra = 0u64;
        let mut class = Class::Plain;
        let mut jtype: Option<[u8; 16]> = None;

        if primary && matches!(marker, APP1 | APP2 | APP11) {
            let n = data_len.min(PEEK as u64) as usize;
            let peek = r.take(n).await?;

            if marker == APP2 {
                if peek.starts_with(MPF_SIGNATURE) {
                    hdr_extra = MPF_SIGNATURE.len() as u64;
                }
            } else if marker == APP1 {
                if peek.starts_with(XMP_SIGNATURE) {
                    kind = SegmentKind::Metadata;
                    hdr_extra = XMP_SIG_LEN as u64;
                    class = Class::XmpMain;
                } else if peek.starts_with(XMP_EXT_SIGNATURE)
                    && data_len >= EXT_PREFIX_LEN as u64
                    && xmp_open.is_some()
                {
                    kind = SegmentKind::Metadata;
                    hdr_extra = EXT_PREFIX_LEN as u64;
                    class = Class::XmpExt;
                } else if peek.starts_with(EXIF_SIGNATURE) {
                    kind = SegmentKind::Metadata;
                    hdr_extra = EXIF_SIGNATURE.len() as u64;
                    class = Class::Exif;
                }
            } else if n >= 16
                && peek[0..2] == JP[..]
                && peek[12..16] == JUMB[..]
                && !uuid_boxes.contains_key(&u16::from_be_bytes([peek[2], peek[3]]))
            {
                let en = u16::from_be_bytes([peek[2], peek[3]]);
                let z = u32::from_be_bytes([peek[4], peek[5], peek[6], peek[7]]);
                // The spec numbers packets from 1, but real files (e.g. Designer.jpeg)
                // start at 0; treat 0 and 1 as the first packet.
                let first = z <= 1;
                let overhead = if first { 8 } else { 16 };
                let continues = !first && jumbf_open.as_ref().is_some_and(|o| o.en == en);
                if continues && mstart != *jumbf_end {
                    return Err(Error::InvalidFormat(
                        "JUMBF APP11 segments are not contiguous".into(),
                    ));
                }
                if data_len >= overhead && (first || continues) {
                    kind = SegmentKind::Metadata;
                    hdr_extra = overhead;
                    class = Class::Jumbf { en, z };
                    // The type is in the first packet: after the 8 bytes of the XT
                    // header (CI, En, Z) come the superbox and its description box.
                    if first {
                        jtype = crate::jumbf::superbox_type(&peek[8..]);
                    }
                }
            } else if marker == APP11 && n >= 8 && peek[..2] == JP {
                let en = u16::from_be_bytes([peek[2], peek[3]]);
                let z = u32::from_be_bytes([peek[4], peek[5], peek[6], peek[7]]);
                let first = z <= 1 && n >= 16 && &peek[12..16] == b"uuid";
                if first || uuid_boxes.contains_key(&en) {
                    let size = if first {
                        let size32 = u32::from_be_bytes(peek[8..12].try_into().unwrap());
                        let size = if size32 == 1 && n >= 24 {
                            u64::from_be_bytes(peek[16..24].try_into().unwrap())
                        } else {
                            u64::from(size32)
                        };
                        if size < if size32 == 1 { 32 } else { 24 } {
                            return Err(Error::InvalidFormat("JPEG XT UUID box too short".into()));
                        }
                        Some(size)
                    } else {
                        None
                    };
                    kind = SegmentKind::Metadata;
                    hdr_extra = 8;
                    class = Class::Uuid { en, z, size };
                }
            } else if n >= 8 && peek[4..8] == JUMB[..] {
                kind = SegmentKind::Metadata;
                class = Class::JumbfRaw;
                jtype = crate::jumbf::superbox_type(peek);
            }
        }

        let id = b.push_span(
            kind,
            Name::Marker(marker),
            (4 + hdr_extra) as u32,
            data_len - hdr_extra,
            0,
        )?;

        match class {
            Class::Plain => {}
            Class::Exif => b.item_of_segments(ItemInfo::exif(), &[id])?,
            Class::XmpMain => {
                if let Some(ids) = xmp_open.take() {
                    b.item_of_segments(ItemInfo::xmp(), &ids)?;
                }
                *xmp_open = Some(vec![id]);
            }
            Class::XmpExt => {
                if let Some(ids) = xmp_open.as_mut() {
                    ids.push(id);
                }
            }
            Class::Jumbf { en, z } => {
                if z <= 1 {
                    if let Some(o) = jumbf_open.take() {
                        b.item_of_segments(o.info(), &o.ids)?;
                    }
                    *jumbf_open = Some(Open {
                        en,
                        ids: vec![id],
                        ty: jtype,
                    });
                } else if let Some(o) = jumbf_open.as_mut() {
                    o.ids.push(id);
                }
                *jumbf_end = mstart + seg_total;
            }
            Class::JumbfRaw => {
                if let Some(o) = jumbf_open.take() {
                    b.item_of_segments(o.info(), &o.ids)?;
                }
                *jumbf_open = Some(Open {
                    en: 0,
                    ids: vec![id],
                    ty: jtype,
                });
                *jumbf_end = mstart + seg_total;
            }
            Class::Uuid { en, z, size } => {
                let raw = uuid_boxes.entry(en).or_default();
                if raw.parts.insert(z, id).is_some() || (size.is_some() && raw.size.is_some()) {
                    return Err(Error::InvalidFormat("duplicate JPEG XT UUID packet".into()));
                }
                if size.is_some() {
                    raw.size = size;
                }
            }
        }

        offset = mstart + seg_total;
    }
}

/// Whether another JPEG image starts at `offset` (`FF D8 FF`).
async fn next_is_image(io: &mut Io, offset: u64) -> Result<bool> {
    let mut m = [0u8; 3];
    io.read_at(offset, &mut m).await?;
    Ok(m == [0xff, SOI, 0xff])
}

/// The Multi-Picture Format index: where each entry's size and offset fields are
/// in an MPF block (the bytes after `MPF\0`), and the byte order of the block.
/// Offsets in the entries are relative to the start of the block.
struct MpIndex {
    little: bool,
    /// Position of each entry's size field; its offset field follows.
    entries: Vec<usize>,
}

impl MpIndex {
    fn parse(p: &[u8]) -> Option<Self> {
        let little = match p.get(..2)? {
            b"II" => true,
            b"MM" => false,
            _ => return None,
        };
        let me = Self {
            little,
            entries: Vec::new(),
        };
        if me.u16(p, 2)? != 0x2a {
            return None;
        }
        let ifd = me.u32(p, 4)? as usize;
        if ifd < 8 {
            return None;
        }
        let count = me.u16(p, ifd)? as usize;
        // The IFD: a count, the entries, and the offset of the next IFD.
        let ifd_end = ifd.checked_add(2 + count * 12 + 4)?;
        if ifd_end > p.len() {
            return None;
        }
        let mut array = None;
        let mut images = None;
        for i in 0..count {
            // Entry fields: tag, type, count, value (inline, or the offset of data).
            let e = ifd + 2 + i * 12;
            let (tag, ty, n, val) = (
                me.u16(p, e)?,
                me.u16(p, e + 2)?,
                me.u32(p, e + 4)?,
                me.u32(p, e + 8)?,
            );
            match tag {
                // NumberOfImages: one LONG.
                0xb001 => {
                    if images.is_some() || ty != 4 || n != 1 {
                        return None;
                    }
                    images = Some(val as usize);
                }
                // MPEntry: UNDEFINED, 16 bytes per image. A second one would leave
                // readers disagreeing about which index is the real one.
                0xb002 => {
                    if array.is_some() || ty != 7 {
                        return None;
                    }
                    array = Some((val as usize, n as usize));
                }
                _ => {}
            }
        }
        let (at, len) = array?;
        let end = at.checked_add(len)?;
        if len == 0 || len % 16 != 0 || end > p.len() {
            return None;
        }
        // The entries are rewritten in place, so they must not overlap the header or
        // the IFD, and the block must be self-consistent about how many there are.
        if at < 8 || (at < ifd_end && ifd < end) {
            return None;
        }
        if images.is_some_and(|n| n != len / 16) {
            return None;
        }
        let entries = (0..len / 16).map(|k| at + 16 * k + 4).collect();
        Some(Self { entries, ..me })
    }

    fn u16(&self, p: &[u8], at: usize) -> Option<u16> {
        let b: [u8; 2] = p.get(at..at.checked_add(2)?)?.try_into().ok()?;
        Some(if self.little {
            u16::from_le_bytes(b)
        } else {
            u16::from_be_bytes(b)
        })
    }

    fn u32(&self, p: &[u8], at: usize) -> Option<u32> {
        let b: [u8; 4] = p.get(at..at.checked_add(4)?)?.try_into().ok()?;
        Some(if self.little {
            u32::from_le_bytes(b)
        } else {
            u32::from_be_bytes(b)
        })
    }

    fn put(&self, p: &mut [u8], at: usize, v: u32) {
        let b = if self.little {
            v.to_le_bytes()
        } else {
            v.to_be_bytes()
        };
        p[at..at + 4].copy_from_slice(&b);
    }
}

/// Every MPF block in the primary image, as the segments holding them. A valid
/// file has at most one.
async fn find_all_mpf(src: &Structure, io: &mut Io, primary_end: usize) -> Result<Vec<SegmentId>> {
    let mut found = Vec::new();
    for (i, seg) in src.segments()[..primary_end].iter().enumerate() {
        if seg.name() == Name::Marker(APP2) && seg.header().len() == 4 + MPF_SIGNATURE.len() as u64
        {
            let h = seg.header();
            let mut tail = [0u8; MPF_SIGNATURE.len()];
            io.read_at(h.sub(4, tail.len() as u64)?.offset(), &mut tail)
                .await?;
            if tail == *MPF_SIGNATURE {
                found.push(SegmentId::from_index(i)?);
            }
        }
    }
    Ok(found)
}

/// The MPF block of the source, as the segment holding it.
#[cfg(test)]
fn find_mpf<R: Read + Seek>(
    src: &Structure,
    rd: &mut R,
    primary_end: usize,
) -> Result<Option<SegmentId>> {
    use crate::container_api::block_on;

    let found = block_on(src.total_size(), rd, |mut io| async move {
        find_all_mpf(src, &mut io, primary_end).await
    })?;
    Ok(found.first().copied())
}

/// The MPF block rewritten for the output structure, or `None` if no image moved.
///
/// The block records the size and offset of every image, and the offsets count
/// from the block itself, so anything that changes the size of the primary image
/// or moves the block invalidates it. Each recorded value is shifted by how far
/// the image or the block moved. The block has the same length as before, so the
/// structure does not depend on it.
async fn fix_mpf(
    src: &Structure,
    io: &mut Io,
    dest_of: &[Option<SegmentId>],
    dest: &Structure,
) -> Result<Option<(SegmentId, Vec<u8>)>> {
    let subs = src.subassets();
    let primary_end = subs[0].segments().end;
    if subs.len() < 2 {
        return Ok(None);
    }
    let blocks = find_all_mpf(src, io, primary_end).await?;
    let Some(&id) = blocks.first() else {
        return Ok(None);
    };
    let Some(dest_id) = dest_of[id.index()] else {
        return Ok(None);
    };
    let old_base = src.segment(id)?.payload().offset();
    let new_base = dest.segment(dest_id)?.payload().offset();
    let images: Vec<usize> = (0..subs.len())
        .filter(|&k| subs[k].media_type().is_some())
        .collect();
    let moved = images.iter().any(|&k| {
        let (s, d) = (&subs[k], &dest.subassets()[k]);
        s.range() != d.range()
    }) || old_base != new_base;
    if !moved {
        return Ok(None);
    }
    // Only an edit that must rewrite the index needs to know which one is real.
    if blocks.len() > 1 {
        return Err(Error::Ambiguous {
            what: "MPF block",
            count: blocks.len(),
        });
    }

    let block = src.segment(id)?.payload();
    let mut payload = io.read_vec(block.offset(), block.len() as usize).await?;
    let bad = || Error::InvalidFormat("MPF index is not well formed".into());
    let mismatch = |what: String, recorded: u64, found: u64| {
        Error::InvalidFormat(format!(
            "MPF index does not match the images in the file: {what} is recorded as {recorded}, \
             found {found}"
        ))
    };
    let to_u32 = |v: u64| -> Result<u32> {
        u32::try_from(v).map_err(|_| Error::LimitExceeded {
            what: "MPF value",
            limit: u32::MAX as u64,
        })
    };
    let index = MpIndex::parse(&payload).ok_or_else(bad)?;
    if index.entries.len() != images.len() {
        return Err(mismatch(
            "the number of images".into(),
            index.entries.len() as u64,
            images.len() as u64,
        ));
    }
    for (n, &k) in images.iter().enumerate() {
        let (s, d) = (subs[k].range(), dest.subassets()[k].range());
        let at = index.entries[n];

        // The recorded values must describe the file as it is. Rewriting a wrong
        // index would only move the error. The size of the first image is the one
        // exception: writers in the wild record a few hundred bytes less than the
        // image (every Pixel Ultra HDR sample does), nothing is located by it, and
        // it is rewritten to the true size below. One that claims more than the
        // image is not.
        let size = u64::from(index.u32(&payload, at).ok_or_else(bad)?);
        let size_ok = if n == 0 {
            size <= s.len()
        } else {
            size == s.len()
        };
        if !size_ok {
            return Err(mismatch(format!("the size of image {n}"), size, s.len()));
        }
        index.put(&mut payload, at, to_u32(d.len())?);

        // The first image is at offset 0 by definition; the others are recorded
        // relative to the block, and are what readers find the images by.
        let off = u64::from(index.u32(&payload, at + 4).ok_or_else(bad)?);
        let expected = if n == 0 {
            Some(0)
        } else {
            s.offset().checked_sub(old_base)
        };
        match expected {
            Some(e) if e == off => {}
            e => {
                return Err(mismatch(
                    format!("the offset of image {n}"),
                    off,
                    e.unwrap_or(0),
                ))
            }
        }
        if n > 0 {
            let new = d.offset().checked_sub(new_base).ok_or_else(bad)?;
            index.put(&mut payload, at + 4, to_u32(new)?);
        }
    }
    Ok(Some((dest_id, payload)))
}

/// What the entropy-coded data scanner found.
enum Event {
    /// A restart marker `FF Dn`: offset of its `FF` and the marker byte.
    Rst(u64, u8),
    /// The first marker that is not a restart marker: offset of its `FF`.
    Marker(u64),
}

/// The state of a scan of entropy-coded data, which sees it in chunks. `FF 00` is
/// stuffing and `FF FF` is fill; `FF D0..D7` is a restart marker; any other `FF xx`
/// ends the scan.
#[derive(Default)]
struct Entropy {
    /// The last byte of the previous chunk, or the previous byte, was `FF`.
    prev_ff: bool,
}

impl Entropy {
    /// The next event in `chunk`, which starts at stream offset `base`, looking from
    /// `*idx` on and leaving it after what was found. `None` when the chunk is used
    /// up.
    fn next_in(&mut self, chunk: &[u8], base: u64, idx: &mut usize) -> Option<Event> {
        while *idx < chunk.len() {
            if !self.prev_ff {
                // Entropy data is almost all non-0xFF: skip to the next 0xFF.
                match memchr::memchr(0xff, &chunk[*idx..]) {
                    Some(p) => {
                        *idx += p + 1;
                        self.prev_ff = true;
                    }
                    None => *idx = chunk.len(),
                }
                continue;
            }
            // The previous byte was 0xFF; this one says what it was.
            let byte = chunk[*idx];
            let at = base + *idx as u64;
            *idx += 1;
            match byte {
                0x00 => self.prev_ff = false,
                0xff => {} // fill: the last FF is the marker prefix
                0xd0..=0xd7 => {
                    self.prev_ff = false;
                    return Some(Event::Rst(at - 1, byte));
                }
                _ => return Some(Event::Marker(at - 1)),
            }
        }
        None
    }
}

// ----------------------------------------------------------------------------
// Planning
// ----------------------------------------------------------------------------

enum Op<'a> {
    /// Copy a source segment unchanged.
    Copy(SegmentId),
    /// Standard XMP in one APP1.
    XmpStd { payload: &'a [u8] },
    /// Stub main XMP pointing at extended XMP.
    XmpMain { payload: Vec<u8> },
    /// One extended XMP chunk.
    XmpExt {
        guid: [u8; 32],
        total: u32,
        offset: u32,
        payload: &'a [u8],
    },
    /// One JPEG XT APP11 part of a C2PA store.
    Jumbf {
        en: u16,
        seq: u32,
        lbox_tbox: [u8; 8],
        payload: &'a [u8],
    },
}

/// The marker of a new segment.
fn new_marker(op: &Op<'_>) -> Result<u8> {
    match op {
        Op::Copy(_) => Err(Error::InvalidFormat("not a new segment".into())),
        Op::XmpStd { .. } | Op::XmpMain { .. } | Op::XmpExt { .. } => Ok(APP1),
        Op::Jumbf { .. } => Ok(APP11),
    }
}

/// New items of the destination, and the ops they are made of.
type Groups = Vec<(ItemInfo, Vec<usize>)>;

fn push_new_xmp<'a>(ops: &mut Vec<Op<'a>>, groups: &mut Groups, xmp: &'a [u8]) -> Result<()> {
    let first = ops.len();
    if xmp.len() as u64 <= MAX_STD_XMP {
        ops.push(Op::XmpStd { payload: xmp });
    } else {
        let total = u32::try_from(xmp.len()).map_err(|_| Error::LimitExceeded {
            what: "XMP size",
            limit: u32::MAX as u64,
        })?;
        let guid_str = format!("{:032x}", md5::compute(xmp));
        if guid_str.len() != 32 {
            return Err(Error::InvalidFormat("unexpected GUID length".into()));
        }
        let mut guid = [0u8; 32];
        guid.copy_from_slice(guid_str.as_bytes());
        let stub = format!(
            r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
  <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
    <rdf:Description rdf:about=""
      xmlns:xmpNote="http://ns.adobe.com/xmp/note/">
      <xmpNote:HasExtendedXMP>{guid_str}</xmpNote:HasExtendedXMP>
    </rdf:Description>
  </rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>"#
        );
        ops.push(Op::XmpMain {
            payload: stub.into_bytes(),
        });
        let mut off = 0usize;
        while off < xmp.len() {
            let n = (xmp.len() - off).min(EXT_CHUNK);
            ops.push(Op::XmpExt {
                guid,
                total,
                offset: off as u32,
                payload: &xmp[off..off + n],
            });
            off += n;
        }
    }
    groups.push((ItemInfo::xmp(), (first..ops.len()).collect()));
    Ok(())
}

/// Add the APP11 segments of C2PA store `jumbf`, as JUMBF box instance `en`.
fn push_new_jumbf<'a>(
    ops: &mut Vec<Op<'a>>,
    groups: &mut Groups,
    jumbf: &'a [u8],
    en: u16,
) -> Result<()> {
    if jumbf.len() < 8 || jumbf[4..8] != JUMB[..] {
        return Err(Error::InvalidFormat(
            "JUMBF must begin with a jumb superbox (LBox, TBox)".into(),
        ));
    }
    // JPEG carries JUMBF of any type, and tells a C2PA store by its type.
    let ty = crate::jumbf::superbox_type(jumbf);
    if ty != Some(crate::jumbf::C2PA_STORE_TYPE) {
        return Err(Error::InvalidFormat(
            "a C2PA store in JPEG must be a JUMBF superbox of the C2PA store type".into(),
        ));
    }
    let mut lbox_tbox = [0u8; 8];
    lbox_tbox.copy_from_slice(&jumbf[..8]);
    let first = ops.len();
    for (i, chunk) in jumbf.chunks(JUMBF_CHUNK).enumerate() {
        let seq = u32::try_from(i + 1).map_err(|_| Error::LimitExceeded {
            what: "JUMBF parts",
            limit: u32::MAX as u64,
        })?;
        ops.push(Op::Jumbf {
            en,
            seq,
            lbox_tbox,
            payload: chunk,
        });
    }
    groups.push((
        ItemInfo::c2pa().jumbf_type(ty).native_id(u64::from(en)),
        (first..ops.len()).collect(),
    ));
    Ok(())
}

/// New metadata goes before the first non-application marker.
fn is_insertion_point(seg: &Segment) -> bool {
    seg.kind() != SegmentKind::Preamble
        && matches!(seg.name(), Name::Marker(m) if !(0xE0..=0xEF).contains(&m) && m != 0xFE)
}

/// Decide what the output contains and describe how to write it.
async fn plan<'a>(src: &Structure, io: &mut Io, updates: &'a Updates) -> Result<WritePlan<'a>> {
    let (ops, groups) = plan_ops(src, updates)?;
    let mut b = PlanBuilder::new(src);
    let mut ids = Vec::with_capacity(ops.len());
    for op in ops {
        ids.push(match op {
            Op::Copy(sid) => b.copy_segment(sid)?,
            new => {
                let marker = new_marker(&new)?;
                let mut hdr = [0u8; MAX_HEADER];
                let (n, _) = encode_new(&new, &mut hdr)?;
                let payload: Cow<'a, [u8]> = match new {
                    Op::XmpStd { payload }
                    | Op::XmpExt { payload, .. }
                    | Op::Jumbf { payload, .. } => Cow::Borrowed(payload),
                    Op::XmpMain { payload } => Cow::Owned(payload),
                    Op::Copy(_) => return Err(Error::InvalidFormat("not a new segment".into())),
                };
                b.put_segment(
                    SegmentKind::Metadata,
                    Name::Marker(marker),
                    hdr[..n].to_vec(),
                    payload,
                    &[][..],
                )?
            }
        });
    }
    // New items first, then those of kept segments, as they were.
    for (info, idx) in groups {
        let group: Vec<SegmentId> = idx.iter().map(|&i| ids[i]).collect();
        b.item(info, &group)?;
    }
    b.carry_items(|_| true);
    let dest_of = (src.subassets().len() > 1).then(|| b.dest_map().to_vec());
    let mut plan = b.finish()?;
    if let Some(dest_of) = dest_of {
        if let Some((id, payload)) = fix_mpf(src, io, &dest_of, plan.structure()).await? {
            plan.replace(id, Role::Payload, payload)?;
        }
    }
    Ok(plan)
}

/// Decide what the output contains: the ops, and the items made of new ones.
fn plan_ops<'a>(src: &Structure, updates: &'a Updates) -> Result<(Vec<Op<'a>>, Groups)> {
    let n = src.segments().len();
    let primary_end = src.subassets()[0].segments().end;
    let mut ops: Vec<Op<'a>> = Vec::with_capacity(n + 2);
    let mut groups: Groups = Vec::new();
    let mut xmp = MetadataSlot::new(updates.xmp());
    let mut c2pa = MetadataSlot::new(updates.c2pa());
    let mut inserted = false;

    // What each segment holds, from the items: XMP, the C2PA store, or anything
    // else (other JUMBF included), which is kept. A new store takes a box instance
    // number (En) that no other JPEG XT box (JUMBF or UUID) uses.
    let mut held: Vec<Option<ItemKind>> = vec![None; n];
    let mut used_en = Vec::new();
    for item in src.items() {
        let kind = item.kind();
        match kind {
            ItemKind::Xmp | ItemKind::C2pa => {}
            _ if matches!(
                item.encoding(),
                crate::Encoding::Jumbf | crate::Encoding::IsoBmff
            ) =>
            {
                used_en.extend(item.native_id());
                continue;
            }
            _ => continue,
        }
        for p in item.extents() {
            held[p.segment().index()] = Some(kind);
        }
    }
    let en = std::iter::once(XT_EN)
        .chain(1..=u16::MAX)
        .find(|en| !used_en.contains(&u64::from(*en)))
        .ok_or(Error::LimitExceeded {
            what: "JUMBF box instances",
            limit: u64::from(u16::MAX),
        })?;

    for (i, seg) in src.segments().iter().enumerate() {
        let id = SegmentId::from_index(i)?;
        match held[i] {
            Some(ItemKind::Xmp) => match xmp.existing() {
                Existing::Keep => ops.push(Op::Copy(id)),
                Existing::Replace(d) => push_new_xmp(&mut ops, &mut groups, d)?,
                _ => {}
            },
            Some(ItemKind::C2pa) => match c2pa.existing() {
                Existing::Keep => ops.push(Op::Copy(id)),
                Existing::Replace(d) => push_new_jumbf(&mut ops, &mut groups, d, en)?,
                _ => {}
            },
            Some(_) => ops.push(Op::Copy(id)),
            None => {
                if !inserted && i < primary_end && is_insertion_point(seg) {
                    inserted = true;
                    if let Some(d) = xmp.pending() {
                        push_new_xmp(&mut ops, &mut groups, d)?;
                    }
                    if let Some(d) = c2pa.pending() {
                        push_new_jumbf(&mut ops, &mut groups, d, en)?;
                    }
                }
                ops.push(Op::Copy(id));
            }
        }
    }
    Ok((ops, groups))
}

fn put_marker_len(hdr: &mut [u8], marker: u8, header_len: u32, payload_len: u64) -> Result<()> {
    let v = (header_len as u64 - 2).saturating_add(payload_len);
    let v = u16::try_from(v).map_err(|_| Error::LimitExceeded {
        what: "JPEG segment length",
        limit: MAX_LEN_FIELD,
    })?;
    hdr[0] = 0xff;
    hdr[1] = marker;
    hdr[2..4].copy_from_slice(&v.to_be_bytes());
    Ok(())
}

/// Build the header of a new segment in `hdr`; returns its length and the payload.
fn encode_new<'o>(op: &'o Op<'_>, hdr: &mut [u8; MAX_HEADER]) -> Result<(usize, &'o [u8])> {
    let (n, payload): (usize, &[u8]) = match op {
        Op::Copy(_) => return Err(Error::InvalidFormat("not a new segment".into())),
        Op::XmpStd { payload } => {
            let h = 4 + XMP_SIG_LEN;
            put_marker_len(&mut hdr[..], APP1, h as u32, payload.len() as u64)?;
            hdr[4..h].copy_from_slice(XMP_SIGNATURE);
            (h, payload)
        }
        Op::XmpMain { payload } => {
            let h = 4 + XMP_SIG_LEN;
            put_marker_len(&mut hdr[..], APP1, h as u32, payload.len() as u64)?;
            hdr[4..h].copy_from_slice(XMP_SIGNATURE);
            (h, payload.as_slice())
        }
        Op::XmpExt {
            guid,
            total,
            offset,
            payload,
        } => {
            let h = 4 + EXT_PREFIX_LEN;
            put_marker_len(&mut hdr[..], APP1, h as u32, payload.len() as u64)?;
            let mut p = 4;
            hdr[p..p + EXT_SIG_LEN].copy_from_slice(XMP_EXT_SIGNATURE);
            p += EXT_SIG_LEN;
            hdr[p..p + 32].copy_from_slice(guid);
            p += 32;
            hdr[p..p + 4].copy_from_slice(&total.to_be_bytes());
            p += 4;
            hdr[p..p + 4].copy_from_slice(&offset.to_be_bytes());
            (h, payload)
        }
        Op::Jumbf {
            en,
            seq,
            lbox_tbox,
            payload,
        } => {
            let h = if *seq > 1 { 4 + 16 } else { 4 + 8 };
            put_marker_len(&mut hdr[..], APP11, h as u32, payload.len() as u64)?;
            hdr[4..6].copy_from_slice(&JP);
            hdr[6..8].copy_from_slice(&en.to_be_bytes());
            hdr[8..12].copy_from_slice(&seq.to_be_bytes());
            if *seq > 1 {
                hdr[12..20].copy_from_slice(lbox_tbox);
            }
            (h, payload)
        }
    };
    Ok((n, payload))
}

/// The segments `write` inserts for new XMP or a C2PA store, as one byte string.
fn compose(kind: ItemKind, data: &[u8]) -> Result<Vec<u8>> {
    let mut ops = Vec::new();
    let mut groups = Groups::new();
    match kind {
        ItemKind::C2pa => push_new_jumbf(&mut ops, &mut groups, data, XT_EN)?,
        ItemKind::Xmp => push_new_xmp(&mut ops, &mut groups, data)?,
        _ => return Err(Error::UnsupportedFormat),
    }
    let mut out = Vec::with_capacity(data.len() + ops.len() * MAX_HEADER);
    for op in &ops {
        let mut hdr = [0u8; MAX_HEADER];
        let (n, payload) = encode_new(op, &mut hdr)?;
        out.extend_from_slice(&hdr[..n]);
        out.extend_from_slice(payload);
    }
    Ok(out)
}

// ----------------------------------------------------------------------------
// Reading
// ----------------------------------------------------------------------------

/// The JUMBF bytes (XT framing removed, extents concatenated), or `None`.
/// Several distinct JUMBF boxes is an error.
#[cfg(test)]
fn read_jumbf<R: Read + Seek>(s: &Structure, src: &mut R) -> Result<Option<Vec<u8>>> {
    match s.item(ItemKind::C2pa)? {
        Some(e) => s.read_item(src, e).map(Some),
        None => Ok(None),
    }
}

/// The XMP packet, or `None`. With extended XMP, the reassembled extended
/// packet is returned (the standard packet only carries a pointer to it).
fn read_xmp<R: Read + Seek>(s: &Structure, src: &mut R) -> Result<Option<Vec<u8>>> {
    let Some(e) = s.item(ItemKind::Xmp)? else {
        return Ok(None);
    };
    if e.extent_count() == 1 {
        return s.read_item(src, e).map(Some);
    }

    let parts: Vec<&Extent> = e.extents().collect();
    let mut guid: Option<[u8; 32]> = None;
    let mut total: Option<u32> = None;
    let mut capacity = 0u64;
    let mut chunks: Vec<(ByteRange, u32)> = Vec::with_capacity(parts.len() - 1);

    for p in &parts[1..] {
        let header = s.segment(p.segment())?.header();
        if header.len() < 40 {
            return Err(Error::invalid_segment(
                header.offset(),
                "extended XMP header too short",
            ));
        }
        let tail = s.read_range(src, header.sub(header.len() - 40, 40)?)?;
        let mut g = [0u8; 32];
        g.copy_from_slice(&tail[..32]);
        let t = u32::from_be_bytes([tail[32], tail[33], tail[34], tail[35]]);
        let off = u32::from_be_bytes([tail[36], tail[37], tail[38], tail[39]]);
        match (guid, total) {
            (Some(pg), Some(pt)) if pg != g || pt != t => {
                return Err(Error::InvalidFormat(
                    "inconsistent extended XMP parts".into(),
                ));
            }
            _ => {
                guid = Some(g);
                total = Some(t);
            }
        }
        capacity = capacity.saturating_add(p.range().len());
        chunks.push((p.range(), off));
    }

    let total = total.ok_or(Error::NotFound {
        what: "extended XMP",
    })?;
    // The allocation is bounded by data actually present in the file.
    if total > MAX_EXT_XMP || total as u64 > capacity {
        return Err(Error::LimitExceeded {
            what: "extended XMP size",
            limit: capacity.min(MAX_EXT_XMP as u64),
        });
    }
    let mut out = vec![0u8; total as usize];
    for (range, off) in chunks {
        let end = off as u64 + range.len();
        if end > total as u64 {
            return Err(Error::invalid_segment(
                range.offset(),
                "extended XMP chunk outside declared length",
            ));
        }
        let data = s.read_range(src, range)?;
        out[off as usize..end as usize].copy_from_slice(&data);
    }
    Ok(Some(out))
}

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

    use sha2::{Digest, Sha256};

    use super::*;
    use crate::{
        testing::{c2pa_store_of_len, jumbf, rewrite, Conformance},
        Chunk, NullSink, Sink,
    };

    fn marker(m: u8, data: &[u8]) -> Vec<u8> {
        let mut v = vec![0xff, m];
        v.extend_from_slice(&((data.len() + 2) as u16).to_be_bytes());
        v.extend_from_slice(data);
        v
    }

    fn sample_jpeg() -> Vec<u8> {
        let mut v = vec![0xff, SOI];
        v.extend(marker(0xe0, b"JFIF\0\x01\x01\0\0\x01\0\x01\0\0"));
        v.extend(marker(0xdb, &[0u8; 65]));
        v.extend(marker(0xdb, &[1u8; 65])); // second DQT
        v.extend(marker(0xc0, &[8, 0, 1, 0, 1, 1, 1, 0x11, 0]));
        v.extend(marker(0xc4, &[0u8; 20]));
        v.extend(marker(SOS, &[1, 1, 0, 0, 0x3f, 0]));
        v.extend_from_slice(&[0x12, 0x34, 0xff, 0x00, 0x56]);
        v.extend_from_slice(&[0xff, EOI]);
        v
    }

    #[test]
    fn box_names() {
        let n = |m| marker_symbol(m).into_owned();
        assert_eq!(n(0xd8), "SOI");
        assert_eq!(n(0xd9), "EOI");
        assert_eq!(n(0xda), "SOS");
        assert_eq!(n(0xe0), "APP0");
        assert_eq!(n(0xeb), "APP11");
        assert_eq!(n(0xef), "APP15");
        assert_eq!(n(0xc0), "SOF0");
        assert_eq!(n(0xc2), "SOF2");
        assert_eq!(n(0xc4), "DHT");
        assert_eq!(n(0xcc), "DAC");
        assert_eq!(n(0xd0), "RST0");
        assert_eq!(n(0xd7), "RST7");
        assert_eq!(n(0xdb), "DQT");
        assert_eq!(n(0xdd), "DRI");
        assert_eq!(n(0xf0), "JPG0");
        assert_eq!(n(0xfd), "JPG13");
        assert_eq!(n(0xfe), "COM");
        assert_eq!(n(0x10), "RES");
        let s = parse(&mut Cursor::new(sample_jpeg())).unwrap();
        let unnamed = Segment::new(
            ByteRange::new(0, 1).unwrap(),
            0,
            0,
            SegmentKind::Other,
            Name::None,
        )
        .unwrap();
        assert!(s
            .box_name(SegmentId::from_index(0).unwrap(), &unnamed)
            .is_none());
    }

    #[test]
    fn a_scan_is_one_image_data_segment() {
        let j = sample_jpeg();
        let s = parse(&mut Cursor::new(j)).unwrap();
        let scan = s
            .segments()
            .iter()
            .find(|g| g.kind() == SegmentKind::MediaData)
            .unwrap();
        assert_eq!(scan.payload().len(), 5);
    }

    #[test]
    fn conforms() {
        let c = Conformance::new(handler()).c2pa(Some(c2pa_store_of_len(70_000)));
        c.check("sample", &sample_jpeg());
        c.check("minimal", &[0xff, SOI, 0xff, EOI]);

        let mut fill = vec![0xff, SOI];
        fill.extend(marker(0xe0, b"JFIF\0"));
        fill.push(0xff); // fill byte before the next marker
        fill.extend(marker(0xdb, &[0u8; 65]));
        fill.extend_from_slice(&[0xff, EOI]);
        fill.extend_from_slice(b"trailing");
        c.check("fill bytes and trailing data", &fill);

        c.check(
            "multi-picture",
            &mpf_file(&second_image(), b"tail", 0, false),
        );
        c.check(
            "multi-picture, little-endian",
            &mpf_file(&second_image(), b"", 0, true),
        );

        // Too big for one APP1: standard XMP stub plus extended chunks.
        let big = vec![b'x'; 100_000];
        Conformance::new(handler())
            .xmp(Some(big))
            .mutations(false)
            .check("extended xmp", &sample_jpeg());
    }

    #[test]
    fn rejects_malformed_input() {
        let j = sample_jpeg();
        assert!(parse(&mut Cursor::new(j[..j.len() - 10].to_vec())).is_err());
        let bad = vec![0xff, SOI, 0xff, 0xe0, 0xff, 0xff, 1, 2, 3];
        assert!(parse(&mut Cursor::new(bad)).is_err());
        let short_len = vec![0xff, SOI, 0xff, 0xe0, 0x00, 0x01, 0xff, EOI];
        assert!(parse(&mut Cursor::new(short_len)).is_err());
        assert!(parse(&mut Cursor::new(vec![1, 2, 3, 4])).is_err());
    }

    #[test]
    fn minimal_file_still_gets_metadata() {
        let j = vec![0xff, SOI, 0xff, EOI];
        let updates = Updates::new().set_c2pa(c2pa_store_of_len(100));
        let (out, dest) = rewrite(handler(), &j, &updates).unwrap();
        let e = dest.require_item(ItemKind::C2pa).unwrap();
        assert_eq!(
            dest.read_item(&mut Cursor::new(out), e).unwrap(),
            c2pa_store_of_len(100)
        );
    }

    #[test]
    fn single_part_jumbf_round_trip() {
        let j = sample_jpeg();
        let data = c2pa_store_of_len(1000);
        let (out, dest) = rewrite(handler(), &j, &Updates::new().set_c2pa(data.clone())).unwrap();
        let re = parse(&mut Cursor::new(out.clone())).unwrap();
        let e = re.require_item(ItemKind::C2pa).unwrap();
        assert_eq!(e.extent_count(), 1);
        assert_eq!(
            read_jumbf(&re, &mut Cursor::new(out)).unwrap().unwrap(),
            data
        );
        assert_eq!(dest.total_size(), re.total_size());
    }

    #[test]
    fn multi_segment_jumbf_is_one_item_with_visible_headers() {
        let j = sample_jpeg();
        let data = c2pa_store_of_len(150_000);
        let (out, _) = rewrite(handler(), &j, &Updates::new().set_c2pa(data.clone())).unwrap();
        let re = parse(&mut Cursor::new(out.clone())).unwrap();
        let e = re.require_item(ItemKind::C2pa).unwrap();
        assert_eq!(e.extent_count(), 3);
        assert_eq!(e.len(), 150_000);
        assert_eq!(
            re.read_item(&mut Cursor::new(out.clone()), e).unwrap(),
            data
        );
        // Continuation headers repeat LBox/TBox and are header, not payload.
        for p in e.extents().skip(1) {
            let h = re.segment(p.segment()).unwrap().header();
            let tail = &out[(h.end() - 8) as usize..h.end() as usize];
            assert_eq!(tail, &data[..8]);
        }
    }

    #[test]
    fn two_distinct_jumbf_boxes_are_ambiguous() {
        let j = sample_jpeg();
        let (out, _) = rewrite(
            handler(),
            &j,
            &Updates::new().set_c2pa(c2pa_store_of_len(100)),
        )
        .unwrap();
        // Append a second, unrelated JUMBF APP11 (new box instance, Z = 1).
        let mut second = Vec::new();
        let body = c2pa_store_of_len(50);
        let mut data = b"JP".to_vec();
        data.extend_from_slice(&0x9999u16.to_be_bytes());
        data.extend_from_slice(&1u32.to_be_bytes());
        data.extend_from_slice(&body);
        second.extend(marker(APP11, &data));
        // Insert right after SOI. (Before EOI would fall inside the scan data.)
        let at = 2;
        let mut two = out[..at].to_vec();
        two.extend(second);
        two.extend_from_slice(&out[at..]);
        let s = parse(&mut Cursor::new(two)).unwrap();
        assert!(matches!(
            s.item(ItemKind::C2pa),
            Err(Error::Ambiguous { count: 2, .. })
        ));
        assert_eq!(s.items_of(ItemKind::C2pa).count(), 2);
    }

    /// Progressive-style file: two scans, restart markers in the first, and a
    /// manifest placed after the last scan.
    fn multi_scan_jpeg() -> Vec<u8> {
        let mut j = vec![0xff, SOI];
        j.extend(marker(0xe0, b"JFIF\0"));
        j.extend(marker(0xc2, &[8, 0, 1, 0, 1, 1, 1, 0x11, 0]));
        j.extend(marker(0xc4, &[0u8; 20]));
        j.extend(marker(SOS, &[1, 1, 0, 0, 0x3f, 0]));
        // stuffed byte, RST0, fill + RST1
        j.extend_from_slice(&[
            0x11, 0xff, 0x00, 0x22, 0xff, 0xd0, 0x33, 0xff, 0xff, 0xd1, 0x44,
        ]);
        j.extend(marker(0xc4, &[0u8; 20]));
        j.extend(marker(SOS, &[1, 1, 0, 0, 0x3f, 0]));
        j.extend_from_slice(&[0x55, 0x66]);
        let mut d = b"JP".to_vec();
        d.extend_from_slice(&0x0211u16.to_be_bytes());
        d.extend_from_slice(&1u32.to_be_bytes());
        d.extend(c2pa_store_of_len(60));
        j.extend(marker(APP11, &d));
        j.extend_from_slice(&[0xff, EOI]);
        j
    }

    fn elements_of(s: &Structure) -> Vec<(Name, ByteRange)> {
        let mut els = Vec::new();
        s.elements(|_, e| {
            els.push((e.name(), e.range()));
            Ok(())
        })
        .unwrap();
        els
    }

    #[test]
    fn replacing_a_manifest_keeps_its_offset() {
        // C2PA 11.2.3: for an update manifest the store must keep its file offset;
        // only its length may change.
        let j = sample_jpeg();
        let (with, d1) = rewrite(
            handler(),
            &j,
            &Updates::new().set_c2pa(c2pa_store_of_len(100)),
        )
        .unwrap();
        let start = |s: &Structure| {
            let e = s.require_item(ItemKind::C2pa).unwrap();
            let first = e.extents().next().unwrap();
            s.segment(first.segment()).unwrap().range().offset()
        };
        for n in [60usize, 100, 70_000] {
            let (out, d2) = rewrite(
                handler(),
                &with,
                &Updates::new().set_c2pa(c2pa_store_of_len(n)),
            )
            .unwrap();
            assert_eq!(start(&d2), start(&d1), "offset moved for {n} bytes");
            // Everything before the manifest is byte-identical.
            let at = start(&d1) as usize;
            assert_eq!(out[..at], with[..at]);
        }
    }

    #[test]
    fn multi_scan_and_restart_markers() {
        let j = multi_scan_jpeg();
        let s = parse(&mut Cursor::new(j.clone())).unwrap();

        // Two scans; only the first has restart markers.
        let scans: Vec<_> = s
            .segments()
            .iter()
            .filter(|g| g.kind() == SegmentKind::MediaData)
            .collect();
        assert_eq!(scans.len(), 2);
        assert!(scans[0].subdivides());
        assert!(!scans[1].subdivides());

        // The manifest after the last scan is found.
        assert_eq!(s.items_of(ItemKind::C2pa).count(), 1);

        // elements() expands the scan and tiles the file.
        let els = elements_of(&s);
        let names: Vec<Name> = els.iter().map(|(n, _)| *n).collect();
        let m = Name::Marker;
        assert_eq!(
            names,
            [
                m(SOI),
                m(0xe0),
                m(0xc2),
                m(0xc4),
                m(SOS),
                m(0xd0),
                m(0xd1),
                m(0xc4),
                m(SOS),
                m(APP11),
                m(EOI)
            ]
        );
        let mut box_names = Vec::new();
        s.elements(|id, element| {
            box_names.push(s.box_name(id, element).unwrap().into_owned());
            Ok(())
        })
        .unwrap();
        assert_eq!(
            box_names,
            ["SOI", "APP0", "SOF2", "DHT", "SOS", "RST0", "RST1", "DHT", "SOS", "APP11", "EOI"]
        );
        let mut next = 0;
        for (name, r) in &els {
            assert_eq!(r.offset(), next);
            next = r.end();
            if let Name::Marker(c @ 0xd0..=0xd7) = name {
                assert_eq!(
                    &j[r.offset() as usize..r.offset() as usize + 2],
                    &[0xff, *c]
                );
            }
        }
        assert_eq!(next, j.len() as u64);

        // Round trip preserves structure, including the subdivision flag.
        let (out, dest) = rewrite(handler(), &j, &Updates::new()).unwrap();
        assert_eq!(out, j);
        assert_eq!(dest.segments(), s.segments());

        // Set replaces the manifest that follows the scans; no second one appears.
        let (out, dest) = rewrite(
            handler(),
            &j,
            &Updates::new().set_c2pa(c2pa_store_of_len(200)),
        )
        .unwrap();
        assert_eq!(dest.items_of(ItemKind::C2pa).count(), 1);
        let re = parse(&mut Cursor::new(out)).unwrap();
        assert_eq!(re.segments(), dest.segments());
    }

    #[test]
    fn restart_markers_do_not_inflate_the_structure() {
        let mut j = vec![0xff, SOI];
        j.extend(marker(SOS, &[1, 1, 0, 0, 0x3f, 0]));
        for i in 0..20_000u32 {
            j.extend_from_slice(&[0x01, 0xff, 0xd0 + (i % 8) as u8]);
        }
        j.extend_from_slice(&[0xff, EOI]);
        let s = parse(&mut Cursor::new(j.clone())).unwrap();
        assert!(s.segments().len() <= 4, "{} segments", s.segments().len());
        // SOI, the scan up to its first restart marker, 20 000 restart elements, EOI.
        assert_eq!(elements_of(&s).len(), 1 + 1 + 20_000 + 1);
    }

    #[test]
    fn a_restart_marker_may_open_the_entropy_data() {
        let mut j = vec![0xff, SOI];
        j.extend(marker(SOS, &[1, 1, 0, 0, 0x3f, 0]));
        let sos_end = j.len() as u64;
        j.extend_from_slice(&[0xff, 0xd0, 0x01, 0xff, 0xd1, 0x02, 0xff, EOI]);
        let s = parse(&mut Cursor::new(j.clone())).unwrap();
        let els = elements_of(&s);
        let names: Vec<Name> = els.iter().map(|(n, _)| *n).collect();
        let m = Name::Marker;
        assert_eq!(names, [m(SOI), m(SOS), m(0xd0), m(0xd1), m(EOI)]);
        assert_eq!(els[1].1.end(), sos_end, "the scan box is its header");
    }

    #[test]
    fn elements_pass_through_when_nothing_subdivides() {
        let j = sample_jpeg();
        let s = parse(&mut Cursor::new(j.clone())).unwrap();
        let els = elements_of(&s);
        assert_eq!(els.len(), s.segments().len());
        for ((_, r), g) in els.iter().zip(s.segments()) {
            assert_eq!(*r, g.range());
        }
    }

    #[test]
    fn jumbf_segments_must_be_contiguous() {
        // C2PA A.3.1: APP11 segments of one manifest are sequential and contiguous.
        let j = sample_jpeg();
        let body = c2pa_store_of_len(100);
        let packet = |z: u32, data: &[u8]| {
            let mut d = b"JP".to_vec();
            d.extend_from_slice(&0x0211u16.to_be_bytes());
            d.extend_from_slice(&z.to_be_bytes());
            d.extend_from_slice(data);
            marker(APP11, &d)
        };
        let p1 = packet(1, &body[..60]);
        let mut rest = body[..8].to_vec(); // repeated LBox/TBox
        rest.extend_from_slice(&body[60..]);
        let p2 = packet(2, &rest);
        let build = |between: &[u8]| {
            let mut v = j[..2].to_vec();
            v.extend(&p1);
            v.extend_from_slice(between);
            v.extend(&p2);
            v.extend_from_slice(&j[2..]);
            v
        };

        let ok = parse(&mut Cursor::new(build(&[]))).unwrap();
        let e = ok.require_item(ItemKind::C2pa).unwrap();
        assert_eq!(e.extent_count(), 2);

        let gap = marker(0xfe, b"comment"); // COM between the packets
        assert!(matches!(
            parse(&mut Cursor::new(build(&gap))),
            Err(Error::InvalidFormat(_))
        ));
    }

    #[test]
    fn a_c2pa_store_is_told_by_its_superbox_type() {
        let store = c2pa_store_of_len(100);
        let (out, dest) =
            rewrite(handler(), &sample_jpeg(), &Updates::new().set_c2pa(store)).unwrap();
        let s = parse(&mut Cursor::new(out)).unwrap();
        for st in [&dest, &s] {
            let e = st.require_item(ItemKind::C2pa).unwrap();
            assert_eq!(e.jumbf_type(), Some(crate::jumbf::C2PA_STORE_TYPE));
            assert_eq!(e.native_id(), Some(u64::from(XT_EN)));
        }

        // JUMBF of another type is other JUMBF, not a store.
        let other = with_jumbf(&sample_jpeg(), 7, &jumbf([2; 16], &[b"other"]));
        let s = parse(&mut Cursor::new(other)).unwrap();
        assert!(s.item(ItemKind::C2pa).unwrap().is_none());
        let e = s.require_item(ItemKind::Other).unwrap();
        assert_eq!(e.encoding(), crate::Encoding::Jumbf);
        assert_eq!(e.jumbf_type(), Some([2; 16]));
        assert_eq!(e.native_id(), Some(7));
    }

    #[test]
    fn a_c2pa_store_must_have_the_c2pa_type() {
        let j = parse(&mut Cursor::new(sample_jpeg())).unwrap();
        let mut untyped = vec![0u8; 40];
        untyped[0..4].copy_from_slice(&40u32.to_be_bytes());
        untyped[4..8].copy_from_slice(b"jumb");
        for store in [jumbf([1; 16], &[b"other"]), untyped] {
            let updates = Updates::new().set_c2pa(store);
            assert!(matches!(
                j.write_plan(&mut Cursor::new(sample_jpeg()), &updates),
                Err(Error::InvalidFormat(_))
            ));
        }
    }

    #[test]
    fn zero_based_xt_packet_is_recognised() {
        // Some writers (e.g. Designer.jpeg) number the first XT packet Z = 0.
        let j = sample_jpeg();
        let body = c2pa_store_of_len(100);
        let mut data = b"JP".to_vec();
        data.extend_from_slice(&0xf400u16.to_be_bytes());
        data.extend_from_slice(&0u32.to_be_bytes());
        data.extend_from_slice(&body);
        let mut with = j[..2].to_vec();
        with.extend(marker(APP11, &data));
        with.extend_from_slice(&j[2..]);

        let s = parse(&mut Cursor::new(with.clone())).unwrap();
        assert_eq!(s.items_of(ItemKind::C2pa).count(), 1);
        let e = s.require_item(ItemKind::C2pa).unwrap();
        assert_eq!(
            s.read_item(&mut Cursor::new(with.clone()), e).unwrap(),
            body
        );

        // Set replaces it rather than adding a second manifest.
        let new = c2pa_store_of_len(200);
        let (out, dest) = rewrite(handler(), &with, &Updates::new().set_c2pa(new)).unwrap();
        assert_eq!(dest.items_of(ItemKind::C2pa).count(), 1);
        assert_eq!(
            parse(&mut Cursor::new(out))
                .unwrap()
                .items_of(ItemKind::C2pa)
                .count(),
            1
        );
    }

    /// `jpeg` with `body` in one JPEG XT APP11 segment, box instance `en`, after SOI.
    fn with_jumbf(jpeg: &[u8], en: u16, body: &[u8]) -> Vec<u8> {
        let mut data = b"JP".to_vec();
        data.extend_from_slice(&en.to_be_bytes());
        data.extend_from_slice(&1u32.to_be_bytes());
        data.extend_from_slice(body);
        let mut out = jpeg[..2].to_vec();
        out.extend(marker(APP11, &data));
        out.extend_from_slice(&jpeg[2..]);
        out
    }

    fn jumbf_of(out: &[u8], s: &Structure, e: &crate::Item) -> Vec<u8> {
        s.read_item(&mut Cursor::new(out.to_vec()), e).unwrap()
    }

    /// A file holding other JUMBF, in the box instance a new store would take by
    /// default, and a C2PA store; and the two.
    fn store_and_other() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
        let other = jumbf([2; 16], &[b"other"]);
        let store = c2pa_store_of_len(300);
        let file = with_jumbf(&sample_jpeg(), XT_EN, &other);
        let (file, _) = rewrite(handler(), &file, &Updates::new().set_c2pa(store.clone())).unwrap();
        (file, store, other)
    }

    fn other_jumbf(out: &[u8], s: &Structure) -> Vec<u8> {
        let e = s.require_item(ItemKind::Other).unwrap();
        assert_eq!(e.encoding(), crate::Encoding::Jumbf);
        jumbf_of(out, s, e)
    }

    #[test]
    fn a_new_store_takes_a_box_instance_other_jumbf_does_not_use() {
        let (file, store, other) = store_and_other();
        let s = parse(&mut Cursor::new(file.clone())).unwrap();
        let e = s.require_item(ItemKind::C2pa).unwrap();
        assert_eq!(e.native_id(), Some(1));
        assert_eq!(jumbf_of(&file, &s, e), store);
        assert_eq!(other_jumbf(&file, &s), other);
    }

    #[test]
    fn a_new_store_avoids_the_box_instance_of_a_uuid_box() {
        let mut uuid_box = 32u32.to_be_bytes().to_vec();
        uuid_box.extend_from_slice(b"uuid");
        uuid_box.extend_from_slice(&[9; 16]);
        uuid_box.extend_from_slice(b"payload!");
        let file = with_jumbf(&sample_jpeg(), XT_EN, &uuid_box);
        let store = c2pa_store_of_len(100);
        let (out, _) = rewrite(handler(), &file, &Updates::new().set_c2pa(store.clone())).unwrap();
        let s = parse(&mut Cursor::new(out.clone())).unwrap();
        let e = s.require_item(ItemKind::C2pa).unwrap();
        assert_eq!(e.native_id(), Some(1));
        assert_eq!(jumbf_of(&out, &s, e), store);
        let u = s.require_item(ItemKind::Other).unwrap();
        assert_eq!(u.encoding(), crate::Encoding::IsoBmff);
        assert_eq!(jumbf_of(&out, &s, u), uuid_box);
    }

    #[test]
    fn other_jumbf_is_kept_when_the_store_changes() {
        let (file, _, other) = store_and_other();
        let store2 = c2pa_store_of_len(5000);
        let (out, dest) =
            rewrite(handler(), &file, &Updates::new().set_c2pa(store2.clone())).unwrap();
        let s = parse(&mut Cursor::new(out.clone())).unwrap();
        for st in [&dest, &s] {
            let e = st.require_item(ItemKind::C2pa).unwrap();
            assert_eq!(jumbf_of(&out, st, e), store2);
            assert_eq!(other_jumbf(&out, st), other);
        }

        for updates in [Updates::new().remove_c2pa(), Updates::remove_all()] {
            let (out, _) = rewrite(handler(), &file, &updates).unwrap();
            let s = parse(&mut Cursor::new(out.clone())).unwrap();
            assert!(s.item(ItemKind::C2pa).unwrap().is_none());
            assert_eq!(other_jumbf(&out, &s), other);
        }

        let (out, _) = rewrite(handler(), &file, &Updates::new()).unwrap();
        assert_eq!(out, file);
    }

    #[test]
    fn two_c2pa_stores_are_ambiguous_and_a_set_replaces_both() {
        let one = with_jumbf(&sample_jpeg(), 5, &c2pa_store_of_len(60));
        let two = with_jumbf(&one, 6, &c2pa_store_of_len(70));
        let s = parse(&mut Cursor::new(two.clone())).unwrap();
        assert_eq!(s.items_of(ItemKind::C2pa).count(), 2);
        assert!(matches!(s.c2pa_item(), Err(Error::Ambiguous { .. })));
        let (_, dest) = rewrite(
            handler(),
            &two,
            &Updates::new().set_c2pa(c2pa_store_of_len(80)),
        )
        .unwrap();
        assert_eq!(dest.items_of(ItemKind::C2pa).count(), 1);
    }

    #[test]
    fn a_large_store_records_its_type_from_the_first_packet() {
        let big = c2pa_store_of_len(150_000);
        let (out, dest) = rewrite(
            handler(),
            &sample_jpeg(),
            &Updates::new().set_c2pa(big.clone()),
        )
        .unwrap();
        let s = parse(&mut Cursor::new(out.clone())).unwrap();
        for st in [&dest, &s] {
            let e = st.require_item(ItemKind::C2pa).unwrap();
            assert!(e.extent_count() > 1);
            assert_eq!(e.jumbf_type(), Some(crate::jumbf::C2PA_STORE_TYPE));
        }
        assert_eq!(
            jumbf_of(&out, &s, s.require_item(ItemKind::C2pa).unwrap()),
            big
        );
    }

    #[test]
    fn rejects_invalid_new_jumbf() {
        let j = sample_jpeg();
        let s = parse(&mut Cursor::new(j.clone())).unwrap();
        for bad in [vec![], vec![0u8; 7], vec![0u8; 100]] {
            let updates = Updates::new().set_c2pa(bad);
            let r = s.write(
                &mut Cursor::new(j.clone()),
                &mut Cursor::new(Vec::new()),
                &updates,
                &mut NullSink,
            );
            assert!(r.is_err());
        }
    }

    /// The case that motivated the redesign: every extent's payload is excluded,
    /// every segment's header is hashed. Three independent routes must agree.
    #[test]
    fn multi_part_exclusion_three_routes_agree() {
        struct Hash(Sha256);
        impl Sink for Hash {
            fn wants(&self, seg: &Segment, role: Role) -> bool {
                !(seg.name() == Name::Marker(APP11) && role == Role::Payload)
            }

            fn chunk(&mut self, c: Chunk<'_>) -> Result<()> {
                self.0.update(c.data);
                Ok(())
            }
        }

        let j = sample_jpeg();
        let s = parse(&mut Cursor::new(j.clone())).unwrap();
        let updates = Updates::new().set_c2pa(c2pa_store_of_len(150_000));
        let mut sink = Hash(Sha256::new());
        let mut out = Cursor::new(Vec::new());
        let dest = s
            .write(&mut Cursor::new(j), &mut out, &updates, &mut sink)
            .unwrap();
        let bytes = out.into_inner();
        let streamed = sink.0.finalize().to_vec();

        // Route 2: walk the finished structure.
        let mut walked = Sha256::new();
        let mut src = Cursor::new(bytes.clone());
        let mut buf = vec![0u8; 4096];
        for r in dest.regions() {
            let seg = dest.segment(r.segment).unwrap();
            if seg.name() == Name::Marker(APP11) && r.role == Role::Payload {
                continue;
            }
            dest.stream_range(&mut src, r.range, &mut buf, |b| {
                walked.update(b);
                Ok(())
            })
            .unwrap();
        }

        // Route 3: hash everything outside the item's extents.
        let e = dest.require_item(ItemKind::C2pa).unwrap();
        assert_eq!(e.extent_count(), 3);
        let mut outside = Sha256::new();
        let mut pos = 0usize;
        for p in e.extents() {
            let r = p.range();
            outside.update(&bytes[pos..r.offset() as usize]);
            pos = r.end() as usize;
        }
        outside.update(&bytes[pos..]);

        assert_eq!(streamed, walked.finalize().to_vec());
        assert_eq!(streamed, outside.finalize().to_vec());
    }

    #[test]
    fn patch_multi_part_changes_only_payloads() {
        let j = sample_jpeg();
        let placeholder = c2pa_store_of_len(150_000);
        let s = parse(&mut Cursor::new(j.clone())).unwrap();
        let mut out = Cursor::new(Vec::new());
        let dest = s
            .write(
                &mut Cursor::new(j),
                &mut out,
                &Updates::new().set_c2pa(placeholder),
                &mut NullSink,
            )
            .unwrap();
        let before = out.get_ref().clone();

        let e = dest.require_item(ItemKind::C2pa).unwrap().clone();
        let signed = c2pa_store_of_len(140_000);
        dest.patch(&mut out, &e, &signed).unwrap();
        let after = out.into_inner();

        assert_eq!(before.len(), after.len());
        let in_payload = |i: usize| {
            e.extents()
                .any(|p| p.range().contains(&ByteRange::new(i as u64, 1).unwrap()))
        };
        for i in 0..before.len() {
            if !in_payload(i) {
                assert_eq!(before[i], after[i], "byte {i} outside payload changed");
            }
        }
        let re = parse(&mut Cursor::new(after.clone())).unwrap();
        let data = read_jumbf(&re, &mut Cursor::new(after)).unwrap().unwrap();
        assert_eq!(&data[..140_000], &signed[..]);
        assert!(data[140_000..].iter().all(|&b| b == 0));
        assert!(dest
            .patch(&mut Cursor::new(vec![0u8; 10]), &e, &vec![1u8; 150_001])
            .is_err());
    }

    #[test]
    fn xmp_standard_and_extended_round_trip() {
        let j = sample_jpeg();

        let small = b"<x:xmpmeta/>".to_vec();
        let (out, _) = rewrite(handler(), &j, &Updates::new().set_xmp(small.clone())).unwrap();
        let re = parse(&mut Cursor::new(out.clone())).unwrap();
        assert_eq!(
            read_xmp(&re, &mut Cursor::new(out)).unwrap().unwrap(),
            small
        );

        let big = vec![b'x'; 70_000];
        let (out, dest) = rewrite(handler(), &j, &Updates::new().set_xmp(big.clone())).unwrap();
        let re = parse(&mut Cursor::new(out.clone())).unwrap();
        let e = re.require_item(ItemKind::Xmp).unwrap();
        assert_eq!(e.extent_count(), 3); // stub + two extended chunks
        assert_eq!(dest.require_item(ItemKind::Xmp).unwrap().extent_count(), 3);
        assert_eq!(
            read_xmp(&re, &mut Cursor::new(out.clone()))
                .unwrap()
                .unwrap(),
            big
        );

        // Keeping extended XMP copies it unchanged.
        let (kept, _) = rewrite(handler(), &out, &Updates::new()).unwrap();
        assert_eq!(kept, out);
    }

    #[test]
    fn extended_xmp_length_cannot_force_allocation() {
        // Declared total far larger than the data present must be refused.
        let j = sample_jpeg();
        let big = vec![b'x'; 70_000];
        let (mut out, _) = rewrite(handler(), &j, &Updates::new().set_xmp(big)).unwrap();
        // Corrupt the declared total of every extended chunk to 90 MB.
        let re = parse(&mut Cursor::new(out.clone())).unwrap();
        let e = re.require_item(ItemKind::Xmp).unwrap();
        for p in e.extents().skip(1) {
            let h = re.segment(p.segment()).unwrap().header();
            let at = (h.end() - 8) as usize;
            out[at..at + 4].copy_from_slice(&(90u32 * 1024 * 1024).to_be_bytes());
        }
        let re = parse(&mut Cursor::new(out.clone())).unwrap();
        assert!(read_xmp(&re, &mut Cursor::new(out)).is_err());
    }

    /// Image 2 of an MPF file: a complete small JPEG.
    fn second_image() -> Vec<u8> {
        let mut v = vec![0xff, SOI];
        v.extend(marker(0xe0, b"JFIF\0\x01\x01\0\0\x01\0\x01\0\0"));
        v.extend(marker(0xdb, &[2u8; 65]));
        v.extend(marker(SOS, &[1, 1, 0, 0, 0x3f, 0]));
        v.extend_from_slice(&[0x9a, 0xbc, 0xff, 0x00, 0xde]);
        v.extend_from_slice(&[0xff, EOI]);
        v
    }

    /// An MPF file: the primary image carries the MPF index, then `second`, then
    /// `trailing`. `skew` is added to the second image's recorded offset.
    fn mpf_file(second: &[u8], trailing: &[u8], skew: u32, little: bool) -> Vec<u8> {
        let u16b = |v: u16| {
            if little {
                v.to_le_bytes()
            } else {
                v.to_be_bytes()
            }
        };
        let u32b = |v: u32| {
            if little {
                v.to_le_bytes()
            } else {
                v.to_be_bytes()
            }
        };
        let build = |first_len: u32, second_off: u32| -> Vec<u8> {
            let mut b = Vec::new();
            b.extend_from_slice(if little { b"II" } else { b"MM" });
            b.extend_from_slice(&u16b(0x2a));
            b.extend_from_slice(&u32b(8));
            b.extend_from_slice(&u16b(3));
            for (tag, ty, count, val) in [
                (0xb000u16, 7u16, 4u32, u32::from_be_bytes(*b"0100")),
                (0xb001, 4, 1, 2),
                (0xb002, 7, 32, 50),
            ] {
                b.extend_from_slice(&u16b(tag));
                b.extend_from_slice(&u16b(ty));
                b.extend_from_slice(&u32b(count));
                b.extend_from_slice(&if tag == 0xb000 {
                    val.to_be_bytes()
                } else {
                    u32b(val)
                });
            }
            b.extend_from_slice(&u32b(0));
            assert_eq!(b.len(), 50);
            for (size, off) in [(first_len, 0), (second.len() as u32, second_off)] {
                b.extend_from_slice(&u32b(0x030000));
                b.extend_from_slice(&u32b(size));
                b.extend_from_slice(&u32b(off));
                b.extend_from_slice(&u16b(0));
                b.extend_from_slice(&u16b(0));
            }
            b
        };
        let head = |block: &[u8]| -> Vec<u8> {
            let mut v = vec![0xff, SOI];
            v.extend(marker(0xe0, b"JFIF\0\x01\x01\0\0\x01\0\x01\0\0"));
            let mut app2 = MPF_SIGNATURE.to_vec();
            app2.extend_from_slice(block);
            v.extend(marker(APP2, &app2));
            v.extend(marker(0xdb, &[0u8; 65]));
            v.extend(marker(SOS, &[1, 1, 0, 0, 0x3f, 0]));
            v.extend_from_slice(&[0x12, 0x34, 0xff, 0x00, 0x56]);
            v.extend_from_slice(&[0xff, EOI]);
            v
        };
        let first_len = head(&build(0, 0)).len() as u32;
        let base = 2 + 18 + 4 + 4; // SOI, APP0, APP2 marker/length, "MPF\0"
        let mut f = head(&build(first_len, first_len - base + skew));
        f.extend_from_slice(second);
        f.extend_from_slice(trailing);
        f
    }

    /// The (size, offset) pairs recorded in the file's MPF block.
    fn recorded(file: &[u8]) -> (Vec<(u32, u32)>, u64) {
        let s = parse(&mut Cursor::new(file.to_vec())).unwrap();
        let id = find_mpf(
            &s,
            &mut Cursor::new(file.to_vec()),
            s.subassets()[0].segments().end,
        )
        .unwrap()
        .unwrap();
        let payload = s.segment(id).unwrap().payload();
        let block = s
            .read_range(&mut Cursor::new(file.to_vec()), payload)
            .unwrap();
        let ix = MpIndex::parse(&block).unwrap();
        let pairs = ix
            .entries
            .iter()
            .map(|&at| (ix.u32(&block, at).unwrap(), ix.u32(&block, at + 4).unwrap()))
            .collect();
        (pairs, payload.offset())
    }

    fn assert_index_matches_structure(file: &[u8]) {
        let s = parse(&mut Cursor::new(file.to_vec())).unwrap();
        let (pairs, base) = recorded(file);
        let images: Vec<_> = s
            .subassets()
            .iter()
            .filter(|a| a.media_type().is_some())
            .collect();
        assert_eq!(pairs.len(), images.len());
        for (n, (a, (size, off))) in images.iter().zip(pairs).enumerate() {
            assert_eq!(size as u64, a.range().len(), "size of image {n}");
            let expect = if n == 0 { 0 } else { a.range().offset() - base };
            assert_eq!(off as u64, expect, "offset of image {n}");
        }
    }

    #[test]
    fn mpo_is_served_by_the_jpeg_handler() {
        let f = mpf_file(&second_image(), b"", 0, false);
        let reg = crate::HandlerRegistry::new().with_handler(JpegHandler);
        let s = Structure::parse(&reg, &mut Cursor::new(f.clone()), Some("mpo")).unwrap();
        assert_eq!(s.media_type(), "image/jpeg");
        assert_eq!(s.subassets().len(), 2);
        let s = Structure::parse(&reg, &mut Cursor::new(f), None).unwrap();
        assert_eq!(s.subassets().len(), 2);
    }

    #[test]
    fn multi_picture_file_is_listed_as_parts() {
        for little in [false, true] {
            let second = second_image();
            let f = mpf_file(&second, b"", 0, little);
            let s = parse(&mut Cursor::new(f.clone())).unwrap();
            let subs = s.subassets();
            assert_eq!(subs.len(), 2);
            assert!(subs[0].is_primary() && !subs[1].is_primary());
            assert_eq!(subs[1].range().len(), second.len() as u64);
            assert_eq!(subs[1].range().end(), f.len() as u64);
            assert_eq!(subs[1].media_type(), Some("image/jpeg"));
            // Parts tile the file, and the second image's segments are listed in
            // order: SOI, APP0, DQT, SOS, EOI.
            assert_eq!(subs[0].range().end(), subs[1].range().offset());
            assert_eq!(subs[0].segments().end, subs[1].segments().start);
            let names: Vec<_> = s.segments()[subs[1].segments()]
                .iter()
                .enumerate()
                .map(|(i, g)| {
                    let id = SegmentId::from_index(subs[1].segments().start + i).unwrap();
                    s.box_name(id, g).unwrap().into_owned()
                })
                .collect();
            assert_eq!(names, ["SOI", "APP0", "DQT", "SOS", "EOI"]);
            assert_eq!(subs[1].relative(subs[1].range().offset() + 3), Some(3));
            assert_eq!(subs[1].relative(0), None);
            assert_index_matches_structure(&f);
        }
    }

    #[test]
    fn plain_files_have_one_part() {
        let j = sample_jpeg();
        let s = parse(&mut Cursor::new(j.clone())).unwrap();
        assert_eq!(s.subassets().len(), 1);
        assert_eq!(s.subassets()[0].range().len(), j.len() as u64);
        assert_eq!(s.subassets()[0].media_type(), Some("image/jpeg"));
        // Trailing data of a single image stays part of it.
        let mut t = j;
        t.extend_from_slice(b"trailing");
        let s = parse(&mut Cursor::new(t)).unwrap();
        assert_eq!(s.subassets().len(), 1);
    }

    #[test]
    fn data_after_the_last_image_is_a_final_part() {
        let f = mpf_file(&second_image(), b"\0\0\0\x18ftypmp42 trailing", 0, false);
        let s = parse(&mut Cursor::new(f.clone())).unwrap();
        let subs = s.subassets();
        assert_eq!(subs.len(), 3);
        assert_eq!(subs[2].media_type(), None);
        assert_eq!(subs[2].range().end(), f.len() as u64);
        assert_eq!(subs[1].range().end(), subs[2].range().offset());
    }

    #[test]
    fn editing_the_primary_image_keeps_the_mpf_index_valid() {
        for little in [false, true] {
            let second = second_image();
            let f = mpf_file(&second, b"tail", 0, little);
            let updates = Updates::new()
                .set_c2pa(c2pa_store_of_len(200))
                .set_xmp(b"<x:xmpmeta/>".to_vec());
            let (out, dest) = rewrite(handler(), &f, &updates).unwrap();
            assert!(out.len() > f.len());

            let re = parse(&mut Cursor::new(out.clone())).unwrap();
            assert_eq!(re.subassets().len(), 3);
            assert_index_matches_structure(&out);
            // Later images and trailing data are untouched.
            let subs = re.subassets();
            assert_eq!(
                &out[subs[1].range().offset() as usize..subs[1].range().end() as usize],
                &second[..]
            );
            assert_eq!(&out[subs[2].range().offset() as usize..], b"tail");
            // The planned structure is the written one, parts included.
            assert_eq!(dest.subassets(), re.subassets());
            let planned = parse(&mut Cursor::new(f.clone()))
                .unwrap()
                .plan(&mut Cursor::new(f.clone()), &updates)
                .unwrap();
            assert_eq!(planned.subassets(), re.subassets());

            // The edited file is its own fixed point, and removal restores the index.
            let (again, _) = rewrite(handler(), &out, &Updates::new()).unwrap();
            assert_eq!(again, out);
            let (back, _) = rewrite(handler(), &out, &Updates::remove_all()).unwrap();
            assert_index_matches_structure(&back);
            assert_eq!(back.len(), f.len());
        }
    }

    #[test]
    fn metadata_goes_in_the_primary_image_only() {
        let f = mpf_file(&second_image(), b"", 0, false);
        let (out, _) = rewrite(
            handler(),
            &f,
            &Updates::new().set_c2pa(c2pa_store_of_len(64)),
        )
        .unwrap();
        let re = parse(&mut Cursor::new(out)).unwrap();
        let primary = re.subassets()[0].segments();
        let e = re.require_item(ItemKind::C2pa).unwrap();
        assert!(e.extents().all(|p| primary.contains(&p.segment().index())));
    }

    #[test]
    fn an_index_that_does_not_match_the_images_is_refused_on_edit_only() {
        // Records one image where the file has two.
        let mut f = mpf_file(&second_image(), b"", 0, false);
        let s = parse(&mut Cursor::new(f.clone())).unwrap();
        let id = find_mpf(
            &s,
            &mut Cursor::new(f.clone()),
            s.subassets()[0].segments().end,
        )
        .unwrap()
        .unwrap();
        // The number-of-entries field of tag 0xB002 is at block offset 8 + 2 + 24 + 4.
        let at = s.segment(id).unwrap().payload().offset() as usize + 8 + 2 + 24 + 4;
        f[at..at + 4].copy_from_slice(&16u32.to_be_bytes());
        let (kept, _) = rewrite(handler(), &f, &Updates::new()).unwrap();
        assert_eq!(kept, f);
        let s = parse(&mut Cursor::new(f.clone())).unwrap();
        let err = s
            .write(
                &mut Cursor::new(f.clone()),
                &mut Cursor::new(Vec::new()),
                &Updates::new().set_c2pa(c2pa_store_of_len(64)),
                &mut NullSink,
            )
            .unwrap_err();
        assert!(matches!(err, Error::InvalidFormat(_)), "{err:?}");
    }

    #[test]
    fn a_hash_over_the_parts_covers_every_byte() {
        let f = mpf_file(&second_image(), b"tail", 0, false);
        let s = parse(&mut Cursor::new(f.clone())).unwrap();
        let mut whole = Sha256::new();
        let mut per_part: Vec<Sha256> = s.subassets().iter().map(|_| Sha256::new()).collect();
        let subs = s.subassets().to_vec();
        s.read(&mut Cursor::new(f.clone()), &mut |c: Chunk<'_>| {
            whole.update(c.data);
            let k = subs
                .iter()
                .position(|a| a.segments().contains(&c.segment.index()))
                .unwrap();
            per_part[k].update(c.data);
            Ok(())
        })
        .unwrap();
        for (a, h) in subs.iter().zip(per_part) {
            let bytes = &f[a.range().offset() as usize..a.range().end() as usize];
            assert_eq!(h.finalize()[..], Sha256::digest(bytes)[..]);
        }
        assert_eq!(whole.finalize()[..], Sha256::digest(&f)[..]);
    }

    /// Where the MPF block (the bytes after `MPF\0`) starts in the file, and a copy.
    fn mpf_block(f: &[u8]) -> (usize, Vec<u8>) {
        let s = parse(&mut Cursor::new(f.to_vec())).unwrap();
        let id = find_mpf(
            &s,
            &mut Cursor::new(f.to_vec()),
            s.subassets()[0].segments().end,
        )
        .unwrap()
        .unwrap();
        let r = s.segment(id).unwrap().payload();
        let (a, b) = (r.offset() as usize, r.end() as usize);
        (a, f[a..b].to_vec())
    }

    #[test]
    fn bytes_that_only_look_like_an_image_are_trailing_data() {
        let junk: [&[u8]; 4] = [
            b"\xFF\xD8\xFF garbage that is not a jpeg",
            b"\xFF\xD8\xFF\xE0\x00\x01",       // marker length below 2
            b"\xFF\xD8\xFF\xE1\xFF\xFF short", // segment runs past the end
            b"\xFF\xD8\xFF\xDB",               // cut off inside a marker
        ];
        for t in junk {
            // After a single image: part of it, as before multi-picture support.
            let mut f = sample_jpeg();
            f.extend_from_slice(t);
            let s = parse(&mut Cursor::new(f.clone())).unwrap();
            assert_eq!(s.subassets().len(), 1);
            assert_eq!(s.trailing().map(|r| r.len()), Some(t.len() as u64));
            let (out, _) = rewrite(handler(), &f, &Updates::new()).unwrap();
            assert_eq!(out, f);

            // After the last image of a multi-picture file: a part of its own.
            let second = second_image();
            let f = mpf_file(&second, t, 0, false);
            let s = parse(&mut Cursor::new(f.clone())).unwrap();
            let subs = s.subassets();
            assert_eq!(subs.len(), 3);
            assert_eq!(subs[1].range().len(), second.len() as u64);
            assert_eq!(subs[2].media_type(), None);
            assert_eq!(&f[subs[2].range().offset() as usize..], t);
            let (out, _) = rewrite(
                handler(),
                &f,
                &Updates::new().set_c2pa(c2pa_store_of_len(64)),
            )
            .unwrap();
            assert_index_matches_structure(&out);
        }
    }

    #[test]
    fn data_beyond_the_first_image_is_reported_as_trailing() {
        use crate::ByteRange;
        let j = sample_jpeg();
        let s = parse(&mut Cursor::new(j.clone())).unwrap();
        assert_eq!(s.trailing(), None);

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

        // In a multi-picture file everything after the first image is beyond it.
        for tail in [&b""[..], b"tail"] {
            let f = mpf_file(&second_image(), tail, 0, false);
            let s = parse(&mut Cursor::new(f.clone())).unwrap();
            let first_end = s.subassets()[0].range().end();
            assert_eq!(
                s.trailing(),
                Some(ByteRange::new(first_end, f.len() as u64 - first_end).unwrap())
            );

            // An edit moves it with the file, and what was planned is what is written.
            let (out, dest) = rewrite(
                handler(),
                &f,
                &Updates::new().set_c2pa(c2pa_store_of_len(200)),
            )
            .unwrap();
            let re = parse(&mut Cursor::new(out.clone())).unwrap();
            assert_eq!(dest.trailing(), re.trailing());
            let r = re.trailing().unwrap();
            assert_eq!(&out[r.offset() as usize..], &f[first_end as usize..]);

            // Removing the metadata puts it back where it was.
            let (back, _) = rewrite(handler(), &out, &Updates::remove_all()).unwrap();
            assert_eq!(back.len(), f.len());
        }
    }

    #[test]
    fn a_second_image_cut_short_is_trailing_data() {
        let second = second_image();
        let f = mpf_file(&second[..second.len() - 2], b"", 0, false);
        let s = parse(&mut Cursor::new(f.clone())).unwrap();
        assert_eq!(s.subassets().len(), 1);
        let (out, _) = rewrite(handler(), &f, &Updates::new()).unwrap();
        assert_eq!(out, f);
    }

    #[test]
    fn an_index_that_disagrees_with_the_file_is_refused_on_edit_only() {
        let edit = Updates::new().set_c2pa(c2pa_store_of_len(64));
        let good = mpf_file(&second_image(), b"", 0, false);
        let (base, _) = mpf_block(&good);
        assert!(rewrite(handler(), &good, &edit).is_ok());
        // Entries start at block offset 50, 16 bytes each: attributes, size, offset.
        for (what, at) in [
            ("offset of the first image", 58),
            ("size of the second image", 70),
            ("offset of the second image", 74),
        ] {
            let mut f = good.clone();
            f[base + at + 3] ^= 1;
            // Copying unchanged never consults the index.
            let (kept, _) = rewrite(handler(), &f, &Updates::new()).unwrap();
            assert_eq!(kept, f, "{what}");
            let err = rewrite(handler(), &f, &edit).unwrap_err();
            assert!(matches!(err, Error::InvalidFormat(_)), "{what}: {err:?}");
        }
    }

    #[test]
    fn a_first_image_size_recorded_short_is_accepted_and_corrected() {
        let edit = Updates::new().set_c2pa(c2pa_store_of_len(64));
        let good = mpf_file(&second_image(), b"", 0, false);
        let (base, block) = mpf_block(&good);
        let first_len = parse(&mut Cursor::new(good.clone())).unwrap().subassets()[0]
            .range()
            .len();
        let set_size = |f: &mut Vec<u8>, v: u32| {
            f[base + 54..base + 58].copy_from_slice(&v.to_be_bytes());
        };
        assert_eq!(
            u32::from_be_bytes(block[54..58].try_into().unwrap()) as u64,
            first_len
        );

        // Recorded a few hundred bytes short, as Pixel Ultra HDR files do.
        for short in [1u32, 307, first_len as u32 - 1] {
            let mut f = good.clone();
            set_size(&mut f, first_len as u32 - short.min(first_len as u32 - 1));
            let (kept, _) = rewrite(handler(), &f, &Updates::new()).unwrap();
            assert_eq!(kept, f, "copying never consults the index");
            let (out, _) = rewrite(handler(), &f, &edit).unwrap();
            assert_index_matches_structure(&out);
        }

        // Claiming more than the image is refused.
        let mut f = good.clone();
        set_size(&mut f, first_len as u32 + 1);
        let err = rewrite(handler(), &f, &edit).unwrap_err();
        assert!(matches!(err, Error::InvalidFormat(_)), "{err:?}");
        assert!(err.to_string().contains("size of image 0"), "{err}");
    }

    #[test]
    fn a_hostile_mpf_index_is_not_parsed() {
        for little in [false, true] {
            let f = mpf_file(&second_image(), b"", 0, little);
            let (_, block) = mpf_block(&f);
            let ix = MpIndex::parse(&block).expect("a good index parses");
            assert_eq!(ix.entries, [54, 70]);

            let w16 = |b: &mut [u8], at: usize, v: u16| {
                let v = if little {
                    v.to_le_bytes()
                } else {
                    v.to_be_bytes()
                };
                b[at..at + 2].copy_from_slice(&v);
            };
            let w32 = |b: &mut [u8], at: usize, v: u32| {
                let v = if little {
                    v.to_le_bytes()
                } else {
                    v.to_be_bytes()
                };
                b[at..at + 4].copy_from_slice(&v);
            };
            // Layout: header 0..8, IFD at 8 (count, then entries at 10, 22, 34 with
            // tag/type/count/value at +0/+2/+4/+8), next IFD at 46, entries at 50.
            let end = block.len() as u32;
            let cases: Vec<(&str, Vec<u8>)> = {
                let with = |f: &dyn Fn(&mut Vec<u8>)| {
                    let mut b = block.clone();
                    f(&mut b);
                    b
                };
                vec![
                    ("magic", with(&|b| w16(b, 2, 0x2b))),
                    ("byte order", with(&|b| b[0] = b'X')),
                    ("IFD inside the header", with(&|b| w32(b, 4, 4))),
                    ("IFD past the end", with(&|b| w32(b, 4, 0xffff_fff0))),
                    ("huge entry count", with(&|b| w16(b, 8, 0xffff))),
                    ("array inside the header", with(&|b| w32(b, 42, 0))),
                    ("array over the IFD", with(&|b| w32(b, 42, 20))),
                    ("array past the end", with(&|b| w32(b, 42, end - 16))),
                    ("length not a multiple of 16", with(&|b| w32(b, 38, 31))),
                    ("empty array", with(&|b| w32(b, 38, 0))),
                    ("array of the wrong type", with(&|b| w16(b, 36, 4))),
                    ("second MPEntry", with(&|b| w16(b, 22, 0xb002))),
                    ("image count disagrees", with(&|b| w32(b, 30, 3))),
                    ("image count of the wrong type", with(&|b| w16(b, 24, 3))),
                ]
            };
            for (what, b) in cases {
                assert!(MpIndex::parse(&b).is_none(), "{what} (little: {little})");
            }

            // Any prefix of the block is refused without panicking.
            for n in 0..block.len() {
                assert!(MpIndex::parse(&block[..n]).is_none(), "{n} bytes");
            }
        }
    }

    #[test]
    fn two_mpf_blocks_are_ambiguous_only_when_an_edit_needs_the_index() {
        let f = mpf_file(&second_image(), b"", 0, false);
        let s = parse(&mut Cursor::new(f.clone())).unwrap();
        let id = find_mpf(
            &s,
            &mut Cursor::new(f.clone()),
            s.subassets()[0].segments().end,
        )
        .unwrap()
        .unwrap();
        let x = s.segment(id).unwrap().range();
        let (a, b) = (x.offset() as usize, x.end() as usize);
        let mut dup = f[..b].to_vec();
        dup.extend_from_slice(&f[a..b]);
        dup.extend_from_slice(&f[b..]);

        let (kept, _) = rewrite(handler(), &dup, &Updates::new()).unwrap();
        assert_eq!(kept, dup);
        let err = rewrite(
            handler(),
            &dup,
            &Updates::new().set_c2pa(c2pa_store_of_len(64)),
        )
        .unwrap_err();
        assert!(
            matches!(
                err,
                Error::Ambiguous {
                    what: "MPF block",
                    ..
                }
            ),
            "{err:?}"
        );
    }

    /// Every byte of the MPF block altered several ways: parsing and copying never
    /// fail or panic, and an edit that is accepted leaves an index that matches.
    #[test]
    fn a_mutated_mpf_block_is_refused_or_stays_consistent() {
        let edit = Updates::new().set_c2pa(c2pa_store_of_len(64));
        for little in [false, true] {
            let good = mpf_file(&second_image(), b"tail", 0, little);
            let (base, block) = mpf_block(&good);
            let mut accepted = 0;
            for pos in 0..block.len() {
                let o = block[pos];
                for v in [
                    o ^ 0xff,
                    0,
                    1,
                    0xff,
                    o.wrapping_add(1),
                    o.wrapping_sub(1),
                    o ^ 0x80,
                ] {
                    let mut f = good.clone();
                    f[base + pos] = v;
                    let (kept, _) = rewrite(handler(), &f, &Updates::new()).unwrap();
                    assert_eq!(kept, f);
                    if let Ok((out, dest)) = rewrite(handler(), &f, &edit) {
                        accepted += 1;
                        let re = parse(&mut Cursor::new(out.clone())).unwrap();
                        assert_eq!(re.subassets(), dest.subassets());
                        assert_index_matches_structure(&out);
                    }
                }
            }
            assert!(
                accepted > 0,
                "changes to bytes the edit ignores are accepted"
            );
        }
    }
}