c2pa 0.80.3

Rust SDK for C2PA (Coalition for Content Provenance and Authenticity) implementors
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
// Copyright 2022 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.

use std::{
    collections::HashMap,
    fs::File,
    io::{BufReader, Cursor, Write},
    path::*,
};

use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use img_parts::{
    jpeg::{
        markers::{self, APP0, APP15, COM, DQT, DRI, P, RST0, RST7, SOF0, SOF15, SOS, Z},
        Jpeg, JpegSegment,
    },
    Bytes, DynImage,
};
use serde_bytes::ByteBuf;

use crate::{
    assertions::{BoxMap, C2PA_BOXHASH},
    asset_io::{
        rename_or_move, AssetBoxHash, AssetIO, CAIRead, CAIReadWrite, CAIReader, CAIWriter,
        ComposedManifestRef, HashBlockObjectType, HashObjectPositions, RemoteRefEmbed,
        RemoteRefEmbedType,
    },
    error::{Error, Result},
    utils::{
        io_utils::tempfile_builder,
        xmp_inmemory_utils::{add_provenance, MIN_XMP},
    },
};

static SUPPORTED_TYPES: [&str; 3] = ["jpg", "jpeg", "image/jpeg"];

const XMP_SIGNATURE: &str = "http://ns.adobe.com/xap/1.0/";
const XMP_SIGNATURE_BUFFER_SIZE: usize = XMP_SIGNATURE.len() + 1; // skip null or space char at end

const MAX_JPEG_MARKER_SIZE: usize = 64000; // technically it's 64K but a bit smaller is fine

const C2PA_MARKER: [u8; 4] = [0x63, 0x32, 0x70, 0x61];

fn vec_compare(va: &[u8], vb: &[u8]) -> bool {
    (va.len() == vb.len()) &&  // zip stops at the shortest
     va.iter()
       .zip(vb)
       .all(|(a,b)| a == b)
}

// Return contents of APP1 segment if it is an XMP segment.
fn extract_xmp(seg: &JpegSegment) -> Option<&str> {
    let (sig, rest) = seg.contents().split_at_checked(XMP_SIGNATURE_BUFFER_SIZE)?;
    if sig.starts_with(XMP_SIGNATURE.as_bytes()) {
        std::str::from_utf8(rest).ok()
    } else {
        None
    }
}

// Extract XMP from bytes.
fn xmp_from_bytes(asset_bytes: &[u8]) -> Option<String> {
    let jpeg = Jpeg::from_bytes(Bytes::copy_from_slice(asset_bytes)).ok()?;
    let mut segs = jpeg.segments_by_marker(markers::APP1);
    segs.find_map(extract_xmp).map(String::from)
}

fn add_required_segs_to_stream(
    input_stream: &mut dyn CAIRead,
    output_stream: &mut dyn CAIReadWrite,
) -> Result<()> {
    let mut buf: Vec<u8> = Vec::new();
    input_stream.rewind()?;
    input_stream.read_to_end(&mut buf).map_err(Error::IoError)?;
    input_stream.rewind()?;

    let dimg_opt = DynImage::from_bytes(buf.into())
        .map_err(|_err| Error::InvalidAsset("Could not parse input JPEG".to_owned()))?;

    if let Some(DynImage::Jpeg(jpeg)) = dimg_opt {
        if jpeg.segments().is_empty() {
            return Err(Error::InvalidAsset("JPEG has no segments".to_owned()));
        }

        // check for JUMBF Seg
        let cai_app11 = get_cai_segments(&jpeg)?; // make sure we only check for C2PA segments

        if cai_app11.is_empty() {
            // create dummy JUMBF seg
            let mut no_bytes: Vec<u8> = vec![0; 50]; // enough bytes to be valid
            no_bytes.splice(16..20, C2PA_MARKER); // cai UUID signature
            let aio = JpegIO {};
            aio.write_cai(input_stream, output_stream, &no_bytes)?;
        } else {
            // just clone
            input_stream.rewind()?;
            output_stream.rewind()?;
            std::io::copy(input_stream, output_stream)?;
        }
    } else {
        return Err(Error::UnsupportedType);
    }

    Ok(())
}

// all cai specific segments
fn get_cai_segments(jpeg: &img_parts::jpeg::Jpeg) -> Result<Vec<usize>> {
    let mut cai_segs: Vec<usize> = Vec::new();

    let segments = jpeg.segments();

    let mut cai_en: Vec<u8> = Vec::new();
    let mut cai_seg_cnt: u32 = 0;

    for (i, segment) in segments.iter().enumerate() {
        let raw_bytes = segment.contents();
        let seg_type = segment.marker();

        if raw_bytes.len() > 16 && seg_type == markers::APP11 {
            // we need at least 16 bytes in each segment for CAI
            let mut raw_vec = raw_bytes.to_vec();
            let _ci = raw_vec.as_mut_slice()[0..2].to_vec();
            let en = raw_vec.as_mut_slice()[2..4].to_vec();
            let mut z_vec = Cursor::new(raw_vec.as_mut_slice()[4..8].to_vec());
            let _z = z_vec.read_u32::<BigEndian>()?;

            let is_cai_continuation = vec_compare(&cai_en, &en);

            if cai_seg_cnt > 0 && is_cai_continuation {
                cai_seg_cnt += 1;
                cai_segs.push(i);
            } else {
                // check if this is a CAI JUMBF block
                let jumb_type = &raw_vec
                    .as_mut_slice()
                    .get(24..28)
                    .ok_or(Error::InvalidAsset(
                        "Invalid JPEG CAI JUMBF block".to_string(),
                    ))?;

                let is_cai = vec_compare(&C2PA_MARKER, jumb_type);
                if is_cai {
                    cai_segs.push(i);
                    cai_seg_cnt = 1;
                    cai_en.clone_from(&en); // store the identifier
                }
            }
        }
    }

    Ok(cai_segs)
}

// delete cai segments
fn delete_cai_segments(jpeg: &mut img_parts::jpeg::Jpeg) -> Result<Option<usize>> {
    let cai_segs = get_cai_segments(jpeg)?;
    let jpeg_segs = jpeg.segments_mut();

    let insertion_point = if !cai_segs.is_empty() {
        Some(cai_segs[0])
    } else {
        None
    };

    // remove cai segments
    for seg in cai_segs.iter().rev() {
        jpeg_segs.remove(*seg);
    }

    Ok(insertion_point)
}

pub struct JpegIO {}

