-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathlib.rs
More file actions
6232 lines (5622 loc) · 210 KB
/
lib.rs
File metadata and controls
6232 lines (5622 loc) · 210 KB
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
//! Module for parsing ISO Base Media Format aka video/mp4 streams.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// `clippy::upper_case_acronyms` is a nightly-only lint as of 2021-03-15, so we
// allow `clippy::unknown_clippy_lints` to ignore it on stable - but
// `clippy::unknown_clippy_lints` has been renamed in nightly, so we need to
// allow `renamed_and_removed_lints` to ignore a warning for that.
#![allow(renamed_and_removed_lints)]
#![allow(clippy::unknown_clippy_lints)]
#![allow(clippy::upper_case_acronyms)]
#[macro_use]
extern crate log;
extern crate bitreader;
extern crate byteorder;
extern crate fallible_collections;
extern crate num_traits;
use bitreader::{BitReader, ReadInto};
use byteorder::{ReadBytesExt, WriteBytesExt};
use fallible_collections::TryRead;
use fallible_collections::TryReserveError;
use num_traits::Num;
use std::convert::{TryFrom, TryInto as _};
use std::fmt;
use std::io::Cursor;
use std::io::{Read, Take};
#[macro_use]
mod macros;
mod boxes;
use crate::boxes::{BoxType, FourCC};
// Unit tests.
#[cfg(test)]
mod tests;
#[cfg(feature = "unstable-api")]
pub mod unstable;
/// The HEIF image and image collection brand
/// The 'mif1' brand indicates structural requirements on files
/// See HEIF (ISO 23008-12:2017) § 10.2.1
pub const MIF1_BRAND: FourCC = FourCC { value: *b"mif1" };
/// The HEIF image sequence brand
/// The 'msf1' brand indicates structural requirements on files
/// See HEIF (ISO 23008-12:2017) § 10.3.1
pub const MSF1_BRAND: FourCC = FourCC { value: *b"msf1" };
/// The brand to identify AV1 image items
/// The 'avif' brand indicates structural requirements on files
/// See <https://aomediacodec.github.io/av1-avif/#image-and-image-collection-brand>
pub const AVIF_BRAND: FourCC = FourCC { value: *b"avif" };
/// The brand to identify AVIF image sequences
/// The 'avis' brand indicates structural requirements on files
/// See <https://aomediacodec.github.io/av1-avif/#image-and-image-collection-brand>
pub const AVIS_BRAND: FourCC = FourCC { value: *b"avis" };
/// A trait to indicate a type can be infallibly converted to `u64`.
/// This should only be implemented for infallible conversions, so only unsigned types are valid.
trait ToU64 {
fn to_u64(self) -> u64;
}
/// Statically verify that the platform `usize` can fit within a `u64`.
/// If the size won't fit on the given platform, this will fail at compile time, but if a type
/// which can fail TryInto<usize> is used, it may panic.
impl ToU64 for usize {
fn to_u64(self) -> u64 {
static_assertions::const_assert!(
std::mem::size_of::<usize>() <= std::mem::size_of::<u64>()
);
self.try_into().expect("usize -> u64 conversion failed")
}
}
/// A trait to indicate a type can be infallibly converted to `usize`.
/// This should only be implemented for infallible conversions, so only unsigned types are valid.
pub trait ToUsize {
fn to_usize(self) -> usize;
}
/// Statically verify that the given type can fit within a `usize`.
/// If the size won't fit on the given platform, this will fail at compile time, but if a type
/// which can fail TryInto<usize> is used, it may panic.
macro_rules! impl_to_usize_from {
( $from_type:ty ) => {
impl ToUsize for $from_type {
fn to_usize(self) -> usize {
static_assertions::const_assert!(
std::mem::size_of::<$from_type>() <= std::mem::size_of::<usize>()
);
self.try_into().expect(concat!(
stringify!($from_type),
" -> usize conversion failed"
))
}
}
};
}
impl_to_usize_from!(u8);
impl_to_usize_from!(u16);
impl_to_usize_from!(u32);
/// Indicate the current offset (i.e., bytes already read) in a reader
trait Offset {
fn offset(&self) -> u64;
}
/// Wraps a reader to track the current offset
struct OffsetReader<'a, T: 'a> {
reader: &'a mut T,
offset: u64,
}
impl<'a, T> OffsetReader<'a, T> {
fn new(reader: &'a mut T) -> Self {
Self { reader, offset: 0 }
}
}
impl<'a, T> Offset for OffsetReader<'a, T> {
fn offset(&self) -> u64 {
self.offset
}
}
impl<'a, T: Read> Read for OffsetReader<'a, T> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let bytes_read = self.reader.read(buf)?;
trace!("Read {} bytes at offset {}", bytes_read, self.offset);
self.offset = self
.offset
.checked_add(bytes_read.to_u64())
.expect("total bytes read too large for offset type");
Ok(bytes_read)
}
}
pub type TryVec<T> = fallible_collections::TryVec<T>;
pub type TryString = fallible_collections::TryVec<u8>;
pub type TryHashMap<K, V> = fallible_collections::TryHashMap<K, V>;
pub type TryBox<T> = fallible_collections::TryBox<T>;
// To ensure we don't use stdlib allocating types by accident
#[allow(dead_code)]
struct Vec;
#[allow(dead_code)]
struct Box;
#[allow(dead_code)]
struct HashMap;
#[allow(dead_code)]
struct String;
/// The return value to the C API
/// Any detail that needs to be communicated to the caller must be encoded here
/// since the [`Error`] type's associated data is part of the FFI.
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Status {
Ok = 0,
BadArg = 1,
Invalid = 2,
Unsupported = 3,
Eof = 4,
Io = 5,
Oom = 6,
A1lxEssential,
A1opNoEssential,
AlacBadMagicCookieSize,
AlacFlagsNonzero,
Av1cMissing,
BitReaderError,
BoxBadSize,
BoxBadWideSize,
CheckParserStateErr,
ColrBadQuantity,
ColrBadSize,
ColrBadType,
ColrReservedNonzero,
ConstructionMethod,
CttsBadSize,
CttsBadVersion,
DflaBadMetadataBlockSize,
DflaFlagsNonzero,
DflaMissingMetadata,
DflaStreamInfoBadSize,
DflaStreamInfoNotFirst,
DopsChannelMappingWriteErr,
DopsOpusHeadWriteErr,
ElstBadVersion,
EsdsBadAudioSampleEntry,
EsdsBadDescriptor,
EsdsDecSpecificIntoTagQuantity,
FtypBadSize,
FtypNotFirst,
HdlrNameMultipleNul,
HdlrNameNoNul,
HdlrNameNotUtf8,
HdlrNotFirst,
HdlrPredefinedNonzero,
HdlrReservedNonzero,
HdlrTypeNotPict,
HdlrUnsupportedVersion,
HdrlBadQuantity,
IdatBadQuantity,
IdatMissing,
IinfBadChild,
IinfBadQuantity,
IlocBadConstructionMethod,
IlocBadExtent,
IlocBadExtentCount,
IlocBadFieldSize,
IlocBadQuantity,
IlocBadSize,
IlocDuplicateItemId,
IlocMissing,
IlocNotFound,
IlocOffsetOverflow,
ImageItemType,
InfeFlagsNonzero,
InvalidUtf8,
IpcoIndexOverflow,
IpmaBadIndex,
IpmaBadItemOrder,
IpmaBadQuantity,
IpmaBadVersion,
IpmaDuplicateItemId,
IpmaFlagsNonzero,
IpmaIndexZeroNoEssential,
IpmaTooBig,
IpmaTooSmall,
IprpBadChild,
IprpBadQuantity,
IprpConflict,
IrefBadQuantity,
IrefRecursion,
IspeMissing,
ItemTypeMissing,
LselBadLayerId,
LselNoEssential,
MdhdBadTimescale,
MdhdBadVersion,
MehdBadVersion,
MetaBadQuantity,
MissingAvifOrAvisBrand,
MissingMif1Brand,
MoovBadQuantity,
MoovMissing,
MultipleAlpha,
MvhdBadTimescale,
MvhdBadVersion,
NoImage,
PitmBadQuantity,
PitmMissing,
PixiBadChannelCount,
PixiMissing,
PsshSizeOverflow,
ReadBufErr,
SchiQuantity,
StsdBadAudioSampleEntry,
StsdBadVideoSampleEntry,
TkhdBadVersion,
TxformBeforeIspe,
TxformNoEssential,
TxformOrder,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Feature {
A1lx,
A1op,
Auxc,
Av1c,
Avis,
Clap,
Colr,
Grid,
Imir,
Ipro,
Irot,
Ispe,
Lsel,
Pasp,
Pixi,
}
impl Feature {
fn supported(self) -> bool {
match self {
Self::Auxc
| Self::Av1c
| Self::Colr
| Self::Imir
| Self::Irot
| Self::Ispe
| Self::Pasp
| Self::Pixi
| Self::Lsel => true,
Self::A1lx | Self::A1op | Self::Clap | Self::Grid | Self::Ipro | Self::Avis => false,
}
}
}
impl TryFrom<&ItemProperty> for Feature {
type Error = Error;
fn try_from(item_property: &ItemProperty) -> Result<Self, Self::Error> {
Ok(match item_property {
ItemProperty::AuxiliaryType(_) => Self::Auxc,
ItemProperty::AV1Config(_) => Self::Av1c,
ItemProperty::Channels(_) => Self::Pixi,
ItemProperty::CleanAperture => Self::Clap,
ItemProperty::Colour(_) => Self::Colr,
ItemProperty::ImageSpatialExtents(_) => Self::Ispe,
ItemProperty::LayeredImageIndexing => Self::A1lx,
ItemProperty::LayerSelection(_) => Self::Lsel,
ItemProperty::Mirroring(_) => Self::Imir,
ItemProperty::OperatingPointSelector => Self::A1op,
ItemProperty::PixelAspectRatio(_) => Self::Pasp,
ItemProperty::Rotation(_) => Self::Irot,
item_property => {
error!("No known Feature variant for {:?}", item_property);
return Err(Error::Unsupported("missing Feature fox ItemProperty"));
}
})
}
}
/// A collection to indicate unsupported features that were encountered during
/// parsing. Since the default behavior for many such features is to ignore
/// them, this often not fatal and there may be several to report.
#[derive(Debug, Default)]
pub struct UnsupportedFeatures(u32);
impl UnsupportedFeatures {
pub fn new() -> Self {
Self(0x0)
}
pub fn into_bitfield(&self) -> u32 {
self.0
}
fn feature_to_bitfield(feature: Feature) -> u32 {
let index = feature as usize;
assert!(
u8::BITS.to_usize() * std::mem::size_of::<Self>() > index,
"You're gonna need a bigger bitfield"
);
let bitfield = 1u32 << index;
assert_eq!(bitfield.count_ones(), 1);
bitfield
}
pub fn insert(&mut self, feature: Feature) {
warn!("Unsupported feature: {:?}", feature);
self.0 |= Self::feature_to_bitfield(feature);
}
pub fn contains(&self, feature: Feature) -> bool {
self.0 & Self::feature_to_bitfield(feature) != 0x0
}
pub fn is_empty(&self) -> bool {
self.0 == 0x0
}
}
impl<T> From<Status> for Result<T> {
/// A convenience method to enable shortcuts like
/// ```
/// # use mp4parse::{Result,Status};
/// # let _: Result<()> =
/// Status::MissingAvifOrAvisBrand.into();
/// ```
/// instead of
/// ```
/// # use mp4parse::{Error,Result,Status};
/// # let _: Result<()> =
/// Err(Error::from(Status::MissingAvifOrAvisBrand));
/// ```
/// Note that `Status::Ok` can't be supported this way and will panic.
fn from(parse_status: Status) -> Self {
match parse_status {
Status::Ok => panic!("Can't determine Ok(_) inner value from Status"),
err_status => Err(err_status.into()),
}
}
}
/// For convenience of creating an error for an unsupported feature which we
/// want to communicate the specific feature back to the C API caller
impl From<Status> for Error {
fn from(parse_status: Status) -> Self {
match parse_status {
Status::Ok
| Status::BadArg
| Status::Invalid
| Status::Unsupported
| Status::Eof
| Status::Io
| Status::Oom => {
panic!("Status -> Error is only for Status:InvalidData errors")
}
_ => Self::InvalidData(parse_status),
}
}
}
impl From<Status> for &str {
fn from(status: Status) -> Self {
match status {
Status::Ok
| Status::BadArg
| Status::Invalid
| Status::Unsupported
| Status::Eof
| Status::Io
| Status::Oom => {
panic!("Status -> Error is only for specific parsing errors")
}
Status::A1lxEssential => {
"AV1LayeredImageIndexingProperty (a1lx) shall not be marked as essential \
per https://aomediacodec.github.io/av1-avif/#layered-image-indexing-property-description"
}
Status::A1opNoEssential => {
"OperatingPointSelectorProperty (a1op) shall be marked as essential \
per https://aomediacodec.github.io/av1-avif/#operating-point-selector-property-description"
}
Status::AlacBadMagicCookieSize => {
"ALACSpecificBox magic cookie is the wrong size"
}
Status::AlacFlagsNonzero => {
"no-zero alac (ALAC) flags"
}
Status::Av1cMissing => {
"One AV1 Item Configuration Property (av1C) is mandatory for an \
image item of type 'av01' \
per AVIF specification § 2.2.1"
}
Status::BitReaderError => {
"Bitwise read failed"
}
Status::BoxBadSize => {
"malformed size"
}
Status::BoxBadWideSize => {
"malformed wide size"
}
Status::CheckParserStateErr => {
"unread box content or bad parser sync"
}
Status::ColrBadQuantity => {
"Each item shall have at most one property association with a
ColourInformationBox (colr) for a given value of colour_type \
per HEIF (ISO/IEC DIS 23008-12) § 6.5.5.1"
}
Status::ColrBadSize => {
"Unexpected size for colr box"
}
Status::ColrBadType => {
"Unsupported colour_type for ColourInformationBox"
}
Status::ColrReservedNonzero => {
"The 7 reserved bits at the end of the ColourInformationBox \
for colour_type == 'nclx' must be 0 \
per ISOBMFF (ISO 14496-12:2020) § 12.1.5.2"
}
Status::ConstructionMethod => {
"construction_method shall be 0 (file) or 1 (idat) per MIAF (ISO 23000-22:2019) § 7.2.1.7"
}
Status::CttsBadSize => {
"insufficient data in 'ctts' box"
}
Status::CttsBadVersion => {
"unsupported version in 'ctts' box"
}
Status::DflaBadMetadataBlockSize => {
"FLACMetadataBlock larger than parent box"
}
Status::DflaFlagsNonzero => {
"no-zero dfLa (FLAC) flags"
}
Status::DflaMissingMetadata => {
"FLACSpecificBox missing metadata"
}
Status::DflaStreamInfoBadSize => {
"FLACSpecificBox STREAMINFO block is the wrong size"
}
Status::DflaStreamInfoNotFirst => {
"FLACSpecificBox must have STREAMINFO metadata first"
}
Status::DopsChannelMappingWriteErr => {
"Couldn't write channel mapping table data."
}
Status::DopsOpusHeadWriteErr => {
"Couldn't write OpusHead tag."
}
Status::ElstBadVersion => {
"unhandled elst version"
}
Status::EsdsBadAudioSampleEntry => {
"malformed audio sample entry"
}
Status::EsdsBadDescriptor => {
"Invalid descriptor."
}
Status::EsdsDecSpecificIntoTagQuantity => {
"There can be only one DecSpecificInfoTag descriptor"
}
Status::FtypBadSize => {
"invalid ftyp size"
}
Status::FtypNotFirst => {
"The FileTypeBox shall be placed as early as possible in the file \
per ISOBMFF (ISO 14496-12:2020) § 4.3.1"
}
Status::HdlrNameMultipleNul => {
"The HandlerBox 'name' field shall have a NUL byte \
only in the final position \
per ISOBMFF (ISO 14496-12:2020) § 8.4.3.2"
}
Status::HdlrNameNoNul => {
"The HandlerBox 'name' field shall be null-terminated \
per ISOBMFF (ISO 14496-12:2020) § 8.4.3.2"
}
Status::HdlrNameNotUtf8 => {
"The HandlerBox 'name' field shall be valid utf8 \
per ISOBMFF (ISO 14496-12:2020) § 8.4.3.2"
}
Status::HdlrNotFirst => {
"The HandlerBox shall be the first contained box within the MetaBox \
per MIAF (ISO 23000-22:2019) § 7.2.1.5"
}
Status::HdlrPredefinedNonzero => {
"The HandlerBox 'pre_defined' field shall be 0 \
per ISOBMFF (ISO 14496-12:2020) § 8.4.3.2"
}
Status::HdlrReservedNonzero => {
"The HandlerBox 'reserved' fields shall be 0 \
per ISOBMFF (ISO 14496-12:2020) § 8.4.3.2"
}
Status::HdlrTypeNotPict => {
"The HandlerBox handler_type must be 'pict' \
per MIAF (ISO 23000-22:2019) § 7.2.1.5"
}
Status::HdlrUnsupportedVersion => {
"The HandlerBox version shall be 0 (zero) \
per ISOBMFF (ISO 14496-12:2020) § 8.4.3.2"
}
Status::HdrlBadQuantity => {
"There shall be exactly one hdlr box \
per ISOBMFF (ISO 14496-12:2020) § 8.4.3.1"
}
Status::IdatBadQuantity => {
"There shall be zero or one idat boxes \
per ISOBMFF (ISO 14496-12:2020) § 8.11.11"
}
Status::IdatMissing => {
"ItemLocationBox (iloc) construction_method indicates 1 (idat), \
but no idat box is present."
}
Status::IinfBadChild => {
"iinf box shall contain only infe boxes \
per ISOBMFF (ISO 14496-12:2020) § 8.11.6.2"
}
Status::IinfBadQuantity => {
"There shall be zero or one iinf boxes \
per ISOBMFF (ISO 14496-12:2020) § 8.11.6.1"
}
Status::IlocBadConstructionMethod => {
"construction_method is taken from the set 0, 1 or 2 \
per ISOBMFF (ISO 14496-12:2020) § 8.11.3.3"
}
Status::IlocBadExtent => {
"extent_count != 1 requires explicit offset and length \
per ISOBMFF (ISO 14496-12:2020) § 8.11.3.3"
}
Status::IlocBadExtentCount => {
"extent_count must have a value 1 or greater \
per ISOBMFF (ISO 14496-12:2020) § 8.11.3.3"
}
Status::IlocBadFieldSize => {
"value must be in the set {0, 4, 8}"
}
Status::IlocBadQuantity => {
"There shall be zero or one iloc boxes \
per ISOBMFF (ISO 14496-12:2020) § 8.11.3.1"
}
Status::IlocBadSize => {
"invalid iloc size"
}
Status::IlocDuplicateItemId => {
"duplicate item_ID in iloc"
}
Status::IlocMissing => {
"iloc missing"
}
Status::IlocNotFound => {
"ItemLocationBox (iloc) contains an extent not present in any mdat or idat box"
}
Status::IlocOffsetOverflow => {
"offset calculation overflow"
}
Status::ImageItemType => {
"Image item type is neither 'av01' nor 'grid'"
}
Status::InfeFlagsNonzero => {
"'infe' flags field shall be 0 \
per ISOBMFF (ISO 14496-12:2020) § 8.11.6.2"
}
Status::InvalidUtf8 => {
"invalid utf8"
}
Status::IpcoIndexOverflow => {
"ipco index overflow"
}
Status::IpmaBadIndex => {
"Invalid property index in ipma"
}
Status::IpmaBadItemOrder => {
"Each ItemPropertyAssociation box shall be ordered by increasing item_ID"
}
Status::IpmaBadQuantity => {
"There shall be at most one ItemPropertyAssociationbox with a given pair of \
values of version and flags \
per ISOBMFF (ISO 14496-12:2020) § 8.11.14.1"
}
Status::IpmaBadVersion => {
"The ipma version 0 should be used unless 32-bit item_ID values are needed \
per ISOBMFF (ISO 14496-12:2020) § 8.11.14.1"
}
Status::IpmaDuplicateItemId => {
"There shall be at most one occurrence of a given item_ID, \
in the set of ItemPropertyAssociationBox boxes \
per ISOBMFF (ISO 14496-12:2020) § 8.11.14.1"
}
Status::IpmaFlagsNonzero => {
"Unless there are more than 127 properties in the ItemPropertyContainerBox, \
flags should be equal to 0 \
per ISOBMFF (ISO 14496-12:2020) § 8.11.14.1"
}
Status::IpmaIndexZeroNoEssential => {
"the essential indicator shall be 0 for property index 0 \
per ISOBMFF (ISO 14496-12:2020) § 8.11.14.3"
}
Status::IpmaTooBig => {
"ipma box exceeds maximum size for entry_count"
}
Status::IpmaTooSmall => {
"ipma box below minimum size for entry_count"
}
Status::IprpBadChild => {
"unexpected iprp child"
}
Status::IprpBadQuantity => {
"There shall be zero or one iprp boxes \
per ISOBMFF (ISO 14496-12:2020) § 8.11.14.1"
}
Status::IprpConflict => {
"conflicting item property values"
}
Status::IrefBadQuantity => {
"There shall be zero or one iref boxes \
per ISOBMFF (ISO 14496-12:2020) § 8.11.12.1"
}
Status::IrefRecursion => {
"from_item_id and to_item_id must be different"
}
Status::IspeMissing => {
"Missing 'ispe' property for image item, required \
per HEIF (ISO/IEC 23008-12:2017) § 6.5.3.1"
}
Status::ItemTypeMissing => {
"No ItemInfoEntry for item_ID"
}
Status::LselNoEssential => {
"LayerSelectorProperty (lsel) shall be marked as essential \
per HEIF (ISO/IEC 23008-12:2017) § 6.5.11.1"
}
Status::LselBadLayerId => {
"LayerSelectorProperty (lsel) shall be between 0 and 3, \
or the special value 0xFFFF \
per https://aomediacodec.github.io/av1-avif/#layer-selector-property"
}
Status::MdhdBadTimescale => {
"zero timescale in mdhd"
}
Status::MdhdBadVersion => {
"unhandled mdhd version"
}
Status::MehdBadVersion => {
"unhandled mehd version"
}
Status::MetaBadQuantity => {
"There should be zero or one meta boxes \
per ISOBMFF (ISO 14496-12:2020) § 8.11.1.1"
}
Status::MissingAvifOrAvisBrand => {
"The file shall list 'avif' or 'avis' in the compatible_brands field
of the FileTypeBox \
per https://aomediacodec.github.io/av1-avif/#file-constraints"
}
Status::MissingMif1Brand => {
"The FileTypeBox should contain 'mif1' in the compatible_brands list \
per MIAF (ISO 23000-22:2019/Amd. 2:2021) § 7.2.1.2"
}
Status::MoovBadQuantity => {
"Multiple moov boxes found; \
files with avis or msf1 brands shall contain exactly one moov box \
per ISOBMFF (ISO 14496-12:2020) § 8.2.1.1"
}
Status::MoovMissing => {
"No moov box found; \
files with avis or msf1 brands shall contain exactly one moov box \
per ISOBMFF (ISO 14496-12:2020) § 8.2.1.1"
}
Status::MultipleAlpha => {
"multiple alpha planes"
}
Status::MvhdBadTimescale => {
"zero timescale in mvhd"
}
Status::MvhdBadVersion => {
"unhandled mvhd version"
}
Status::NoImage => "No primary image or image sequence found",
Status::PitmBadQuantity => {
"There shall be zero or one pitm boxes \
per ISOBMFF (ISO 14496-12:2020) § 8.11.4.1"
}
Status::PitmMissing => {
"Missing required PrimaryItemBox (pitm), required \
per HEIF (ISO/IEC 23008-12:2017) § 10.2.1"
}
Status::PixiBadChannelCount => {
"invalid num_channels"
}
Status::PixiMissing => {
"The pixel information property shall be associated with every image \
that is displayable (not hidden) \
per MIAF (ISO/IEC 23000-22:2019) specification § 7.3.6.6"
}
Status::PsshSizeOverflow => {
"overflow in read_pssh"
}
Status::ReadBufErr => {
"failed buffer read"
}
Status::SchiQuantity => {
"tenc box should be only one at most in sinf box"
}
Status::StsdBadAudioSampleEntry => {
"malformed audio sample entry"
}
Status::StsdBadVideoSampleEntry => {
"malformed video sample entry"
}
Status::TkhdBadVersion => {
"unhandled tkhd version"
}
Status::TxformBeforeIspe => {
"Every image item shall be associated with one property of \
type ImageSpatialExtentsProperty (ispe), prior to the \
association of all transformative properties. \
per HEIF (ISO/IEC 23008-12:2017) § 6.5.3.1"
}
Status::TxformNoEssential => {
"All transformative properties associated with coded and \
derived images required or conditionally required by this \
document shall be marked as essential \
per MIAF (ISO 23000-22:2019) § 7.3.9"
}
Status::TxformOrder => {
"These properties, if used, shall be indicated to be applied \
in the following order: clean aperture first, then rotation, \
then mirror. \
per MIAF (ISO/IEC 23000-22:2019) § 7.3.6.7"
}
}
}
}
impl From<Error> for Status {
fn from(error: Error) -> Self {
match error {
Error::Unsupported(_) => Self::Unsupported,
Error::InvalidData(parse_status) => parse_status,
Error::UnexpectedEOF => Self::Eof,
Error::Io(_) => {
// Getting std::io::ErrorKind::UnexpectedEof is normal
// but our From trait implementation should have converted
// those to our Error::UnexpectedEOF variant.
Self::Io
}
Error::MoovMissing => Self::MoovMissing,
Error::OutOfMemory => Self::Oom,
}
}
}
impl From<Result<(), Status>> for Status {
fn from(result: Result<(), Status>) -> Self {
match result {
Ok(()) => Status::Ok,
Err(Status::Ok) => unreachable!(),
Err(e) => e,
}
}
}
impl<T> From<Result<T>> for Status {
fn from(result: Result<T>) -> Self {
match result {
Ok(_) => Status::Ok,
Err(e) => Status::from(e),
}
}
}
impl From<fallible_collections::TryReserveError> for Status {
fn from(_: fallible_collections::TryReserveError) -> Self {
Status::Oom
}
}
impl From<std::io::Error> for Status {
fn from(_: std::io::Error) -> Self {
Status::Io
}
}
/// Describes parser failures.
///
/// This enum wraps the standard `io::Error` type, unified with
/// our own parser error states and those of crates we use.
#[derive(Debug)]
pub enum Error {
/// Parse error caused by corrupt or malformed data.
/// See the helper [`From<Status> for Error`](enum.Error.html#impl-From<Status>)
InvalidData(Status),
/// Parse error caused by limited parser support rather than invalid data.
Unsupported(&'static str),
/// Reflect `std::io::ErrorKind::UnexpectedEof` for short data.
UnexpectedEOF,
/// Propagate underlying errors from `std::io`.
Io(std::io::Error),
/// read_mp4 terminated without detecting a moov box.
MoovMissing,
/// Out of memory
OutOfMemory,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl std::error::Error for Error {}
impl From<bitreader::BitReaderError> for Error {
fn from(_: bitreader::BitReaderError) -> Error {
Status::BitReaderError.into()
}
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Error {
match err.kind() {
std::io::ErrorKind::UnexpectedEof => Error::UnexpectedEOF,
_ => Error::Io(err),
}
}
}
impl From<std::string::FromUtf8Error> for Error {
fn from(_: std::string::FromUtf8Error) -> Error {
Status::InvalidUtf8.into()
}
}
impl From<std::str::Utf8Error> for Error {
fn from(_: std::str::Utf8Error) -> Error {
Status::InvalidUtf8.into()
}
}
impl From<std::num::TryFromIntError> for Error {
fn from(_: std::num::TryFromIntError) -> Error {
Error::Unsupported("integer conversion failed")
}
}
impl From<Error> for std::io::Error {
fn from(err: Error) -> Self {
let kind = match err {
Error::UnexpectedEOF => std::io::ErrorKind::UnexpectedEof,
Error::Io(io_err) => return io_err,
_ => std::io::ErrorKind::Other,
};
Self::new(kind, err)
}
}
impl From<TryReserveError> for Error {
fn from(_: TryReserveError) -> Error {
Error::OutOfMemory
}
}
/// Result shorthand using our Error enum.
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Basic ISO box structure.
///
/// mp4 files are a sequence of possibly-nested 'box' structures. Each box
/// begins with a header describing the length of the box's data and a
/// four-byte box type which identifies the type of the box. Together these
/// are enough to interpret the contents of that section of the file.
///
/// See ISOBMFF (ISO 14496-12:2020) § 4.2
#[derive(Debug, Clone, Copy)]
struct BoxHeader {
/// Box type.
name: BoxType,
/// Size of the box in bytes.
size: u64,
/// Offset to the start of the contained data (or header size).
offset: u64,
/// Uuid for extended type.
#[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
uuid: Option<[u8; 16]>,
}
impl BoxHeader {
const MIN_SIZE: u64 = 8; // 4-byte size + 4-byte type
const MIN_LARGE_SIZE: u64 = 16; // 4-byte size + 4-byte type + 16-byte size
}
/// File type box 'ftyp'.
#[derive(Debug)]
struct FileTypeBox {
#[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
major_brand: FourCC,
#[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
minor_version: u32,
compatible_brands: TryVec<FourCC>,
}
impl FileTypeBox {
fn contains(&self, brand: &FourCC) -> bool {
self.compatible_brands.contains(brand) || self.major_brand == *brand
}
}
/// Movie header box 'mvhd'.
#[derive(Debug)]
struct MovieHeaderBox {
pub timescale: u32,
#[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
duration: u64,
}
#[derive(Debug, Clone, Copy)]
pub struct Matrix {
pub a: i32, // 16.16 fix point
pub b: i32, // 16.16 fix point
pub u: i32, // 2.30 fix point
pub c: i32, // 16.16 fix point
pub d: i32, // 16.16 fix point
pub v: i32, // 2.30 fix point
pub x: i32, // 16.16 fix point
pub y: i32, // 16.16 fix point
pub w: i32, // 2.30 fix point
}
/// Track header box 'tkhd'
#[derive(Debug, Clone)]
pub struct TrackHeaderBox {
track_id: u32,
pub disabled: bool,
pub duration: u64,
pub width: u32,
pub height: u32,
pub matrix: Matrix,
}
/// Edit list box 'elst'