-
Notifications
You must be signed in to change notification settings - Fork 42
/
bmff_io.rs
2004 lines (1702 loc) · 68.5 KB
/
bmff_io.rs
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
// 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::{
cmp::min,
collections::HashMap,
fs::{File, OpenOptions},
io::{Cursor, Read, Seek, SeekFrom, Write},
path::Path,
};
use atree::{Arena, Token};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use conv::ValueFrom;
use tempfile::Builder;
use crate::{
assertions::{BmffMerkleMap, ExclusionsMap},
asset_io::{
rename_or_copy, AssetIO, AssetPatch, CAIRead, CAIReadWrite, CAIReader, CAIWriter,
HashObjectPositions, RemoteRefEmbed, RemoteRefEmbedType,
},
error::{Error, Result},
utils::{
hash_utils::{vec_compare, HashRange},
xmp_inmemory_utils::{add_provenance, MIN_XMP},
},
};
pub struct BmffIO {
#[allow(dead_code)]
bmff_format: String, // can be used for specialized BMFF cases
}
const HEADER_SIZE: u64 = 8; // 4 byte type + 4 byte size
const HEADER_SIZE_LARGE: u64 = 16; // 4 byte type + 4 byte size + 8 byte large size
const C2PA_UUID: [u8; 16] = [
0xd8, 0xfe, 0xc3, 0xd6, 0x1b, 0x0e, 0x48, 0x3c, 0x92, 0x97, 0x58, 0x28, 0x87, 0x7e, 0xc4, 0x81,
];
const XMP_UUID: [u8; 16] = [
0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac,
];
const MANIFEST: &str = "manifest";
const MERKLE: &str = "merkle";
// ISO IEC 14496-12_2022 FullBoxes
const FULL_BOX_TYPES: &[&str; 80] = &[
"pdin", "mvhd", "tkhd", "mdhd", "hdlr", "nmhd", "elng", "stsd", "stdp", "stts", "ctts", "cslg",
"stss", "stsh", "stdp", "elst", "dref", "stsz", "stz2", "stsc", "stco", "co64", "padb", "subs",
"saiz", "saio", "mehd", "trex", "mfhd", "tfhd", "trun", "tfra", "mfro", "tfdt", "leva", "trep",
"assp", "sbgp", "sgpd", "csgp", "cprt", "tsel", "kind", "meta", "xml ", "bxml", "iloc", "pitm",
"ipro", "infe", "iinf", "iref", "ipma", "schm", "fiin", "fpar", "fecr", "gitn", "fire", "stri",
"stsg", "stvi", "csch", "sidx", "ssix", "prft", "srpp", "vmhd", "smhd", "srat", "chnl", "dmix",
"txtC", "mime", "uri ", "uriI", "hmhd", "sthd", "vvhd", "medc",
];
static SUPPORTED_TYPES: [&str; 13] = [
"avif",
"heif",
"heic",
"mp4",
"m4a",
"mov",
"application/mp4",
"audio/mp4",
"image/avif",
"image/heic",
"image/heif",
"video/mp4",
"video/quicktime",
];
macro_rules! boxtype {
($( $name:ident => $value:expr ),*) => {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BoxType {
$( $name, )*
UnknownBox(u32),
}
impl From<u32> for BoxType {
fn from(t: u32) -> BoxType {
match t {
$( $value => BoxType::$name, )*
_ => BoxType::UnknownBox(t),
}
}
}
impl From<BoxType> for u32 {
fn from(t: BoxType) -> u32 {
match t {
$( BoxType::$name => $value, )*
BoxType::UnknownBox(t) => t,
}
}
}
}
}
boxtype! {
Empty => 0x0000_0000,
UuidBox => 0x75756964,
FtypBox => 0x66747970,
MvhdBox => 0x6d766864,
MfhdBox => 0x6d666864,
FreeBox => 0x66726565,
MdatBox => 0x6d646174,
MoovBox => 0x6d6f6f76,
MvexBox => 0x6d766578,
MehdBox => 0x6d656864,
TrexBox => 0x74726578,
EmsgBox => 0x656d7367,
MoofBox => 0x6d6f6f66,
TkhdBox => 0x746b6864,
TfhdBox => 0x74666864,
EdtsBox => 0x65647473,
MdiaBox => 0x6d646961,
ElstBox => 0x656c7374,
MfraBox => 0x6d667261,
MdhdBox => 0x6d646864,
HdlrBox => 0x68646c72,
MinfBox => 0x6d696e66,
VmhdBox => 0x766d6864,
StblBox => 0x7374626c,
StsdBox => 0x73747364,
SttsBox => 0x73747473,
CttsBox => 0x63747473,
StssBox => 0x73747373,
StscBox => 0x73747363,
StszBox => 0x7374737A,
StcoBox => 0x7374636F,
Co64Box => 0x636F3634,
TrakBox => 0x7472616b,
TrafBox => 0x74726166,
TrefBox => 0x74726566,
TregBox => 0x74726567,
TrunBox => 0x7472756E,
UdtaBox => 0x75647461,
DinfBox => 0x64696e66,
DrefBox => 0x64726566,
UrlBox => 0x75726C20,
SmhdBox => 0x736d6864,
Avc1Box => 0x61766331,
AvcCBox => 0x61766343,
Hev1Box => 0x68657631,
HvcCBox => 0x68766343,
Mp4aBox => 0x6d703461,
EsdsBox => 0x65736473,
Tx3gBox => 0x74783367,
VpccBox => 0x76706343,
Vp09Box => 0x76703039,
MetaBox => 0x6D657461,
SchiBox => 0x73636869,
IlocBox => 0x696C6F63
}
struct BoxHeaderLite {
pub name: BoxType,
pub size: u64,
pub fourcc: String,
pub large_size: bool,
}
impl BoxHeaderLite {
pub fn new(name: BoxType, size: u64, fourcc: &str) -> Self {
Self {
name,
size,
fourcc: fourcc.to_string(),
large_size: false,
}
}
pub fn read<R: Read + ?Sized>(reader: &mut R) -> Result<Self> {
// Create and read to buf.
let mut buf = [0u8; 8]; // 8 bytes for box header.
reader.read_exact(&mut buf)?;
// Get size.
let mut s = [0u8; 4];
s.clone_from_slice(&buf[0..4]);
let size = u32::from_be_bytes(s);
// Get box type string.
let mut t = [0u8; 4];
t.clone_from_slice(&buf[4..8]);
let fourcc = String::from_utf8_lossy(&buf[4..8]).to_string();
let typ = u32::from_be_bytes(t);
// Get largesize if size is 1
if size == 1 {
reader.read_exact(&mut buf)?;
let largesize = u64::from_be_bytes(buf);
Ok(BoxHeaderLite {
name: BoxType::from(typ),
size: largesize,
fourcc,
large_size: true,
})
} else {
Ok(BoxHeaderLite {
name: BoxType::from(typ),
size: size as u64,
fourcc,
large_size: false,
})
}
}
pub fn write<W: Write>(&self, writer: &mut W) -> Result<u64> {
if self.size > u32::MAX as u64 {
writer.write_u32::<BigEndian>(1)?;
writer.write_u32::<BigEndian>(self.name.into())?;
writer.write_u64::<BigEndian>(self.size)?;
Ok(16)
} else {
writer.write_u32::<BigEndian>(self.size as u32)?;
writer.write_u32::<BigEndian>(self.name.into())?;
Ok(8)
}
}
}
fn write_box_uuid_extension<W: Write>(w: &mut W, uuid: &[u8; 16]) -> Result<u64> {
w.write_all(uuid)?;
Ok(16)
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BoxInfo {
path: String,
parent: Option<Token>,
pub offset: u64,
pub size: u64,
box_type: BoxType,
user_type: Option<Vec<u8>>,
version: Option<u8>,
flags: Option<u32>,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BoxInfoLite {
pub path: String,
pub offset: u64,
pub size: u64,
}
fn read_box_header_ext<R: Read + Seek + ?Sized>(reader: &mut R) -> Result<(u8, u32)> {
let version = reader.read_u8()?;
let flags = reader.read_u24::<BigEndian>()?;
Ok((version, flags))
}
fn write_box_header_ext<W: Write>(w: &mut W, v: u8, f: u32) -> Result<u64> {
w.write_u8(v)?;
w.write_u24::<BigEndian>(f)?;
Ok(4)
}
fn box_start<R: Read + Seek + ?Sized>(reader: &mut R, is_large: bool) -> Result<u64> {
if is_large {
Ok(reader.stream_position()? - HEADER_SIZE_LARGE)
} else {
Ok(reader.stream_position()? - HEADER_SIZE)
}
}
fn _skip_bytes<R: Read + Seek + ?Sized>(reader: &mut R, size: u64) -> Result<()> {
reader.seek(SeekFrom::Current(size as i64))?;
Ok(())
}
fn skip_bytes_to<R: Read + Seek + ?Sized>(reader: &mut R, pos: u64) -> Result<u64> {
let pos = reader.seek(SeekFrom::Start(pos))?;
Ok(pos)
}
fn write_c2pa_box<W: Write>(
w: &mut W,
data: &[u8],
is_manifest: bool,
merkle_data: &[u8],
) -> Result<()> {
let purpose_size = if is_manifest {
MANIFEST.len() + 1
} else {
MERKLE.len() + 1
};
let merkle_size = if is_manifest { 8 } else { merkle_data.len() };
let size = 8 + 16 + 4 + purpose_size + merkle_size + data.len(); // header + UUID + version/flags + data + zero terminated purpose + merkle data
let bh = BoxHeaderLite::new(BoxType::UuidBox, size as u64, "uuid");
// write out header
bh.write(w)?;
// write out c2pa extension UUID
write_box_uuid_extension(w, &C2PA_UUID)?;
// write out version and flags
let version: u8 = 0;
let flags: u32 = 0;
write_box_header_ext(w, version, flags)?;
// write purpose
if is_manifest {
w.write_all(MANIFEST.as_bytes())?;
w.write_u8(0)?;
// write no merkle flag
w.write_u64::<BigEndian>(0)?;
} else {
w.write_all(MERKLE.as_bytes())?;
w.write_u8(0)?;
// write merkle cbor
w.write_all(merkle_data)?;
}
// write out data
w.write_all(data)?;
Ok(())
}
fn write_xmp_box<W: Write>(w: &mut W, data: &[u8]) -> Result<()> {
let size = 8 + 16 + 4 + data.len(); // header + UUID + data
let bh = BoxHeaderLite::new(BoxType::UuidBox, size as u64, "uuid");
// write out header
bh.write(w)?;
// write out XMP extension UUID
write_box_uuid_extension(w, &XMP_UUID)?;
// write out data
w.write_all(data)?;
Ok(())
}
fn _write_free_box<W: Write>(w: &mut W, size: usize) -> Result<()> {
if size < 8 {
return Err(Error::BadParam("cannot adjust free space".to_string()));
}
let zeros = vec![0u8; size - 8];
let bh = BoxHeaderLite::new(BoxType::FreeBox, size as u64, "free");
// write out header
bh.write(w)?;
// write out header
w.write_all(&zeros)?;
Ok(())
}
fn add_token_to_cache(bmff_path_map: &mut HashMap<String, Vec<Token>>, path: String, token: Token) {
if let Some(token_list) = bmff_path_map.get_mut(&path) {
token_list.push(token);
} else {
let token_list = vec![token];
bmff_path_map.insert(path, token_list);
}
}
fn path_from_token(bmff_tree: &Arena<BoxInfo>, current_node_token: &Token) -> Result<String> {
let ancestors = current_node_token.ancestors(bmff_tree);
let mut path = bmff_tree[*current_node_token].data.path.clone();
for parent in ancestors {
path = format!("{}/{}", parent.data.path, path);
}
if path.is_empty() {
path = "/".to_string();
}
Ok(path)
}
fn get_top_level_box_offsets(
bmff_tree: &Arena<BoxInfo>,
bmff_path_map: &HashMap<String, Vec<Token>>,
) -> Vec<u64> {
let mut tl_offsets = Vec::new();
for (p, t) in bmff_path_map {
// look for top level offsets
if p.matches('/').count() == 1 {
for token in t {
if let Some(box_info) = bmff_tree.get(*token) {
tl_offsets.push(box_info.data.offset);
}
}
}
}
tl_offsets
}
fn get_top_level_boxes(
bmff_tree: &Arena<BoxInfo>,
bmff_path_map: &HashMap<String, Vec<Token>>,
) -> Vec<BoxInfoLite> {
let mut tl_boxes = Vec::new();
for (p, t) in bmff_path_map {
// look for top level offsets
if p.matches('/').count() == 1 {
for token in t {
if let Some(box_info) = bmff_tree.get(*token) {
tl_boxes.push(BoxInfoLite {
path: box_info.data.path.clone(),
offset: box_info.data.offset,
size: box_info.data.size,
});
}
}
}
}
tl_boxes
}
pub fn bmff_to_jumbf_exclusions(
reader: &mut dyn CAIRead,
bmff_exclusions: &[ExclusionsMap],
bmff_v2: bool,
) -> Result<Vec<HashRange>> {
let size = reader.seek(SeekFrom::End(0))?;
reader.rewind()?;
// create root node
let root_box = BoxInfo {
path: "".to_string(),
offset: 0,
size,
box_type: BoxType::Empty,
parent: None,
user_type: None,
version: None,
flags: None,
};
let (mut bmff_tree, root_token) = Arena::with_data(root_box);
let mut bmff_map: HashMap<String, Vec<Token>> = HashMap::new();
// build layout of the BMFF structure
build_bmff_tree(reader, size, &mut bmff_tree, &root_token, &mut bmff_map)?;
// get top level box offsets
let mut tl_offsets = get_top_level_box_offsets(&bmff_tree, &bmff_map);
tl_offsets.sort();
let mut exclusions = Vec::new();
for bmff_exclusion in bmff_exclusions {
if let Some(box_token_list) = bmff_map.get(&bmff_exclusion.xpath) {
for box_token in box_token_list {
let box_info = &bmff_tree[*box_token].data;
let box_start = box_info.offset;
let box_length = box_info.size;
let exclusion_start = box_start;
let exclusion_length = box_length;
// adjust exclusion bounds as needed
// check the length
if let Some(desired_length) = bmff_exclusion.length {
if desired_length as u64 != box_length {
continue;
}
}
// check the version
if let Some(desired_version) = bmff_exclusion.version {
if let Some(box_version) = box_info.version {
if desired_version != box_version {
continue;
}
}
}
// check the flags
if let Some(desired_flag_bytes) = &bmff_exclusion.flags {
let mut temp_bytes = [0u8; 4];
if desired_flag_bytes.len() >= 3 {
temp_bytes[0] = desired_flag_bytes[0];
temp_bytes[1] = desired_flag_bytes[1];
temp_bytes[2] = desired_flag_bytes[2];
}
let desired_flags = u32::from_be_bytes(temp_bytes);
if let Some(box_flags) = box_info.flags {
let exact = if let Some(is_exact) = bmff_exclusion.exact {
is_exact
} else {
true
};
if exact {
if desired_flags != box_flags {
continue;
}
} else {
// bitwise match
if (desired_flags | box_flags) != desired_flags {
continue;
}
}
}
}
// check data match
if let Some(data_map_vec) = &bmff_exclusion.data {
let mut should_add = true;
for data_map in data_map_vec {
// move to the start of exclusion
skip_bytes_to(reader, box_start + data_map.offset as u64)?;
// match the data
let mut buf = vec![0u8; data_map.value.len()];
reader.read_exact(&mut buf)?;
// does not match so skip
if !vec_compare(&data_map.value, &buf) {
should_add = false;
break;
}
}
if !should_add {
continue;
}
}
// reduce range if desired
if let Some(subset_vec) = &bmff_exclusion.subset {
for subset in subset_vec {
let exclusion = HashRange::new(
(exclusion_start + subset.offset as u64) as usize,
(if subset.length == 0 {
exclusion_length - subset.offset as u64
} else {
min(subset.length as u64, exclusion_length)
}) as usize,
);
exclusions.push(exclusion);
}
} else {
// exclude box in its entirty
let exclusion =
HashRange::new(exclusion_start as usize, exclusion_length as usize);
exclusions.push(exclusion);
// for BMFF V2 hashes we do not add hash offsets for top level boxes
// that are completely excluded, so remove from BMFF V2 hash offset calc
if let Some(pos) = tl_offsets.iter().position(|x| *x == exclusion_start) {
tl_offsets.remove(pos);
}
}
}
}
}
// add remaining top level offsets to be included when generating BMFF V2 hashes
// note: this is technically not an exclusion but a replacement with a new range of bytes to be hashed
if bmff_v2 {
for tl_start in tl_offsets {
let mut exclusion = HashRange::new(tl_start as usize, 1);
exclusion.set_bmff_offset(tl_start);
exclusions.push(exclusion);
}
}
Ok(exclusions)
}
// `iloc`, `stco` and `co64` elements contain absolute file offsets so they need to be adjusted based on whether content was added or removed.
// todo: when fragment support is added adjust these (/moof/iloc, /moof/mfro, /moof/traf/saio, /sidx)
fn adjust_known_offsets<W: Write + CAIRead + ?Sized>(
output: &mut W,
bmff_tree: &Arena<BoxInfo>,
bmff_path_map: &HashMap<String, Vec<Token>>,
adjust: i32,
) -> Result<()> {
let start_pos = output.stream_position()?; // save starting point
// handle 32 bit offsets
if let Some(stco_list) = bmff_path_map.get("/moov/trak/mdia/minf/stbl/stco") {
for stco_token in stco_list {
let stco_box_info = &bmff_tree[*stco_token].data;
if stco_box_info.box_type != BoxType::StcoBox {
return Err(Error::InvalidAsset("Bad BMFF".to_string()));
}
// read stco box and patch
output.seek(SeekFrom::Start(stco_box_info.offset))?;
// read header
let header = BoxHeaderLite::read(output)
.map_err(|_err| Error::InvalidAsset("Bad BMFF".to_string()))?;
if header.name != BoxType::StcoBox {
return Err(Error::InvalidAsset("Bad BMFF".to_string()));
}
// read extended header
let (_version, _flags) = read_box_header_ext(output)?; // box extensions
// get count of offsets
let entry_count = output.read_u32::<BigEndian>()?;
// read and patch offsets
let entry_start_pos = output.stream_position()?;
let mut entries: Vec<u32> = Vec::new();
for _e in 0..entry_count {
let offset = output.read_u32::<BigEndian>()?;
let new_offset = if adjust < 0 {
offset
- u32::try_from(adjust.abs()).map_err(|_| {
Error::InvalidAsset("Bad BMFF offset adjustment".to_string())
})?
} else {
offset
+ u32::try_from(adjust).map_err(|_| {
Error::InvalidAsset("Bad BMFF offset adjustment".to_string())
})?
};
entries.push(new_offset);
}
// write updated offsets
output.seek(SeekFrom::Start(entry_start_pos))?;
for e in entries {
output.write_u32::<BigEndian>(e)?;
}
}
}
// handle 64 offsets
if let Some(co64_list) = bmff_path_map.get("/moov/trak/mdia/minf/stbl/co64") {
for co64_token in co64_list {
let co64_box_info = &bmff_tree[*co64_token].data;
if co64_box_info.box_type != BoxType::Co64Box {
return Err(Error::InvalidAsset("Bad BMFF".to_string()));
}
// read co64 box and patch
output.seek(SeekFrom::Start(co64_box_info.offset))?;
// read header
let header = BoxHeaderLite::read(output)
.map_err(|_err| Error::InvalidAsset("Bad BMFF".to_string()))?;
if header.name != BoxType::Co64Box {
return Err(Error::InvalidAsset("Bad BMFF".to_string()));
}
// read extended header
let (_version, _flags) = read_box_header_ext(output)?; // box extensions
// get count of offsets
let entry_count = output.read_u32::<BigEndian>()?;
// read and patch offsets
let entry_start_pos = output.stream_position()?;
let mut entries: Vec<u64> = Vec::new();
for _e in 0..entry_count {
let offset = output.read_u64::<BigEndian>()?;
let new_offset = if adjust < 0 {
offset
- u64::try_from(adjust.abs()).map_err(|_| {
Error::InvalidAsset("Bad BMFF offset adjustment".to_string())
})?
} else {
offset
+ u64::try_from(adjust).map_err(|_| {
Error::InvalidAsset("Bad BMFF offset adjustment".to_string())
})?
};
entries.push(new_offset);
}
// write updated offsets
output.seek(SeekFrom::Start(entry_start_pos))?;
for e in entries {
output.write_u64::<BigEndian>(e)?;
}
}
}
// handle meta iloc
if let Some(iloc_list) = bmff_path_map.get("/meta/iloc") {
for iloc_token in iloc_list {
let iloc_box_info = &bmff_tree[*iloc_token].data;
if iloc_box_info.box_type != BoxType::IlocBox {
return Err(Error::InvalidAsset("Bad BMFF".to_string()));
}
// read iloc box and patch
output.seek(SeekFrom::Start(iloc_box_info.offset))?;
// read header
let header = BoxHeaderLite::read(output)
.map_err(|_err| Error::InvalidAsset("Bad BMFF".to_string()))?;
if header.name != BoxType::IlocBox {
return Err(Error::InvalidAsset("Bad BMFF".to_string()));
}
// read extended header
let (version, _flags) = read_box_header_ext(output)?; // box extensions
// read next 16 bits (in file byte order)
let mut iloc_header = [0u8, 2];
output.read_exact(&mut iloc_header)?;
// get offset size (high nibble)
let offset_size: u8 = (iloc_header[0] & 0xf0) >> 4;
// get length size (low nibble)
let length_size: u8 = iloc_header[0] & 0x0f;
// get box offset size (high nibble)
let base_offset_size: u8 = (iloc_header[1] & 0xf0) >> 4;
// get index size (low nibble)
let index_size: u8 = iloc_header[1] & 0x0f;
// get item count
let item_count = match version {
_v if version < 2 => output.read_u16::<BigEndian>()? as u32,
_v if version == 2 => output.read_u32::<BigEndian>()?,
_ => {
return Err(Error::InvalidAsset(
"Bad BMFF unknown iloc format".to_string(),
))
}
};
// walk the iloc items and patch
for _i in 0..item_count {
// read item id
let _item_id = match version {
_v if version < 2 => output.read_u16::<BigEndian>()? as u32,
2 => output.read_u32::<BigEndian>()?,
_ => {
return Err(Error::InvalidAsset(
"Bad BMFF: unknown iloc item".to_string(),
))
}
};
// read construction method
let construction_method = if version == 1 || version == 2 {
let mut cm_bytes = [0u8, 2];
output.read_exact(&mut cm_bytes)?;
// lower nibble of 2nd byte
cm_bytes[1] & 0x0f
} else {
0
};
// read data reference index
let _data_reference_index = output.read_u16::<BigEndian>()?;
let base_offset_file_pos = output.stream_position()?;
let base_offset = match base_offset_size {
0 => 0_u64,
4 => output.read_u32::<BigEndian>()? as u64,
8 => output.read_u64::<BigEndian>()?,
_ => {
return Err(Error::InvalidAsset(
"Bad BMFF: unknown iloc offset size".to_string(),
))
}
};
// patch the offsets if needed
if construction_method == 0 {
// file offset construction method
if base_offset_size == 4 {
let new_offset = if adjust < 0 {
u32::try_from(base_offset).map_err(|_| {
Error::InvalidAsset("Bad BMFF offset adjustment".to_string())
})? - u32::try_from(adjust.abs()).map_err(|_| {
Error::InvalidAsset("Bad BMFF offset adjustment".to_string())
})?
} else {
u32::try_from(base_offset).map_err(|_| {
Error::InvalidAsset("Bad BMFF offset adjustment".to_string())
})? + u32::try_from(adjust).map_err(|_| {
Error::InvalidAsset("Bad BMFF offset adjustment".to_string())
})?
};
output.seek(SeekFrom::Start(base_offset_file_pos))?;
output.write_u32::<BigEndian>(new_offset)?;
}
if base_offset_size == 8 {
let new_offset = if adjust < 0 {
base_offset
- u64::try_from(adjust.abs()).map_err(|_| {
Error::InvalidAsset("Bad BMFF offset adjustment".to_string())
})?
} else {
base_offset
+ u64::try_from(adjust).map_err(|_| {
Error::InvalidAsset("Bad BMFF offset adjustment".to_string())
})?
};
output.seek(SeekFrom::Start(base_offset_file_pos))?;
output.write_u64::<BigEndian>(new_offset)?;
}
}
// read extent count
let extent_count = output.read_u16::<BigEndian>()?;
// consume the extents
for _e in 0..extent_count {
let _extent_index = if version == 1 || (version == 2 && index_size > 0) {
match base_offset_size {
4 => Some(output.read_u32::<BigEndian>()? as u64),
8 => Some(output.read_u64::<BigEndian>()?),
_ => None,
}
} else {
None
};
let extent_offset_file_pos = output.stream_position()?;
let extent_offset = match offset_size {
0 => 0_u64,
4 => output.read_u32::<BigEndian>()? as u64,
8 => output.read_u64::<BigEndian>()?,
_ => {
return Err(Error::InvalidAsset(
"Bad BMFF: unknown iloc extent_offset size".to_string(),
))
}
};
// no base offset so just adjust the raw extent_offset value
if construction_method == 0 && base_offset == 0 && extent_offset != 0 {
output.seek(SeekFrom::Start(extent_offset_file_pos))?;
match offset_size {
4 => {
let new_offset = if adjust < 0 {
extent_offset as u32
- u32::try_from(adjust.abs()).map_err(|_| {
Error::InvalidAsset(
"Bad BMFF offset adjustment".to_string(),
)
})?
} else {
extent_offset as u32
+ u32::try_from(adjust).map_err(|_| {
Error::InvalidAsset(
"Bad BMFF offset adjustment".to_string(),
)
})?
};
output.write_u32::<BigEndian>(new_offset)?;
}
8 => {
let new_offset = if adjust < 0 {
extent_offset
- u64::try_from(adjust.abs()).map_err(|_| {
Error::InvalidAsset(
"Bad BMFF offset adjustment".to_string(),
)
})?
} else {
extent_offset
+ u64::try_from(adjust).map_err(|_| {
Error::InvalidAsset(
"Bad BMFF offset adjustment".to_string(),
)
})?
};
output.write_u64::<BigEndian>(new_offset)?;
}
_ => {
return Err(Error::InvalidAsset(
"Bad BMFF: unknown extent_offset format".to_string(),
))
}
}
}
let _extent_length = match length_size {
0 => 0_u64,
4 => output.read_u32::<BigEndian>()? as u64,
8 => output.read_u64::<BigEndian>()?,
_ => {
return Err(Error::InvalidAsset(
"Bad BMFF: unknown iloc offset size".to_string(),
))
}
};
}
}
}
}
// restore seek point
output.seek(SeekFrom::Start(start_pos))?;
output.flush()?;
Ok(())
}
pub(crate) fn build_bmff_tree<R: Read + Seek + ?Sized>(
reader: &mut R,
end: u64,
bmff_tree: &mut Arena<BoxInfo>,
current_node: &Token,
bmff_path_map: &mut HashMap<String, Vec<Token>>,
) -> Result<()> {
let start = reader.stream_position()?;
let mut current = start;
while current < end {
// Get box header.
let header = BoxHeaderLite::read(reader)
.map_err(|_err| Error::InvalidAsset("Bad BMFF".to_string()))?;
// Break if size zero BoxHeader
let s = header.size;
if s == 0 {
break;
}
// Match and parse the supported atom boxes.
match header.name {
BoxType::UuidBox => {
let start = box_start(reader, header.large_size)?;
let mut extended_type = [0u8; 16]; // 16 bytes of UUID
reader.read_exact(&mut extended_type)?;
let (version, flags) = read_box_header_ext(reader)?;
let b = BoxInfo {
path: header.fourcc.clone(),
offset: start,
size: s,
box_type: BoxType::UuidBox,
parent: Some(*current_node),
user_type: Some(extended_type.to_vec()),
version: Some(version),
flags: Some(flags),
};
let new_token = current_node.append(bmff_tree, b);
let path = path_from_token(bmff_tree, &new_token)?;
add_token_to_cache(bmff_path_map, path, new_token);
// position seek pointer
skip_bytes_to(reader, start + s)?;
}
// container box types
BoxType::MoovBox
| BoxType::TrakBox
| BoxType::MdiaBox
| BoxType::MinfBox
| BoxType::StblBox
| BoxType::MoofBox
| BoxType::TrafBox
| BoxType::EdtsBox
| BoxType::UdtaBox
| BoxType::DinfBox
| BoxType::TrefBox
| BoxType::TregBox
| BoxType::MvexBox
| BoxType::MfraBox
| BoxType::MetaBox
| BoxType::SchiBox => {
let start = box_start(reader, header.large_size)?;