impl CAIReader for JpegIO {
    fn read_cai(&self, asset_reader: &mut dyn CAIRead) -> Result<Vec<u8>> {
        let mut buffer: Vec<u8> = Vec::new();

        let mut manifest_store_cnt = 0;

        // load the bytes
        let mut buf: Vec<u8> = Vec::new();

        asset_reader.rewind()?;
        asset_reader.read_to_end(&mut buf).map_err(Error::IoError)?;

        let dimg_opt = DynImage::from_bytes(buf.into()).map_err(|err| match err {
            img_parts::Error::WrongSignature => JpegError::InvalidFileSignature {
                reason: format!(
                    "it may be because the stream does not start with \"{} {}\"",
                    markers::P,
                    markers::SOI
                ),
            }
            .into(),
            _ => Error::InvalidAsset("Could not parse input JPEG".to_owned()),
        })?;

        if let Some(dimg) = dimg_opt {
            match dimg {
                DynImage::Jpeg(jpeg) => {
                    if jpeg.segments().is_empty() {
                        return Err(Error::InvalidAsset("JPEG has no segments".to_owned()));
                    }

                    let app11 = jpeg.segments_by_marker(markers::APP11);
                    let mut cai_en: Vec<u8> = Vec::new();
                    let mut cai_seg_cnt: u32 = 0;
                    for segment in app11 {
                        let raw_bytes = segment.contents();
                        if raw_bytes.len() > 16 {
                            // we need at least 16 bytes in each segment for CAI
                            let mut raw_vec = raw_bytes.to_vec();
                            let _ci = raw_vec.as_mut_slice()[0..2].to_vec();
                            let en = raw_vec.as_mut_slice()[2..4].to_vec();
                            let mut z_vec = Cursor::new(raw_vec.as_mut_slice()[4..8].to_vec());
                            let z = z_vec.read_u32::<BigEndian>()?;

                            let is_cai_continuation = vec_compare(&cai_en, &en);

                            if cai_seg_cnt > 0 && is_cai_continuation {
                                // make sure this is a cai segment for additional segments,
                                if z <= cai_seg_cnt {
                                    // this a non contiguous segment with same "en" so a bad set of data
                                    // reset and continue to search
                                    cai_en = Vec::new();
                                    continue;
                                }
                                // take out LBox & TBox
                                buffer.append(&mut raw_vec.as_mut_slice()[16..].to_vec());

                                cai_seg_cnt += 1;
                            } else if raw_vec.len() > 28 {
                                // must be at least 28 bytes for this to be a valid JUMBF box
                                // check if this is a CAI JUMBF block
                                let jumb_type = &raw_vec.as_mut_slice()[24..28];
                                let is_cai = vec_compare(&C2PA_MARKER, jumb_type);

                                if is_cai {
                                    if manifest_store_cnt == 1 {
                                        return Err(Error::TooManyManifestStores);
                                    }

                                    buffer.append(&mut raw_vec.as_mut_slice()[8..].to_vec());
                                    cai_seg_cnt = 1;
                                    cai_en.clone_from(&en); // store the identifier

                                    manifest_store_cnt += 1;
                                }
                            }
                        }
                    }
                }
                _ => return Err(Error::InvalidAsset("Unknown image format".to_owned())),
            };
        } else {
            return Err(Error::UnsupportedType);
        }

        if buffer.is_empty() {
            return Err(Error::JumbfNotFound);
        }

        Ok(buffer)
    }

    // Get XMP block
    fn read_xmp(&self, asset_reader: &mut dyn CAIRead) -> Option<String> {
        // load the bytes
        let mut buf: Vec<u8> = Vec::new();
        match asset_reader.read_to_end(&mut buf) {
            Ok(_) => xmp_from_bytes(&buf),
            Err(_) => None,
        }
    }
}

impl CAIWriter for JpegIO {
    fn write_cai(
        &self,
        input_stream: &mut dyn CAIRead,
        output_stream: &mut dyn CAIReadWrite,
        store_bytes: &[u8],
    ) -> Result<()> {
        let mut buf = Vec::new();
        // read the whole asset
        input_stream.rewind()?;
        input_stream.read_to_end(&mut buf).map_err(Error::IoError)?;
        let mut jpeg = Jpeg::from_bytes(buf.into()).map_err(|_err| Error::EmbeddingError)?;

        // remove existing CAI segments
        let insertion_point = match delete_cai_segments(&mut jpeg)? {
            Some(i) if i > 0 => i, // note the Jpeg::from_bytes Vec does not contain the SOI marker
            _ => {
                // insert after last APP0 if it exists (JFIF compatible), otherwise at the beginning (after SOI)
                let app0_index = jpeg
                    .segments()
                    .iter()
                    .rposition(|segment| segment.marker() == APP0);
                app0_index.map_or(0, |i| i + 1)
            }
        };

        let mut seg_chucks = store_bytes.chunks(MAX_JPEG_MARKER_SIZE);
        let num_segments = seg_chucks.len();

        for seg in 0..num_segments {
            /*
                If the size of the box payload is less than 2^32-8 bytes,
                then all fields except the XLBox field, that is: Le, CI, En, Z, LBox and TBox,
                shall be present in all JPEG XT marker segment representing this box,
                regardless of whether the marker segments starts this box,
                or continues a box started by a former JPEG XT Marker segment.
            */
            // we need to prefix the JUMBF with the JPEG XT markers (ISO 19566-5)
            // CI: JPEG extensions marker - JP
            // En: Box Instance Number  - 0x0001
            //          (NOTE: can be any unique ID, so we pick one that shouldn't conflict)
            // Z: Packet sequence number - 0x00000001...
            let ci = vec![0x4a, 0x50];
            let en = vec![0x02, 0x11];
            let z: u32 = u32::try_from(seg + 1)
                .map_err(|_| Error::InvalidAsset("Too many JUMBF segments".to_string()))?; //seg.to_be_bytes();

            let mut seg_data = Vec::new();
            seg_data.extend(ci);
            seg_data.extend(en);
            seg_data.extend(z.to_be_bytes());
            if seg > 0 {
                // the LBox and TBox are already in the JUMBF
                // but we need to duplicate them in all other segments
                let lbox_tbox = store_bytes
                    .get(0..8)
                    .ok_or(Error::InvalidAsset("Store bytes too short".to_string()))?;
                seg_data.extend(lbox_tbox);
            }

            // make sure we have some...
            if let Some(next_seg) = seg_chucks.next() {
                seg_data.extend(next_seg);
            }

            let seg_bytes = Bytes::from(seg_data);
            let app11_segment = JpegSegment::new_with_contents(markers::APP11, seg_bytes);
            if seg + insertion_point <= jpeg.segments().len() {
                jpeg.segments_mut()
                    .insert(seg + insertion_point, app11_segment); // we put this in the beginning...
            } else {
                return Err(Error::InvalidAsset("JPEG JUMBF segment error".to_owned()));
            }
        }

        output_stream.rewind()?;
        jpeg.encoder()
            .write_to(output_stream)
            .map_err(|_err| Error::InvalidAsset("JPEG write error".to_owned()))?;

        Ok(())
    }

    fn get_object_locations_from_stream(
        &self,
        input_stream: &mut dyn CAIRead,
    ) -> Result<Vec<HashObjectPositions>> {
        let mut cai_en: Vec<u8> = Vec::new();
        let mut cai_seg_cnt: u32 = 0;

        let mut positions: Vec<HashObjectPositions> = Vec::new();
        let mut curr_offset = 2; // start after JPEG marker

        let output_vec: Vec<u8> = Vec::new();
        let mut output_stream = Cursor::new(output_vec);
        // make sure the file has the required segments so we can generate all the required offsets
        add_required_segs_to_stream(input_stream, &mut output_stream)?;

        let buf: Vec<u8> = output_stream.into_inner();

        let dimg = DynImage::from_bytes(buf.into())
            .map_err(|e| Error::OtherError(Box::new(e)))?
            .ok_or(Error::UnsupportedType)?;

        let mut cai_loc = HashObjectPositions {
            offset: 0,
            length: 0,
            htype: HashBlockObjectType::Cai,
        };

        match dimg {
            DynImage::Jpeg(jpeg) => {
                if jpeg.segments().is_empty() {
                    return Err(Error::InvalidAsset("JPEG has no segments".to_owned()));
                }
                for seg in jpeg.segments() {
                    match seg.marker() {
                        markers::APP11 => {
                            // JUMBF marker
                            let raw_bytes = seg.contents();

                            if raw_bytes.len() > 16 {
                                // we need at least 16 bytes in each segment for CAI
                                let mut raw_vec = raw_bytes.to_vec();
                                let _ci = raw_vec.as_mut_slice()[0..2].to_vec();
                                let en = raw_vec.as_mut_slice()[2..4].to_vec();

                                let is_cai_continuation = vec_compare(&cai_en, &en);

                                if cai_seg_cnt > 0 && is_cai_continuation {
                                    cai_seg_cnt += 1;
                                    cai_loc.length += seg.len_with_entropy();
                                } else {
                                    // check if this is a CAI JUMBF block
                                    let jumb_type = raw_vec
                                        .get(24..28)
                                        .ok_or(Error::InvalidAsset(
                                            "Invalid JPEG CAI JUMBF block".to_string(),
                                        ))?
                                        .to_vec();
                                    let is_cai = vec_compare(&C2PA_MARKER, &jumb_type);
                                    if is_cai {
                                        cai_seg_cnt = 1;
                                        cai_en.clone_from(&en); // store the identifier

                                        cai_loc.offset = curr_offset;
                                        cai_loc.length += seg.len_with_entropy();
                                    } else {
                                        // save other for completeness sake
                                        let v = HashObjectPositions {
                                            offset: curr_offset,
                                            length: seg.len_with_entropy(),
                                            htype: HashBlockObjectType::Other,
                                        };
                                        positions.push(v);
                                    }
                                }
                            }
                        }
                        markers::APP1 => {
                            // XMP marker or EXIF or Extra XMP
                            let v = HashObjectPositions {
                                offset: curr_offset,
                                length: seg.len_with_entropy(),
                                htype: HashBlockObjectType::Xmp,
                            };
                            // todo: pick the app1 that is the xmp (not crucial as it gets hashed either way)
                            positions.push(v);
                        }
                        _ => {
                            // save other for completeness sake
                            let v = HashObjectPositions {
                                offset: curr_offset,
                                length: seg.len_with_entropy(),
                                htype: HashBlockObjectType::Other,
                            };

                            positions.push(v);
                        }
                    }
                    curr_offset += seg.len_with_entropy();
                }
            }
            _ => return Err(Error::InvalidAsset("Unknown image format".to_owned())),
        }

        if cai_loc.length > 0 {
            positions.push(cai_loc);
        }

        Ok(positions)
    }

    fn remove_cai_store_from_stream(
        &self,
        input_stream: &mut dyn CAIRead,
        output_stream: &mut dyn CAIReadWrite,
    ) -> Result<()> {
        let mut buf = Vec::new();
        // read the whole asset
        input_stream.rewind()?;
        input_stream.read_to_end(&mut buf).map_err(Error::IoError)?;
        let mut jpeg = Jpeg::from_bytes(buf.into()).map_err(|_err| Error::EmbeddingError)?;

        // remove existing CAI segments
        delete_cai_segments(&mut jpeg)?;

        output_stream.rewind()?;
        jpeg.encoder()
            .write_to(output_stream)
            .map_err(|_err| Error::InvalidAsset("JPEG write error".to_owned()))?;

        Ok(())
    }
}

impl AssetIO for JpegIO {
    fn read_cai_store(&self, asset_path: &Path) -> Result<Vec<u8>> {
        let mut f = File::open(asset_path)?;

        self.read_cai(&mut f)
    }

    fn save_cai_store(&self, asset_path: &std::path::Path, store_bytes: &[u8]) -> Result<()> {
        let mut input_stream = std::fs::OpenOptions::new()
            .read(true)
            //.truncate(true)
            .open(asset_path)
            .map_err(Error::IoError)?;

        let mut temp_file = tempfile_builder("c2pa_temp")?;

        self.write_cai(&mut input_stream, &mut temp_file, store_bytes)?;

        // copy temp file to asset
        rename_or_move(temp_file, asset_path)
    }

    fn get_object_locations(&self, asset_path: &Path) -> Result<Vec<HashObjectPositions>> {
        let mut file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(asset_path)
            .map_err(Error::IoError)?;

        self.get_object_locations_from_stream(&mut file)
    }

    fn remove_cai_store(&self, asset_path: &Path) -> Result<()> {
        let input = std::fs::read(asset_path).map_err(Error::IoError)?;

        let mut jpeg = Jpeg::from_bytes(input.into()).map_err(|_err| Error::EmbeddingError)?;

        // remove existing CAI segments
        delete_cai_segments(&mut jpeg)?;

        // save updated file
        let output = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .truncate(true)
            .open(asset_path)
            .map_err(Error::IoError)?;

        jpeg.encoder()
            .write_to(output)
            .map_err(|_err| Error::InvalidAsset("JPEG write error".to_owned()))?;

        Ok(())
    }

    fn new(_asset_type: &str) -> Self
    where
        Self: Sized,
    {
        JpegIO {}
    }

    fn get_handler(&self, asset_type: &str) -> Box<dyn AssetIO> {
        Box::new(JpegIO::new(asset_type))
    }

    fn get_reader(&self) -> &dyn CAIReader {
        self
    }

    fn get_writer(&self, asset_type: &str) -> Option<Box<dyn CAIWriter>> {
        Some(Box::new(JpegIO::new(asset_type)))
    }

    fn remote_ref_writer_ref(&self) -> Option<&dyn RemoteRefEmbed> {
        Some(self)
    }

    fn asset_box_hash_ref(&self) -> Option<&dyn AssetBoxHash> {
        Some(self)
    }

    fn composed_data_ref(&self) -> Option<&dyn ComposedManifestRef> {
        Some(self)
    }

    fn supported_types(&self) -> &[&str] {
        &SUPPORTED_TYPES
    }
}

impl RemoteRefEmbed for JpegIO {
    #[allow(unused_variables)]
    fn embed_reference(
        &self,
        asset_path: &Path,
        embed_ref: crate::asset_io::RemoteRefEmbedType,
    ) -> Result<()> {
        match &embed_ref {
            crate::asset_io::RemoteRefEmbedType::Xmp(_manifest_uri) => {
                let mut file = std::fs::File::open(asset_path)?;
                let mut temp = Cursor::new(Vec::new());
                self.embed_reference_to_stream(&mut file, &mut temp, embed_ref)?;
                let mut output = std::fs::OpenOptions::new()
                    .read(true)
                    .write(true)
                    .truncate(true)
                    .open(asset_path)
                    .map_err(Error::IoError)?;
                temp.set_position(0);
                std::io::copy(&mut temp, &mut output).map_err(Error::IoError)?;
                Ok(())
            }
            crate::asset_io::RemoteRefEmbedType::StegoS(_) => Err(Error::UnsupportedType),
            crate::asset_io::RemoteRefEmbedType::StegoB(_) => Err(Error::UnsupportedType),
            crate::asset_io::RemoteRefEmbedType::Watermark(_) => Err(Error::UnsupportedType),
        }
    }

    fn embed_reference_to_stream(
        &self,
        source_stream: &mut dyn CAIRead,
        output_stream: &mut dyn CAIReadWrite,
        embed_ref: RemoteRefEmbedType,
    ) -> Result<()> {
        match embed_ref {
            crate::asset_io::RemoteRefEmbedType::Xmp(manifest_uri) => {
                let mut buf = Vec::new();
                // read the whole asset
                source_stream.rewind()?;
                source_stream
                    .read_to_end(&mut buf)
                    .map_err(Error::IoError)?;
                let mut jpeg =
                    Jpeg::from_bytes(buf.into()).map_err(|_err| Error::EmbeddingError)?;

                // find any existing XMP segment and remember where it was
                let segments = jpeg.segments_mut();
                let (xmp_index, xmp) = segments
                    .iter()
                    .enumerate()
                    .find_map(|(i, seg)| {
                        if seg.marker() == markers::APP1 {
                            Some((Some(i), extract_xmp(seg)?))
                        } else {
                            None
                        }
                    })
                    .unwrap_or((None, MIN_XMP));

                // add provenance and JPEG XMP prefix
                let xmp = format!("{XMP_SIGNATURE}\0{}", add_provenance(xmp, &manifest_uri)?);
                let segment = JpegSegment::new_with_contents(markers::APP1, Bytes::from(xmp));
                // insert or add the segment
                match xmp_index {
                    Some(i) => segments[i] = segment,
                    None => segments.insert(1, segment),
                }

                jpeg.encoder()
                    .write_to(output_stream)
                    .map_err(|_err| Error::InvalidAsset("JPEG write error".to_owned()))?;
                Ok(())
            }
            crate::asset_io::RemoteRefEmbedType::StegoS(_) => Err(Error::UnsupportedType),
            crate::asset_io::RemoteRefEmbedType::StegoB(_) => Err(Error::UnsupportedType),
            crate::asset_io::RemoteRefEmbedType::Watermark(_) => Err(Error::UnsupportedType),
        }
    }
}

fn in_entropy(marker: u8) -> bool {
    matches!(marker, RST0..=RST7 | Z)
}

// img-parts does not correctly return the true size of the SOS segment.  This utility
// finds the correct break point for single image JPEGs.  We will need a new JPEG decoder
// to handle those.  Also this function can be removed if img-parts ever addresses this issue
// and support MPF JPEGs.
fn get_entropy_size(input_stream: &mut dyn CAIRead) -> Result<usize> {
    // Search the entropy data looking for non entropy segment marker.  The first valid seg marker before we hit
    // end of the file.

    let mut buf_reader = BufReader::new(input_stream);

    let mut size = 0;

    loop {
        match buf_reader.read_u8() {
            Ok(curr_byte) => {
                if curr_byte == P {
                    let next_byte = buf_reader.read_u8()?;

                    if !in_entropy(next_byte) {
                        break;
                    } else {
                        size += 1;
                    }
                }
                size += 1;
            }
            Err(e) => return Err(Error::IoError(e)),
        }
    }

    Ok(size)
}

fn has_length(marker: u8) -> bool {
    matches!(marker, APP0..=APP15 | SOF0..=SOF15 | SOS | COM | DQT | DRI)
}

fn get_seg_size(input_stream: &mut dyn CAIRead) -> Result<usize> {
    let p = input_stream.read_u8()?;
    let marker = if p == P {
        input_stream.read_u8()?
    } else {
        return Err(Error::InvalidAsset(
            "Cannot read segment marker".to_string(),
        ));
    };

    if has_length(marker) {
        let val: usize = input_stream.read_u16::<BigEndian>()? as usize;
        Ok(val + 2)
    } else {
        Ok(2)
    }
}

fn make_box_maps(input_stream: &mut dyn CAIRead) -> Result<Vec<BoxMap>> {
    let segment_names = HashMap::from([
        (0xe0u8, "APP0"),
        (0xe1u8, "APP1"),
        (0xe2u8, "APP2"),
        (0xe3u8, "APP3"),
        (0xe4u8, "APP4"),
        (0xe5u8, "APP5"),
        (0xe6u8, "APP6"),
        (0xe7u8, "APP7"),
        (0xe8u8, "APP8"),
        (0xe9u8, "APP9"),
        (0xeau8, "APP10"),
        (0xebu8, "APP11"),
        (0xecu8, "APP12"),
        (0xedu8, "APP13"),
        (0xeeu8, "APP14"),
        (0xefu8, "APP15"),
        (0xfeu8, "COM"),
        (0xc4u8, "DHT"),
        (0xdbu8, "DQT"),
        (0xddu8, "DRI"),
        (0xd9u8, "EOI"),
        (0xd0u8, "RST0"),
        (0xd1u8, "RST1"),
        (0xd2u8, "RST2"),
        (0xd3u8, "RST3"),
        (0xd4u8, "RST4"),
        (0xd5u8, "RST5"),
        (0xd6u8, "RST6"),
        (0xd7u8, "RST7"),
        (0xc0u8, "SOF0"),
        (0xc1u8, "SOF1"),
        (0xc2u8, "SOF2"),
        (0xd8u8, "SOI"),
        (0xdau8, "SOS"),
        (0xf0u8, "JPG0"),
        (0xf1u8, "JPG1"),
        (0xf2u8, "JPG2"),
        (0xf3u8, "JPG3"),
        (0xf4u8, "JPG4"),
        (0xf5u8, "JPG5"),
        (0xf6u8, "JPG6"),
        (0xf7u8, "JPG7"),
        (0xf8u8, "JPG8"),
        (0xf9u8, "JPG9"),
        (0xfau8, "JPG10"),
        (0xfbu8, "JPG11"),
        (0xfcu8, "JPG12"),
        (0xfdu8, "JPG13"),
    ]);

    let mut box_maps = Vec::new();
    let mut cai_en: Vec<u8> = Vec::new();
    let mut cai_seg_cnt: u32 = 0;
    let mut cai_index = 0;

    input_stream.rewind()?;

    let buf_reader = BufReader::new(input_stream);
    let mut reader = jfifdump::Reader::new(buf_reader)
        .map_err(|_e| Error::InvalidAsset("could not read JPEG segments".to_string()))?;

    while let Ok(seg) = reader.next_segment() {
        match seg.kind {
            jfifdump::SegmentKind::Eoi => {
                let bm = BoxMap {
                    names: vec!["EOI".to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::Soi => {
                let bm = BoxMap {
                    names: vec!["SOI".to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::App { nr, data } if nr == 0x0b => {
                let nr = nr | 0xe0;

                // JUMBF marker
                let raw_bytes = data;

                if raw_bytes.len() > 16 {
                    // we need at least 16 bytes in each segment for CAI
                    let mut raw_vec = raw_bytes.to_vec();
                    let _ci = raw_vec.as_mut_slice()[0..2].to_vec();
                    let en = raw_vec.as_mut_slice()[2..4].to_vec();

                    let is_cai_continuation = vec_compare(&cai_en, &en);

                    if cai_seg_cnt > 0 && is_cai_continuation {
                        cai_seg_cnt += 1;

                        if let Some(cai_bm) = box_maps.get_mut(cai_index) {
                            cai_bm.range_len += (raw_bytes.len() + 4) as u64;
                        } else {
                            return Err(Error::InvalidAsset(
                                "CAI segment index out of bounds".to_string(),
                            ));
                        }
                    } else {
                        // check if this is a CAI JUMBF block
                        let jumb_type = raw_vec
                            .as_mut_slice()
                            .get(24..28)
                            .ok_or(Error::InvalidAsset(
                                "Invalid JPEG CAI JUMBF block".to_string(),
                            ))?
                            .to_vec();
                        let is_cai = vec_compare(&C2PA_MARKER, &jumb_type);
                        if is_cai {
                            cai_seg_cnt = 1;
                            cai_en.clone_from(&en); // store the identifier

                            let c2pa_bm = BoxMap {
                                names: vec![C2PA_BOXHASH.to_string()],
                                alg: None,
                                hash: ByteBuf::from(Vec::new()),
                                excluded: None,
                                pad: ByteBuf::from(Vec::new()),
                                range_start: seg.position as u64,
                                range_len: (raw_bytes.len() + 4) as u64,
                            };

                            box_maps.push(c2pa_bm);
                            cai_index = box_maps.len() - 1;
                        } else {
                            let name = segment_names
                                .get(&nr)
                                .ok_or(Error::InvalidAsset("Unknown segment marker".to_owned()))?;

                            let bm = BoxMap {
                                names: vec![name.to_string()],
                                alg: None,
                                hash: ByteBuf::from(Vec::new()),
                                excluded: None,
                                pad: ByteBuf::from(Vec::new()),
                                range_start: seg.position as u64,
                                range_len: 0,
                            };

                            box_maps.push(bm);
                        }
                    }
                }
            }
            jfifdump::SegmentKind::App { nr, data } => {
                let nr = nr | 0xe0;
                let _data = data;

                let name = segment_names
                    .get(&nr)
                    .ok_or(Error::InvalidAsset("Unknown segment marker".to_owned()))?;

                let bm = BoxMap {
                    names: vec![name.to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::App0Jfif(_) => {
                let bm = BoxMap {
                    names: vec!["APP0".to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::Dqt(_) => {
                let bm = BoxMap {
                    names: vec!["DQT".to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::Dht(_) => {
                let bm = BoxMap {
                    names: vec!["DHT".to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::Dac(_) => {
                let bm = BoxMap {
                    names: vec!["DAC".to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::Frame(f) => {
                let name = segment_names
                    .get(&f.sof)
                    .ok_or(Error::InvalidAsset("Unknown segment marker".to_owned()))?;

                let bm = BoxMap {
                    names: vec![name.to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::Scan(_s) => {
                let bm = BoxMap {
                    names: vec!["SOS".to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::Dri(_) => {
                let bm = BoxMap {
                    names: vec!["DRI".to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::Rst(r) => {
                let bm = BoxMap {
                    names: vec![format!("RST{}", r.nr)],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::Comment(_) => {
                let bm = BoxMap {
                    names: vec!["COM".to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
            jfifdump::SegmentKind::Unknown { marker, data: _ } => {
                let name = segment_names
                    .get(&marker)
                    .ok_or(Error::InvalidAsset("Unknown segment marker".to_owned()))?;

                let bm = BoxMap {
                    names: vec![name.to_string()],
                    alg: None,
                    hash: ByteBuf::from(Vec::new()),
                    excluded: None,
                    pad: ByteBuf::from(Vec::new()),
                    range_start: seg.position as u64,
                    range_len: 0,
                };

                box_maps.push(bm);
            }
        }
    }

    Ok(box_maps)
}

impl AssetBoxHash for JpegIO {
    fn get_box_map(&self, input_stream: &mut dyn CAIRead) -> Result<Vec<BoxMap>> {
        let mut box_maps = make_box_maps(input_stream)?;

        // If no C2PA APP11 segment exists in the source, synthesize a placeholder
        // entry at the standard insertion point (immediately after the 2-byte SOI
        // marker at offset 0).  This is needed on the signing path so that the box
        // list covers the full file layout after embedding: verification re-derives
        // byte positions from the current (embedded) file, and the C2PA entry must
        // be present so the name-matching loop in `verify_stream_hash` can skip it.
        // When a real C2PA segment is already present (e.g. during verification or
        // re-signing) this block is skipped and the real entry is used as-is.
        let has_c2pa = box_maps
            .iter()
            .any(|bm| bm.names.first().is_some_and(|n| n == C2PA_BOXHASH));

        if !has_c2pa {
            let mut c2pa_box = BoxMap {
                names: vec![C2PA_BOXHASH.to_string()],
                alg: None,
                hash: ByteBuf::from(Vec::new()),
                excluded: Some(true),
                pad: ByteBuf::from(Vec::new()),
                range_start: 0,
                range_len: 0,
            };
            // SOI is always first; insert the C2PA box right after it or after APP0 if it exists.
            let app0_index = box_maps
                .iter()
                .position(|bm| bm.names.first().is_some_and(|n| n == "APP0"));
            match app0_index {
                Some(i) => {
                    let app0_box = &box_maps[i];
                    input_stream.seek(std::io::SeekFrom::Start(app0_box.range_start))?;
                    let size = get_seg_size(input_stream)?;

                    c2pa_box.range_start = app0_box.range_start + size as u64;
                    box_maps.insert(i + 1, c2pa_box)
                }
                None if box_maps.len() > 1 => {
                    let box0 = &box_maps[0];
                    input_stream.seek(std::io::SeekFrom::Start(box0.range_start))?;
                    let size = get_seg_size(input_stream)?;

                    c2pa_box.range_start = box0.range_start + size as u64;
                    box_maps.insert(1, c2pa_box)
                }
                None => return Err(Error::InvalidAsset("JPEG file has no segments".to_string())),
            };
        }

        for bm in box_maps.iter_mut() {
            if let Some(name) = bm.names.first() {
                if name == C2PA_BOXHASH {
                    continue;
                }
            }

            input_stream.seek(std::io::SeekFrom::Start(bm.range_start))?;

            let size = if bm.names.first().is_some_and(|name| name == "SOS") {
                let mut size = get_seg_size(input_stream)?;

                input_stream.seek(std::io::SeekFrom::Start(bm.range_start + size as u64))?;

                size += get_entropy_size(input_stream)?;

                size
            } else {
                get_seg_size(input_stream)?
            };

            bm.range_len = size as u64;
        }

        Ok(box_maps)
    }
}

impl ComposedManifestRef for JpegIO {
    fn compose_manifest(&self, manifest_data: &[u8], _format: &str) -> Result<Vec<u8>> {
        let mut seg_chucks = manifest_data.chunks(MAX_JPEG_MARKER_SIZE);
        let num_segments = seg_chucks.len(); // recalculate based on actual chunks

        let mut segments = Vec::new();

        for seg in 0..num_segments {
            /*
                If the size of the box payload is less than 2^32-8 bytes,
                then all fields except the XLBox field, that is: Le, CI, En, Z, LBox and TBox,
                shall be present in all JPEG XT marker segment representing this box,
                regardless of whether the marker segments starts this box,
                or continues a box started by a former JPEG XT Marker segment.
            */
            // we need to prefix the JUMBF with the JPEG XT markers (ISO 19566-5)
            // CI: JPEG extensions marker - JP
            // En: Box Instance Number  - 0x0001
            //          (NOTE: can be any unique ID, so we pick one that shouldn't conflict)
            // Z: Packet sequence number - 0x00000001...
            let ci = vec![0x4a, 0x50];
            let en = vec![0x02, 0x11];
            let z: u32 = u32::try_from(seg + 1)
                .map_err(|_| Error::InvalidAsset("Too many JUMBF segments".to_string()))?; //seg.to_be_bytes();

            let mut seg_data = Vec::new();
            seg_data.extend(ci);
            seg_data.extend(en);
            seg_data.extend(z.to_be_bytes());
            if seg > 0 {
                // the LBox and TBox are already in the JUMBF
                // but we need to duplicate them in all other segments
                let lbox_tbox = manifest_data
                    .get(0..8)
                    .ok_or(Error::InvalidAsset("Manifest data too short".to_string()))?;
                seg_data.extend(lbox_tbox);
            }

            // make sure we have some...
            if let Some(next_seg) = seg_chucks.next() {
                seg_data.extend(next_seg);
            }

            let seg_bytes = Bytes::from(seg_data);
            let app11_segment = JpegSegment::new_with_contents(markers::APP11, seg_bytes);
            segments.push(app11_segment);
        }

        let output = Vec::with_capacity(manifest_data.len() * 2);
        let mut out_stream = Cursor::new(output);

        // right out segments
        for s in segments {
            // maker
            out_stream.write_u8(markers::P)?;
            out_stream.write_u8(s.marker())?;

            //len
            out_stream.write_u16::<BigEndian>(s.contents().len() as u16 + 2)?;

            // data
            out_stream.write_all(s.contents())?;
        }

        Ok(out_stream.into_inner())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum JpegError {
    #[error("invalid file signature: {reason}")]
    InvalidFileSignature { reason: String },
}

#[cfg(test)]
pub mod tests {
    #![allow(clippy::unwrap_used)]

    use std::io::{Read, Seek};

    use c2pa_macros::c2pa_test_async;
    #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
    use wasm_bindgen_test::*;

    use super::*;
    use crate::utils::io_utils::{safe_vec, tempdirectory};
    #[test]
    fn test_extract_xmp() {
        let contents = Bytes::from_static(b"http://ns.adobe.com/xap/1.0/\0stuff");
        let seg = JpegSegment::new_with_contents(markers::APP1, contents);
        let result = extract_xmp(&seg);
        assert_eq!(result, Some("stuff"));

        let contents = Bytes::from_static(b"http://ns.adobe.com/xap/1.0/ stuff");
        let seg = JpegSegment::new_with_contents(markers::APP1, contents);
        let result = extract_xmp(&seg);
        assert_eq!(result, Some("stuff"));

        let contents = Bytes::from_static(b"tiny");
        let seg = JpegSegment::new_with_contents(markers::APP1, contents);
        let result = extract_xmp(&seg);
        assert_eq!(result, None);

        let contents = Bytes::from_static(b"http://ns.adobe.com/xap/1.0/");
        let seg = JpegSegment::new_with_contents(markers::APP1, contents);
        let result = extract_xmp(&seg);
        assert_eq!(result, None);
    }

    #[test]
    fn test_remove_c2pa() {
        let source = crate::utils::test::fixture_path("CA.jpg");

        let temp_dir = tempdirectory().unwrap();
        let output = crate::utils::test::temp_dir_path(&temp_dir, "CA_test.jpg");

        std::fs::copy(source, &output).unwrap();
        let jpeg_io = JpegIO {};

        jpeg_io.remove_cai_store(&output).unwrap();

        // read back in asset, JumbfNotFound is expected since it was removed
        match jpeg_io.read_cai_store(&output) {
            Err(Error::JumbfNotFound) => (),
            _ => unreachable!(),
        }
    }

    #[test]
    fn test_remove_c2pa_from_stream() {
        let source = crate::utils::test::fixture_path("CA.jpg");

        let source_bytes = std::fs::read(source).unwrap();
        let mut source_stream = Cursor::new(source_bytes);

        let jpeg_io = JpegIO {};
        let jpg_writer = jpeg_io.get_writer("jpg").unwrap();

        let output_bytes = Vec::new();
        let mut output_stream = Cursor::new(output_bytes);

        jpg_writer
            .remove_cai_store_from_stream(&mut source_stream, &mut output_stream)
            .unwrap();

        // read back in asset, JumbfNotFound is expected since it was removed
        let jpg_reader = jpeg_io.get_reader();
        match jpg_reader.read_cai(&mut output_stream) {
            Err(Error::JumbfNotFound) => (),
            _ => unreachable!(),
        }
    }

    #[test]
    fn test_xmp_read_write() {
        let source = crate::utils::test::fixture_path("CA.jpg");

        let temp_dir = tempdirectory().unwrap();
        let output = crate::utils::test::temp_dir_path(&temp_dir, "CA_test.jpg");

        std::fs::copy(source, &output).unwrap();

        let test_msg = "this some test xmp data";
        let handler = JpegIO::new("");

        // write xmp
        let assetio_handler = handler.get_handler("jpg");

        let remote_ref_handler = assetio_handler.remote_ref_writer_ref().unwrap();

        remote_ref_handler
            .embed_reference(&output, RemoteRefEmbedType::Xmp(test_msg.to_string()))
            .unwrap();

        // read back in XMP
        let mut file_reader = std::fs::File::open(&output).unwrap();
        let read_xmp = assetio_handler
            .get_reader()
            .read_xmp(&mut file_reader)
            .unwrap();

        assert!(read_xmp.contains(test_msg));
    }

    #[c2pa_test_async]
    async fn test_xmp_read_write_stream() {
        let source_bytes = include_bytes!("../../tests/fixtures/CA.jpg");

        let test_msg = "this some test xmp data";
        let handler = JpegIO::new("");

        let assetio_handler = handler.get_handler("jpg");

        let remote_ref_handler = assetio_handler.remote_ref_writer_ref().unwrap();

        let mut source_stream = Cursor::new(source_bytes.to_vec());
        let mut output_stream = Cursor::new(Vec::new());
        remote_ref_handler
            .embed_reference_to_stream(
                &mut source_stream,
                &mut output_stream,
                RemoteRefEmbedType::Xmp(test_msg.to_string()),
            )
            .unwrap();

        output_stream.set_position(0);

        // read back in XMP
        let read_xmp = assetio_handler
            .get_reader()
            .read_xmp(&mut output_stream)
            .unwrap();

        output_stream.set_position(0);

        //std::fs::write("../target/xmp_write.jpg", output_stream.into_inner()).unwrap();

        assert!(read_xmp.contains(test_msg));
    }

    #[test]
    fn test_embeddable_manifest() {
        let jpeg_io = JpegIO {};

        let source = crate::utils::test::fixture_path("CA.jpg");

        let ol = jpeg_io.get_object_locations(&source).unwrap();

        let cai_loc = ol
            .iter()
            .find(|o| o.htype == HashBlockObjectType::Cai)
            .unwrap();
        let curr_manifest = jpeg_io.read_cai_store(&source).unwrap();

        let temp_dir = tempdirectory().unwrap();
        let output = crate::utils::test::temp_dir_path(&temp_dir, "CA_test.jpg");

        std::fs::copy(source, &output).unwrap();

        // remove existing
        jpeg_io.remove_cai_store(&output).unwrap();

        // generate new manifest data
        let em = jpeg_io
            .composed_data_ref()
            .unwrap()
            .compose_manifest(&curr_manifest, "jpeg")
            .unwrap();

        // insert new manifest
        let outbuf = Vec::new();
        let mut out_stream = Cursor::new(outbuf);

        let mut before = vec![0u8; cai_loc.offset];
        let mut in_file = std::fs::File::open(&output).unwrap();

        // write before
        in_file.read_exact(before.as_mut_slice()).unwrap();
        out_stream.write_all(&before).unwrap();

        // write composed bytes
        out_stream.write_all(&em).unwrap();

        // write bytes after
        let mut after_buf = Vec::new();
        in_file.read_to_end(&mut after_buf).unwrap();
        out_stream.write_all(&after_buf).unwrap();

        // read manifest back in from new in-memory JPEG
        out_stream.rewind().unwrap();
        let restored_manifest = jpeg_io.read_cai(&mut out_stream).unwrap();

        assert_eq!(&curr_manifest, &restored_manifest);
    }

    #[test]
    fn test_crash_write_cai() {
        let data = [
            0xff, 0xd8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xd9, 0x00, 0x00, 0x00, 0x06, 0xc9,
        ];

        let mut stream = Cursor::new(&data);

        let jpeg_io = JpegIO {};

        let result = jpeg_io.get_object_locations_from_stream(&mut stream);
        assert!(matches!(result, Err(Error::InvalidAsset(_))));
    }

    #[test]
    fn test_crash_get_cai_segments() {
        let data = [
            0xff, 0xd8, 0xff, 0xfd, 0x60, 0xff, 0xff, 0xeb, 0x00, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b,
            0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b,
            0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b,
            0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b,
            0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b,
            0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x1b, 0x27, 0xc2, 0xb8, 0x00, 0x00,
            0xa3, 0x54, 0x8d, 0x8a, 0xff, 0x0b, 0x50, 0x50, 0x49, 0xff, 0xfb, 0xfb, 0xfb, 0xfb,
            0xfb, 0xfb, 0xfb, 0xfb, 0x00, 0x00, 0x00, 0x00, 0xf3, 0xff, 0x55, 0xff, 0xd8, 0xff,
            0x89, 0x50, 0x4e, 0x47, 0x52, 0x49, 0x46, 0x51, 0x42, 0x45, 0x57, 0x46, 0xff, 0xff,
            0x00, 0xff, 0xff, 0xd8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xdf, 0xff, 0xd8, 0xe5,
            0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5,
            0xe5, 0xe5, 0xe5, 0xff, 0xff, 0xff, 0xff, 0xff, 0x52, 0x00, 0x04, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xec,
            0xe5, 0xe5, 0xe5, 0xe5, 0x50, 0x4e, 0x47, 0xda, 0x3a, 0x10, 0xff, 0x60, 0xff, 0xff,
            0x53, 0x00, 0x00, 0x00, 0x52, 0x49, 0x46, 0x46, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5,
            0xff, 0xff, 0xff, 0xff, 0xff, 0x52, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xec, 0xe5, 0xe5, 0xe5,
            0xe5, 0x50, 0x4e, 0x47, 0xda, 0x00, 0x10, 0xff, 0x60, 0xff, 0xff, 0xeb, 0x00, 0x27,
            0xc2, 0xb8, 0x00, 0x00, 0xff, 0xff, 0xff, 0x0b, 0x50, 0x52, 0x49, 0xff, 0xa3, 0x01,
            0x00, 0x00, 0x00, 0xc2, 0xb8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07,
            0x28, 0xa4, 0x0d, 0x0a, 0xff, 0x60, 0xff, 0xff, 0xff, 0xff, 0xff, 0x24, 0xff, 0xff,
            0xff, 0x44, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa3, 0x54, 0xe5, 0xe5,
            0xe5, 0xe5, 0x50, 0x4e, 0x47, 0xda, 0x3a, 0x10, 0xff, 0x60, 0xff, 0xff, 0xeb, 0x00,
            0x27, 0xc2, 0xb8, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xff, 0xff,
            0xff, 0xff, 0xff, 0x52, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xe5, 0xec, 0xe5, 0xe5, 0xe5, 0xe5, 0x50,
            0x4e, 0x47, 0xda, 0x00, 0x10, 0xff, 0x60, 0xff, 0xff, 0xeb, 0x00, 0x27, 0xc2, 0xb8,
            0x00, 0x00, 0xff, 0xff, 0xff, 0x0b, 0x89, 0x50, 0x4e, 0x47, 0x53, 0x00, 0x00, 0x00,
            0x52, 0x49, 0x46, 0x46, 0x0d, 0x0a, 0x1a, 0x0a, 0x50, 0x52, 0x49, 0xff, 0xa3, 0x01,
            0x00, 0x00, 0x00, 0xc2, 0xb8, 0xff, 0x07, 0xff, 0x60, 0x25, 0xff, 0xff, 0xff, 0xff,
            0xdf, 0x24, 0xff, 0xff, 0x00, 0x00, 0xf3, 0xff, 0xff, 0x24, 0xff, 0xff, 0xfb, 0xfb,
            0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0xfb, 0x00,
            0x27, 0xc2, 0xff, 0xd9, 0xff, 0x00, 0xff, 0xff,
        ];

        let mut stream = Cursor::new(&data);

        let jpeg_io = JpegIO {};

        let result = jpeg_io.get_object_locations_from_stream(&mut stream);
        assert!(matches!(result, Err(Error::InvalidAsset(_))));
    }

    #[test]
    fn test_crash_jpeg_segments() {
        let data = [
            0xff, 0xd8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x47,
            0xd2, 0x00, 0x10, 0xff, 0x60, 0xff, 0xff, 0xeb, 0x00, 0x27, 0xc2, 0xb8, 0xff, 0xd8,
            0xff, 0xff, 0x60, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0x60, 0xff, 0x4e, 0x4e, 0x4e, 0xff, 0x00, 0x00, 0x2b, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0x3d, 0xff, 0xff, 0x00, 0xff, 0x5c, 0xff, 0xff, 0xda,
            0x00, 0x02, 0x00, 0x01, 0x00, 0xff, 0x0b, 0x50, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0x10, 0x00, 0x00, 0x59, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0xdf, 0xdf, 0x52, 0x49, 0x46, 0x46, 0xff, 0xff, 0xff, 0xff, 0x3d, 0xff,
            0xff, 0x00, 0xff, 0x5c, 0x4b, 0x4e, 0x60, 0xff, 0xff, 0x00, 0x00, 0x2b, 0xff, 0xff,
            0x3d, 0xff, 0xff, 0x00, 0xff, 0x5c, 0xff, 0xff, 0xda, 0x00, 0x10, 0x00, 0x00, 0x59,
            0x00, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x00, 0x00, 0x07, 0x60, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x60, 0xff, 0x4e, 0x4e, 0x4e,
            0xff, 0x00, 0x00, 0x2b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3d, 0xff,
            0xff, 0x00, 0xff, 0x5c, 0xff, 0xff, 0xda, 0x00, 0x10, 0x00, 0x00, 0x59, 0x00, 0x00,
            0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdf, 0xdf, 0x52, 0x49, 0x46,
            0x46, 0x25, 0x00, 0x00, 0xdf, 0xdf, 0x52, 0x49, 0x46, 0xad, 0x46, 0x6f, 0x00, 0x6f,
            0x00,
        ];

        let mut stream = Cursor::new(&data);

        let jpeg_io = JpegIO {};

        let _ = jpeg_io.get_object_locations_from_stream(&mut stream);
    }

    #[test]
    fn test_crash_jpeg_segments_equal_chunk_multiple() {
        let some_data = safe_vec(MAX_JPEG_MARKER_SIZE as u64 * 3, Some(1u8)).unwrap();
        let source = crate::utils::test::fixture_path("CA.jpg");
        let mut source_stream = std::fs::File::open(source).unwrap();

        let jpeg_io = JpegIO {};
        let output = Vec::new();
        let mut output_stream = Cursor::new(output);

        let _ = jpeg_io.write_cai(&mut source_stream, &mut output_stream, &some_data);
    }
}