Debian Codegraph @

third_party/rust/mp4parse/src/lib.rs

raw
1 //! Module for parsing ISO Base Media Format aka video/mp4 streams.
2
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
7 // `clippy::upper_case_acronyms` is a nightly-only lint as of 2021-03-15, so we
8 // allow `clippy::unknown_clippy_lints` to ignore it on stable - but
9 // `clippy::unknown_clippy_lints` has been renamed in nightly, so we need to
10 // allow `renamed_and_removed_lints` to ignore a warning for that.
11 #![allow(renamed_and_removed_lints)]
12 #![allow(clippy::unknown_clippy_lints)]
13 #![allow(clippy::upper_case_acronyms)]
14
15 #[macro_use]
16 extern crate log;
17
18 extern crate bitreader;
19 extern crate byteorder;
20 extern crate fallible_collections;
21 extern crate num_traits;
22 use bitreader::{BitReader, ReadInto};
23 use byteorder::{ReadBytesExt, WriteBytesExt};
24
25 use fallible_collections::TryRead;
26 use fallible_collections::TryReserveError;
27
28 use num_traits::Num;
29 use std::convert::{TryFrom, TryInto as _};
30 use std::fmt;
31 use std::io::Cursor;
32 use std::io::{Read, Take};
33
34 #[macro_use]
35 mod macros;
36
37 mod boxes;
38 use crate::boxes::{BoxType, FourCC};
39
40 // Unit tests.
41 #[cfg(test)]
42 mod tests;
43
44 #[cfg(feature = "unstable-api")]
45 pub mod unstable;
46
47 /// The HEIF image and image collection brand
48 /// The 'mif1' brand indicates structural requirements on files
49 /// See HEIF (ISO 23008-12:2017) § 10.2.1
50 pub const MIF1_BRAND: FourCC = FourCC { value: *b"mif1" };
51
52 /// The HEIF image sequence brand
53 /// The 'msf1' brand indicates structural requirements on files
54 /// See HEIF (ISO 23008-12:2017) § 10.3.1
55 pub const MSF1_BRAND: FourCC = FourCC { value: *b"msf1" };
56
57 /// The brand to identify AV1 image items
58 /// The 'avif' brand indicates structural requirements on files
59 /// See <https://aomediacodec.github.io/av1-avif/#image-and-image-collection-brand>
60 pub const AVIF_BRAND: FourCC = FourCC { value: *b"avif" };
61
62 /// The brand to identify AVIF image sequences
63 /// The 'avis' brand indicates structural requirements on files
64 /// See <https://aomediacodec.github.io/av1-avif/#image-and-image-collection-brand>
65 pub const AVIS_BRAND: FourCC = FourCC { value: *b"avis" };
66
67 /// A trait to indicate a type can be infallibly converted to `u64`.
68 /// This should only be implemented for infallible conversions, so only unsigned types are valid.
69 trait ToU64 {
70 fn to_u64(self) -> u64;
71 }
72
73 /// Statically verify that the platform `usize` can fit within a `u64`.
74 /// If the size won't fit on the given platform, this will fail at compile time, but if a type
75 /// which can fail `TryInto<usize>` is used, it may panic.
76 impl ToU64 for usize {
77 fn to_u64(self) -> u64 {
78 static_assertions::const_assert!(
79 std::mem::size_of::<usize>() <= std::mem::size_of::<u64>()
80 );
81 self.try_into().expect("usize -> u64 conversion failed")
82 }
83 }
84
85 /// A trait to indicate a type can be infallibly converted to `usize`.
86 /// This should only be implemented for infallible conversions, so only unsigned types are valid.
87 pub trait ToUsize {
88 fn to_usize(self) -> usize;
89 }
90
91 /// Statically verify that the given type can fit within a `usize`.
92 /// If the size won't fit on the given platform, this will fail at compile time, but if a type
93 /// which can fail `TryInto<usize>` is used, it may panic.
94 macro_rules! impl_to_usize_from {
95 ( $from_type:ty ) => {
96 impl ToUsize for $from_type {
97 fn to_usize(self) -> usize {
98 static_assertions::const_assert!(
99 std::mem::size_of::<$from_type>() <= std::mem::size_of::<usize>()
100 );
101 self.try_into().expect(concat!(
102 stringify!($from_type),
103 " -> usize conversion failed"
104 ))
105 }
106 }
107 };
108 }
109
110 impl_to_usize_from!(u8);
111 impl_to_usize_from!(u16);
112 impl_to_usize_from!(u32);
113
114 /// Indicate the current offset (i.e., bytes already read) in a reader
115 trait Offset {
116 fn offset(&self) -> u64;
117 }
118
119 /// Wraps a reader to track the current offset
120 struct OffsetReader<'a, T: 'a> {
121 reader: &'a mut T,
122 offset: u64,
123 }
124
125 impl<'a, T> OffsetReader<'a, T> {
126 fn new(reader: &'a mut T) -> Self {
127 Self { reader, offset: 0 }
128 }
129 }
130
131 impl<T> Offset for OffsetReader<'_, T> {
132 fn offset(&self) -> u64 {
133 self.offset
134 }
135 }
136
137 impl<T: Read> Read for OffsetReader<'_, T> {
138 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
139 let bytes_read = self.reader.read(buf)?;
140 trace!("Read {} bytes at offset {}", bytes_read, self.offset);
141 self.offset = self
142 .offset
143 .checked_add(bytes_read.to_u64())
144 .expect("total bytes read too large for offset type");
145 Ok(bytes_read)
146 }
147 }
148
149 pub type TryVec<T> = fallible_collections::TryVec<T>;
150 pub type TryString = fallible_collections::TryVec<u8>;
151 pub type TryHashMap<K, V> = fallible_collections::TryHashMap<K, V>;
152 pub type TryBox<T> = fallible_collections::TryBox<T>;
153
154 // To ensure we don't use stdlib allocating types by accident
155 #[allow(dead_code)]
156 struct Vec;
157 #[allow(dead_code)]
158 struct Box;
159 #[allow(dead_code)]
160 struct HashMap;
161 #[allow(dead_code)]
162 struct String;
163
164 /// The return value to the C API
165 /// Any detail that needs to be communicated to the caller must be encoded here
166 /// since the [`Error`] type's associated data is part of the FFI.
167 #[repr(C)]
168 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
169 pub enum Status {
170 Ok = 0,
171 BadArg = 1,
172 Invalid = 2,
173 Unsupported = 3,
174 Eof = 4,
175 Io = 5,
176 Oom = 6,
177 A1lxEssential,
178 A1opNoEssential,
179 AlacBadMagicCookieSize,
180 AlacFlagsNonzero,
181 Av1cMissing,
182 BitReaderError,
183 BoxBadSize,
184 BoxBadWideSize,
185 CheckParserStateErr,
186 ColrBadQuantity,
187 ColrBadSize,
188 ColrBadType,
189 ColrReservedNonzero,
190 ConstructionMethod,
191 CttsBadSize,
192 CttsBadVersion,
193 DflaBadMetadataBlockSize,
194 DflaFlagsNonzero,
195 DflaMissingMetadata,
196 DflaStreamInfoBadSize,
197 DflaStreamInfoNotFirst,
198 DopsChannelMappingWriteErr,
199 DopsOpusHeadWriteErr,
200 ElstBadVersion,
201 EsdsBadAudioSampleEntry,
202 EsdsBadDescriptor,
203 EsdsDecSpecificIntoTagQuantity,
204 FtypBadSize,
205 FtypNotFirst,
206 HdlrNameNoNul,
207 HdlrNameNotUtf8,
208 HdlrNotFirst,
209 HdlrPredefinedNonzero,
210 HdlrReservedNonzero,
211 HdlrTypeNotPict,
212 HdlrUnsupportedVersion,
213 HdrlBadQuantity,
214 IdatBadQuantity,
215 IdatMissing,
216 IinfBadChild,
217 IinfBadQuantity,
218 IlocBadConstructionMethod,
219 IlocBadExtent,
220 IlocBadExtentCount,
221 IlocBadFieldSize,
222 IlocBadQuantity,
223 IlocBadSize,
224 IlocDuplicateItemId,
225 IlocNotFound,
226 IlocOffsetOverflow,
227 ImageItemType,
228 InfeFlagsNonzero,
229 InvalidUtf8,
230 IpcoIndexOverflow,
231 IpmaBadIndex,
232 IpmaBadItemOrder,
233 IpmaBadQuantity,
234 IpmaBadVersion,
235 IpmaDuplicateItemId,
236 IpmaFlagsNonzero,
237 IpmaIndexZeroNoEssential,
238 IpmaTooBig,
239 IpmaTooSmall,
240 IprpBadChild,
241 IprpBadQuantity,
242 IprpConflict,
243 IrefBadQuantity,
244 IrefRecursion,
245 IspeMissing,
246 ItemTypeMissing,
247 LselNoEssential,
248 MdhdBadTimescale,
249 MdhdBadVersion,
250 MehdBadVersion,
251 MetaBadQuantity,
252 MissingAvifOrAvisBrand,
253 MissingMif1Brand,
254 MoovBadQuantity,
255 MoovMissing,
256 MultipleAlpha,
257 MvhdBadTimescale,
258 MvhdBadVersion,
259 NoImage,
260 PitmBadQuantity,
261 PitmMissing,
262 PitmNotFound,
263 PixiBadChannelCount,
264 PixiMissing,
265 PsshSizeOverflow,
266 ReadBufErr,
267 SchiQuantity,
268 StsdBadAudioSampleEntry,
269 StsdBadVideoSampleEntry,
270 TkhdBadVersion,
271 TxformBeforeIspe,
272 TxformNoEssential,
273 TxformOrder,
274 }
275
276 #[repr(C)]
277 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
278 pub enum Feature {
279 A1lx,
280 A1op,
281 Auxc,
282 Av1c,
283 Avis,
284 Clap,
285 Colr,
286 Grid,
287 Imir,
288 Ipro,
289 Irot,
290 Ispe,
291 Lsel,
292 Pasp,
293 Pixi,
294 }
295
296 impl Feature {
297 fn supported(self) -> bool {
298 match self {
299 Self::Auxc
300 | Self::Av1c
301 | Self::Avis
302 | Self::Colr
303 | Self::Imir
304 | Self::Irot
305 | Self::Ispe
306 | Self::Pasp
307 | Self::Pixi => true,
308 Self::A1lx | Self::A1op | Self::Clap | Self::Grid | Self::Ipro | Self::Lsel => false,
309 }
310 }
311 }
312
313 impl TryFrom<&ItemProperty> for Feature {
314 type Error = Error;
315
316 fn try_from(item_property: &ItemProperty) -> Result<Self, Self::Error> {
317 Ok(match item_property {
318 ItemProperty::AuxiliaryType(_) => Self::Auxc,
319 ItemProperty::AV1Config(_) => Self::Av1c,
320 ItemProperty::Channels(_) => Self::Pixi,
321 ItemProperty::CleanAperture => Self::Clap,
322 ItemProperty::Colour(_) => Self::Colr,
323 ItemProperty::ImageSpatialExtents(_) => Self::Ispe,
324 ItemProperty::LayeredImageIndexing => Self::A1lx,
325 ItemProperty::LayerSelection => Self::Lsel,
326 ItemProperty::Mirroring(_) => Self::Imir,
327 ItemProperty::OperatingPointSelector => Self::A1op,
328 ItemProperty::PixelAspectRatio(_) => Self::Pasp,
329 ItemProperty::Rotation(_) => Self::Irot,
330 item_property => {
331 error!("No known Feature variant for {:?}", item_property);
332 return Err(Error::Unsupported("missing Feature fox ItemProperty"));
333 }
334 })
335 }
336 }
337
338 /// A collection to indicate unsupported features that were encountered during
339 /// parsing. Since the default behavior for many such features is to ignore
340 /// them, this often not fatal and there may be several to report.
341 #[derive(Debug, Default)]
342 pub struct UnsupportedFeatures(u32);
343
344 impl UnsupportedFeatures {
345 pub fn new() -> Self {
346 Self(0x0)
347 }
348
349 pub fn into_bitfield(&self) -> u32 {
350 self.0
351 }
352
353 fn feature_to_bitfield(feature: Feature) -> u32 {
354 let index = feature as usize;
355 assert!(
356 u8::BITS.to_usize() * std::mem::size_of::<Self>() > index,
357 "You're gonna need a bigger bitfield"
358 );
359 let bitfield = 1u32 << index;
360 assert_eq!(bitfield.count_ones(), 1);
361 bitfield
362 }
363
364 pub fn insert(&mut self, feature: Feature) {
365 warn!("Unsupported feature: {:?}", feature);
366 self.0 |= Self::feature_to_bitfield(feature);
367 }
368
369 pub fn contains(&self, feature: Feature) -> bool {
370 self.0 & Self::feature_to_bitfield(feature) != 0x0
371 }
372
373 pub fn is_empty(&self) -> bool {
374 self.0 == 0x0
375 }
376 }
377
378 impl<T> From<Status> for Result<T> {
379 /// A convenience method to enable shortcuts like
380 /// ```
381 /// # use mp4parse::{Result,Status};
382 /// # let _: Result<()> =
383 /// Status::MissingAvifOrAvisBrand.into();
384 /// ```
385 /// instead of
386 /// ```
387 /// # use mp4parse::{Error,Result,Status};
388 /// # let _: Result<()> =
389 /// Err(Error::from(Status::MissingAvifOrAvisBrand));
390 /// ```
391 /// Note that `Status::Ok` can't be supported this way and will panic.
392 fn from(parse_status: Status) -> Self {
393 match parse_status {
394 Status::Ok => panic!("Can't determine Ok(_) inner value from Status"),
395 err_status => Err(err_status.into()),
396 }
397 }
398 }
399
400 /// For convenience of creating an error for an unsupported feature which we
401 /// want to communicate the specific feature back to the C API caller
402 impl From<Status> for Error {
403 fn from(parse_status: Status) -> Self {
404 match parse_status {
405 Status::Ok
406 | Status::BadArg
407 | Status::Invalid
408 | Status::Unsupported
409 | Status::Eof
410 | Status::Io
411 | Status::Oom => {
412 panic!("Status -> Error is only for Status:InvalidData errors")
413 }
414 _ => Self::InvalidData(parse_status),
415 }
416 }
417 }
418
419 impl From<Status> for &str {
420 fn from(status: Status) -> Self {
421 match status {
422 Status::Ok
423 | Status::BadArg
424 | Status::Invalid
425 | Status::Unsupported
426 | Status::Eof
427 | Status::Io
428 | Status::Oom => {
429 panic!("Status -> Error is only for specific parsing errors")
430 }
431 Status::A1lxEssential => {
432 "AV1LayeredImageIndexingProperty (a1lx) shall not be marked as essential \
433 per https://aomediacodec.github.io/av1-avif/#layered-image-indexing-property-description"
434 }
435 Status::A1opNoEssential => {
436 "OperatingPointSelectorProperty (a1op) shall be marked as essential \
437 per https://aomediacodec.github.io/av1-avif/#operating-point-selector-property-description"
438 }
439 Status::AlacBadMagicCookieSize => {
440 "ALACSpecificBox magic cookie is the wrong size"
441 }
442 Status::AlacFlagsNonzero => {
443 "no-zero alac (ALAC) flags"
444 }
445 Status::Av1cMissing => {
446 "One AV1 Item Configuration Property (av1C) is mandatory for an \
447 image item of type 'av01' \
448 per AVIF specification § 2.2.1"
449 }
450 Status::BitReaderError => {
451 "Bitwise read failed"
452 }
453 Status::BoxBadSize => {
454 "malformed size"
455 }
456 Status::BoxBadWideSize => {
457 "malformed wide size"
458 }
459 Status::CheckParserStateErr => {
460 "unread box content or bad parser sync"
461 }
462 Status::ColrBadQuantity => {
463 "Each item shall have at most one property association with a
464 ColourInformationBox (colr) for a given value of colour_type \
465 per HEIF (ISO/IEC DIS 23008-12) § 6.5.5.1"
466 }
467 Status::ColrBadSize => {
468 "Unexpected size for colr box"
469 }
470 Status::ColrBadType => {
471 "Unsupported colour_type for ColourInformationBox"
472 }
473 Status::ColrReservedNonzero => {
474 "The 7 reserved bits at the end of the ColourInformationBox \
475 for colour_type == 'nclx' must be 0 \
476 per ISOBMFF (ISO 14496-12:2020) § 12.1.5.2"
477 }
478 Status::ConstructionMethod => {
479 "construction_method shall be 0 (file) or 1 (idat) per MIAF (ISO 23000-22:2019) § 7.2.1.7"
480 }
481 Status::CttsBadSize => {
482 "insufficient data in 'ctts' box"
483 }
484 Status::CttsBadVersion => {
485 "unsupported version in 'ctts' box"
486 }
487 Status::DflaBadMetadataBlockSize => {
488 "FLACMetadataBlock larger than parent box"
489 }
490 Status::DflaFlagsNonzero => {
491 "no-zero dfLa (FLAC) flags"
492 }
493 Status::DflaMissingMetadata => {
494 "FLACSpecificBox missing metadata"
495 }
496 Status::DflaStreamInfoBadSize => {
497 "FLACSpecificBox STREAMINFO block is the wrong size"
498 }
499 Status::DflaStreamInfoNotFirst => {
500 "FLACSpecificBox must have STREAMINFO metadata first"
501 }
502 Status::DopsChannelMappingWriteErr => {
503 "Couldn't write channel mapping table data."
504 }
505 Status::DopsOpusHeadWriteErr => {
506 "Couldn't write OpusHead tag."
507 }
508 Status::ElstBadVersion => {
509 "unhandled elst version"
510 }
511 Status::EsdsBadAudioSampleEntry => {
512 "malformed audio sample entry"
513 }
514 Status::EsdsBadDescriptor => {
515 "Invalid descriptor."
516 }
517 Status::EsdsDecSpecificIntoTagQuantity => {
518 "There can be only one DecSpecificInfoTag descriptor"
519 }
520 Status::FtypBadSize => {
521 "invalid ftyp size"
522 }
523 Status::FtypNotFirst => {
524 "The FileTypeBox shall be placed as early as possible in the file \
525 per ISOBMFF (ISO 14496-12:2020) § 4.3.1"
526 }
527 Status::HdlrNameNoNul => {
528 "The HandlerBox 'name' field shall be null-terminated \
529 per ISOBMFF (ISO 14496-12:2020) § 8.4.3.2"
530 }
531 Status::HdlrNameNotUtf8 => {
532 "The HandlerBox 'name' field shall be valid utf8 \
533 per ISOBMFF (ISO 14496-12:2020) § 8.4.3.2"
534 }
535 Status::HdlrNotFirst => {
536 "The HandlerBox shall be the first contained box within the MetaBox \
537 per MIAF (ISO 23000-22:2019) § 7.2.1.5"
538 }
539 Status::HdlrPredefinedNonzero => {
540 "The HandlerBox 'pre_defined' field shall be 0 \
541 per ISOBMFF (ISO 14496-12:2020) § 8.4.3.2"
542 }
543 Status::HdlrReservedNonzero => {
544 "The HandlerBox 'reserved' fields shall be 0 \
545 per ISOBMFF (ISO 14496-12:2020) § 8.4.3.2"
546 }
547 Status::HdlrTypeNotPict => {
548 "The HandlerBox handler_type must be 'pict' \
549 per MIAF (ISO 23000-22:2019) § 7.2.1.5"
550 }
551 Status::HdlrUnsupportedVersion => {
552 "The HandlerBox version shall be 0 (zero) \
553 per ISOBMFF (ISO 14496-12:2020) § 8.4.3.2"
554 }
555 Status::HdrlBadQuantity => {
556 "There shall be exactly one hdlr box \
557 per ISOBMFF (ISO 14496-12:2020) § 8.4.3.1"
558 }
559 Status::IdatBadQuantity => {
560 "There shall be zero or one idat boxes \
561 per ISOBMFF (ISO 14496-12:2020) § 8.11.11"
562 }
563 Status::IdatMissing => {
564 "ItemLocationBox (iloc) construction_method indicates 1 (idat), \
565 but no idat box is present."
566 }
567 Status::IinfBadChild => {
568 "iinf box shall contain only infe boxes \
569 per ISOBMFF (ISO 14496-12:2020) § 8.11.6.2"
570 }
571 Status::IinfBadQuantity => {
572 "There shall be zero or one iinf boxes \
573 per ISOBMFF (ISO 14496-12:2020) § 8.11.6.1"
574 }
575 Status::IlocBadConstructionMethod => {
576 "construction_method is taken from the set 0, 1 or 2 \
577 per ISOBMFF (ISO 14496-12:2020) § 8.11.3.3"
578 }
579 Status::IlocBadExtent => {
580 "extent_count != 1 requires explicit offset and length \
581 per ISOBMFF (ISO 14496-12:2020) § 8.11.3.3"
582 }
583 Status::IlocBadExtentCount => {
584 "extent_count must have a value 1 or greater \
585 per ISOBMFF (ISO 14496-12:2020) § 8.11.3.3"
586 }
587 Status::IlocBadFieldSize => {
588 "value must be in the set {0, 4, 8}"
589 }
590 Status::IlocBadQuantity => {
591 "There shall be zero or one iloc boxes \
592 per ISOBMFF (ISO 14496-12:2020) § 8.11.3.1"
593 }
594 Status::IlocBadSize => {
595 "invalid iloc size"
596 }
597 Status::IlocDuplicateItemId => {
598 "duplicate item_ID in iloc"
599 }
600 Status::IlocNotFound => {
601 "ItemLocationBox (iloc) contains an extent not present in any mdat or idat box"
602 }
603 Status::IlocOffsetOverflow => {
604 "offset calculation overflow"
605 }
606 Status::ImageItemType => {
607 "Image item type is neither 'av01' nor 'grid'"
608 }
609 Status::InfeFlagsNonzero => {
610 "'infe' flags field shall be 0 \
611 per ISOBMFF (ISO 14496-12:2020) § 8.11.6.2"
612 }
613 Status::InvalidUtf8 => {
614 "invalid utf8"
615 }
616 Status::IpcoIndexOverflow => {
617 "ipco index overflow"
618 }
619 Status::IpmaBadIndex => {
620 "Invalid property index in ipma"
621 }
622 Status::IpmaBadItemOrder => {
623 "Each ItemPropertyAssociation box shall be ordered by increasing item_ID"
624 }
625 Status::IpmaBadQuantity => {
626 "There shall be at most one ItemPropertyAssociationbox with a given pair of \
627 values of version and flags \
628 per ISOBMFF (ISO 14496-12:2020) § 8.11.14.1"
629 }
630 Status::IpmaBadVersion => {
631 "The ipma version 0 should be used unless 32-bit item_ID values are needed \
632 per ISOBMFF (ISO 14496-12:2020) § 8.11.14.1"
633 }
634 Status::IpmaDuplicateItemId => {
635 "There shall be at most one occurrence of a given item_ID, \
636 in the set of ItemPropertyAssociationBox boxes \
637 per ISOBMFF (ISO 14496-12:2020) § 8.11.14.1"
638 }
639 Status::IpmaFlagsNonzero => {
640 "Unless there are more than 127 properties in the ItemPropertyContainerBox, \
641 flags should be equal to 0 \
642 per ISOBMFF (ISO 14496-12:2020) § 8.11.14.1"
643 }
644 Status::IpmaIndexZeroNoEssential => {
645 "the essential indicator shall be 0 for property index 0 \
646 per ISOBMFF (ISO 14496-12:2020) § 8.11.14.3"
647 }
648 Status::IpmaTooBig => {
649 "ipma box exceeds maximum size for entry_count"
650 }
651 Status::IpmaTooSmall => {
652 "ipma box below minimum size for entry_count"
653 }
654 Status::IprpBadChild => {
655 "unexpected iprp child"
656 }
657 Status::IprpBadQuantity => {
658 "There shall be zero or one iprp boxes \
659 per ISOBMFF (ISO 14496-12:2020) § 8.11.14.1"
660 }
661 Status::IprpConflict => {
662 "conflicting item property values"
663 }
664 Status::IrefBadQuantity => {
665 "There shall be zero or one iref boxes \
666 per ISOBMFF (ISO 14496-12:2020) § 8.11.12.1"
667 }
668 Status::IrefRecursion => {
669 "from_item_id and to_item_id must be different"
670 }
671 Status::IspeMissing => {
672 "Missing 'ispe' property for image item, required \
673 per HEIF (ISO/IEC 23008-12:2017) § 6.5.3.1"
674 }
675 Status::ItemTypeMissing => {
676 "No ItemInfoEntry for item_ID"
677 }
678 Status::LselNoEssential => {
679 "LayerSelectorProperty (lsel) shall be marked as essential \
680 per HEIF (ISO/IEC 23008-12:2017) § 6.5.11.1"
681 }
682 Status::MdhdBadTimescale => {
683 "zero timescale in mdhd"
684 }
685 Status::MdhdBadVersion => {
686 "unhandled mdhd version"
687 }
688 Status::MehdBadVersion => {
689 "unhandled mehd version"
690 }
691 Status::MetaBadQuantity => {
692 "There should be zero or one meta boxes \
693 per ISOBMFF (ISO 14496-12:2020) § 8.11.1.1"
694 }
695 Status::MissingAvifOrAvisBrand => {
696 "The file shall list 'avif' or 'avis' in the compatible_brands field
697 of the FileTypeBox \
698 per https://aomediacodec.github.io/av1-avif/#file-constraints"
699 }
700 Status::MissingMif1Brand => {
701 "The FileTypeBox should contain 'mif1' in the compatible_brands list \
702 per MIAF (ISO 23000-22:2019/Amd. 2:2021) § 7.2.1.2"
703 }
704 Status::MoovBadQuantity => {
705 "Multiple moov boxes found; \
706 files with avis or msf1 brands shall contain exactly one moov box \
707 per ISOBMFF (ISO 14496-12:2020) § 8.2.1.1"
708 }
709 Status::MoovMissing => {
710 "No moov box found; \
711 files with avis or msf1 brands shall contain exactly one moov box \
712 per ISOBMFF (ISO 14496-12:2020) § 8.2.1.1"
713 }
714 Status::MultipleAlpha => {
715 "multiple alpha planes"
716 }
717 Status::MvhdBadTimescale => {
718 "zero timescale in mvhd"
719 }
720 Status::MvhdBadVersion => {
721 "unhandled mvhd version"
722 }
723 Status::NoImage => "No primary image or image sequence found",
724 Status::PitmBadQuantity => {
725 "There shall be zero or one pitm boxes \
726 per ISOBMFF (ISO 14496-12:2020) § 8.11.4.1"
727 }
728 Status::PitmMissing => {
729 "Missing required PrimaryItemBox (pitm), required \
730 per HEIF (ISO/IEC 23008-12:2017) § 10.2.1"
731 }
732 Status::PitmNotFound => {
733 "PrimaryItemBox (pitm) referenced an item ID that was not present"
734 }
735 Status::PixiBadChannelCount => {
736 "invalid num_channels"
737 }
738 Status::PixiMissing => {
739 "The pixel information property shall be associated with every image \
740 that is displayable (not hidden) \
741 per MIAF (ISO/IEC 23000-22:2019) specification § 7.3.6.6"
742 }
743 Status::PsshSizeOverflow => {
744 "overflow in read_pssh"
745 }
746 Status::ReadBufErr => {
747 "failed buffer read"
748 }
749 Status::SchiQuantity => {
750 "tenc box should be only one at most in sinf box"
751 }
752 Status::StsdBadAudioSampleEntry => {
753 "malformed audio sample entry"
754 }
755 Status::StsdBadVideoSampleEntry => {
756 "malformed video sample entry"
757 }
758 Status::TkhdBadVersion => {
759 "unhandled tkhd version"
760 }
761 Status::TxformBeforeIspe => {
762 "Every image item shall be associated with one property of \
763 type ImageSpatialExtentsProperty (ispe), prior to the \
764 association of all transformative properties. \
765 per HEIF (ISO/IEC 23008-12:2017) § 6.5.3.1"
766 }
767 Status::TxformNoEssential => {
768 "All transformative properties associated with coded and \
769 derived images required or conditionally required by this \
770 document shall be marked as essential \
771 per MIAF (ISO 23000-22:2019) § 7.3.9"
772 }
773 Status::TxformOrder => {
774 "These properties, if used, shall be indicated to be applied \
775 in the following order: clean aperture first, then rotation, \
776 then mirror. \
777 per MIAF (ISO/IEC 23000-22:2019) § 7.3.6.7"
778 }
779 }
780 }
781 }
782
783 impl From<Error> for Status {
784 fn from(error: Error) -> Self {
785 match error {
786 Error::Unsupported(_) => Self::Unsupported,
787 Error::InvalidData(parse_status) => parse_status,
788 Error::UnexpectedEOF => Self::Eof,
789 Error::Io(_) => {
790 // Getting std::io::ErrorKind::UnexpectedEof is normal
791 // but our From trait implementation should have converted
792 // those to our Error::UnexpectedEOF variant.
793 Self::Io
794 }
795 Error::MoovMissing => Self::MoovMissing,
796 Error::OutOfMemory => Self::Oom,
797 }
798 }
799 }
800
801 impl From<Result<(), Status>> for Status {
802 fn from(result: Result<(), Status>) -> Self {
803 match result {
804 Ok(()) => Status::Ok,
805 Err(Status::Ok) => unreachable!(),
806 Err(e) => e,
807 }
808 }
809 }
810
811 impl<T> From<Result<T>> for Status {
812 fn from(result: Result<T>) -> Self {
813 match result {
814 Ok(_) => Status::Ok,
815 Err(e) => Status::from(e),
816 }
817 }
818 }
819
820 impl From<fallible_collections::TryReserveError> for Status {
821 fn from(_: fallible_collections::TryReserveError) -> Self {
822 Status::Oom
823 }
824 }
825
826 impl From<std::io::Error> for Status {
827 fn from(_: std::io::Error) -> Self {
828 Status::Io
829 }
830 }
831
832 /// Describes parser failures.
833 ///
834 /// This enum wraps the standard `io::Error` type, unified with
835 /// our own parser error states and those of crates we use.
836 #[derive(Debug)]
837 pub enum Error {
838 /// Parse error caused by corrupt or malformed data.
839 /// See the helper [`From<Status> for Error`](enum.Error.html#impl-From<Status>)
840 InvalidData(Status),
841 /// Parse error caused by limited parser support rather than invalid data.
842 Unsupported(&'static str),
843 /// Reflect `std::io::ErrorKind::UnexpectedEof` for short data.
844 UnexpectedEOF,
845 /// Propagate underlying errors from `std::io`.
846 Io(std::io::Error),
847 /// read_mp4 terminated without detecting a moov box.
848 MoovMissing,
849 /// Out of memory
850 OutOfMemory,
851 }
852
853 impl std::fmt::Display for Error {
854 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
855 write!(f, "{self:?}")
856 }
857 }
858
859 impl std::error::Error for Error {}
860
861 impl From<bitreader::BitReaderError> for Error {
862 fn from(_: bitreader::BitReaderError) -> Error {
863 Status::BitReaderError.into()
864 }
865 }
866
867 impl From<std::io::Error> for Error {
868 fn from(err: std::io::Error) -> Error {
869 match err.kind() {
870 std::io::ErrorKind::UnexpectedEof => Error::UnexpectedEOF,
871 _ => Error::Io(err),
872 }
873 }
874 }
875
876 impl From<std::string::FromUtf8Error> for Error {
877 fn from(_: std::string::FromUtf8Error) -> Error {
878 Status::InvalidUtf8.into()
879 }
880 }
881
882 impl From<std::str::Utf8Error> for Error {
883 fn from(_: std::str::Utf8Error) -> Error {
884 Status::InvalidUtf8.into()
885 }
886 }
887
888 impl From<std::num::TryFromIntError> for Error {
889 fn from(_: std::num::TryFromIntError) -> Error {
890 Error::Unsupported("integer conversion failed")
891 }
892 }
893
894 impl From<Error> for std::io::Error {
895 fn from(err: Error) -> Self {
896 let kind = match err {
897 Error::UnexpectedEOF => std::io::ErrorKind::UnexpectedEof,
898 Error::Io(io_err) => return io_err,
899 _ => std::io::ErrorKind::Other,
900 };
901 Self::new(kind, err)
902 }
903 }
904
905 impl From<TryReserveError> for Error {
906 fn from(_: TryReserveError) -> Error {
907 Error::OutOfMemory
908 }
909 }
910
911 /// Result shorthand using our Error enum.
912 pub type Result<T, E = Error> = std::result::Result<T, E>;
913
914 /// Basic ISO box structure.
915 ///
916 /// mp4 files are a sequence of possibly-nested 'box' structures. Each box
917 /// begins with a header describing the length of the box's data and a
918 /// four-byte box type which identifies the type of the box. Together these
919 /// are enough to interpret the contents of that section of the file.
920 ///
921 /// See ISOBMFF (ISO 14496-12:2020) § 4.2
922 #[derive(Debug, Clone, Copy)]
923 struct BoxHeader {
924 /// Box type.
925 name: BoxType,
926 /// Size of the box in bytes.
927 size: u64,
928 /// Offset to the start of the contained data (or header size).
929 offset: u64,
930 /// Uuid for extended type.
931 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
932 uuid: Option<[u8; 16]>,
933 }
934
935 impl BoxHeader {
936 const MIN_SIZE: u64 = 8; // 4-byte size + 4-byte type
937 const MIN_LARGE_SIZE: u64 = 16; // 4-byte size + 4-byte type + 16-byte size
938 }
939
940 /// File type box 'ftyp'.
941 #[derive(Debug)]
942 struct FileTypeBox {
943 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
944 major_brand: FourCC,
945 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
946 minor_version: u32,
947 compatible_brands: TryVec<FourCC>,
948 }
949
950 impl FileTypeBox {
951 fn contains(&self, brand: &FourCC) -> bool {
952 self.compatible_brands.contains(brand) || self.major_brand == *brand
953 }
954 }
955
956 /// Movie header box 'mvhd'.
957 #[derive(Debug)]
958 struct MovieHeaderBox {
959 pub timescale: u32,
960 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
961 duration: u64,
962 }
963
964 #[derive(Debug, Clone, Copy)]
965 pub struct Matrix {
966 pub a: i32, // 16.16 fix point
967 pub b: i32, // 16.16 fix point
968 pub u: i32, // 2.30 fix point
969 pub c: i32, // 16.16 fix point
970 pub d: i32, // 16.16 fix point
971 pub v: i32, // 2.30 fix point
972 pub x: i32, // 16.16 fix point
973 pub y: i32, // 16.16 fix point
974 pub w: i32, // 2.30 fix point
975 }
976
977 /// Track header box 'tkhd'
978 #[derive(Debug, Clone)]
979 pub struct TrackHeaderBox {
980 track_id: u32,
981 pub disabled: bool,
982 pub duration: u64,
983 pub width: u32,
984 pub height: u32,
985 pub matrix: Matrix,
986 }
987
988 /// Edit list box 'elst'
989 #[derive(Debug)]
990 struct EditListBox {
991 looped: bool,
992 edits: TryVec<Edit>,
993 }
994
995 #[derive(Debug)]
996 struct Edit {
997 segment_duration: u64,
998 media_time: i64,
999 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
1000 media_rate_integer: i16,
1001 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
1002 media_rate_fraction: i16,
1003 }
1004
1005 /// Media header box 'mdhd'
1006 #[derive(Debug)]
1007 struct MediaHeaderBox {
1008 timescale: u32,
1009 duration: u64,
1010 }
1011
1012 // Chunk offset box 'stco' or 'co64'
1013 #[derive(Debug)]
1014 pub struct ChunkOffsetBox {
1015 pub offsets: TryVec<u64>,
1016 }
1017
1018 // Sync sample box 'stss'
1019 #[derive(Debug)]
1020 pub struct SyncSampleBox {
1021 pub samples: TryVec<u32>,
1022 }
1023
1024 // Sample to chunk box 'stsc'
1025 #[derive(Debug)]
1026 pub struct SampleToChunkBox {
1027 pub samples: TryVec<SampleToChunk>,
1028 }
1029
1030 #[derive(Debug)]
1031 pub struct SampleToChunk {
1032 pub first_chunk: u32,
1033 pub samples_per_chunk: u32,
1034 pub sample_description_index: u32,
1035 }
1036
1037 // Sample size box 'stsz'
1038 #[derive(Debug)]
1039 pub struct SampleSizeBox {
1040 pub sample_size: u32,
1041 pub sample_sizes: TryVec<u32>,
1042 }
1043
1044 // Time to sample box 'stts'
1045 #[derive(Debug)]
1046 pub struct TimeToSampleBox {
1047 pub samples: TryVec<Sample>,
1048 }
1049
1050 #[repr(C)]
1051 #[derive(Debug)]
1052 pub struct Sample {
1053 pub sample_count: u32,
1054 pub sample_delta: u32,
1055 }
1056
1057 #[derive(Debug, Clone, Copy)]
1058 pub enum TimeOffsetVersion {
1059 Version0(u32),
1060 Version1(i32),
1061 }
1062
1063 #[derive(Debug, Clone)]
1064 pub struct TimeOffset {
1065 pub sample_count: u32,
1066 pub time_offset: TimeOffsetVersion,
1067 }
1068
1069 #[derive(Debug)]
1070 pub struct CompositionOffsetBox {
1071 pub samples: TryVec<TimeOffset>,
1072 }
1073
1074 // Handler reference box 'hdlr'
1075 #[derive(Debug)]
1076 struct HandlerBox {
1077 handler_type: FourCC,
1078 }
1079
1080 // Sample description box 'stsd'
1081 #[derive(Debug)]
1082 pub struct SampleDescriptionBox {
1083 pub descriptions: TryVec<SampleEntry>,
1084 }
1085
1086 #[derive(Debug)]
1087 pub enum SampleEntry {
1088 Audio(AudioSampleEntry),
1089 Video(VideoSampleEntry),
1090 Unknown,
1091 }
1092
1093 #[derive(Debug)]
1094 pub struct TrackReferenceBox {
1095 pub references: TryVec<TrackReferenceEntry>,
1096 }
1097
1098 impl TrackReferenceBox {
1099 pub fn has_auxl_reference(&self, track_id: u32) -> bool {
1100 self.references.iter().any(|entry| match entry {
1101 TrackReferenceEntry::Auxiliary(aux_entry) => aux_entry.track_ids.contains(&track_id),
1102 })
1103 }
1104 }
1105
1106 #[derive(Debug)]
1107 pub enum TrackReferenceEntry {
1108 Auxiliary(TrackReference),
1109 }
1110
1111 #[derive(Debug)]
1112 pub struct TrackReference {
1113 pub track_ids: TryVec<u32>,
1114 }
1115
1116 /// An Elementary Stream Descriptor
1117 /// See MPEG-4 Systems (ISO 14496-1:2010) § 7.2.6.5
1118 #[allow(non_camel_case_types)]
1119 #[derive(Debug, Default)]
1120 pub struct ES_Descriptor {
1121 pub audio_codec: CodecType,
1122 pub audio_object_type: Option<u16>,
1123 pub extended_audio_object_type: Option<u16>,
1124 pub audio_sample_rate: Option<u32>,
1125 pub audio_channel_count: Option<u16>,
1126 #[cfg(feature = "mp4v")]
1127 pub video_codec: CodecType,
1128 pub codec_esds: TryVec<u8>,
1129 pub decoder_specific_data: TryVec<u8>, // Data in DECODER_SPECIFIC_TAG
1130 }
1131
1132 #[allow(non_camel_case_types)]
1133 #[derive(Debug)]
1134 pub enum AudioCodecSpecific {
1135 ES_Descriptor(ES_Descriptor),
1136 FLACSpecificBox(FLACSpecificBox),
1137 OpusSpecificBox(OpusSpecificBox),
1138 ALACSpecificBox(ALACSpecificBox),
1139 MP3,
1140 LPCM,
1141 #[cfg(feature = "3gpp")]
1142 AMRSpecificBox(TryVec<u8>),
1143 }
1144
1145 #[derive(Debug)]
1146 pub struct AudioSampleEntry {
1147 pub codec_type: CodecType,
1148 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
1149 data_reference_index: u16,
1150 pub channelcount: u32,
1151 pub samplesize: u16,
1152 pub samplerate: f64,
1153 pub codec_specific: AudioCodecSpecific,
1154 pub protection_info: TryVec<ProtectionSchemeInfoBox>,
1155 }
1156
1157 #[derive(Debug)]
1158 pub enum VideoCodecSpecific {
1159 AVCConfig(TryVec<u8>),
1160 VPxConfig(VPxConfigBox),
1161 AV1Config(AV1ConfigBox),
1162 ESDSConfig(TryVec<u8>),
1163 H263Config(TryVec<u8>),
1164 HEVCConfig(TryVec<u8>),
1165 }
1166
1167 #[derive(Debug)]
1168 pub struct VideoSampleEntry {
1169 pub codec_type: CodecType,
1170 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
1171 data_reference_index: u16,
1172 pub width: u16,
1173 pub height: u16,
1174 pub codec_specific: VideoCodecSpecific,
1175 pub protection_info: TryVec<ProtectionSchemeInfoBox>,
1176 pub pixel_aspect_ratio: Option<f32>,
1177 }
1178
1179 /// Represent a Video Partition Codec Configuration 'vpcC' box (aka vp9). The meaning of each
1180 /// field is covered in detail in "VP Codec ISO Media File Format Binding".
1181 #[derive(Debug)]
1182 pub struct VPxConfigBox {
1183 /// An integer that specifies the VP codec profile.
1184 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
1185 profile: u8,
1186 /// An integer that specifies a VP codec level all samples conform to the following table.
1187 /// For a description of the various levels, please refer to the VP9 Bitstream Specification.
1188 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
1189 level: u8,
1190 /// An integer that specifies the bit depth of the luma and color components. Valid values
1191 /// are 8, 10, and 12.
1192 pub bit_depth: u8,
1193 /// Really an enum defined by the "Colour primaries" section of ISO 23091-2:2019 § 8.1.
1194 pub colour_primaries: u8,
1195 /// Really an enum defined by "VP Codec ISO Media File Format Binding".
1196 pub chroma_subsampling: u8,
1197 /// Really an enum defined by the "Transfer characteristics" section of ISO 23091-2:2019 § 8.2.
1198 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
1199 transfer_characteristics: u8,
1200 /// Really an enum defined by the "Matrix coefficients" section of ISO 23091-2:2019 § 8.3.
1201 /// Available in 'VP Codec ISO Media File Format' version 1 only.
1202 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
1203 matrix_coefficients: Option<u8>,
1204 /// Indicates the black level and range of the luma and chroma signals. 0 = legal range
1205 /// (e.g. 16-235 for 8 bit sample depth); 1 = full range (e.g. 0-255 for 8-bit sample depth).
1206 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
1207 video_full_range_flag: bool,
1208 /// This is not used for VP8 and VP9 . Intended for binary codec initialization data.
1209 pub codec_init: TryVec<u8>,
1210 }
1211
1212 /// See [AV1-ISOBMFF § 2.3.3](https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax)
1213 #[derive(Debug)]
1214 pub struct AV1ConfigBox {
1215 pub profile: u8,
1216 pub level: u8,
1217 pub tier: u8,
1218 pub bit_depth: u8,
1219 pub monochrome: bool,
1220 pub chroma_subsampling_x: u8,
1221 pub chroma_subsampling_y: u8,
1222 pub chroma_sample_position: u8,
1223 pub initial_presentation_delay_present: bool,
1224 pub initial_presentation_delay_minus_one: u8,
1225 // The raw config contained in the av1c box. Because some decoders accept this data as a binary
1226 // blob, rather than as structured data, we store the blob here for convenience.
1227 pub raw_config: TryVec<u8>,
1228 }
1229
1230 impl AV1ConfigBox {
1231 const CONFIG_OBUS_OFFSET: usize = 4;
1232
1233 pub fn config_obus(&self) -> &[u8] {
1234 &self.raw_config[Self::CONFIG_OBUS_OFFSET..]
1235 }
1236 }
1237
1238 #[derive(Debug)]
1239 pub struct FLACMetadataBlock {
1240 pub block_type: u8,
1241 pub data: TryVec<u8>,
1242 }
1243
1244 /// Represents a FLACSpecificBox 'dfLa'
1245 #[derive(Debug)]
1246 pub struct FLACSpecificBox {
1247 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
1248 version: u8,
1249 pub blocks: TryVec<FLACMetadataBlock>,
1250 }
1251
1252 #[derive(Debug)]
1253 struct ChannelMappingTable {
1254 stream_count: u8,
1255 coupled_count: u8,
1256 channel_mapping: TryVec<u8>,
1257 }
1258
1259 /// Represent an OpusSpecificBox 'dOps'
1260 #[derive(Debug)]
1261 pub struct OpusSpecificBox {
1262 pub version: u8,
1263 output_channel_count: u8,
1264 pre_skip: u16,
1265 input_sample_rate: u32,
1266 output_gain: i16,
1267 channel_mapping_family: u8,
1268 channel_mapping_table: Option<ChannelMappingTable>,
1269 }
1270
1271 /// Represent an ALACSpecificBox 'alac'
1272 #[derive(Debug)]
1273 pub struct ALACSpecificBox {
1274 #[allow(dead_code)] // See https://github.com/mozilla/mp4parse-rust/issues/340
1275 version: u8,
1276 pub data: TryVec<u8>,
1277 }
1278
1279 #[derive(Debug)]
1280 pub struct MovieExtendsBox {
1281 pub fragment_duration: Option<MediaScaledTime>,
1282 }
1283
1284 pub type ByteData = TryVec<u8>;
1285
1286 #[derive(Debug, Default)]
1287 pub struct ProtectionSystemSpecificHeaderBox {
1288 pub system_id: ByteData,
1289 pub kid: TryVec<ByteData>,
1290 pub data: ByteData,
1291
1292 // The entire pssh box (include header) required by Gecko.
1293 pub box_content: ByteData,
1294 }
1295
1296 #[derive(Debug, Default, Clone)]
1297 pub struct SchemeTypeBox {
1298 pub scheme_type: FourCC,
1299 pub scheme_version: u32,
1300 }
1301
1302 #[derive(Debug, Default)]
1303 pub struct TrackEncryptionBox {
1304 pub is_encrypted: u8,
1305 pub iv_size: u8,
1306 pub kid: TryVec<u8>,
1307 // Members for pattern encryption schemes
1308 pub crypt_byte_block_count: Option<u8>,
1309 pub skip_byte_block_count: Option<u8>,
1310 pub constant_iv: Option<TryVec<u8>>,
1311 // End pattern encryption scheme members
1312 }
1313
1314 #[derive(Debug, Default)]
1315 pub struct ProtectionSchemeInfoBox {
1316 pub original_format: FourCC,
1317 pub scheme_type: Option<SchemeTypeBox>,
1318 pub tenc: Option<TrackEncryptionBox>,
1319 }
1320
1321 /// Represents a userdata box 'udta'.
1322 /// Currently, only the metadata atom 'meta'
1323 /// is parsed.
1324 #[derive(Debug, Default)]
1325 pub struct UserdataBox {
1326 pub meta: Option<MetadataBox>,
1327 }
1328
1329 /// Represents possible contents of the
1330 /// ©gen or gnre atoms within a metadata box.
1331 /// 'udta.meta.ilst' may only have either a
1332 /// standard genre box 'gnre' or a custom
1333 /// genre box '©gen', but never both at once.
1334 #[derive(Debug, PartialEq)]
1335 pub enum Genre {
1336 /// A standard ID3v1 numbered genre.
1337 StandardGenre(u8),
1338 /// Any custom genre string.
1339 CustomGenre(TryString),
1340 }
1341
1342 /// Represents the contents of a 'stik'
1343 /// atom that indicates content types within
1344 /// iTunes.
1345 #[derive(Debug, Clone, Eq, PartialEq)]
1346 pub enum MediaType {
1347 /// Movie is stored as 0 in a 'stik' atom.
1348 Movie, // 0
1349 /// Normal is stored as 1 in a 'stik' atom.
1350 Normal, // 1
1351 /// AudioBook is stored as 2 in a 'stik' atom.
1352 AudioBook, // 2
1353 /// WhackedBookmark is stored as 5 in a 'stik' atom.
1354 WhackedBookmark, // 5
1355 /// MusicVideo is stored as 6 in a 'stik' atom.
1356 MusicVideo, // 6
1357 /// ShortFilm is stored as 9 in a 'stik' atom.
1358 ShortFilm, // 9
1359 /// TVShow is stored as 10 in a 'stik' atom.
1360 TVShow, // 10
1361 /// Booklet is stored as 11 in a 'stik' atom.
1362 Booklet, // 11
1363 /// An unknown 'stik' value.
1364 Unknown(u8),
1365 }
1366
1367 /// Represents the parental advisory rating on the track,
1368 /// stored within the 'rtng' atom.
1369 #[derive(Debug, Clone, Eq, PartialEq)]
1370 pub enum AdvisoryRating {
1371 /// Clean is always stored as 2 in an 'rtng' atom.
1372 Clean, // 2
1373 /// A value of 0 in an 'rtng' atom indicates 'Inoffensive'
1374 Inoffensive, // 0
1375 /// Any non 2 or 0 value in 'rtng' indicates the track is explicit.
1376 Explicit(u8),
1377 }
1378
1379 /// Represents the contents of 'ilst' atoms within
1380 /// a metadata box 'meta', parsed as iTunes metadata using
1381 /// the conventional tags.
1382 #[derive(Debug, Default)]
1383 pub struct MetadataBox {
1384 /// The album name, '©alb'
1385 pub album: Option<TryString>,
1386 /// The artist name '©art' or '©ART'
1387 pub artist: Option<TryString>,
1388 /// The album artist 'aART'
1389 pub album_artist: Option<TryString>,
1390 /// Track comments '©cmt'
1391 pub comment: Option<TryString>,
1392 /// The date or year field '©day'
1393 ///
1394 /// This is stored as an arbitrary string,
1395 /// and may not necessarily be in a valid date
1396 /// format.
1397 pub year: Option<TryString>,
1398 /// The track title '©nam'
1399 pub title: Option<TryString>,
1400 /// The track genre '©gen' or 'gnre'.
1401 pub genre: Option<Genre>,
1402 /// The track number 'trkn'.
1403 pub track_number: Option<u8>,
1404 /// The disc number 'disk'
1405 pub disc_number: Option<u8>,
1406 /// The total number of tracks on the disc,
1407 /// stored in 'trkn'
1408 pub total_tracks: Option<u8>,
1409 /// The total number of discs in the album,
1410 /// stored in 'disk'
1411 pub total_discs: Option<u8>,
1412 /// The composer of the track '©wrt'
1413 pub composer: Option<TryString>,
1414 /// The encoder used to create this track '©too'
1415 pub encoder: Option<TryString>,
1416 /// The encoded-by settingo this track '©enc'
1417 pub encoded_by: Option<TryString>,
1418 /// The tempo or BPM of the track 'tmpo'
1419 pub beats_per_minute: Option<u8>,
1420 /// Copyright information of the track 'cprt'
1421 pub copyright: Option<TryString>,
1422 /// Whether or not this track is part of a compilation 'cpil'
1423 pub compilation: Option<bool>,
1424 /// The advisory rating of this track 'rtng'
1425 pub advisory: Option<AdvisoryRating>,
1426 /// The personal rating of this track, 'rate'.
1427 ///
1428 /// This is stored in the box as string data, but
1429 /// the format is an integer percentage from 0 - 100,
1430 /// where 100 is displayed as 5 stars out of 5.
1431 pub rating: Option<TryString>,
1432 /// The grouping this track belongs to '©grp'
1433 pub grouping: Option<TryString>,
1434 /// The media type of this track 'stik'
1435 pub media_type: Option<MediaType>, // stik
1436 /// Whether or not this track is a podcast 'pcst'
1437 pub podcast: Option<bool>,
1438 /// The category of ths track 'catg'
1439 pub category: Option<TryString>,
1440 /// The podcast keyword 'keyw'
1441 pub keyword: Option<TryString>,
1442 /// The podcast url 'purl'
1443 pub podcast_url: Option<TryString>,
1444 /// The podcast episode GUID 'egid'
1445 pub podcast_guid: Option<TryString>,
1446 /// The description of the track 'desc'
1447 pub description: Option<TryString>,
1448 /// The long description of the track 'ldes'.
1449 ///
1450 /// Unlike other string fields, the long description field
1451 /// can be longer than 256 characters.
1452 pub long_description: Option<TryString>,
1453 /// The lyrics of the track '©lyr'.
1454 ///
1455 /// Unlike other string fields, the lyrics field
1456 /// can be longer than 256 characters.
1457 pub lyrics: Option<TryString>,
1458 /// The name of the TV network this track aired on 'tvnn'.
1459 pub tv_network_name: Option<TryString>,
1460 /// The name of the TV Show for this track 'tvsh'.
1461 pub tv_show_name: Option<TryString>,
1462 /// The name of the TV Episode for this track 'tven'.
1463 pub tv_episode_name: Option<TryString>,
1464 /// The number of the TV Episode for this track 'tves'.
1465 pub tv_episode_number: Option<u8>,
1466 /// The season of the TV Episode of this track 'tvsn'.
1467 pub tv_season: Option<u8>,
1468 /// The date this track was purchased 'purd'.
1469 pub purchase_date: Option<TryString>,
1470 /// Whether or not this track supports gapless playback 'pgap'
1471 pub gapless_playback: Option<bool>,
1472 /// Any cover artwork attached to this track 'covr'
1473 ///
1474 /// 'covr' is unique in that it may contain multiple 'data' sub-entries,
1475 /// each an image file. Here, each subentry's raw binary data is exposed,
1476 /// which may contain image data in JPEG or PNG format.
1477 pub cover_art: Option<TryVec<TryVec<u8>>>,
1478 /// The owner of the track 'ownr'
1479 pub owner: Option<TryString>,
1480 /// Whether or not this track is HD Video 'hdvd'
1481 pub hd_video: Option<bool>,
1482 /// The name of the track to sort by 'sonm'
1483 pub sort_name: Option<TryString>,
1484 /// The name of the album to sort by 'soal'
1485 pub sort_album: Option<TryString>,
1486 /// The name of the artist to sort by 'soar'
1487 pub sort_artist: Option<TryString>,
1488 /// The name of the album artist to sort by 'soaa'
1489 pub sort_album_artist: Option<TryString>,
1490 /// The name of the composer to sort by 'soco'
1491 pub sort_composer: Option<TryString>,
1492 /// Metadata
1493 #[cfg(feature = "meta-xml")]
1494 pub xml: Option<XmlBox>,
1495 }
1496
1497 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.2.1
1498 #[cfg(feature = "meta-xml")]
1499 #[derive(Debug)]
1500 pub enum XmlBox {
1501 /// XML metadata
1502 StringXmlBox(TryString),
1503 /// Binary XML metadata
1504 BinaryXmlBox(TryVec<u8>),
1505 }
1506
1507 /// Internal data structures.
1508 #[derive(Debug, Default)]
1509 pub struct MediaContext {
1510 pub timescale: Option<MediaTimeScale>,
1511 /// Tracks found in the file.
1512 pub tracks: TryVec<Track>,
1513 pub mvex: Option<MovieExtendsBox>,
1514 pub psshs: TryVec<ProtectionSystemSpecificHeaderBox>,
1515 pub userdata: Option<Result<UserdataBox>>,
1516 #[cfg(feature = "meta-xml")]
1517 pub metadata: Option<Result<MetadataBox>>,
1518 }
1519
1520 /// An ISOBMFF item as described by an iloc box. For the sake of avoiding copies,
1521 /// this can either be represented by the `Location` variant, which indicates
1522 /// where the data exists within a `DataBox` stored separately, or the `Data`
1523 /// variant which owns the data. Unfortunately, it's not simple to represent
1524 /// this as a [`std::borrow::Cow`], or other reference-based type, because
1525 /// multiple instances may references different parts of the same [`DataBox`]
1526 /// and we want to avoid the copy that splitting the storage would entail.
1527 enum IsobmffItem {
1528 MdatLocation(Extent),
1529 IdatLocation(Extent),
1530 Data(TryVec<u8>),
1531 }
1532
1533 impl fmt::Debug for IsobmffItem {
1534 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1535 match &self {
1536 IsobmffItem::MdatLocation(extent) | IsobmffItem::IdatLocation(extent) => f
1537 .debug_struct("IsobmffItem::Location")
1538 .field("0", &format_args!("{extent:?}"))
1539 .finish(),
1540 IsobmffItem::Data(data) => f
1541 .debug_struct("IsobmffItem::Data")
1542 .field("0", &format_args!("{} bytes", data.len()))
1543 .finish(),
1544 }
1545 }
1546 }
1547
1548 #[derive(Debug)]
1549 struct AvifItem {
1550 /// The `item_ID` from ISOBMFF (ISO 14496-12:2020) § 8.11.3
1551 ///
1552 /// See [`read_iloc`]
1553 id: ItemId,
1554
1555 /// AV1 Image Item per <https://aomediacodec.github.io/av1-avif/#image-item>
1556 image_data: IsobmffItem,
1557 }
1558
1559 impl AvifItem {
1560 fn with_inline_data(id: ItemId) -> Self {
1561 Self {
1562 id,
1563 image_data: IsobmffItem::Data(TryVec::new()),
1564 }
1565 }
1566 }
1567
1568 #[derive(Default, Debug)]
1569 pub struct AvifContext {
1570 /// Level of deviation from the specification before failing the parse
1571 strictness: ParseStrictness,
1572 /// Storage elements which can be located anywhere within the "file" identified by
1573 /// [`BoxType::ItemLocationBox`]es using [`ConstructionMethod::File`].
1574 /// Referred to by the [`IsobmffItem`]`::*Location` variants of the `AvifItem`s in this struct
1575 media_storage: TryVec<DataBox>,
1576 /// Similar to `media_storage`, but for a single optional chunk of storage within the
1577 /// MetaBox itentified by [`BoxType::ItemLocationBox`]es using [`ConstructionMethod::Idat`].
1578 item_data_box: Option<DataBox>,
1579 /// The item indicated by the `pitm` box, See ISOBMFF (ISO 14496-12:2020) § 8.11.4
1580 /// May be `None` in the pure image sequence case.
1581 primary_item: Option<AvifItem>,
1582 /// Associated alpha channel for the primary item, if any
1583 alpha_item: Option<AvifItem>,
1584 /// If true, divide RGB values by the alpha value.
1585 /// See `prem` in MIAF (ISO 23000-22:2019) § 7.3.5.2
1586 pub premultiplied_alpha: bool,
1587 /// All properties associated with `primary_item` or `alpha_item`
1588 item_properties: ItemPropertiesBox,
1589 /// Should probably only ever be [`AVIF_BRAND`] or [`AVIS_BRAND`], but other values
1590 /// are legal as long as one of the two is the `compatible_brand` list.
1591 pub major_brand: FourCC,
1592 /// Information on the sequence contained in the image, or None if not present
1593 pub sequence: Option<MediaContext>,
1594 /// A collection of unsupported features encountered during the parse
1595 pub unsupported_features: UnsupportedFeatures,
1596 }
1597
1598 impl AvifContext {
1599 pub fn primary_item_is_present(&self) -> bool {
1600 self.primary_item.is_some()
1601 }
1602
1603 pub fn primary_item_coded_data(&self) -> Option<&[u8]> {
1604 self.primary_item
1605 .as_ref()
1606 .map(|item| self.item_as_slice(item))
1607 }
1608
1609 pub fn primary_item_bits_per_channel(&self) -> Option<Result<&[u8]>> {
1610 self.primary_item
1611 .as_ref()
1612 .map(|item| self.image_bits_per_channel(item.id))
1613 }
1614
1615 pub fn alpha_item_is_present(&self) -> bool {
1616 self.alpha_item.is_some()
1617 }
1618
1619 pub fn alpha_item_coded_data(&self) -> Option<&[u8]> {
1620 self.alpha_item
1621 .as_ref()
1622 .map(|item| self.item_as_slice(item))
1623 }
1624
1625 pub fn alpha_item_bits_per_channel(&self) -> Option<Result<&[u8]>> {
1626 self.alpha_item
1627 .as_ref()
1628 .map(|item| self.image_bits_per_channel(item.id))
1629 }
1630
1631 fn image_bits_per_channel(&self, item_id: ItemId) -> Result<&[u8]> {
1632 match self
1633 .item_properties
1634 .get(item_id, BoxType::PixelInformationBox)?
1635 {
1636 Some(ItemProperty::Channels(pixi)) => Ok(pixi.bits_per_channel.as_slice()),
1637 Some(other_property) => panic!("property key mismatch: {:?}", other_property),
1638 None => Ok(&[]),
1639 }
1640 }
1641
1642 pub fn spatial_extents_ptr(&self) -> Result<*const ImageSpatialExtentsProperty> {
1643 if let Some(primary_item) = &self.primary_item {
1644 match self
1645 .item_properties
1646 .get(primary_item.id, BoxType::ImageSpatialExtentsProperty)?
1647 {
1648 Some(ItemProperty::ImageSpatialExtents(ispe)) => Ok(ispe),
1649 Some(other_property) => panic!("property key mismatch: {:?}", other_property),
1650 None => {
1651 fail_with_status_if(
1652 self.strictness != ParseStrictness::Permissive,
1653 Status::IspeMissing,
1654 )?;
1655 Ok(std::ptr::null())
1656 }
1657 }
1658 } else {
1659 Ok(std::ptr::null())
1660 }
1661 }
1662
1663 /// Returns None if there is no primary item or it has no associated NCLX colour boxes.
1664 pub fn nclx_colour_information_ptr(&self) -> Option<Result<*const NclxColourInformation>> {
1665 if let Some(primary_item) = &self.primary_item {
1666 match self.item_properties.get_multiple(primary_item.id, |prop| {
1667 matches!(prop, ItemProperty::Colour(ColourInformation::Nclx(_)))
1668 }) {
1669 Ok(nclx_colr_boxes) => match *nclx_colr_boxes.as_slice() {
1670 [] => None,
1671 [ItemProperty::Colour(ColourInformation::Nclx(nclx)), ..] => {
1672 if nclx_colr_boxes.len() > 1 {
1673 warn!("Multiple nclx colr boxes, using first");
1674 }
1675 Some(Ok(nclx))
1676 }
1677 _ => unreachable!("Expect only ColourInformation::Nclx(_) matches"),
1678 },
1679 Err(e) => Some(Err(e)),
1680 }
1681 } else {
1682 None
1683 }
1684 }
1685
1686 /// Returns None if there is no primary item or it has no associated ICC colour boxes.
1687 pub fn icc_colour_information(&self) -> Option<Result<&[u8]>> {
1688 if let Some(primary_item) = &self.primary_item {
1689 match self.item_properties.get_multiple(primary_item.id, |prop| {
1690 matches!(prop, ItemProperty::Colour(ColourInformation::Icc(_, _)))
1691 }) {
1692 Ok(icc_colr_boxes) => match *icc_colr_boxes.as_slice() {
1693 [] => None,
1694 [ItemProperty::Colour(ColourInformation::Icc(icc, _)), ..] => {
1695 if icc_colr_boxes.len() > 1 {
1696 warn!("Multiple ICC profiles in colr boxes, using first");
1697 }
1698 Some(Ok(icc.bytes.as_slice()))
1699 }
1700 _ => unreachable!("Expect only ColourInformation::Icc(_) matches"),
1701 },
1702 Err(e) => Some(Err(e)),
1703 }
1704 } else {
1705 None
1706 }
1707 }
1708
1709 pub fn image_rotation(&self) -> Result<ImageRotation> {
1710 if let Some(primary_item) = &self.primary_item {
1711 match self
1712 .item_properties
1713 .get(primary_item.id, BoxType::ImageRotation)?
1714 {
1715 Some(ItemProperty::Rotation(irot)) => Ok(*irot),
1716 Some(other_property) => panic!("property key mismatch: {:?}", other_property),
1717 None => Ok(ImageRotation::D0),
1718 }
1719 } else {
1720 Ok(ImageRotation::D0)
1721 }
1722 }
1723
1724 pub fn image_mirror_ptr(&self) -> Result<*const ImageMirror> {
1725 if let Some(primary_item) = &self.primary_item {
1726 match self
1727 .item_properties
1728 .get(primary_item.id, BoxType::ImageMirror)?
1729 {
1730 Some(ItemProperty::Mirroring(imir)) => Ok(imir),
1731 Some(other_property) => panic!("property key mismatch: {:?}", other_property),
1732 None => Ok(std::ptr::null()),
1733 }
1734 } else {
1735 Ok(std::ptr::null())
1736 }
1737 }
1738
1739 pub fn pixel_aspect_ratio_ptr(&self) -> Result<*const PixelAspectRatio> {
1740 if let Some(primary_item) = &self.primary_item {
1741 match self
1742 .item_properties
1743 .get(primary_item.id, BoxType::PixelAspectRatioBox)?
1744 {
1745 Some(ItemProperty::PixelAspectRatio(pasp)) => Ok(pasp),
1746 Some(other_property) => panic!("property key mismatch: {:?}", other_property),
1747 None => Ok(std::ptr::null()),
1748 }
1749 } else {
1750 Ok(std::ptr::null())
1751 }
1752 }
1753
1754 /// A helper for the various `AvifItem`s to expose a reference to the
1755 /// underlying data while avoiding copies.
1756 fn item_as_slice<'a>(&'a self, item: &'a AvifItem) -> &'a [u8] {
1757 match &item.image_data {
1758 IsobmffItem::MdatLocation(extent) => {
1759 for mdat in &self.media_storage {
1760 if let Some(slice) = mdat.get(extent) {
1761 return slice;
1762 }
1763 }
1764 unreachable!(
1765 "IsobmffItem::MdatLocation requires the location exists in AvifContext::media_storage"
1766 );
1767 }
1768 IsobmffItem::IdatLocation(extent) => {
1769 self.item_data_box
1770 .as_ref()
1771 .and_then(|idat| idat.get(extent))
1772 .unwrap_or_else(|| unreachable!("IsobmffItem::IdatLocation equires the location exists in AvifContext::item_data_box"))
1773 }
1774 IsobmffItem::Data(data) => data.as_slice(),
1775 }
1776 }
1777 }
1778
1779 struct AvifMeta {
1780 item_references: TryVec<SingleItemTypeReferenceBox>,
1781 item_properties: ItemPropertiesBox,
1782 /// Required for AvifImageType::Primary, but optional otherwise
1783 /// See HEIF (ISO/IEC 23008-12:2017) § 7.1, 10.2.1
1784 primary_item_id: Option<ItemId>,
1785 item_infos: TryVec<ItemInfoEntry>,
1786 iloc_items: TryHashMap<ItemId, ItemLocationBoxItem>,
1787 item_data_box: Option<DataBox>,
1788 }
1789
1790 #[derive(Debug)]
1791 enum DataBoxMetadata {
1792 Idat,
1793 Mdat {
1794 /// Offset of `data` from the beginning of the "file". See ConstructionMethod::File.
1795 /// Note: the file may not be an actual file, read_avif supports any `&mut impl Read`
1796 /// source for input. However we try to match the terminology used in the spec.
1797 file_offset: u64,
1798 },
1799 }
1800
1801 /// Represents either an Item Data Box (ISOBMFF (ISO 14496-12:2020) § 8.11.11)
1802 /// Or a Media Data Box (ISOBMFF (ISO 14496-12:2020) § 8.1.1)
1803 struct DataBox {
1804 metadata: DataBoxMetadata,
1805 data: TryVec<u8>,
1806 }
1807
1808 impl fmt::Debug for DataBox {
1809 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1810 f.debug_struct("DataBox")
1811 .field("metadata", &self.metadata)
1812 .field("data", &format_args!("{} bytes", self.data.len()))
1813 .finish()
1814 }
1815 }
1816
1817 fn u64_to_usize_logged(x: u64) -> Option<usize> {
1818 match x.try_into() {
1819 Ok(x) => Some(x),
1820 Err(e) => {
1821 error!("{:?} converting {:?}", e, x);
1822 None
1823 }
1824 }
1825 }
1826
1827 impl DataBox {
1828 fn from_mdat(file_offset: u64, data: TryVec<u8>) -> Self {
1829 Self {
1830 metadata: DataBoxMetadata::Mdat { file_offset },
1831 data,
1832 }
1833 }
1834
1835 fn from_idat(data: TryVec<u8>) -> Self {
1836 Self {
1837 metadata: DataBoxMetadata::Idat,
1838 data,
1839 }
1840 }
1841
1842 fn data(&self) -> &[u8] {
1843 &self.data
1844 }
1845
1846 /// Convert an absolute offset to an offset relative to the beginning of the
1847 /// slice [`DataBox::data`] returns. Returns None if the offset would be
1848 /// negative or if the offset would overflow a `usize`.
1849 fn start(&self, offset: u64) -> Option<usize> {
1850 match self.metadata {
1851 DataBoxMetadata::Idat => u64_to_usize_logged(offset),
1852 DataBoxMetadata::Mdat { file_offset } => {
1853 let start = offset.checked_sub(file_offset);
1854 if start.is_none() {
1855 error!("Overflow subtracting {} + {}", offset, file_offset);
1856 }
1857 u64_to_usize_logged(start?)
1858 }
1859 }
1860 }
1861
1862 /// Returns an appropriate variant of [`IsobmffItem`] to describe the extent
1863 /// referencing data within this type of box.
1864 fn location(&self, extent: &Extent) -> IsobmffItem {
1865 match self.metadata {
1866 DataBoxMetadata::Idat => IsobmffItem::IdatLocation(extent.clone()),
1867 DataBoxMetadata::Mdat { .. } => IsobmffItem::MdatLocation(extent.clone()),
1868 }
1869 }
1870
1871 /// Return a slice from the DataBox specified by the provided `extent`.
1872 /// Returns `None` if the extent isn't fully contained by the DataBox or if
1873 /// either the offset or length (if the extent is bounded) of the slice
1874 /// would overflow a `usize`.
1875 fn get<'a>(&'a self, extent: &'a Extent) -> Option<&'a [u8]> {
1876 match extent {
1877 Extent::WithLength { offset, len } => {
1878 let start = self.start(*offset)?;
1879 let end = start.checked_add(*len);
1880 if end.is_none() {
1881 error!("Overflow adding {} + {}", start, len);
1882 }
1883 self.data().get(start..end?)
1884 }
1885 Extent::ToEnd { offset } => {
1886 let start = self.start(*offset)?;
1887 self.data().get(start..)
1888 }
1889 }
1890 }
1891 }
1892
1893 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1894 struct PropertyIndex(u16);
1895 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
1896 struct ItemId(u32);
1897
1898 impl ItemId {
1899 fn read(src: &mut impl ReadBytesExt, version: u8) -> Result<ItemId> {
1900 Ok(ItemId(if version == 0 {
1901 be_u16(src)?.into()
1902 } else {
1903 be_u32(src)?
1904 }))
1905 }
1906 }
1907
1908 /// Used for 'infe' boxes within 'iinf' boxes
1909 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.6
1910 /// Only versions {2, 3} are supported
1911 #[derive(Debug)]
1912 struct ItemInfoEntry {
1913 item_id: ItemId,
1914 item_type: u32,
1915 }
1916
1917 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.12
1918 #[derive(Debug)]
1919 struct SingleItemTypeReferenceBox {
1920 item_type: FourCC,
1921 from_item_id: ItemId,
1922 to_item_id: ItemId,
1923 }
1924
1925 /// Potential sizes (in bytes) of variable-sized fields of the 'iloc' box
1926 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.3
1927 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1928 enum IlocFieldSize {
1929 Zero,
1930 Four,
1931 Eight,
1932 }
1933
1934 impl IlocFieldSize {
1935 fn as_bits(&self) -> u8 {
1936 match self {
1937 IlocFieldSize::Zero => 0,
1938 IlocFieldSize::Four => 32,
1939 IlocFieldSize::Eight => 64,
1940 }
1941 }
1942 }
1943
1944 impl TryFrom<u8> for IlocFieldSize {
1945 type Error = Error;
1946
1947 fn try_from(value: u8) -> Result<Self> {
1948 match value {
1949 0 => Ok(Self::Zero),
1950 4 => Ok(Self::Four),
1951 8 => Ok(Self::Eight),
1952 _ => Status::IlocBadFieldSize.into(),
1953 }
1954 }
1955 }
1956
1957 #[derive(Debug, PartialEq, Eq)]
1958 enum IlocVersion {
1959 Zero,
1960 One,
1961 Two,
1962 }
1963
1964 impl TryFrom<u8> for IlocVersion {
1965 type Error = Error;
1966
1967 fn try_from(value: u8) -> Result<Self> {
1968 match value {
1969 0 => Ok(Self::Zero),
1970 1 => Ok(Self::One),
1971 2 => Ok(Self::Two),
1972 _ => Err(Error::Unsupported("unsupported version in 'iloc' box")),
1973 }
1974 }
1975 }
1976
1977 /// Used for 'iloc' boxes
1978 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.3
1979 /// `base_offset` is omitted since it is integrated into the ranges in `extents`
1980 /// `data_reference_index` is omitted, since only 0 (i.e., this file) is supported
1981 #[derive(Debug)]
1982 struct ItemLocationBoxItem {
1983 construction_method: ConstructionMethod,
1984 /// Unused for ConstructionMethod::Idat
1985 extents: TryVec<Extent>,
1986 }
1987
1988 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.3
1989 ///
1990 /// Note: per MIAF (ISO 23000-22:2019) § 7.2.1.7:<br />
1991 /// > MIAF image items are constrained as follows:<br />
1992 /// > — `construction_method` shall be equal to 0 for MIAF image items that are coded image items.<br />
1993 /// > — `construction_method` shall be equal to 0 or 1 for MIAF image items that are derived image items.
1994 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1995 enum ConstructionMethod {
1996 File = 0,
1997 Idat = 1,
1998 Item = 2,
1999 }
2000
2001 /// Describes a region where a item specified by an `ItemLocationBoxItem` is stored.
2002 /// The offset is `u64` since that's the maximum possible size and since the relative
2003 /// nature of `DataBox` means this can still possibly succeed even in the case
2004 /// that the raw value exceeds usize::MAX on platforms where that type is smaller
2005 /// than u64. However, `len` is stored as a `usize` since no value larger than
2006 /// `usize::MAX` can be used in a successful indexing operation in rust.
2007 /// `extent_index` is omitted since it's only used for ConstructionMethod::Item which
2008 /// is currently not implemented.
2009 #[derive(Clone, Debug)]
2010 enum Extent {
2011 WithLength { offset: u64, len: usize },
2012 ToEnd { offset: u64 },
2013 }
2014
2015 #[derive(Debug, PartialEq, Eq, Default)]
2016 pub enum TrackType {
2017 Audio,
2018 Video,
2019 Picture,
2020 AuxiliaryVideo,
2021 Metadata,
2022 #[default]
2023 Unknown,
2024 }
2025
2026 // This type is used by mp4parse_capi since it needs to be passed from FFI consumers
2027 // The C-visible struct is renamed via mp4parse_capi/cbindgen.toml to match naming conventions
2028 #[repr(C)]
2029 #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
2030 pub enum ParseStrictness {
2031 Permissive, // Error only on ambiguous inputs
2032 #[default]
2033 Normal, // Error on "shall" directives, log warnings for "should"
2034 Strict, // Error on "should" directives
2035 }
2036
2037 fn fail_with_status_if(violation: bool, status: Status) -> Result<()> {
2038 let error = Error::from(status);
2039 if violation {
2040 Err(error)
2041 } else {
2042 warn!("{:?}", error);
2043 Ok(())
2044 }
2045 }
2046
2047 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2048 pub enum CodecType {
2049 #[default]
2050 Unknown,
2051 MP3,
2052 AAC,
2053 FLAC,
2054 Opus,
2055 H264, // 14496-10
2056 MP4V, // 14496-2
2057 AV1,
2058 VP9,
2059 VP8,
2060 EncryptedVideo,
2061 EncryptedAudio,
2062 LPCM, // QT
2063 ALAC,
2064 H263,
2065 HEVC, // 23008-2
2066 #[cfg(feature = "3gpp")]
2067 AMRNB,
2068 #[cfg(feature = "3gpp")]
2069 AMRWB,
2070 }
2071
2072 /// The media's global (mvhd) timescale in units per second.
2073 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
2074 pub struct MediaTimeScale(pub u64);
2075
2076 /// A time to be scaled by the media's global (mvhd) timescale.
2077 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
2078 pub struct MediaScaledTime(pub u64);
2079
2080 /// The track's local (mdhd) timescale.
2081 /// Members are timescale units per second and the track id.
2082 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
2083 pub struct TrackTimeScale<T: Num>(pub T, pub usize);
2084
2085 /// A time to be scaled by the track's local (mdhd) timescale.
2086 /// Members are time in scale units and the track id.
2087 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
2088 pub struct TrackScaledTime<T>(pub T, pub usize);
2089
2090 impl<T> std::ops::Add for TrackScaledTime<T>
2091 where
2092 T: num_traits::CheckedAdd,
2093 {
2094 type Output = Option<Self>;
2095
2096 fn add(self, other: TrackScaledTime<T>) -> Self::Output {
2097 self.0.checked_add(&other.0).map(|sum| Self(sum, self.1))
2098 }
2099 }
2100
2101 #[derive(Debug, Default)]
2102 pub struct Track {
2103 pub id: usize,
2104 pub track_type: TrackType,
2105 pub looped: Option<bool>,
2106 pub empty_duration: Option<MediaScaledTime>,
2107 pub edited_duration: Option<MediaScaledTime>,
2108 pub media_time: Option<TrackScaledTime<u64>>,
2109 pub timescale: Option<TrackTimeScale<u64>>,
2110 pub duration: Option<TrackScaledTime<u64>>,
2111 pub track_id: Option<u32>,
2112 pub tkhd: Option<TrackHeaderBox>, // TODO(kinetik): find a nicer way to export this.
2113 pub stsd: Option<SampleDescriptionBox>,
2114 pub stts: Option<TimeToSampleBox>,
2115 pub stsc: Option<SampleToChunkBox>,
2116 pub stsz: Option<SampleSizeBox>,
2117 pub stco: Option<ChunkOffsetBox>, // It is for stco or co64.
2118 pub stss: Option<SyncSampleBox>,
2119 pub ctts: Option<CompositionOffsetBox>,
2120 pub tref: Option<TrackReferenceBox>,
2121 }
2122
2123 impl Track {
2124 fn new(id: usize) -> Track {
2125 Track {
2126 id,
2127 ..Default::default()
2128 }
2129 }
2130 }
2131
2132 /// See ISOBMFF (ISO 14496-12:2020) § 4.2
2133 struct BMFFBox<'a, T: 'a> {
2134 head: BoxHeader,
2135 content: Take<&'a mut T>,
2136 }
2137
2138 struct BoxIter<'a, T: 'a> {
2139 src: &'a mut T,
2140 }
2141
2142 impl<T: Read> BoxIter<'_, T> {
2143 fn new(src: &mut T) -> BoxIter<T> {
2144 BoxIter { src }
2145 }
2146
2147 fn next_box(&mut self) -> Result<Option<BMFFBox<T>>> {
2148 let r = read_box_header(self.src);
2149 match r {
2150 Ok(h) => Ok(Some(BMFFBox {
2151 head: h,
2152 content: self.src.take(h.size.saturating_sub(h.offset)),
2153 })),
2154 Err(Error::UnexpectedEOF) => Ok(None),
2155 Err(e) => Err(e),
2156 }
2157 }
2158 }
2159
2160 impl<T: Read> Read for BMFFBox<'_, T> {
2161 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
2162 self.content.read(buf)
2163 }
2164 }
2165
2166 impl<T: Read> TryRead for BMFFBox<'_, T> {
2167 fn try_read_to_end(&mut self, buf: &mut TryVec<u8>) -> std::io::Result<usize> {
2168 fallible_collections::try_read_up_to(self, self.bytes_left(), buf)
2169 }
2170 }
2171
2172 impl<T: Offset> Offset for BMFFBox<'_, T> {
2173 fn offset(&self) -> u64 {
2174 self.content.get_ref().offset()
2175 }
2176 }
2177
2178 impl<'a, T: Read> BMFFBox<'a, T> {
2179 fn bytes_left(&self) -> u64 {
2180 self.content.limit()
2181 }
2182
2183 fn get_header(&self) -> &BoxHeader {
2184 &self.head
2185 }
2186
2187 fn box_iter(&mut self) -> BoxIter<BMFFBox<'a, T>> {
2188 BoxIter::new(self)
2189 }
2190 }
2191
2192 impl<T> Drop for BMFFBox<'_, T> {
2193 fn drop(&mut self) {
2194 if self.content.limit() > 0 {
2195 let name: FourCC = From::from(self.head.name);
2196 debug!("Dropping {} bytes in '{}'", self.content.limit(), name);
2197 }
2198 }
2199 }
2200
2201 /// Read and parse a box header.
2202 ///
2203 /// Call this first to determine the type of a particular mp4 box
2204 /// and its length. Used internally for dispatching to specific
2205 /// parsers for the internal content, or to get the length to
2206 /// skip unknown or uninteresting boxes.
2207 ///
2208 /// See ISOBMFF (ISO 14496-12:2020) § 4.2
2209 fn read_box_header<T: ReadBytesExt>(src: &mut T) -> Result<BoxHeader> {
2210 let size32 = be_u32(src)?;
2211 let name = BoxType::from(be_u32(src)?);
2212 let size = match size32 {
2213 // valid only for top-level box and indicates it's the last box in the file. usually mdat.
2214 0 => {
2215 if name == BoxType::MediaDataBox {
2216 0
2217 } else {
2218 return Err(Error::Unsupported("unknown sized box"));
2219 }
2220 }
2221 1 => be_u64(src)?,
2222 _ => u64::from(size32),
2223 };
2224 trace!("read_box_header: name: {:?}, size: {}", name, size);
2225 let mut offset = match size32 {
2226 1 => BoxHeader::MIN_LARGE_SIZE,
2227 _ => BoxHeader::MIN_SIZE,
2228 };
2229 let uuid = if name == BoxType::UuidBox {
2230 if size >= offset + 16 {
2231 let mut buffer = [0u8; 16];
2232 let count = src.read(&mut buffer)?;
2233 offset += count.to_u64();
2234 if count == 16 {
2235 Some(buffer)
2236 } else {
2237 debug!("malformed uuid (short read)");
2238 return Err(Error::UnexpectedEOF);
2239 }
2240 } else {
2241 None
2242 }
2243 } else {
2244 None
2245 };
2246 match size32 {
2247 0 => (),
2248 1 if offset > size => return Err(Error::from(Status::BoxBadWideSize)),
2249 _ if offset > size => return Err(Error::from(Status::BoxBadSize)),
2250 _ => (),
2251 }
2252 Ok(BoxHeader {
2253 name,
2254 size,
2255 offset,
2256 uuid,
2257 })
2258 }
2259
2260 /// Parse the extra header fields for a full box.
2261 fn read_fullbox_extra<T: ReadBytesExt>(src: &mut T) -> Result<(u8, u32)> {
2262 let version = src.read_u8()?;
2263 let flags_a = src.read_u8()?;
2264 let flags_b = src.read_u8()?;
2265 let flags_c = src.read_u8()?;
2266 Ok((
2267 version,
2268 (u32::from(flags_a) << 16) | (u32::from(flags_b) << 8) | u32::from(flags_c),
2269 ))
2270 }
2271
2272 // Parse the extra fields for a full box whose flag fields must be zero.
2273 fn read_fullbox_version_no_flags<T: ReadBytesExt>(src: &mut T) -> Result<u8> {
2274 let (version, flags) = read_fullbox_extra(src)?;
2275
2276 if flags != 0 {
2277 return Err(Error::Unsupported("expected flags to be 0"));
2278 }
2279
2280 Ok(version)
2281 }
2282
2283 /// Skip over the entire contents of a box.
2284 fn skip_box_content<T: Read>(src: &mut BMFFBox<T>) -> Result<()> {
2285 // Skip the contents of unknown chunks.
2286 let to_skip = {
2287 let header = src.get_header();
2288 debug!("{:?} (skipped)", header);
2289 header
2290 .size
2291 .checked_sub(header.offset)
2292 .ok_or(Error::Unsupported("Skipping past unknown sized box"))?
2293 };
2294 assert_eq!(to_skip, src.bytes_left());
2295 skip(src, to_skip)
2296 }
2297
2298 /// Skip over the remain data of a box.
2299 fn skip_box_remain<T: Read>(src: &mut BMFFBox<T>) -> Result<()> {
2300 let remain = {
2301 let header = src.get_header();
2302 let len = src.bytes_left();
2303 debug!("remain {} (skipped) in {:?}", len, header);
2304 len
2305 };
2306 skip(src, remain)
2307 }
2308
2309 #[derive(Debug)]
2310 enum AvifImageType {
2311 Primary,
2312 Sequence,
2313 Both,
2314 }
2315
2316 impl AvifImageType {
2317 fn has_primary(&self) -> bool {
2318 match self {
2319 Self::Primary | Self::Both => true,
2320 Self::Sequence => false,
2321 }
2322 }
2323
2324 fn has_sequence(&self) -> bool {
2325 match self {
2326 Self::Primary => false,
2327 Self::Sequence | Self::Both => true,
2328 }
2329 }
2330 }
2331
2332 /// Read the contents of an AVIF file
2333 pub fn read_avif<T: Read>(f: &mut T, strictness: ParseStrictness) -> Result<AvifContext> {
2334 debug!("read_avif(strictness: {:?})", strictness);
2335
2336 let mut f = OffsetReader::new(f);
2337 let mut iter = BoxIter::new(&mut f);
2338 let expected_image_type;
2339 let mut unsupported_features = UnsupportedFeatures::new();
2340
2341 // 'ftyp' box must occur first; see ISOBMFF (ISO 14496-12:2020) § 4.3.1
2342 let major_brand = if let Some(mut b) = iter.next_box()? {
2343 if b.head.name == BoxType::FileTypeBox {
2344 let ftyp = read_ftyp(&mut b)?;
2345
2346 let has_avif_brand = ftyp.contains(&AVIF_BRAND);
2347 let has_avis_brand = ftyp.contains(&AVIS_BRAND);
2348 let has_mif1_brand = ftyp.contains(&MIF1_BRAND);
2349 let has_msf1_brand = ftyp.contains(&MSF1_BRAND);
2350
2351 let primary_image_expected = has_mif1_brand || has_avif_brand;
2352 let image_sequence_expected = has_msf1_brand || has_avis_brand;
2353
2354 expected_image_type = if primary_image_expected && image_sequence_expected {
2355 AvifImageType::Both
2356 } else if primary_image_expected {
2357 AvifImageType::Primary
2358 } else if image_sequence_expected {
2359 AvifImageType::Sequence
2360 } else {
2361 return Status::NoImage.into();
2362 };
2363 debug!("expected_image_type: {:?}", expected_image_type);
2364
2365 if primary_image_expected && !has_mif1_brand {
2366 fail_with_status_if(
2367 strictness == ParseStrictness::Strict,
2368 Status::MissingMif1Brand,
2369 )?;
2370 }
2371
2372 if !has_avif_brand && !has_avis_brand {
2373 fail_with_status_if(
2374 strictness != ParseStrictness::Permissive,
2375 Status::MissingAvifOrAvisBrand,
2376 )?;
2377 }
2378
2379 ftyp.major_brand
2380 } else {
2381 return Status::FtypNotFirst.into();
2382 }
2383 } else {
2384 return Status::FtypNotFirst.into();
2385 };
2386
2387 let mut meta = None;
2388 let mut image_sequence = None;
2389 let mut media_storage = TryVec::new();
2390
2391 loop {
2392 let mut b = match iter.next_box() {
2393 Ok(Some(b)) => b,
2394 Ok(_) => break,
2395 Err(Error::UnexpectedEOF) => {
2396 if strictness == ParseStrictness::Strict {
2397 return Err(Error::UnexpectedEOF);
2398 }
2399 break;
2400 }
2401 Err(error) => return Err(error),
2402 };
2403
2404 trace!("read_avif parsing {:?} box", b.head.name);
2405 match b.head.name {
2406 BoxType::MetadataBox => {
2407 if meta.is_some() {
2408 return Status::MetaBadQuantity.into();
2409 }
2410 meta = Some(read_avif_meta(
2411 &mut b,
2412 strictness,
2413 &mut unsupported_features,
2414 )?);
2415 }
2416 BoxType::MovieBox if expected_image_type.has_sequence() => {
2417 if image_sequence.is_some() {
2418 return Status::MoovBadQuantity.into();
2419 }
2420 image_sequence = Some(read_moov(&mut b, None)?);
2421 }
2422 BoxType::MediaDataBox => {
2423 let file_offset = b.offset();
2424 let data = if b.head.size == 0 {
2425 // Unknown sized `mdat`, read in chunks until EOF.
2426 const BUF_SIZE: usize = 64 * 1024;
2427 let mut data = TryVec::with_capacity(BUF_SIZE)?;
2428 loop {
2429 let got = fallible_collections::try_read_up_to(
2430 b.content.get_mut(),
2431 BUF_SIZE as u64,
2432 &mut data,
2433 )?;
2434 if got == 0 {
2435 // Mark `content` as consumed.
2436 b.content.set_limit(0);
2437 break;
2438 }
2439 }
2440 data
2441 } else {
2442 b.read_into_try_vec()?
2443 };
2444 media_storage.push(DataBox::from_mdat(file_offset, data))?;
2445 }
2446 _ => {
2447 let result = skip_box_content(&mut b);
2448 // Allow garbage at EOF if we aren't in strict mode.
2449 if b.bytes_left() > 0 && strictness != ParseStrictness::Strict {
2450 break;
2451 }
2452 result?;
2453 }
2454 }
2455
2456 check_parser_state!(b.content);
2457 }
2458
2459 let AvifMeta {
2460 item_references,
2461 item_properties,
2462 primary_item_id,
2463 item_infos,
2464 iloc_items,
2465 item_data_box,
2466 } = meta.ok_or_else(|| Error::from(Status::MetaBadQuantity))?;
2467
2468 let (alpha_item_id, premultiplied_alpha) = if let Some(primary_item_id) = primary_item_id {
2469 let mut alpha_item_ids = item_references
2470 .iter()
2471 // Auxiliary image for the primary image
2472 .filter(|iref| {
2473 iref.to_item_id == primary_item_id
2474 && iref.from_item_id != primary_item_id
2475 && iref.item_type == b"auxl"
2476 })
2477 .map(|iref| iref.from_item_id)
2478 // which has the alpha property
2479 .filter(|&item_id| item_properties.is_alpha(item_id));
2480 let alpha_item_id = alpha_item_ids.next();
2481 if alpha_item_ids.next().is_some() {
2482 return Status::MultipleAlpha.into();
2483 }
2484
2485 let premultiplied_alpha = alpha_item_id.is_some_and(|alpha_item_id| {
2486 item_references.iter().any(|iref| {
2487 iref.from_item_id == primary_item_id
2488 && iref.to_item_id == alpha_item_id
2489 && iref.item_type == b"prem"
2490 })
2491 });
2492
2493 (alpha_item_id, premultiplied_alpha)
2494 } else {
2495 (None, false)
2496 };
2497
2498 debug!("primary_item_id: {:?}", primary_item_id);
2499 debug!("alpha_item_id: {:?}", alpha_item_id);
2500 let mut primary_item = None;
2501 let mut alpha_item = None;
2502
2503 // store data or record location of relevant items
2504 for (item_id, loc) in iloc_items {
2505 let item = if Some(item_id) == primary_item_id {
2506 &mut primary_item
2507 } else if Some(item_id) == alpha_item_id {
2508 &mut alpha_item
2509 } else {
2510 continue;
2511 };
2512
2513 assert!(item.is_none());
2514
2515 // If our item is spread over multiple extents, we'll need to copy it
2516 // into a contiguous buffer. Otherwise, we can just store the extent
2517 // and return a pointer into the mdat/idat later to avoid the copy.
2518 if loc.extents.len() > 1 {
2519 *item = Some(AvifItem::with_inline_data(item_id))
2520 }
2521
2522 trace!(
2523 "{:?} construction_method: {:?}",
2524 item_id,
2525 loc.construction_method
2526 );
2527
2528 // Generalize the process of connecting items to their data; returns
2529 // true if the extent is successfully added to the AvifItem
2530 let mut find_and_add_to_item = |extent: &Extent, dat: &DataBox| -> Result<bool> {
2531 if let Some(extent_slice) = dat.get(extent) {
2532 match item {
2533 None => {
2534 trace!("Using IsobmffItem::Location");
2535 *item = Some(AvifItem {
2536 id: item_id,
2537 image_data: dat.location(extent),
2538 });
2539 }
2540 Some(AvifItem {
2541 image_data: IsobmffItem::Data(bytes),
2542 ..
2543 }) => {
2544 trace!("Using IsobmffItem::Data");
2545 // We could potentially optimize memory usage by trying to avoid reading
2546 // or storing dat boxes which aren't used by our API, but for now it seems
2547 // like unnecessary complexity
2548 bytes.extend_from_slice(extent_slice)?;
2549 }
2550 _ => unreachable!(),
2551 }
2552 return Ok(true);
2553 }
2554 Ok(false)
2555 };
2556
2557 match loc.construction_method {
2558 ConstructionMethod::File => {
2559 for extent in loc.extents {
2560 let mut found = false;
2561 // try to find an mdat which contains the extent
2562 for mdat in media_storage.iter() {
2563 if find_and_add_to_item(&extent, mdat)? {
2564 found = true;
2565 break;
2566 }
2567 }
2568
2569 if !found {
2570 return Status::IlocNotFound.into();
2571 }
2572 }
2573 }
2574 ConstructionMethod::Idat => {
2575 if let Some(idat) = &item_data_box {
2576 for extent in loc.extents {
2577 let found = find_and_add_to_item(&extent, idat)?;
2578 if !found {
2579 return Status::IlocNotFound.into();
2580 }
2581 }
2582 } else {
2583 return Status::IdatMissing.into();
2584 }
2585 }
2586 ConstructionMethod::Item => {
2587 fail_with_status_if(
2588 strictness != ParseStrictness::Permissive,
2589 Status::ConstructionMethod,
2590 )?;
2591 }
2592 }
2593
2594 assert!(item.is_some());
2595 }
2596
2597 if (primary_item_id.is_some() && primary_item.is_none())
2598 || (alpha_item_id.is_some() && alpha_item.is_none())
2599 {
2600 fail_with_status_if(strictness == ParseStrictness::Strict, Status::PitmNotFound)?;
2601 }
2602
2603 assert!(primary_item.is_none() || primary_item_id.is_some());
2604 assert!(alpha_item.is_none() || alpha_item_id.is_some());
2605
2606 if expected_image_type.has_primary() && primary_item_id.is_none() {
2607 fail_with_status_if(
2608 strictness != ParseStrictness::Permissive,
2609 Status::PitmMissing,
2610 )?;
2611 }
2612
2613 // Lacking a brand that requires them, it's fine for moov boxes to exist in
2614 // BMFF files; they're simply ignored
2615 if expected_image_type.has_sequence() && image_sequence.is_none() {
2616 fail_with_status_if(
2617 strictness != ParseStrictness::Permissive,
2618 Status::MoovMissing,
2619 )?;
2620 }
2621
2622 // Returns true iff `id` is `Some` and there is no corresponding property for it
2623 let missing_property_for = |id: Option<ItemId>, property: BoxType| -> bool {
2624 id.is_some_and(|id| {
2625 item_properties
2626 .get(id, property)
2627 .map_or(true, |opt| opt.is_none())
2628 })
2629 };
2630
2631 // Generalize the property checks so we can apply them to primary and alpha items
2632 let mut check_image_item = |item: &mut Option<AvifItem>| -> Result<()> {
2633 let item_id = item.as_ref().map(|item| item.id);
2634 let item_type = item_id.and_then(|item_id| {
2635 item_infos
2636 .iter()
2637 .find(|item_info| item_id == item_info.item_id)
2638 .map(|item_info| item_info.item_type)
2639 });
2640
2641 match item_type.map(u32::to_be_bytes).as_ref() {
2642 Some(b"av01") => {
2643 if missing_property_for(item_id, BoxType::AV1CodecConfigurationBox) {
2644 fail_with_status_if(
2645 strictness != ParseStrictness::Permissive,
2646 Status::Av1cMissing,
2647 )?;
2648 }
2649
2650 if missing_property_for(item_id, BoxType::PixelInformationBox) {
2651 // The requirement to include pixi is in the process of being changed
2652 // to allowing its omission to imply a default value. In anticipation
2653 // of that, only give an error in strict mode
2654 // See https://github.com/MPEGGroup/MIAF/issues/9
2655 fail_with_status_if(
2656 if cfg!(feature = "missing-pixi-permitted") {
2657 strictness == ParseStrictness::Strict
2658 } else {
2659 strictness != ParseStrictness::Permissive
2660 },
2661 Status::PixiMissing,
2662 )?;
2663 }
2664
2665 if missing_property_for(item_id, BoxType::ImageSpatialExtentsProperty) {
2666 fail_with_status_if(
2667 strictness != ParseStrictness::Permissive,
2668 Status::IspeMissing,
2669 )?;
2670 }
2671 }
2672 Some(b"grid") => {
2673 // TODO: https://github.com/mozilla/mp4parse-rust/issues/198
2674 unsupported_features.insert(Feature::Grid);
2675 *item = None;
2676 }
2677 Some(_other_type) => return Status::ImageItemType.into(),
2678 None => {
2679 if item.is_some() {
2680 return Status::ItemTypeMissing.into();
2681 }
2682 }
2683 }
2684
2685 if let Some(AvifItem { id, .. }) = item {
2686 if item_properties.forbidden_items.contains(id) {
2687 error!("Not processing item id {:?} since it is associated with essential, but unsupported properties", id);
2688 *item = None;
2689 }
2690 }
2691
2692 Ok(())
2693 };
2694
2695 check_image_item(&mut primary_item)?;
2696 check_image_item(&mut alpha_item)?;
2697
2698 Ok(AvifContext {
2699 strictness,
2700 media_storage,
2701 item_data_box,
2702 primary_item,
2703 alpha_item,
2704 premultiplied_alpha,
2705 item_properties,
2706 major_brand,
2707 sequence: image_sequence,
2708 unsupported_features,
2709 })
2710 }
2711
2712 /// Parse a metadata box in the context of an AVIF
2713 /// Currently requires the primary item to be an av01 item type and generates
2714 /// an error otherwise.
2715 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.1
2716 fn read_avif_meta<T: Read + Offset>(
2717 src: &mut BMFFBox<T>,
2718 strictness: ParseStrictness,
2719 unsupported_features: &mut UnsupportedFeatures,
2720 ) -> Result<AvifMeta> {
2721 let version = read_fullbox_version_no_flags(src)?;
2722
2723 if version != 0 {
2724 return Err(Error::Unsupported("unsupported meta version"));
2725 }
2726
2727 let mut read_handler_box = false;
2728 let mut primary_item_id = None;
2729 let mut item_infos = None;
2730 let mut iloc_items = None;
2731 let mut item_references = None;
2732 let mut item_properties = None;
2733 let mut item_data_box = None;
2734
2735 let mut iter = src.box_iter();
2736 while let Some(mut b) = iter.next_box()? {
2737 trace!("read_avif_meta parsing {:?} box", b.head.name);
2738
2739 if !read_handler_box && b.head.name != BoxType::HandlerBox {
2740 fail_with_status_if(
2741 strictness != ParseStrictness::Permissive,
2742 Status::HdlrNotFirst,
2743 )?;
2744 }
2745
2746 match b.head.name {
2747 BoxType::HandlerBox => {
2748 if read_handler_box {
2749 return Status::HdrlBadQuantity.into();
2750 }
2751 let HandlerBox { handler_type } = read_hdlr(&mut b, strictness)?;
2752 if handler_type != b"pict" {
2753 fail_with_status_if(
2754 strictness != ParseStrictness::Permissive,
2755 Status::HdlrTypeNotPict,
2756 )?;
2757 }
2758 read_handler_box = true;
2759 }
2760 BoxType::ItemInfoBox => {
2761 if item_infos.is_some() {
2762 return Status::IinfBadQuantity.into();
2763 }
2764 item_infos = Some(read_iinf(&mut b, strictness, unsupported_features)?);
2765 }
2766 BoxType::ItemLocationBox => {
2767 if iloc_items.is_some() {
2768 return Status::IlocBadQuantity.into();
2769 }
2770 iloc_items = Some(read_iloc(&mut b)?);
2771 }
2772 BoxType::PrimaryItemBox => {
2773 if primary_item_id.is_some() {
2774 return Status::PitmBadQuantity.into();
2775 }
2776 primary_item_id = Some(read_pitm(&mut b)?);
2777 }
2778 BoxType::ItemReferenceBox => {
2779 if item_references.is_some() {
2780 return Status::IrefBadQuantity.into();
2781 }
2782 item_references = Some(read_iref(&mut b)?);
2783 }
2784 BoxType::ItemPropertiesBox => {
2785 if item_properties.is_some() {
2786 return Status::IprpBadQuantity.into();
2787 }
2788 item_properties = Some(read_iprp(
2789 &mut b,
2790 MIF1_BRAND,
2791 strictness,
2792 unsupported_features,
2793 )?);
2794 }
2795 BoxType::ItemDataBox => {
2796 if item_data_box.is_some() {
2797 return Status::IdatBadQuantity.into();
2798 }
2799 let data = b.read_into_try_vec()?;
2800 item_data_box = Some(DataBox::from_idat(data));
2801 }
2802 _ => skip_box_content(&mut b)?,
2803 }
2804
2805 check_parser_state!(b.content);
2806 }
2807
2808 Ok(AvifMeta {
2809 item_properties: item_properties.unwrap_or_default(),
2810 item_references: item_references.unwrap_or_default(),
2811 primary_item_id,
2812 item_infos: item_infos.unwrap_or_default(),
2813 iloc_items: iloc_items.unwrap_or_default(),
2814 item_data_box,
2815 })
2816 }
2817
2818 /// Parse a Primary Item Box
2819 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.4
2820 fn read_pitm<T: Read>(src: &mut BMFFBox<T>) -> Result<ItemId> {
2821 let version = read_fullbox_version_no_flags(src)?;
2822
2823 let item_id = ItemId(match version {
2824 0 => be_u16(src)?.into(),
2825 1 => be_u32(src)?,
2826 _ => return Err(Error::Unsupported("unsupported pitm version")),
2827 });
2828
2829 Ok(item_id)
2830 }
2831
2832 /// Parse an Item Information Box
2833 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.6
2834 fn read_iinf<T: Read>(
2835 src: &mut BMFFBox<T>,
2836 strictness: ParseStrictness,
2837 unsupported_features: &mut UnsupportedFeatures,
2838 ) -> Result<TryVec<ItemInfoEntry>> {
2839 let version = read_fullbox_version_no_flags(src)?;
2840
2841 match version {
2842 0 | 1 => (),
2843 _ => return Err(Error::Unsupported("unsupported iinf version")),
2844 }
2845
2846 let entry_count = if version == 0 {
2847 be_u16(src)?.to_usize()
2848 } else {
2849 be_u32(src)?.to_usize()
2850 };
2851 let mut item_infos = TryVec::with_capacity(entry_count)?;
2852
2853 let mut iter = src.box_iter();
2854 while let Some(mut b) = iter.next_box()? {
2855 if b.head.name != BoxType::ItemInfoEntry {
2856 return Status::IinfBadChild.into();
2857 }
2858
2859 if let Some(infe) = read_infe(&mut b, strictness, unsupported_features)? {
2860 item_infos.push(infe)?;
2861 }
2862
2863 check_parser_state!(b.content);
2864 }
2865
2866 Ok(item_infos)
2867 }
2868
2869 /// A simple wrapper to interpret a u32 as a 4-byte string in big-endian
2870 /// order without requiring any allocation.
2871 struct U32BE(u32);
2872
2873 impl std::fmt::Display for U32BE {
2874 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2875 match std::str::from_utf8(&self.0.to_be_bytes()) {
2876 Ok(s) => f.write_str(s),
2877 Err(_) => write!(f, "{:x?}", self.0),
2878 }
2879 }
2880 }
2881
2882 /// Parse an Item Info Entry
2883 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.6.2
2884 fn read_infe<T: Read>(
2885 src: &mut BMFFBox<T>,
2886 strictness: ParseStrictness,
2887 unsupported_features: &mut UnsupportedFeatures,
2888 ) -> Result<Option<ItemInfoEntry>> {
2889 let (version, flags) = read_fullbox_extra(src)?;
2890
2891 // According to the standard, it seems the flags field shall be 0, but at
2892 // least one sample AVIF image has a nonzero value.
2893 // See https://github.com/AOMediaCodec/av1-avif/issues/146
2894 if flags != 0 {
2895 fail_with_status_if(
2896 strictness == ParseStrictness::Strict,
2897 Status::InfeFlagsNonzero,
2898 )?;
2899 }
2900
2901 // mif1 brand (see HEIF (ISO 23008-12:2017) § 10.2.1) only requires v2 and 3
2902 let item_id = ItemId(match version {
2903 2 => be_u16(src)?.into(),
2904 3 => be_u32(src)?,
2905 _ => return Err(Error::Unsupported("unsupported version in 'infe' box")),
2906 });
2907
2908 let item_protection_index = be_u16(src)?;
2909
2910 let item_type = be_u32(src)?;
2911 debug!("infe {:?} item_type: {}", item_id, U32BE(item_type));
2912
2913 // There are some additional fields here, but they're not of interest to us
2914 skip_box_remain(src)?;
2915
2916 if item_protection_index != 0 {
2917 unsupported_features.insert(Feature::Ipro);
2918 Ok(None)
2919 } else {
2920 Ok(Some(ItemInfoEntry { item_id, item_type }))
2921 }
2922 }
2923
2924 /// Parse an Item Reference Box
2925 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.12
2926 fn read_iref<T: Read>(src: &mut BMFFBox<T>) -> Result<TryVec<SingleItemTypeReferenceBox>> {
2927 let mut item_references = TryVec::new();
2928 let version = read_fullbox_version_no_flags(src)?;
2929 if version > 1 {
2930 return Err(Error::Unsupported("iref version"));
2931 }
2932
2933 let mut iter = src.box_iter();
2934 while let Some(mut b) = iter.next_box()? {
2935 trace!("read_iref parsing {:?} referenceType", b.head.name);
2936 let from_item_id = ItemId::read(&mut b, version)?;
2937 let reference_count = be_u16(&mut b)?;
2938 item_references.reserve(reference_count.to_usize())?;
2939 for _ in 0..reference_count {
2940 let to_item_id = ItemId::read(&mut b, version)?;
2941 if from_item_id == to_item_id {
2942 return Status::IrefRecursion.into();
2943 }
2944 item_references.push(SingleItemTypeReferenceBox {
2945 item_type: b.head.name.into(),
2946 from_item_id,
2947 to_item_id,
2948 })?;
2949 }
2950 check_parser_state!(b.content);
2951 }
2952
2953 trace!("read_iref -> {:#?}", item_references);
2954
2955 Ok(item_references)
2956 }
2957
2958 /// Parse an Item Properties Box
2959 ///
2960 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.14)
2961 ///
2962 /// Note: HEIF (ISO 23008-12:2017) § 9.3.1 also defines the `iprp` box and
2963 /// related types, but lacks additional requirements specified in 14496-12:2020.
2964 ///
2965 /// Note: Currently HEIF (ISO 23008-12:2017) § 6.5.5.1 specifies "At most one"
2966 /// `colr` box per item, but this is being amended in [DIS 23008-12](https://www.iso.org/standard/83650.html).
2967 /// The new text is likely to be "At most one for a given value of `colour_type`",
2968 /// so this implementation adheres to that language for forward compatibility.
2969 fn read_iprp<T: Read>(
2970 src: &mut BMFFBox<T>,
2971 brand: FourCC,
2972 strictness: ParseStrictness,
2973 unsupported_features: &mut UnsupportedFeatures,
2974 ) -> Result<ItemPropertiesBox> {
2975 let mut iter = src.box_iter();
2976
2977 let properties = match iter.next_box()? {
2978 Some(mut b) if b.head.name == BoxType::ItemPropertyContainerBox => {
2979 read_ipco(&mut b, strictness)
2980 }
2981 Some(_) => Status::IprpBadChild.into(),
2982 None => Err(Error::UnexpectedEOF),
2983 }?;
2984
2985 let mut ipma_version_and_flag_values_seen = TryVec::with_capacity(1)?;
2986 let mut association_entries = TryVec::<ItemPropertyAssociationEntry>::new();
2987 let mut forbidden_items = TryVec::new();
2988
2989 while let Some(mut b) = iter.next_box()? {
2990 if b.head.name != BoxType::ItemPropertyAssociationBox {
2991 return Status::IprpBadChild.into();
2992 }
2993
2994 let (version, flags) = read_fullbox_extra(&mut b)?;
2995 if ipma_version_and_flag_values_seen.contains(&(version, flags)) {
2996 fail_with_status_if(
2997 strictness != ParseStrictness::Permissive,
2998 Status::IpmaBadQuantity,
2999 )?;
3000 }
3001 if flags != 0 && properties.len() <= 127 {
3002 fail_with_status_if(
3003 strictness == ParseStrictness::Strict,
3004 Status::IpmaFlagsNonzero,
3005 )?;
3006 }
3007 ipma_version_and_flag_values_seen.push((version, flags))?;
3008 for association_entry in read_ipma(&mut b, strictness, version, flags)? {
3009 if forbidden_items.contains(&association_entry.item_id) {
3010 warn!(
3011 "Skipping {:?} since the item referenced shall not be processed",
3012 association_entry
3013 );
3014 }
3015
3016 if let Some(previous_entry) = association_entries
3017 .iter()
3018 .find(|e| association_entry.item_id == e.item_id)
3019 {
3020 error!(
3021 "Duplicate ipma entries for item_id\n1: {:?}\n2: {:?}",
3022 previous_entry, association_entry
3023 );
3024 // It's technically possible to make sense of this situation by merging ipma
3025 // boxes, but this is a "shall" requirement, so we'd only do it in
3026 // ParseStrictness::Permissive mode, and this hasn't shown up in the wild
3027 return Status::IpmaDuplicateItemId.into();
3028 }
3029
3030 const TRANSFORM_ORDER: &[BoxType] = &[
3031 BoxType::ImageSpatialExtentsProperty,
3032 BoxType::CleanApertureBox,
3033 BoxType::ImageRotation,
3034 BoxType::ImageMirror,
3035 ];
3036 let mut prev_transform_index = None;
3037 // Realistically, there should only ever be 1 nclx and 1 icc
3038 let mut colour_type_indexes: TryHashMap<FourCC, PropertyIndex> =
3039 TryHashMap::with_capacity(2)?;
3040
3041 for a in &association_entry.associations {
3042 if a.property_index == PropertyIndex(0) {
3043 if a.essential {
3044 fail_with_status_if(
3045 strictness != ParseStrictness::Permissive,
3046 Status::IpmaIndexZeroNoEssential,
3047 )?;
3048 }
3049 continue;
3050 }
3051
3052 if let Some(property) = properties.get(&a.property_index) {
3053 assert!(brand == MIF1_BRAND);
3054
3055 let feature = Feature::try_from(property);
3056 let property_supported = match feature {
3057 Ok(feature) => {
3058 if feature.supported() {
3059 true
3060 } else {
3061 unsupported_features.insert(feature);
3062 false
3063 }
3064 }
3065 Err(_) => false,
3066 };
3067
3068 if !property_supported {
3069 if a.essential && strictness != ParseStrictness::Permissive {
3070 error!("Unsupported essential property {:?}", property);
3071 forbidden_items.push(association_entry.item_id)?;
3072 } else {
3073 debug!(
3074 "Ignoring unknown {} property {:?}",
3075 if a.essential {
3076 "essential"
3077 } else {
3078 "non-essential"
3079 },
3080 property
3081 );
3082 }
3083 }
3084
3085 // Check additional requirements on specific properties
3086 match property {
3087 ItemProperty::AV1Config(_)
3088 | ItemProperty::CleanAperture
3089 | ItemProperty::Mirroring(_)
3090 | ItemProperty::Rotation(_) => {
3091 if !a.essential {
3092 warn!("{:?} is missing required 'essential' bit", property);
3093 // This is a "shall", but it is likely to change, so only
3094 // fail if using strict parsing.
3095 // See https://github.com/mozilla/mp4parse-rust/issues/284
3096 fail_with_status_if(
3097 strictness == ParseStrictness::Strict,
3098 Status::TxformNoEssential,
3099 )?;
3100 }
3101 }
3102
3103 // NOTE: this is contrary to the published specification; see doc comment
3104 // at the beginning of this function for more details
3105 ItemProperty::Colour(colr) => {
3106 let colour_type = colr.colour_type();
3107 if let Some(prev_colr_index) = colour_type_indexes.get(&colour_type) {
3108 warn!(
3109 "Multiple '{}' type colr associations with {:?}: {:?} and {:?}",
3110 colour_type,
3111 association_entry.item_id,
3112 a.property_index,
3113 prev_colr_index
3114 );
3115 fail_with_status_if(
3116 strictness != ParseStrictness::Permissive,
3117 Status::ColrBadQuantity,
3118 )?;
3119 } else {
3120 colour_type_indexes.insert(colour_type, a.property_index)?;
3121 }
3122 }
3123
3124 // The following properties are unsupported, but we still enforce that
3125 // they've been correctly marked as essential or not.
3126 ItemProperty::LayeredImageIndexing => {
3127 assert!(feature.is_ok() && unsupported_features.contains(feature?));
3128 if a.essential {
3129 fail_with_status_if(
3130 strictness != ParseStrictness::Permissive,
3131 Status::A1lxEssential,
3132 )?;
3133 }
3134 }
3135
3136 ItemProperty::LayerSelection => {
3137 assert!(feature.is_ok() && unsupported_features.contains(feature?));
3138 if a.essential {
3139 assert!(
3140 forbidden_items.contains(&association_entry.item_id)
3141 || strictness == ParseStrictness::Permissive
3142 );
3143 } else {
3144 fail_with_status_if(
3145 strictness != ParseStrictness::Permissive,
3146 Status::LselNoEssential,
3147 )?;
3148 }
3149 }
3150
3151 ItemProperty::OperatingPointSelector => {
3152 assert!(feature.is_ok() && unsupported_features.contains(feature?));
3153 if a.essential {
3154 assert!(
3155 forbidden_items.contains(&association_entry.item_id)
3156 || strictness == ParseStrictness::Permissive
3157 );
3158 } else {
3159 fail_with_status_if(
3160 strictness != ParseStrictness::Permissive,
3161 Status::A1opNoEssential,
3162 )?;
3163 }
3164 }
3165
3166 other_property => {
3167 trace!("No additional checks for {:?}", other_property);
3168 }
3169 }
3170
3171 if let Some(transform_index) = TRANSFORM_ORDER
3172 .iter()
3173 .position(|t| *t == BoxType::from(property))
3174 {
3175 if let Some(prev) = prev_transform_index {
3176 if prev >= transform_index {
3177 error!(
3178 "Invalid property order: {:?} after {:?}",
3179 TRANSFORM_ORDER[transform_index], TRANSFORM_ORDER[prev]
3180 );
3181 fail_with_status_if(
3182 strictness != ParseStrictness::Permissive,
3183 if TRANSFORM_ORDER[transform_index]
3184 == BoxType::ImageSpatialExtentsProperty
3185 {
3186 Status::TxformBeforeIspe
3187 } else {
3188 Status::TxformOrder
3189 },
3190 )?;
3191 }
3192 }
3193 prev_transform_index = Some(transform_index);
3194 }
3195 } else {
3196 error!(
3197 "Missing property at {:?} for {:?}",
3198 a.property_index, association_entry.item_id
3199 );
3200 fail_with_status_if(
3201 strictness != ParseStrictness::Permissive,
3202 Status::IpmaBadIndex,
3203 )?;
3204 }
3205 }
3206 association_entries.push(association_entry)?
3207 }
3208
3209 check_parser_state!(b.content);
3210 }
3211
3212 let iprp = ItemPropertiesBox {
3213 properties,
3214 association_entries,
3215 forbidden_items,
3216 };
3217 trace!("read_iprp -> {:#?}", iprp);
3218 Ok(iprp)
3219 }
3220
3221 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.14.1
3222 /// Variants with no associated data are recognized but not necessarily supported.
3223 /// See [`Feature`] to determine support.
3224 #[derive(Debug)]
3225 pub enum ItemProperty {
3226 AuxiliaryType(AuxiliaryTypeProperty),
3227 AV1Config(AV1ConfigBox),
3228 Channels(PixelInformation),
3229 CleanAperture,
3230 Colour(ColourInformation),
3231 ImageSpatialExtents(ImageSpatialExtentsProperty),
3232 LayeredImageIndexing,
3233 LayerSelection,
3234 Mirroring(ImageMirror),
3235 OperatingPointSelector,
3236 PixelAspectRatio(PixelAspectRatio),
3237 Rotation(ImageRotation),
3238 /// Necessary to validate property indices in read_iprp
3239 Unsupported(BoxType),
3240 }
3241
3242 impl From<&ItemProperty> for BoxType {
3243 fn from(item_property: &ItemProperty) -> Self {
3244 match item_property {
3245 ItemProperty::AuxiliaryType(_) => BoxType::AuxiliaryTypeProperty,
3246 ItemProperty::AV1Config(_) => BoxType::AV1CodecConfigurationBox,
3247 ItemProperty::CleanAperture => BoxType::CleanApertureBox,
3248 ItemProperty::Colour(_) => BoxType::ColourInformationBox,
3249 ItemProperty::LayeredImageIndexing => BoxType::AV1LayeredImageIndexingProperty,
3250 ItemProperty::LayerSelection => BoxType::LayerSelectorProperty,
3251 ItemProperty::Mirroring(_) => BoxType::ImageMirror,
3252 ItemProperty::OperatingPointSelector => BoxType::OperatingPointSelectorProperty,
3253 ItemProperty::PixelAspectRatio(_) => BoxType::PixelAspectRatioBox,
3254 ItemProperty::Rotation(_) => BoxType::ImageRotation,
3255 ItemProperty::ImageSpatialExtents(_) => BoxType::ImageSpatialExtentsProperty,
3256 ItemProperty::Channels(_) => BoxType::PixelInformationBox,
3257 ItemProperty::Unsupported(box_type) => *box_type,
3258 }
3259 }
3260 }
3261
3262 #[derive(Debug)]
3263 struct ItemPropertyAssociationEntry {
3264 item_id: ItemId,
3265 associations: TryVec<Association>,
3266 }
3267
3268 /// For storing ItemPropertyAssociation data
3269 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.14.1
3270 #[derive(Debug)]
3271 struct Association {
3272 essential: bool,
3273 property_index: PropertyIndex,
3274 }
3275
3276 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.14.1
3277 ///
3278 /// The properties themselves are stored in `properties`, but the items they're
3279 /// associated with are stored in `association_entries`. It's necessary to
3280 /// maintain this indirection because multiple items can reference the same
3281 /// property. For example, both the primary item and alpha item can share the
3282 /// same [`ImageSpatialExtentsProperty`].
3283 #[derive(Debug, Default)]
3284 pub struct ItemPropertiesBox {
3285 /// `ItemPropertyContainerBox property_container` in the spec
3286 properties: TryHashMap<PropertyIndex, ItemProperty>,
3287 /// `ItemPropertyAssociationBox association[]` in the spec
3288 association_entries: TryVec<ItemPropertyAssociationEntry>,
3289 /// Items that shall not be processed due to unsupported properties that
3290 /// have been marked essential.
3291 /// See HEIF (ISO/IEC 23008-12:2017) § 9.3.1
3292 forbidden_items: TryVec<ItemId>,
3293 }
3294
3295 impl ItemPropertiesBox {
3296 /// For displayable images `av1C`, `pixi` and `ispe` are mandatory, `colr`
3297 /// is typically included too, so we might as well use an even power of 2.
3298 const MIN_PROPERTIES: usize = 4;
3299
3300 fn is_alpha(&self, item_id: ItemId) -> bool {
3301 match self.get(item_id, BoxType::AuxiliaryTypeProperty) {
3302 Ok(Some(ItemProperty::AuxiliaryType(urn))) => {
3303 urn.aux_type.as_slice() == "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha".as_bytes()
3304 }
3305 Ok(Some(other_property)) => panic!("property key mismatch: {:?}", other_property),
3306 Ok(None) => false,
3307 Err(e) => {
3308 error!(
3309 "is_alpha: Error checking AuxiliaryTypeProperty ({}), returning false",
3310 e
3311 );
3312 false
3313 }
3314 }
3315 }
3316
3317 fn get(&self, item_id: ItemId, property_type: BoxType) -> Result<Option<&ItemProperty>> {
3318 match self
3319 .get_multiple(item_id, |prop| BoxType::from(prop) == property_type)?
3320 .as_slice()
3321 {
3322 &[] => Ok(None),
3323 &[single_value] => Ok(Some(single_value)),
3324 multiple_values => {
3325 error!(
3326 "Multiple values for {:?}: {:?}",
3327 property_type, multiple_values
3328 );
3329 // TODO: add test
3330 Status::IprpConflict.into()
3331 }
3332 }
3333 }
3334
3335 fn get_multiple(
3336 &self,
3337 item_id: ItemId,
3338 filter: impl Fn(&ItemProperty) -> bool,
3339 ) -> Result<TryVec<&ItemProperty>> {
3340 let mut values = TryVec::new();
3341 for entry in &self.association_entries {
3342 for a in &entry.associations {
3343 if entry.item_id == item_id {
3344 match self.properties.get(&a.property_index) {
3345 Some(ItemProperty::Unsupported(_)) => {}
3346 Some(property) if filter(property) => values.push(property)?,
3347 _ => {}
3348 }
3349 }
3350 }
3351 }
3352
3353 Ok(values)
3354 }
3355 }
3356
3357 /// An upper bound which can be used to check overflow at compile time
3358 trait UpperBounded {
3359 const MAX: u64;
3360 }
3361
3362 /// Implement type $name as a newtype wrapper around an unsigned int which
3363 /// implements the UpperBounded trait.
3364 macro_rules! impl_bounded {
3365 ( $name:ident, $inner:ty ) => {
3366 #[derive(Clone, Copy)]
3367 pub struct $name($inner);
3368
3369 impl $name {
3370 pub const fn new(n: $inner) -> Self {
3371 Self(n)
3372 }
3373
3374 #[allow(dead_code)]
3375 pub fn get(self) -> $inner {
3376 self.0
3377 }
3378 }
3379
3380 impl UpperBounded for $name {
3381 const MAX: u64 = <$inner>::MAX as u64;
3382 }
3383 };
3384 }
3385
3386 /// Implement type $name as a type representing the product of two unsigned ints
3387 /// which implements the UpperBounded trait.
3388 macro_rules! impl_bounded_product {
3389 ( $name:ident, $multiplier:ty, $multiplicand:ty, $inner:ty) => {
3390 #[derive(Clone, Copy)]
3391 pub struct $name($inner);
3392
3393 impl $name {
3394 pub fn new(value: $inner) -> Self {
3395 assert!(value <= Self::MAX);
3396 Self(value)
3397 }
3398
3399 pub fn get(self) -> $inner {
3400 self.0
3401 }
3402 }
3403
3404 impl UpperBounded for $name {
3405 const MAX: u64 = <$multiplier>::MAX * <$multiplicand>::MAX;
3406 }
3407 };
3408 }
3409
3410 mod bounded_uints {
3411 use crate::UpperBounded;
3412
3413 impl_bounded!(U8, u8);
3414 impl_bounded!(U16, u16);
3415 impl_bounded!(U32, u32);
3416 impl_bounded!(U64, u64);
3417
3418 impl_bounded_product!(U32MulU8, U32, U8, u64);
3419 impl_bounded_product!(U32MulU16, U32, U16, u64);
3420
3421 impl UpperBounded for std::num::NonZeroU8 {
3422 const MAX: u64 = u8::MAX as u64;
3423 }
3424 }
3425
3426 use crate::bounded_uints::*;
3427
3428 /// Implement the multiplication operator for $lhs * $rhs giving $output, which
3429 /// is internally represented as $inner. The operation is statically checked
3430 /// to ensure the product won't overflow $inner, nor exceed <$output>::MAX.
3431 macro_rules! impl_mul {
3432 ( ($lhs:ty , $rhs:ty) => ($output:ty, $inner:ty) ) => {
3433 impl std::ops::Mul<$rhs> for $lhs {
3434 type Output = $output;
3435
3436 fn mul(self, rhs: $rhs) -> Self::Output {
3437 static_assertions::const_assert!(
3438 <$output as UpperBounded>::MAX <= <$inner>::MAX as u64
3439 );
3440 static_assertions::const_assert!(
3441 <$lhs as UpperBounded>::MAX * <$rhs as UpperBounded>::MAX
3442 <= <$output as UpperBounded>::MAX
3443 );
3444
3445 let lhs: $inner = self.get().into();
3446 let rhs: $inner = rhs.get().into();
3447 Self::Output::new(lhs.checked_mul(rhs).expect("infallible"))
3448 }
3449 }
3450 };
3451 }
3452
3453 impl_mul!((U8, std::num::NonZeroU8) => (U16, u16));
3454 impl_mul!((U32, std::num::NonZeroU8) => (U32MulU8, u64));
3455 impl_mul!((U32, U16) => (U32MulU16, u64));
3456
3457 impl std::ops::Add<U32MulU16> for U32MulU8 {
3458 type Output = U64;
3459
3460 fn add(self, rhs: U32MulU16) -> Self::Output {
3461 static_assertions::const_assert!(U32MulU8::MAX + U32MulU16::MAX < U64::MAX);
3462 let lhs: u64 = self.get();
3463 let rhs: u64 = rhs.get();
3464 Self::Output::new(lhs.checked_add(rhs).expect("infallible"))
3465 }
3466 }
3467
3468 const MAX_IPMA_ASSOCIATION_COUNT: U8 = U8::new(u8::MAX);
3469
3470 /// After reading only the `entry_count` field of an ipma box, we can check its
3471 /// basic validity and calculate (assuming validity) the number of associations
3472 /// which will be contained (allowing preallocation of the storage).
3473 /// All the arithmetic is compile-time verified to not overflow via supporting
3474 /// types implementing the UpperBounded trait. Types are declared explicitly to
3475 /// show there isn't any accidental inference to primitive types.
3476 ///
3477 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.14.1
3478 fn calculate_ipma_total_associations(
3479 version: u8,
3480 bytes_left: u64,
3481 entry_count: U32,
3482 num_association_bytes: std::num::NonZeroU8,
3483 ) -> Result<usize> {
3484 let min_entry_bytes =
3485 std::num::NonZeroU8::new(1 /* association_count */ + if version == 0 { 2 } else { 4 })
3486 .unwrap();
3487
3488 let total_non_association_bytes: U32MulU8 = entry_count * min_entry_bytes;
3489 let total_association_bytes: u64 =
3490 if let Some(difference) = bytes_left.checked_sub(total_non_association_bytes.get()) {
3491 // All the storage for the `essential` and `property_index` parts (assuming a valid ipma box size)
3492 difference
3493 } else {
3494 return Status::IpmaTooSmall.into();
3495 };
3496
3497 let max_association_bytes_per_entry: U16 = MAX_IPMA_ASSOCIATION_COUNT * num_association_bytes;
3498 let max_total_association_bytes: U32MulU16 = entry_count * max_association_bytes_per_entry;
3499 let max_bytes_left: U64 = total_non_association_bytes + max_total_association_bytes;
3500
3501 if bytes_left > max_bytes_left.get() {
3502 return Status::IpmaTooBig.into();
3503 }
3504
3505 let total_associations: u64 = total_association_bytes / u64::from(num_association_bytes.get());
3506
3507 Ok(total_associations.try_into()?)
3508 }
3509
3510 /// Parse an ItemPropertyAssociation box
3511 ///
3512 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.14.1
3513 fn read_ipma<T: Read>(
3514 src: &mut BMFFBox<T>,
3515 strictness: ParseStrictness,
3516 version: u8,
3517 flags: u32,
3518 ) -> Result<TryVec<ItemPropertyAssociationEntry>> {
3519 let entry_count = be_u32(src)?;
3520 let num_association_bytes =
3521 std::num::NonZeroU8::new(if flags & 1 == 1 { 2 } else { 1 }).unwrap();
3522
3523 let total_associations = calculate_ipma_total_associations(
3524 version,
3525 src.bytes_left(),
3526 U32::new(entry_count),
3527 num_association_bytes,
3528 )?;
3529 // Assuming most items will have at least `MIN_PROPERTIES` and knowing the
3530 // total number of item -> property associations (`total_associations`),
3531 // we can provide a good estimate for how many elements we'll need in this
3532 // vector, even though we don't know precisely how many items there will be
3533 // properties for.
3534 let mut entries = TryVec::<ItemPropertyAssociationEntry>::with_capacity(
3535 total_associations / ItemPropertiesBox::MIN_PROPERTIES,
3536 )?;
3537
3538 for _ in 0..entry_count {
3539 let item_id = ItemId::read(src, version)?;
3540
3541 if let Some(previous_association) = entries.last() {
3542 #[allow(clippy::comparison_chain)]
3543 if previous_association.item_id > item_id {
3544 return Status::IpmaBadItemOrder.into();
3545 } else if previous_association.item_id == item_id {
3546 return Status::IpmaDuplicateItemId.into();
3547 }
3548 }
3549
3550 let association_count = src.read_u8()?;
3551 let mut associations = TryVec::with_capacity(association_count.to_usize())?;
3552 for _ in 0..association_count {
3553 let association = src
3554 .take(num_association_bytes.get().into())
3555 .read_into_try_vec()?;
3556 let mut association = BitReader::new(association.as_slice());
3557 let essential = association.read_bool()?;
3558 let property_index =
3559 PropertyIndex(association.read_u16(association.remaining().try_into()?)?);
3560 associations.push(Association {
3561 essential,
3562 property_index,
3563 })?;
3564 }
3565
3566 entries.push(ItemPropertyAssociationEntry {
3567 item_id,
3568 associations,
3569 })?;
3570 }
3571
3572 check_parser_state!(src.content);
3573
3574 if version != 0 {
3575 if let Some(ItemPropertyAssociationEntry {
3576 item_id: max_item_id,
3577 ..
3578 }) = entries.last()
3579 {
3580 if *max_item_id <= ItemId(u16::MAX.into()) {
3581 fail_with_status_if(
3582 strictness == ParseStrictness::Strict,
3583 Status::IpmaBadVersion,
3584 )?;
3585 }
3586 }
3587 }
3588
3589 trace!("read_ipma -> {:#?}", entries);
3590
3591 Ok(entries)
3592 }
3593
3594 /// Parse an ItemPropertyContainerBox
3595 ///
3596 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.14.1
3597 fn read_ipco<T: Read>(
3598 src: &mut BMFFBox<T>,
3599 strictness: ParseStrictness,
3600 ) -> Result<TryHashMap<PropertyIndex, ItemProperty>> {
3601 let mut properties = TryHashMap::with_capacity(ItemPropertiesBox::MIN_PROPERTIES)?;
3602
3603 let mut index = PropertyIndex(1); // ipma uses 1-based indexing
3604 let mut iter = src.box_iter();
3605 while let Some(mut b) = iter.next_box()? {
3606 let property = match b.head.name {
3607 BoxType::AuxiliaryTypeProperty => ItemProperty::AuxiliaryType(read_auxc(&mut b)?),
3608 BoxType::AV1CodecConfigurationBox => ItemProperty::AV1Config(read_av1c(&mut b)?),
3609 BoxType::ColourInformationBox => ItemProperty::Colour(read_colr(&mut b, strictness)?),
3610 BoxType::ImageMirror => ItemProperty::Mirroring(read_imir(&mut b)?),
3611 BoxType::ImageRotation => ItemProperty::Rotation(read_irot(&mut b)?),
3612 BoxType::ImageSpatialExtentsProperty => {
3613 ItemProperty::ImageSpatialExtents(read_ispe(&mut b)?)
3614 }
3615 BoxType::PixelAspectRatioBox => ItemProperty::PixelAspectRatio(read_pasp(&mut b)?),
3616 BoxType::PixelInformationBox => ItemProperty::Channels(read_pixi(&mut b)?),
3617
3618 other_box_type => {
3619 // Even if we didn't do anything with other property types, we still store
3620 // a record at the index to identify invalid indices in ipma boxes
3621 skip_box_remain(&mut b)?;
3622 let item_property = match other_box_type {
3623 BoxType::AV1LayeredImageIndexingProperty => ItemProperty::LayeredImageIndexing,
3624 BoxType::CleanApertureBox => ItemProperty::CleanAperture,
3625 BoxType::LayerSelectorProperty => ItemProperty::LayerSelection,
3626 BoxType::OperatingPointSelectorProperty => ItemProperty::OperatingPointSelector,
3627 _ => {
3628 warn!("No ItemProperty variant for {:?}", other_box_type);
3629 ItemProperty::Unsupported(other_box_type)
3630 }
3631 };
3632 debug!("Storing empty record {:?}", item_property);
3633 item_property
3634 }
3635 };
3636 properties.insert(index, property)?;
3637
3638 index = PropertyIndex(
3639 index
3640 .0
3641 .checked_add(1) // must include ignored properties to have correct indexes
3642 .ok_or_else(|| Error::from(Status::IpcoIndexOverflow))?,
3643 );
3644
3645 check_parser_state!(b.content);
3646 }
3647
3648 Ok(properties)
3649 }
3650
3651 #[repr(C)]
3652 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
3653 pub struct ImageSpatialExtentsProperty {
3654 image_width: u32,
3655 image_height: u32,
3656 }
3657
3658 /// Parse image spatial extents property
3659 ///
3660 /// See HEIF (ISO 23008-12:2017) § 6.5.3.1
3661 fn read_ispe<T: Read>(src: &mut BMFFBox<T>) -> Result<ImageSpatialExtentsProperty> {
3662 if read_fullbox_version_no_flags(src)? != 0 {
3663 return Err(Error::Unsupported("ispe version"));
3664 }
3665
3666 let image_width = be_u32(src)?;
3667 let image_height = be_u32(src)?;
3668
3669 Ok(ImageSpatialExtentsProperty {
3670 image_width,
3671 image_height,
3672 })
3673 }
3674
3675 #[repr(C)]
3676 #[derive(Debug)]
3677 pub struct PixelAspectRatio {
3678 h_spacing: u32,
3679 v_spacing: u32,
3680 }
3681
3682 /// Parse pixel aspect ratio property
3683 ///
3684 /// See HEIF (ISO 23008-12:2017) § 6.5.4.1
3685 /// See ISOBMFF (ISO 14496-12:2020) § 12.1.4.2
3686 fn read_pasp<T: Read>(src: &mut BMFFBox<T>) -> Result<PixelAspectRatio> {
3687 let h_spacing = be_u32(src)?;
3688 let v_spacing = be_u32(src)?;
3689
3690 Ok(PixelAspectRatio {
3691 h_spacing,
3692 v_spacing,
3693 })
3694 }
3695
3696 #[derive(Debug)]
3697 pub struct PixelInformation {
3698 bits_per_channel: TryVec<u8>,
3699 }
3700
3701 /// Parse pixel information
3702 /// See HEIF (ISO 23008-12:2017) § 6.5.6
3703 fn read_pixi<T: Read>(src: &mut BMFFBox<T>) -> Result<PixelInformation> {
3704 let version = read_fullbox_version_no_flags(src)?;
3705 if version != 0 {
3706 return Err(Error::Unsupported("pixi version"));
3707 }
3708
3709 let num_channels = src.read_u8()?;
3710 let mut bits_per_channel = TryVec::with_capacity(num_channels.to_usize())?;
3711 let num_channels_read = src.try_read_to_end(&mut bits_per_channel)?;
3712
3713 if u8::try_from(num_channels_read)? != num_channels {
3714 return Status::PixiBadChannelCount.into();
3715 }
3716
3717 check_parser_state!(src.content);
3718 Ok(PixelInformation { bits_per_channel })
3719 }
3720
3721 /// Despite [Rec. ITU-T H.273] (12/2016) defining the CICP fields as having a
3722 /// range of 0-255, and only a small fraction of those values being used,
3723 /// ISOBMFF (ISO 14496-12:2020) § 12.1.5 defines them as 16-bit values in the
3724 /// `colr` box. Since we have no use for the additional range, and it would
3725 /// complicate matters later, we fallibly convert before storing the input.
3726 ///
3727 /// [Rec. ITU-T H.273]: https://www.itu.int/rec/T-REC-H.273-201612-I/en
3728 #[repr(C)]
3729 #[derive(Debug)]
3730 pub struct NclxColourInformation {
3731 colour_primaries: u8,
3732 transfer_characteristics: u8,
3733 matrix_coefficients: u8,
3734 full_range_flag: bool,
3735 }
3736
3737 /// The raw bytes of the ICC profile
3738 #[repr(C)]
3739 pub struct IccColourInformation {
3740 bytes: TryVec<u8>,
3741 }
3742
3743 impl fmt::Debug for IccColourInformation {
3744 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3745 f.debug_struct("IccColourInformation")
3746 .field("data", &format_args!("{} bytes", self.bytes.len()))
3747 .finish()
3748 }
3749 }
3750
3751 #[repr(C)]
3752 #[derive(Debug)]
3753 pub enum ColourInformation {
3754 Nclx(NclxColourInformation),
3755 Icc(IccColourInformation, FourCC),
3756 }
3757
3758 impl ColourInformation {
3759 fn colour_type(&self) -> FourCC {
3760 match self {
3761 Self::Nclx(_) => FourCC::from(*b"nclx"),
3762 Self::Icc(_, colour_type) => colour_type.clone(),
3763 }
3764 }
3765 }
3766
3767 /// Parse colour information
3768 /// See ISOBMFF (ISO 14496-12:2020) § 12.1.5
3769 fn read_colr<T: Read>(
3770 src: &mut BMFFBox<T>,
3771 strictness: ParseStrictness,
3772 ) -> Result<ColourInformation> {
3773 let colour_type = be_u32(src)?.to_be_bytes();
3774
3775 match &colour_type {
3776 b"nclx" => {
3777 const NUM_RESERVED_BITS: u8 = 7;
3778 let colour_primaries = be_u16(src)?.try_into()?;
3779 let transfer_characteristics = be_u16(src)?.try_into()?;
3780 let matrix_coefficients = be_u16(src)?.try_into()?;
3781 let bytes = src.read_into_try_vec()?;
3782 let mut bit_reader = BitReader::new(&bytes);
3783 let full_range_flag = bit_reader.read_bool()?;
3784 if bit_reader.remaining() != NUM_RESERVED_BITS.into() {
3785 error!(
3786 "read_colr expected {} reserved bits, found {}",
3787 NUM_RESERVED_BITS,
3788 bit_reader.remaining()
3789 );
3790 return Status::ColrBadSize.into();
3791 }
3792 if bit_reader.read_u8(NUM_RESERVED_BITS)? != 0 {
3793 fail_with_status_if(
3794 strictness != ParseStrictness::Permissive,
3795 Status::ColrReservedNonzero,
3796 )?;
3797 }
3798
3799 Ok(ColourInformation::Nclx(NclxColourInformation {
3800 colour_primaries,
3801 transfer_characteristics,
3802 matrix_coefficients,
3803 full_range_flag,
3804 }))
3805 }
3806 b"rICC" | b"prof" => Ok(ColourInformation::Icc(
3807 IccColourInformation {
3808 bytes: src.read_into_try_vec()?,
3809 },
3810 FourCC::from(colour_type),
3811 )),
3812 _ => {
3813 error!("read_colr colour_type: {:?}", colour_type);
3814 Status::ColrBadType.into()
3815 }
3816 }
3817 }
3818
3819 #[repr(C)]
3820 #[derive(Clone, Copy, Debug)]
3821 /// Rotation in the positive (that is, anticlockwise) direction
3822 /// Visualized in terms of starting with (⥠) UPWARDS HARPOON WITH BARB LEFT FROM BAR
3823 /// similar to a DIGIT ONE (1)
3824 pub enum ImageRotation {
3825 /// ⥠ UPWARDS HARPOON WITH BARB LEFT FROM BAR
3826 D0,
3827 /// ⥞ LEFTWARDS HARPOON WITH BARB DOWN FROM BAR
3828 D90,
3829 /// ⥝ DOWNWARDS HARPOON WITH BARB RIGHT FROM BAR
3830 D180,
3831 /// ⥛ RIGHTWARDS HARPOON WITH BARB UP FROM BAR
3832 D270,
3833 }
3834
3835 /// Parse image rotation box
3836 /// See HEIF (ISO 23008-12:2017) § 6.5.10
3837 fn read_irot<T: Read>(src: &mut BMFFBox<T>) -> Result<ImageRotation> {
3838 let irot = src.read_into_try_vec()?;
3839 let mut irot = BitReader::new(&irot);
3840 let _reserved = irot.read_u8(6)?;
3841 let image_rotation = match irot.read_u8(2)? {
3842 0 => ImageRotation::D0,
3843 1 => ImageRotation::D90,
3844 2 => ImageRotation::D180,
3845 3 => ImageRotation::D270,
3846 _ => unreachable!(),
3847 };
3848
3849 check_parser_state!(src.content);
3850
3851 Ok(image_rotation)
3852 }
3853
3854 /// The axis about which the image is mirrored (opposite of flip)
3855 /// Visualized in terms of starting with (⥠) UPWARDS HARPOON WITH BARB LEFT FROM BAR
3856 /// similar to a DIGIT ONE (1)
3857 #[repr(C)]
3858 #[derive(Debug)]
3859 pub enum ImageMirror {
3860 /// top and bottom parts exchanged
3861 /// ⥡ DOWNWARDS HARPOON WITH BARB LEFT FROM BAR
3862 TopBottom,
3863 /// left and right parts exchanged
3864 /// ⥜ UPWARDS HARPOON WITH BARB RIGHT FROM BAR
3865 LeftRight,
3866 }
3867
3868 /// Parse image mirroring box
3869 /// See HEIF (ISO 23008-12:2017) § 6.5.12<br />
3870 /// Note: [ISO/IEC 23008-12:2017/DAmd 2](https://www.iso.org/standard/81688.html)
3871 /// reverses the interpretation of the 'imir' box in § 6.5.12.3:
3872 /// > `axis` specifies a vertical (`axis` = 0) or horizontal (`axis` = 1) axis
3873 /// > for the mirroring operation.
3874 ///
3875 /// is replaced with:
3876 /// > `mode` specifies how the mirroring is performed: 0 indicates that the top
3877 /// > and bottom parts of the image are exchanged; 1 specifies that the left and
3878 /// > right parts are exchanged.
3879 /// >
3880 /// > NOTE: In Exif, orientation tag can be used to signal mirroring operations.
3881 /// > Exif orientation tag 4 corresponds to `mode` = 0 of `ImageMirror`, and
3882 /// > Exif orientation tag 2 corresponds to `mode` = 1 accordingly.
3883 ///
3884 /// This implementation conforms to the text in Draft Amendment 2, which is the
3885 /// opposite of the published standard as of 4 June 2021.
3886 fn read_imir<T: Read>(src: &mut BMFFBox<T>) -> Result<ImageMirror> {
3887 let imir = src.read_into_try_vec()?;
3888 let mut imir = BitReader::new(&imir);
3889 let _reserved = imir.read_u8(7)?;
3890 let image_mirror = match imir.read_u8(1)? {
3891 0 => ImageMirror::TopBottom,
3892 1 => ImageMirror::LeftRight,
3893 _ => unreachable!(),
3894 };
3895
3896 check_parser_state!(src.content);
3897
3898 Ok(image_mirror)
3899 }
3900
3901 /// See HEIF (ISO 23008-12:2017) § 6.5.8
3902 #[derive(Debug, PartialEq)]
3903 pub struct AuxiliaryTypeProperty {
3904 aux_type: TryString,
3905 aux_subtype: TryString,
3906 }
3907
3908 /// Parse image properties for auxiliary images
3909 /// See HEIF (ISO 23008-12:2017) § 6.5.8
3910 fn read_auxc<T: Read>(src: &mut BMFFBox<T>) -> Result<AuxiliaryTypeProperty> {
3911 let version = read_fullbox_version_no_flags(src)?;
3912 if version != 0 {
3913 return Err(Error::Unsupported("auxC version"));
3914 }
3915
3916 let mut aux = TryString::new();
3917 src.try_read_to_end(&mut aux)?;
3918
3919 let (aux_type, aux_subtype): (TryString, TryVec<u8>);
3920 if let Some(nul_byte_pos) = aux.iter().position(|&b| b == b'\0') {
3921 let (a, b) = aux.as_slice().split_at(nul_byte_pos);
3922 aux_type = a.try_into()?;
3923 aux_subtype = (b[1..]).try_into()?;
3924 } else {
3925 aux_type = aux;
3926 aux_subtype = TryVec::new();
3927 }
3928
3929 Ok(AuxiliaryTypeProperty {
3930 aux_type,
3931 aux_subtype,
3932 })
3933 }
3934
3935 /// Parse an item location box inside a meta box
3936 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.3
3937 fn read_iloc<T: Read>(src: &mut BMFFBox<T>) -> Result<TryHashMap<ItemId, ItemLocationBoxItem>> {
3938 let version: IlocVersion = read_fullbox_version_no_flags(src)?.try_into()?;
3939
3940 let iloc = src.read_into_try_vec()?;
3941 let mut iloc = BitReader::new(&iloc);
3942
3943 let offset_size: IlocFieldSize = iloc.read_u8(4)?.try_into()?;
3944 let length_size: IlocFieldSize = iloc.read_u8(4)?.try_into()?;
3945 let base_offset_size: IlocFieldSize = iloc.read_u8(4)?.try_into()?;
3946
3947 let index_size: Option<IlocFieldSize> = match version {
3948 IlocVersion::One | IlocVersion::Two => Some(iloc.read_u8(4)?.try_into()?),
3949 IlocVersion::Zero => {
3950 let _reserved = iloc.read_u8(4)?;
3951 None
3952 }
3953 };
3954
3955 let item_count = match version {
3956 IlocVersion::Zero | IlocVersion::One => iloc.read_u32(16)?,
3957 IlocVersion::Two => iloc.read_u32(32)?,
3958 };
3959
3960 let mut items = TryHashMap::with_capacity(item_count.to_usize())?;
3961
3962 for _ in 0..item_count {
3963 let item_id = ItemId(match version {
3964 IlocVersion::Zero | IlocVersion::One => iloc.read_u32(16)?,
3965 IlocVersion::Two => iloc.read_u32(32)?,
3966 });
3967
3968 // The spec isn't entirely clear how an `iloc` should be interpreted for version 0,
3969 // which has no `construction_method` field. It does say:
3970 // "For maximum compatibility, version 0 of this box should be used in preference to
3971 // version 1 with `construction_method==0`, or version 2 when possible."
3972 // We take this to imply version 0 can be interpreted as using file offsets.
3973 let construction_method = match version {
3974 IlocVersion::Zero => ConstructionMethod::File,
3975 IlocVersion::One | IlocVersion::Two => {
3976 let _reserved = iloc.read_u16(12)?;
3977 match iloc.read_u16(4)? {
3978 0 => ConstructionMethod::File,
3979 1 => ConstructionMethod::Idat,
3980 2 => ConstructionMethod::Item,
3981 _ => return Status::IlocBadConstructionMethod.into(),
3982 }
3983 }
3984 };
3985
3986 let data_reference_index = iloc.read_u16(16)?;
3987 if data_reference_index != 0 {
3988 return Err(Error::Unsupported(
3989 "external file references (iloc.data_reference_index != 0) are not supported",
3990 ));
3991 }
3992 let base_offset = iloc.read_u64(base_offset_size.as_bits())?;
3993 let extent_count = iloc.read_u16(16)?;
3994
3995 if extent_count < 1 {
3996 return Status::IlocBadExtentCount.into();
3997 }
3998
3999 // "If only one extent is used (extent_count = 1) then either or both of the
4000 // offset and length may be implied"
4001 if extent_count != 1
4002 && (offset_size == IlocFieldSize::Zero || length_size == IlocFieldSize::Zero)
4003 {
4004 return Status::IlocBadExtent.into();
4005 }
4006
4007 let mut extents = TryVec::with_capacity(extent_count.to_usize())?;
4008
4009 for _ in 0..extent_count {
4010 // Parsed but currently ignored, see `Extent`
4011 let _extent_index = match &index_size {
4012 None | Some(IlocFieldSize::Zero) => None,
4013 Some(index_size) => {
4014 debug_assert!(version == IlocVersion::One || version == IlocVersion::Two);
4015 Some(iloc.read_u64(index_size.as_bits())?)
4016 }
4017 };
4018
4019 // Per ISOBMFF (ISO 14496-12:2020) § 8.11.3.1:
4020 // "If the offset is not identified (the field has a length of zero), then the
4021 // beginning of the source (offset 0) is implied"
4022 // This behavior will follow from BitReader::read_u64(0) -> 0.
4023 let extent_offset = iloc.read_u64(offset_size.as_bits())?;
4024 let extent_length = iloc.read_u64(length_size.as_bits())?.try_into()?;
4025
4026 // "If the length is not specified, or specified as zero, then the entire length of
4027 // the source is implied" (ibid)
4028 let offset = base_offset
4029 .checked_add(extent_offset)
4030 .ok_or_else(|| Error::from(Status::IlocOffsetOverflow))?;
4031 let extent = if extent_length == 0 {
4032 Extent::ToEnd { offset }
4033 } else {
4034 Extent::WithLength {
4035 offset,
4036 len: extent_length,
4037 }
4038 };
4039
4040 extents.push(extent)?;
4041 }
4042
4043 let loc = ItemLocationBoxItem {
4044 construction_method,
4045 extents,
4046 };
4047
4048 if items.insert(item_id, loc)?.is_some() {
4049 return Status::IlocDuplicateItemId.into();
4050 }
4051 }
4052
4053 if iloc.remaining() == 0 {
4054 Ok(items)
4055 } else {
4056 Status::IlocBadSize.into()
4057 }
4058 }
4059
4060 /// Read the contents of a box, including sub boxes.
4061 pub fn read_mp4<T: Read>(f: &mut T) -> Result<MediaContext> {
4062 let mut context = None;
4063 let mut found_ftyp = false;
4064 // TODO(kinetik): Top-level parsing should handle zero-sized boxes
4065 // rather than throwing an error.
4066 let mut iter = BoxIter::new(f);
4067 while let Some(mut b) = iter.next_box()? {
4068 // box ordering: ftyp before any variable length box (inc. moov),
4069 // but may not be first box in file if file signatures etc. present
4070 // fragmented mp4 order: ftyp, moov, pairs of moof/mdat (1-multiple), mfra
4071
4072 // "special": uuid, wide (= 8 bytes)
4073 // isom: moov, mdat, free, skip, udta, ftyp, moof, mfra
4074 // iso2: pdin, meta
4075 // iso3: meco
4076 // iso5: styp, sidx, ssix, prft
4077 // unknown, maybe: id32
4078
4079 // qt: pnot
4080
4081 // possibly allow anything where all printable and/or all lowercase printable
4082 // "four printable characters from the ISO 8859-1 character set"
4083 match b.head.name {
4084 BoxType::FileTypeBox => {
4085 let ftyp = read_ftyp(&mut b)?;
4086 found_ftyp = true;
4087 debug!("{:?}", ftyp);
4088 }
4089 BoxType::MovieBox => {
4090 context = Some(read_moov(&mut b, context)?);
4091 }
4092 #[cfg(feature = "meta-xml")]
4093 BoxType::MetadataBox => {
4094 if let Some(ctx) = &mut context {
4095 ctx.metadata = Some(read_meta(&mut b));
4096 }
4097 }
4098 _ => skip_box_content(&mut b)?,
4099 };
4100 check_parser_state!(b.content);
4101 if context.is_some() {
4102 debug!(
4103 "found moov {}, could stop pure 'moov' parser now",
4104 if found_ftyp {
4105 "and ftyp"
4106 } else {
4107 "but no ftyp"
4108 }
4109 );
4110 }
4111 }
4112
4113 // XXX(kinetik): This isn't perfect, as a "moov" with no contents is
4114 // treated as okay but we haven't found anything useful. Needs more
4115 // thought for clearer behaviour here.
4116 context.ok_or(Error::MoovMissing)
4117 }
4118
4119 /// Parse a Movie Header Box
4120 /// See ISOBMFF (ISO 14496-12:2020) § 8.2.2
4121 fn parse_mvhd<T: Read>(f: &mut BMFFBox<T>) -> Result<Option<MediaTimeScale>> {
4122 let mvhd = read_mvhd(f)?;
4123 debug!("{:?}", mvhd);
4124 if mvhd.timescale == 0 {
4125 return Status::MvhdBadTimescale.into();
4126 }
4127 let timescale = Some(MediaTimeScale(u64::from(mvhd.timescale)));
4128 Ok(timescale)
4129 }
4130
4131 /// Parse a Movie Box
4132 /// See ISOBMFF (ISO 14496-12:2020) § 8.2.1
4133 /// Note that despite the spec indicating "exactly one" moov box should exist at
4134 /// the file container level, we support reading and merging multiple moov boxes
4135 /// such as with tests/test_case_1185230.mp4.
4136 fn read_moov<T: Read>(f: &mut BMFFBox<T>, context: Option<MediaContext>) -> Result<MediaContext> {
4137 let MediaContext {
4138 mut timescale,
4139 mut tracks,
4140 mut mvex,
4141 mut psshs,
4142 mut userdata,
4143 #[cfg(feature = "meta-xml")]
4144 metadata,
4145 } = context.unwrap_or_default();
4146
4147 let mut iter = f.box_iter();
4148 while let Some(mut b) = iter.next_box()? {
4149 match b.head.name {
4150 BoxType::MovieHeaderBox => {
4151 timescale = parse_mvhd(&mut b)?;
4152 }
4153 BoxType::TrackBox => {
4154 let mut track = Track::new(tracks.len());
4155 read_trak(&mut b, &mut track)?;
4156 tracks.push(track)?;
4157 }
4158 BoxType::MovieExtendsBox => {
4159 mvex = Some(read_mvex(&mut b)?);
4160 debug!("{:?}", mvex);
4161 }
4162 BoxType::ProtectionSystemSpecificHeaderBox => {
4163 let pssh = read_pssh(&mut b)?;
4164 debug!("{:?}", pssh);
4165 psshs.push(pssh)?;
4166 }
4167 BoxType::UserdataBox => {
4168 userdata = Some(read_udta(&mut b));
4169 debug!("{:?}", userdata);
4170 if let Some(Err(_)) = userdata {
4171 // There was an error parsing userdata. Such failures are not fatal to overall
4172 // parsing, just skip the rest of the box.
4173 skip_box_remain(&mut b)?;
4174 }
4175 }
4176 _ => skip_box_content(&mut b)?,
4177 };
4178 check_parser_state!(b.content);
4179 }
4180
4181 Ok(MediaContext {
4182 timescale,
4183 tracks,
4184 mvex,
4185 psshs,
4186 userdata,
4187 #[cfg(feature = "meta-xml")]
4188 metadata,
4189 })
4190 }
4191
4192 fn read_pssh<T: Read>(src: &mut BMFFBox<T>) -> Result<ProtectionSystemSpecificHeaderBox> {
4193 let len = src.bytes_left();
4194 let mut box_content = read_buf(src, len)?;
4195 let (system_id, kid, data) = {
4196 let pssh = &mut Cursor::new(&box_content);
4197
4198 let (version, _) = read_fullbox_extra(pssh)?;
4199
4200 let system_id = read_buf(pssh, 16)?;
4201
4202 let mut kid = TryVec::<ByteData>::new();
4203 if version > 0 {
4204 const KID_ELEMENT_SIZE: usize = 16;
4205 let count = be_u32(pssh)?.to_usize();
4206 kid.reserve(
4207 count
4208 .checked_mul(KID_ELEMENT_SIZE)
4209 .ok_or_else(|| Error::from(Status::PsshSizeOverflow))?,
4210 )?;
4211 for _ in 0..count {
4212 let item = read_buf(pssh, KID_ELEMENT_SIZE.to_u64())?;
4213 kid.push(item)?;
4214 }
4215 }
4216
4217 let data_size = be_u32(pssh)?;
4218 let data = read_buf(pssh, data_size.into())?;
4219
4220 (system_id, kid, data)
4221 };
4222
4223 let mut pssh_box = TryVec::new();
4224 write_be_u32(&mut pssh_box, src.head.size.try_into()?)?;
4225 pssh_box.extend_from_slice(b"pssh")?;
4226 pssh_box.append(&mut box_content)?;
4227
4228 Ok(ProtectionSystemSpecificHeaderBox {
4229 system_id,
4230 kid,
4231 data,
4232 box_content: pssh_box,
4233 })
4234 }
4235
4236 /// Parse a Movie Extends Box
4237 /// See ISOBMFF (ISO 14496-12:2020) § 8.8.1
4238 fn read_mvex<T: Read>(src: &mut BMFFBox<T>) -> Result<MovieExtendsBox> {
4239 let mut iter = src.box_iter();
4240 let mut fragment_duration = None;
4241 while let Some(mut b) = iter.next_box()? {
4242 match b.head.name {
4243 BoxType::MovieExtendsHeaderBox => {
4244 let duration = read_mehd(&mut b)?;
4245 fragment_duration = Some(duration);
4246 }
4247 _ => skip_box_content(&mut b)?,
4248 }
4249 }
4250 Ok(MovieExtendsBox { fragment_duration })
4251 }
4252
4253 fn read_mehd<T: Read>(src: &mut BMFFBox<T>) -> Result<MediaScaledTime> {
4254 let (version, _) = read_fullbox_extra(src)?;
4255 let fragment_duration = match version {
4256 1 => be_u64(src)?,
4257 0 => u64::from(be_u32(src)?),
4258 _ => return Status::MehdBadVersion.into(),
4259 };
4260 Ok(MediaScaledTime(fragment_duration))
4261 }
4262
4263 /// Parse a Track Box
4264 /// See ISOBMFF (ISO 14496-12:2020) § 8.3.1.
4265 fn read_trak<T: Read>(f: &mut BMFFBox<T>, track: &mut Track) -> Result<()> {
4266 let mut iter = f.box_iter();
4267 while let Some(mut b) = iter.next_box()? {
4268 match b.head.name {
4269 BoxType::TrackHeaderBox => {
4270 let tkhd = read_tkhd(&mut b)?;
4271 track.track_id = Some(tkhd.track_id);
4272 track.tkhd = Some(tkhd.clone());
4273 debug!("{:?}", tkhd);
4274 }
4275 BoxType::EditBox => read_edts(&mut b, track)?,
4276 BoxType::MediaBox => read_mdia(&mut b, track)?,
4277 BoxType::TrackReferenceBox => track.tref = Some(read_tref(&mut b)?),
4278 _ => skip_box_content(&mut b)?,
4279 };
4280 check_parser_state!(b.content);
4281 }
4282 Ok(())
4283 }
4284
4285 fn read_edts<T: Read>(f: &mut BMFFBox<T>, track: &mut Track) -> Result<()> {
4286 let mut iter = f.box_iter();
4287 while let Some(mut b) = iter.next_box()? {
4288 match b.head.name {
4289 BoxType::EditListBox => {
4290 let elst = read_elst(&mut b)?;
4291 track.looped = Some(elst.looped);
4292 if elst.edits.is_empty() {
4293 debug!("empty edit list");
4294 continue;
4295 }
4296 let mut empty_duration = 0;
4297 let mut idx = 0;
4298 if elst.edits[idx].media_time == -1 {
4299 if elst.edits.len() < 2 {
4300 debug!("expected additional edit, ignoring edit list");
4301 continue;
4302 }
4303 empty_duration = elst.edits[idx].segment_duration;
4304 idx += 1;
4305 }
4306 track.empty_duration = Some(MediaScaledTime(empty_duration));
4307 let media_time = elst.edits[idx].media_time;
4308 if media_time < 0 {
4309 debug!("unexpected negative media time in edit");
4310 }
4311 track.edited_duration = Some(MediaScaledTime(elst.edits[idx].segment_duration));
4312 track.media_time = Some(TrackScaledTime::<u64>(
4313 std::cmp::max(0, media_time) as u64,
4314 track.id,
4315 ));
4316 if elst.edits.len() > 2 {
4317 debug!("ignoring edit list with {} entries", elst.edits.len());
4318 }
4319 debug!("{:?}", elst);
4320 }
4321 _ => skip_box_content(&mut b)?,
4322 };
4323 check_parser_state!(b.content);
4324 }
4325 Ok(())
4326 }
4327
4328 #[allow(clippy::type_complexity)] // Allow the complex return, maybe rework in future
4329 fn parse_mdhd<T: Read>(
4330 f: &mut BMFFBox<T>,
4331 track: &Track,
4332 ) -> Result<(
4333 MediaHeaderBox,
4334 Option<TrackScaledTime<u64>>,
4335 Option<TrackTimeScale<u64>>,
4336 )> {
4337 let mdhd = read_mdhd(f)?;
4338 let duration = match mdhd.duration {
4339 u64::MAX => None,
4340 duration => Some(TrackScaledTime::<u64>(duration, track.id)),
4341 };
4342 if mdhd.timescale == 0 {
4343 return Status::MdhdBadTimescale.into();
4344 }
4345 let timescale = Some(TrackTimeScale::<u64>(u64::from(mdhd.timescale), track.id));
4346 Ok((mdhd, duration, timescale))
4347 }
4348
4349 fn read_mdia<T: Read>(f: &mut BMFFBox<T>, track: &mut Track) -> Result<()> {
4350 let mut iter = f.box_iter();
4351 while let Some(mut b) = iter.next_box()? {
4352 match b.head.name {
4353 BoxType::MediaHeaderBox => {
4354 let (mdhd, duration, timescale) = parse_mdhd(&mut b, track)?;
4355 track.duration = duration;
4356 track.timescale = timescale;
4357 debug!("{:?}", mdhd);
4358 }
4359 BoxType::HandlerBox => {
4360 let hdlr = read_hdlr(&mut b, ParseStrictness::Permissive)?;
4361
4362 match hdlr.handler_type.value.as_ref() {
4363 b"vide" => track.track_type = TrackType::Video,
4364 b"pict" => track.track_type = TrackType::Picture,
4365 b"auxv" => track.track_type = TrackType::AuxiliaryVideo,
4366 b"soun" => track.track_type = TrackType::Audio,
4367 b"meta" => track.track_type = TrackType::Metadata,
4368 _ => (),
4369 }
4370 debug!("{:?}", hdlr);
4371 }
4372 BoxType::MediaInformationBox => read_minf(&mut b, track)?,
4373 _ => skip_box_content(&mut b)?,
4374 };
4375 check_parser_state!(b.content);
4376 }
4377 Ok(())
4378 }
4379
4380 fn read_tref<T: Read>(f: &mut BMFFBox<T>) -> Result<TrackReferenceBox> {
4381 // Will likely only see trefs with one auxl
4382 let mut references = TryVec::with_capacity(1)?;
4383 let mut iter = f.box_iter();
4384 while let Some(mut b) = iter.next_box()? {
4385 match b.head.name {
4386 BoxType::AuxiliaryBox => {
4387 references.push(TrackReferenceEntry::Auxiliary(read_tref_auxl(&mut b)?))?
4388 }
4389 _ => skip_box_content(&mut b)?,
4390 };
4391 check_parser_state!(b.content);
4392 }
4393 Ok(TrackReferenceBox { references })
4394 }
4395
4396 fn read_tref_auxl<T: Read>(f: &mut BMFFBox<T>) -> Result<TrackReference> {
4397 let num_track_ids = (f.bytes_left() / std::mem::size_of::<u32>().to_u64()).try_into()?;
4398 let mut track_ids = TryVec::with_capacity(num_track_ids)?;
4399 for _ in 0..num_track_ids {
4400 track_ids.push(be_u32(f)?)?;
4401 }
4402
4403 Ok(TrackReference { track_ids })
4404 }
4405
4406 fn read_minf<T: Read>(f: &mut BMFFBox<T>, track: &mut Track) -> Result<()> {
4407 let mut iter = f.box_iter();
4408 while let Some(mut b) = iter.next_box()? {
4409 match b.head.name {
4410 BoxType::SampleTableBox => read_stbl(&mut b, track)?,
4411 _ => skip_box_content(&mut b)?,
4412 };
4413 check_parser_state!(b.content);
4414 }
4415 Ok(())
4416 }
4417
4418 fn read_stbl<T: Read>(f: &mut BMFFBox<T>, track: &mut Track) -> Result<()> {
4419 let mut iter = f.box_iter();
4420 while let Some(mut b) = iter.next_box()? {
4421 match b.head.name {
4422 BoxType::SampleDescriptionBox => {
4423 let stsd = read_stsd(&mut b, track)?;
4424 debug!("{:?}", stsd);
4425 track.stsd = Some(stsd);
4426 }
4427 BoxType::TimeToSampleBox => {
4428 let stts = read_stts(&mut b)?;
4429 debug!("{:?}", stts);
4430 track.stts = Some(stts);
4431 }
4432 BoxType::SampleToChunkBox => {
4433 let stsc = read_stsc(&mut b)?;
4434 debug!("{:?}", stsc);
4435 track.stsc = Some(stsc);
4436 }
4437 BoxType::SampleSizeBox => {
4438 let stsz = read_stsz(&mut b)?;
4439 debug!("{:?}", stsz);
4440 track.stsz = Some(stsz);
4441 }
4442 BoxType::ChunkOffsetBox => {
4443 let stco = read_stco(&mut b)?;
4444 debug!("{:?}", stco);
4445 track.stco = Some(stco);
4446 }
4447 BoxType::ChunkLargeOffsetBox => {
4448 let co64 = read_co64(&mut b)?;
4449 debug!("{:?}", co64);
4450 track.stco = Some(co64);
4451 }
4452 BoxType::SyncSampleBox => {
4453 let stss = read_stss(&mut b)?;
4454 debug!("{:?}", stss);
4455 track.stss = Some(stss);
4456 }
4457 BoxType::CompositionOffsetBox => {
4458 let ctts = read_ctts(&mut b)?;
4459 debug!("{:?}", ctts);
4460 track.ctts = Some(ctts);
4461 }
4462 _ => skip_box_content(&mut b)?,
4463 };
4464 check_parser_state!(b.content);
4465 }
4466 Ok(())
4467 }
4468
4469 /// Parse an ftyp box.
4470 /// See ISOBMFF (ISO 14496-12:2020) § 4.3
4471 fn read_ftyp<T: Read>(src: &mut BMFFBox<T>) -> Result<FileTypeBox> {
4472 let major = be_u32(src)?;
4473 let minor = be_u32(src)?;
4474 let bytes_left = src.bytes_left();
4475 if bytes_left % 4 != 0 {
4476 return Status::FtypBadSize.into();
4477 }
4478 // Is a brand_count of zero valid?
4479 let brand_count = bytes_left / 4;
4480 let mut brands = TryVec::with_capacity(brand_count.try_into()?)?;
4481 for _ in 0..brand_count {
4482 brands.push(be_u32(src)?.into())?;
4483 }
4484 Ok(FileTypeBox {
4485 major_brand: From::from(major),
4486 minor_version: minor,
4487 compatible_brands: brands,
4488 })
4489 }
4490
4491 /// Parse an mvhd box.
4492 fn read_mvhd<T: Read>(src: &mut BMFFBox<T>) -> Result<MovieHeaderBox> {
4493 let (version, _) = read_fullbox_extra(src)?;
4494 match version {
4495 // 64 bit creation and modification times.
4496 1 => {
4497 skip(src, 16)?;
4498 }
4499 // 32 bit creation and modification times.
4500 0 => {
4501 skip(src, 8)?;
4502 }
4503 _ => return Status::MvhdBadVersion.into(),
4504 }
4505 let timescale = be_u32(src)?;
4506 let duration = match version {
4507 1 => be_u64(src)?,
4508 0 => {
4509 let d = be_u32(src)?;
4510 if d == u32::MAX {
4511 u64::MAX
4512 } else {
4513 u64::from(d)
4514 }
4515 }
4516 _ => unreachable!("Should have returned Status::MvhdBadVersion"),
4517 };
4518 // Skip remaining valid fields.
4519 skip(src, 80)?;
4520
4521 // Padding could be added in some contents.
4522 skip_box_remain(src)?;
4523 Ok(MovieHeaderBox {
4524 timescale,
4525 duration,
4526 })
4527 }
4528
4529 /// Parse a tkhd box.
4530 fn read_tkhd<T: Read>(src: &mut BMFFBox<T>) -> Result<TrackHeaderBox> {
4531 let (version, flags) = read_fullbox_extra(src)?;
4532 let disabled = flags & 0x1u32 == 0 || flags & 0x2u32 == 0;
4533 match version {
4534 // 64 bit creation and modification times.
4535 1 => {
4536 skip(src, 16)?;
4537 }
4538 // 32 bit creation and modification times.
4539 0 => {
4540 skip(src, 8)?;
4541 }
4542 _ => return Status::TkhdBadVersion.into(),
4543 }
4544 let track_id = be_u32(src)?;
4545 skip(src, 4)?;
4546 let duration = match version {
4547 1 => be_u64(src)?,
4548 0 => u64::from(be_u32(src)?),
4549 _ => unreachable!("Should have returned Status::TkhdBadVersion"),
4550 };
4551 // Skip uninteresting fields.
4552 skip(src, 16)?;
4553
4554 let matrix = Matrix {
4555 a: be_i32(src)?,
4556 b: be_i32(src)?,
4557 u: be_i32(src)?,
4558 c: be_i32(src)?,
4559 d: be_i32(src)?,
4560 v: be_i32(src)?,
4561 x: be_i32(src)?,
4562 y: be_i32(src)?,
4563 w: be_i32(src)?,
4564 };
4565
4566 let width = be_u32(src)?;
4567 let height = be_u32(src)?;
4568 Ok(TrackHeaderBox {
4569 track_id,
4570 disabled,
4571 duration,
4572 width,
4573 height,
4574 matrix,
4575 })
4576 }
4577
4578 /// Parse a elst box.
4579 /// See ISOBMFF (ISO 14496-12:2020) § 8.6.6
4580 fn read_elst<T: Read>(src: &mut BMFFBox<T>) -> Result<EditListBox> {
4581 let (version, flags) = read_fullbox_extra(src)?;
4582 let edit_count = be_u32(src)?;
4583 let mut edits = TryVec::with_capacity(edit_count.to_usize())?;
4584 for _ in 0..edit_count {
4585 let (segment_duration, media_time) = match version {
4586 1 => {
4587 // 64 bit segment duration and media times.
4588 (be_u64(src)?, be_i64(src)?)
4589 }
4590 0 => {
4591 // 32 bit segment duration and media times.
4592 (u64::from(be_u32(src)?), i64::from(be_i32(src)?))
4593 }
4594 _ => return Status::ElstBadVersion.into(),
4595 };
4596 let media_rate_integer = be_i16(src)?;
4597 let media_rate_fraction = be_i16(src)?;
4598 edits.push(Edit {
4599 segment_duration,
4600 media_time,
4601 media_rate_integer,
4602 media_rate_fraction,
4603 })?;
4604 }
4605
4606 // Padding could be added in some contents.
4607 skip_box_remain(src)?;
4608
4609 Ok(EditListBox {
4610 looped: flags == 1,
4611 edits,
4612 })
4613 }
4614
4615 /// Parse a mdhd box.
4616 fn read_mdhd<T: Read>(src: &mut BMFFBox<T>) -> Result<MediaHeaderBox> {
4617 let (version, _) = read_fullbox_extra(src)?;
4618 let (timescale, duration) = match version {
4619 1 => {
4620 // Skip 64-bit creation and modification times.
4621 skip(src, 16)?;
4622
4623 // 64 bit duration.
4624 (be_u32(src)?, be_u64(src)?)
4625 }
4626 0 => {
4627 // Skip 32-bit creation and modification times.
4628 skip(src, 8)?;
4629
4630 // 32 bit duration.
4631 let timescale = be_u32(src)?;
4632 let duration = {
4633 // Since we convert the 32-bit duration to 64-bit by
4634 // upcasting, we need to preserve the special all-1s
4635 // ("unknown") case by hand.
4636 let d = be_u32(src)?;
4637 if d == u32::MAX {
4638 u64::MAX
4639 } else {
4640 u64::from(d)
4641 }
4642 };
4643 (timescale, duration)
4644 }
4645 _ => return Status::MdhdBadVersion.into(),
4646 };
4647
4648 // Skip uninteresting fields.
4649 skip(src, 4)?;
4650
4651 Ok(MediaHeaderBox {
4652 timescale,
4653 duration,
4654 })
4655 }
4656
4657 /// Parse a stco box.
4658 /// See ISOBMFF (ISO 14496-12:2020) § 8.7.5
4659 fn read_stco<T: Read>(src: &mut BMFFBox<T>) -> Result<ChunkOffsetBox> {
4660 let (_, _) = read_fullbox_extra(src)?;
4661 let offset_count = be_u32(src)?;
4662 let mut offsets = TryVec::with_capacity(offset_count.to_usize())?;
4663 for _ in 0..offset_count {
4664 offsets.push(be_u32(src)?.into())?;
4665 }
4666
4667 // Padding could be added in some contents.
4668 skip_box_remain(src)?;
4669
4670 Ok(ChunkOffsetBox { offsets })
4671 }
4672
4673 /// Parse a co64 box.
4674 /// See ISOBMFF (ISO 14496-12:2020) § 8.7.5
4675 fn read_co64<T: Read>(src: &mut BMFFBox<T>) -> Result<ChunkOffsetBox> {
4676 let (_, _) = read_fullbox_extra(src)?;
4677 let offset_count = be_u32(src)?;
4678 let mut offsets = TryVec::with_capacity(offset_count.to_usize())?;
4679 for _ in 0..offset_count {
4680 offsets.push(be_u64(src)?)?;
4681 }
4682
4683 // Padding could be added in some contents.
4684 skip_box_remain(src)?;
4685
4686 Ok(ChunkOffsetBox { offsets })
4687 }
4688
4689 /// Parse a stss box.
4690 /// See ISOBMFF (ISO 14496-12:2020) § 8.6.2
4691 fn read_stss<T: Read>(src: &mut BMFFBox<T>) -> Result<SyncSampleBox> {
4692 let (_, _) = read_fullbox_extra(src)?;
4693 let sample_count = be_u32(src)?;
4694 let mut samples = TryVec::with_capacity(sample_count.to_usize())?;
4695 for _ in 0..sample_count {
4696 samples.push(be_u32(src)?)?;
4697 }
4698
4699 // Padding could be added in some contents.
4700 skip_box_remain(src)?;
4701
4702 Ok(SyncSampleBox { samples })
4703 }
4704
4705 /// Parse a stsc box.
4706 /// See ISOBMFF (ISO 14496-12:2020) § 8.7.4
4707 fn read_stsc<T: Read>(src: &mut BMFFBox<T>) -> Result<SampleToChunkBox> {
4708 let (_, _) = read_fullbox_extra(src)?;
4709 let sample_count = be_u32(src)?;
4710 let mut samples = TryVec::with_capacity(sample_count.to_usize())?;
4711 for _ in 0..sample_count {
4712 let first_chunk = be_u32(src)?;
4713 let samples_per_chunk = be_u32(src)?;
4714 let sample_description_index = be_u32(src)?;
4715 samples.push(SampleToChunk {
4716 first_chunk,
4717 samples_per_chunk,
4718 sample_description_index,
4719 })?;
4720 }
4721
4722 // Padding could be added in some contents.
4723 skip_box_remain(src)?;
4724
4725 Ok(SampleToChunkBox { samples })
4726 }
4727
4728 /// Parse a Composition Time to Sample Box
4729 /// See ISOBMFF (ISO 14496-12:2020) § 8.6.1.3
4730 fn read_ctts<T: Read>(src: &mut BMFFBox<T>) -> Result<CompositionOffsetBox> {
4731 let (version, _) = read_fullbox_extra(src)?;
4732
4733 let counts = be_u32(src)?;
4734
4735 if counts
4736 .checked_mul(8)
4737 .map_or(true, |bytes| u64::from(bytes) > src.bytes_left())
4738 {
4739 return Status::CttsBadSize.into();
4740 }
4741
4742 let mut offsets = TryVec::with_capacity(counts.to_usize())?;
4743 for _ in 0..counts {
4744 let (sample_count, time_offset) = match version {
4745 // According to spec, Version0 shoule be used when version == 0;
4746 // however, some buggy contents have negative value when version == 0.
4747 // So we always use Version1 here.
4748 0..=1 => {
4749 let count = be_u32(src)?;
4750 let offset = TimeOffsetVersion::Version1(be_i32(src)?);
4751 (count, offset)
4752 }
4753 _ => {
4754 return Status::CttsBadVersion.into();
4755 }
4756 };
4757 offsets.push(TimeOffset {
4758 sample_count,
4759 time_offset,
4760 })?;
4761 }
4762
4763 check_parser_state!(src.content);
4764
4765 Ok(CompositionOffsetBox { samples: offsets })
4766 }
4767
4768 /// Parse a stsz box.
4769 /// See ISOBMFF (ISO 14496-12:2020) § 8.7.3.2
4770 fn read_stsz<T: Read>(src: &mut BMFFBox<T>) -> Result<SampleSizeBox> {
4771 let (_, _) = read_fullbox_extra(src)?;
4772 let sample_size = be_u32(src)?;
4773 let sample_count = be_u32(src)?;
4774 let mut sample_sizes = TryVec::new();
4775 if sample_size == 0 {
4776 sample_sizes.reserve(sample_count.to_usize())?;
4777 for _ in 0..sample_count {
4778 sample_sizes.push(be_u32(src)?)?;
4779 }
4780 }
4781
4782 // Padding could be added in some contents.
4783 skip_box_remain(src)?;
4784
4785 Ok(SampleSizeBox {
4786 sample_size,
4787 sample_sizes,
4788 })
4789 }
4790
4791 /// Parse a stts box.
4792 /// See ISOBMFF (ISO 14496-12:2020) § 8.6.1.2
4793 fn read_stts<T: Read>(src: &mut BMFFBox<T>) -> Result<TimeToSampleBox> {
4794 let (_, _) = read_fullbox_extra(src)?;
4795 let sample_count = be_u32(src)?;
4796 let mut samples = TryVec::with_capacity(sample_count.to_usize())?;
4797 for _ in 0..sample_count {
4798 let sample_count = be_u32(src)?;
4799 let sample_delta = be_u32(src)?;
4800 samples.push(Sample {
4801 sample_count,
4802 sample_delta,
4803 })?;
4804 }
4805
4806 // Padding could be added in some contents.
4807 skip_box_remain(src)?;
4808
4809 Ok(TimeToSampleBox { samples })
4810 }
4811
4812 /// Parse a VPx Config Box.
4813 fn read_vpcc<T: Read>(src: &mut BMFFBox<T>) -> Result<VPxConfigBox> {
4814 let (version, _) = read_fullbox_extra(src)?;
4815 let supported_versions = [0, 1];
4816 if !supported_versions.contains(&version) {
4817 return Err(Error::Unsupported("unknown vpcC version"));
4818 }
4819
4820 let profile = src.read_u8()?;
4821 let level = src.read_u8()?;
4822 let (
4823 bit_depth,
4824 colour_primaries,
4825 chroma_subsampling,
4826 transfer_characteristics,
4827 matrix_coefficients,
4828 video_full_range_flag,
4829 ) = if version == 0 {
4830 let (bit_depth, colour_primaries) = {
4831 let byte = src.read_u8()?;
4832 ((byte >> 4) & 0x0f, byte & 0x0f)
4833 };
4834 // Note, transfer_characteristics was known as transfer_function in v0
4835 let (chroma_subsampling, transfer_characteristics, video_full_range_flag) = {
4836 let byte = src.read_u8()?;
4837 ((byte >> 4) & 0x0f, (byte >> 1) & 0x07, (byte & 1) == 1)
4838 };
4839 (
4840 bit_depth,
4841 colour_primaries,
4842 chroma_subsampling,
4843 transfer_characteristics,
4844 None,
4845 video_full_range_flag,
4846 )
4847 } else {
4848 let (bit_depth, chroma_subsampling, video_full_range_flag) = {
4849 let byte = src.read_u8()?;
4850 ((byte >> 4) & 0x0f, (byte >> 1) & 0x07, (byte & 1) == 1)
4851 };
4852 let colour_primaries = src.read_u8()?;
4853 let transfer_characteristics = src.read_u8()?;
4854 let matrix_coefficients = src.read_u8()?;
4855
4856 (
4857 bit_depth,
4858 colour_primaries,
4859 chroma_subsampling,
4860 transfer_characteristics,
4861 Some(matrix_coefficients),
4862 video_full_range_flag,
4863 )
4864 };
4865
4866 let codec_init_size = be_u16(src)?;
4867 let codec_init = read_buf(src, codec_init_size.into())?;
4868
4869 // TODO(rillian): validate field value ranges.
4870 Ok(VPxConfigBox {
4871 profile,
4872 level,
4873 bit_depth,
4874 colour_primaries,
4875 chroma_subsampling,
4876 transfer_characteristics,
4877 matrix_coefficients,
4878 video_full_range_flag,
4879 codec_init,
4880 })
4881 }
4882
4883 /// See [AV1-ISOBMFF § 2.3.3](https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax)
4884 fn read_av1c<T: Read>(src: &mut BMFFBox<T>) -> Result<AV1ConfigBox> {
4885 // We want to store the raw config as well as a structured (parsed) config, so create a copy of
4886 // the raw config so we have it later, and then parse the structured data from that.
4887 let raw_config = src.read_into_try_vec()?;
4888 let mut raw_config_slice = raw_config.as_slice();
4889 let marker_byte = raw_config_slice.read_u8()?;
4890 if marker_byte & 0x80 != 0x80 {
4891 return Err(Error::Unsupported("missing av1C marker bit"));
4892 }
4893 if marker_byte & 0x7f != 0x01 {
4894 return Err(Error::Unsupported("missing av1C marker bit"));
4895 }
4896 let profile_byte = raw_config_slice.read_u8()?;
4897 let profile = (profile_byte & 0xe0) >> 5;
4898 let level = profile_byte & 0x1f;
4899 let flags_byte = raw_config_slice.read_u8()?;
4900 let tier = (flags_byte & 0x80) >> 7;
4901 let bit_depth = match flags_byte & 0x60 {
4902 0x60 => 12,
4903 0x40 => 10,
4904 _ => 8,
4905 };
4906 let monochrome = flags_byte & 0x10 == 0x10;
4907 let chroma_subsampling_x = (flags_byte & 0x08) >> 3;
4908 let chroma_subsampling_y = (flags_byte & 0x04) >> 2;
4909 let chroma_sample_position = flags_byte & 0x03;
4910 let delay_byte = raw_config_slice.read_u8()?;
4911 let initial_presentation_delay_present = (delay_byte & 0x10) == 0x10;
4912 let initial_presentation_delay_minus_one = if initial_presentation_delay_present {
4913 delay_byte & 0x0f
4914 } else {
4915 0
4916 };
4917
4918 Ok(AV1ConfigBox {
4919 profile,
4920 level,
4921 tier,
4922 bit_depth,
4923 monochrome,
4924 chroma_subsampling_x,
4925 chroma_subsampling_y,
4926 chroma_sample_position,
4927 initial_presentation_delay_present,
4928 initial_presentation_delay_minus_one,
4929 raw_config,
4930 })
4931 }
4932
4933 fn read_flac_metadata<T: Read>(src: &mut BMFFBox<T>) -> Result<FLACMetadataBlock> {
4934 let temp = src.read_u8()?;
4935 let block_type = temp & 0x7f;
4936 let length = be_u24(src)?.into();
4937 if length > src.bytes_left() {
4938 return Status::DflaBadMetadataBlockSize.into();
4939 }
4940 let data = read_buf(src, length)?;
4941 Ok(FLACMetadataBlock { block_type, data })
4942 }
4943
4944 /// See MPEG-4 Systems (ISO 14496-1:2010) § 7.2.6.5
4945 fn find_descriptor(data: &[u8], esds: &mut ES_Descriptor) -> Result<()> {
4946 // Tags for elementary stream description
4947 const ESDESCR_TAG: u8 = 0x03;
4948 const DECODER_CONFIG_TAG: u8 = 0x04;
4949 const DECODER_SPECIFIC_TAG: u8 = 0x05;
4950
4951 let mut remains = data;
4952
4953 // Descriptor length should be more than 2 bytes.
4954 while remains.len() > 2 {
4955 let des = &mut Cursor::new(remains);
4956 let tag = des.read_u8()?;
4957
4958 // See MPEG-4 Systems (ISO 14496-1:2010) § 8.3.3 for interpreting size of expandable classes
4959
4960 let mut end: u32 = 0; // It's u8 without declaration type that is incorrect.
4961 // MSB of extend_or_len indicates more bytes, up to 4 bytes.
4962 for _ in 0..4 {
4963 if des.position() == remains.len().to_u64() {
4964 // There's nothing more to read, the 0x80 was actually part of
4965 // the content, and not an extension size.
4966 end = des.position() as u32;
4967 break;
4968 }
4969 let extend_or_len = des.read_u8()?;
4970 end = (end << 7) + u32::from(extend_or_len & 0x7F);
4971 if (extend_or_len & 0b1000_0000) == 0 {
4972 end += des.position() as u32;
4973 break;
4974 }
4975 }
4976
4977 if end.to_usize() > remains.len() || u64::from(end) < des.position() {
4978 return Status::EsdsBadDescriptor.into();
4979 }
4980
4981 let descriptor = &remains[des.position().try_into()?..end.to_usize()];
4982
4983 match tag {
4984 ESDESCR_TAG => {
4985 read_es_descriptor(descriptor, esds)?;
4986 }
4987 DECODER_CONFIG_TAG => {
4988 read_dc_descriptor(descriptor, esds)?;
4989 }
4990 DECODER_SPECIFIC_TAG => {
4991 read_ds_descriptor(descriptor, esds)?;
4992 }
4993 _ => {
4994 debug!("Unsupported descriptor, tag {}", tag);
4995 }
4996 }
4997
4998 remains = &remains[end.to_usize()..remains.len()];
4999 debug!("remains.len(): {}", remains.len());
5000 }
5001
5002 Ok(())
5003 }
5004
5005 fn get_audio_object_type(bit_reader: &mut BitReader) -> Result<u16> {
5006 let mut audio_object_type: u16 = ReadInto::read(bit_reader, 5)?;
5007
5008 // Extend audio object type, for example, HE-AAC.
5009 if audio_object_type == 31 {
5010 let audio_object_type_ext: u16 = ReadInto::read(bit_reader, 6)?;
5011 audio_object_type = 32 + audio_object_type_ext;
5012 }
5013 Ok(audio_object_type)
5014 }
5015
5016 /// See MPEG-4 Systems (ISO 14496-1:2010) § 7.2.6.7 and probably 14496-3 somewhere?
5017 fn read_ds_descriptor(data: &[u8], esds: &mut ES_Descriptor) -> Result<()> {
5018 #[cfg(feature = "mp4v")]
5019 // Check if we are in a Visual esda Box.
5020 if esds.video_codec != CodecType::Unknown {
5021 esds.decoder_specific_data.extend_from_slice(data)?;
5022 return Ok(());
5023 }
5024
5025 // We are in an Audio esda Box.
5026 let frequency_table = [
5027 (0x0, 96000),
5028 (0x1, 88200),
5029 (0x2, 64000),
5030 (0x3, 48000),
5031 (0x4, 44100),
5032 (0x5, 32000),
5033 (0x6, 24000),
5034 (0x7, 22050),
5035 (0x8, 16000),
5036 (0x9, 12000),
5037 (0xa, 11025),
5038 (0xb, 8000),
5039 (0xc, 7350),
5040 ];
5041
5042 let bit_reader = &mut BitReader::new(data);
5043
5044 let mut audio_object_type = get_audio_object_type(bit_reader)?;
5045
5046 let sample_index: u32 = ReadInto::read(bit_reader, 4)?;
5047
5048 // Sample frequency could be from table, or retrieved from stream directly
5049 // if index is 0x0f.
5050 let sample_frequency = match sample_index {
5051 0x0F => Some(ReadInto::read(bit_reader, 24)?),
5052 _ => frequency_table
5053 .iter()
5054 .find(|item| item.0 == sample_index)
5055 .map(|x| x.1),
5056 };
5057
5058 let channel_configuration: u16 = ReadInto::read(bit_reader, 4)?;
5059
5060 let extended_audio_object_type = match audio_object_type {
5061 5 | 29 => Some(5),
5062 _ => None,
5063 };
5064
5065 if audio_object_type == 5 || audio_object_type == 29 {
5066 // We have an explicit signaling for BSAC extension, should the decoder
5067 // decode the BSAC extension (all Gecko's AAC decoders do), then this is
5068 // what the stream will actually look like once decoded.
5069 let _extended_sample_index = ReadInto::read(bit_reader, 4)?;
5070 let _extended_sample_frequency: Option<u32> = match _extended_sample_index {
5071 0x0F => Some(ReadInto::read(bit_reader, 24)?),
5072 _ => frequency_table
5073 .iter()
5074 .find(|item| item.0 == sample_index)
5075 .map(|x| x.1),
5076 };
5077 audio_object_type = get_audio_object_type(bit_reader)?;
5078 let _extended_channel_configuration = match audio_object_type {
5079 22 => ReadInto::read(bit_reader, 4)?,
5080 _ => channel_configuration,
5081 };
5082 };
5083
5084 match audio_object_type {
5085 1..=4 | 6 | 7 | 17 | 19..=23 => {
5086 if sample_frequency.is_none() {
5087 return Err(Error::Unsupported("unknown frequency"));
5088 }
5089
5090 // parsing GASpecificConfig
5091
5092 // If the sampling rate is not one of the rates listed in the right
5093 // column in Table 4.82, the sampling frequency dependent tables
5094 // (code tables, scale factor band tables etc.) must be deduced in
5095 // order for the bitstream payload to be parsed. Since a given
5096 // sampling frequency is associated with only one sampling frequency
5097 // table, and since maximum flexibility is desired in the range of
5098 // possible sampling frequencies, the following table shall be used
5099 // to associate an implied sampling frequency with the desired
5100 // sampling frequency dependent tables.
5101 let sample_frequency_value = match sample_frequency.unwrap() {
5102 0..=9390 => 8000,
5103 9391..=11501 => 11025,
5104 11502..=13855 => 12000,
5105 13856..=18782 => 16000,
5106 18783..=23003 => 22050,
5107 23004..=27712 => 24000,
5108 27713..=37565 => 32000,
5109 37566..=46008 => 44100,
5110 46009..=55425 => 48000,
5111 55426..=75131 => 64000,
5112 75132..=92016 => 88200,
5113 _ => 96000,
5114 };
5115
5116 bit_reader.skip(1)?; // frameLengthFlag
5117 let depend_on_core_order: u8 = ReadInto::read(bit_reader, 1)?;
5118 if depend_on_core_order > 0 {
5119 bit_reader.skip(14)?; // codeCoderDelay
5120 }
5121 bit_reader.skip(1)?; // extensionFlag
5122
5123 let channel_counts = match channel_configuration {
5124 0 => {
5125 debug!("Parsing program_config_element for channel counts");
5126
5127 bit_reader.skip(4)?; // element_instance_tag
5128 bit_reader.skip(2)?; // object_type
5129 bit_reader.skip(4)?; // sampling_frequency_index
5130 let num_front_channel: u8 = ReadInto::read(bit_reader, 4)?;
5131 let num_side_channel: u8 = ReadInto::read(bit_reader, 4)?;
5132 let num_back_channel: u8 = ReadInto::read(bit_reader, 4)?;
5133 let num_lfe_channel: u8 = ReadInto::read(bit_reader, 2)?;
5134 bit_reader.skip(3)?; // num_assoc_data
5135 bit_reader.skip(4)?; // num_valid_cc
5136
5137 let mono_mixdown_present: bool = ReadInto::read(bit_reader, 1)?;
5138 if mono_mixdown_present {
5139 bit_reader.skip(4)?; // mono_mixdown_element_number
5140 }
5141
5142 let stereo_mixdown_present: bool = ReadInto::read(bit_reader, 1)?;
5143 if stereo_mixdown_present {
5144 bit_reader.skip(4)?; // stereo_mixdown_element_number
5145 }
5146
5147 let matrix_mixdown_idx_present: bool = ReadInto::read(bit_reader, 1)?;
5148 if matrix_mixdown_idx_present {
5149 bit_reader.skip(2)?; // matrix_mixdown_idx
5150 bit_reader.skip(1)?; // pseudo_surround_enable
5151 }
5152 let mut _channel_counts = 0;
5153 _channel_counts += read_surround_channel_count(bit_reader, num_front_channel)?;
5154 _channel_counts += read_surround_channel_count(bit_reader, num_side_channel)?;
5155 _channel_counts += read_surround_channel_count(bit_reader, num_back_channel)?;
5156 _channel_counts += read_surround_channel_count(bit_reader, num_lfe_channel)?;
5157 _channel_counts
5158 }
5159 1..=7 => channel_configuration,
5160 // Amendment 4 of the AAC standard in 2013 below
5161 11 => 7, // 6.1 Amendment 4 of the AAC standard in 2013
5162 12 | 14 => 8, // 7.1 (a/d) of ITU BS.2159
5163 _ => {
5164 return Err(Error::Unsupported("invalid channel configuration"));
5165 }
5166 };
5167
5168 esds.audio_object_type = Some(audio_object_type);
5169 esds.extended_audio_object_type = extended_audio_object_type;
5170 esds.audio_sample_rate = Some(sample_frequency_value);
5171 esds.audio_channel_count = Some(channel_counts);
5172 if !esds.decoder_specific_data.is_empty() {
5173 return Status::EsdsDecSpecificIntoTagQuantity.into();
5174 }
5175 esds.decoder_specific_data.extend_from_slice(data)?;
5176
5177 Ok(())
5178 }
5179 _ => Err(Error::Unsupported("unknown aac audio object type")),
5180 }
5181 }
5182
5183 fn read_surround_channel_count(bit_reader: &mut BitReader, channels: u8) -> Result<u16> {
5184 let mut count = 0;
5185 for _ in 0..channels {
5186 let is_cpe: bool = ReadInto::read(bit_reader, 1)?;
5187 count += if is_cpe { 2 } else { 1 };
5188 bit_reader.skip(4)?;
5189 }
5190 Ok(count)
5191 }
5192
5193 /// See MPEG-4 Systems (ISO 14496-1:2010) § 7.2.6.6
5194 fn read_dc_descriptor(data: &[u8], esds: &mut ES_Descriptor) -> Result<()> {
5195 let des = &mut Cursor::new(data);
5196 let object_profile = des.read_u8()?;
5197
5198 #[cfg(feature = "mp4v")]
5199 {
5200 esds.video_codec = match object_profile {
5201 0x20..=0x24 => CodecType::MP4V,
5202 _ => CodecType::Unknown,
5203 };
5204 }
5205
5206 // Skip uninteresting fields.
5207 skip(des, 12)?;
5208
5209 if data.len().to_u64() > des.position() {
5210 find_descriptor(&data[des.position().try_into()?..data.len()], esds)?;
5211 }
5212
5213 esds.audio_codec = match object_profile {
5214 0x40 | 0x66 | 0x67 => CodecType::AAC,
5215 0x69 | 0x6B => CodecType::MP3,
5216 _ => CodecType::Unknown,
5217 };
5218
5219 debug!(
5220 "read_dc_descriptor: esds.audio_codec = {:?}",
5221 esds.audio_codec
5222 );
5223
5224 Ok(())
5225 }
5226
5227 /// See MPEG-4 Systems (ISO 14496-1:2010) § 7.2.6.5
5228 fn read_es_descriptor(data: &[u8], esds: &mut ES_Descriptor) -> Result<()> {
5229 let des = &mut Cursor::new(data);
5230
5231 skip(des, 2)?;
5232
5233 let esds_flags = des.read_u8()?;
5234
5235 // Stream dependency flag, first bit from left most.
5236 if esds_flags & 0x80 > 0 {
5237 // Skip uninteresting fields.
5238 skip(des, 2)?;
5239 }
5240
5241 // Url flag, second bit from left most.
5242 if esds_flags & 0x40 > 0 {
5243 // Skip uninteresting fields.
5244 let skip_es_len = u64::from(des.read_u8()?) + 2;
5245 skip(des, skip_es_len)?;
5246 }
5247
5248 if data.len().to_u64() > des.position() {
5249 find_descriptor(&data[des.position().try_into()?..data.len()], esds)?;
5250 }
5251
5252 Ok(())
5253 }
5254
5255 /// See MP4 (ISO 14496-14:2020) § 6.7.2
5256 fn read_esds<T: Read>(src: &mut BMFFBox<T>) -> Result<ES_Descriptor> {
5257 let (_, _) = read_fullbox_extra(src)?;
5258
5259 let esds_array = read_buf(src, src.bytes_left())?;
5260
5261 let mut es_data = ES_Descriptor::default();
5262 find_descriptor(&esds_array, &mut es_data)?;
5263
5264 es_data.codec_esds = esds_array;
5265
5266 Ok(es_data)
5267 }
5268
5269 /// Parse `FLACSpecificBox`.
5270 /// See [Encapsulation of FLAC in ISO Base Media File Format](https://github.com/xiph/flac/blob/master/doc/isoflac.txt) § 3.3.2
5271 fn read_dfla<T: Read>(src: &mut BMFFBox<T>) -> Result<FLACSpecificBox> {
5272 let (version, flags) = read_fullbox_extra(src)?;
5273 if version != 0 {
5274 return Err(Error::Unsupported("unknown dfLa (FLAC) version"));
5275 }
5276 if flags != 0 {
5277 return Status::DflaFlagsNonzero.into();
5278 }
5279 let mut blocks = TryVec::new();
5280 while src.bytes_left() > 0 {
5281 let block = read_flac_metadata(src)?;
5282 blocks.push(block)?;
5283 }
5284 // The box must have at least one meta block, and the first block
5285 // must be the METADATA_BLOCK_STREAMINFO
5286 if blocks.is_empty() {
5287 return Status::DflaMissingMetadata.into();
5288 } else if blocks[0].block_type != 0 {
5289 return Status::DflaStreamInfoNotFirst.into();
5290 } else if blocks[0].data.len() != 34 {
5291 return Status::DflaStreamInfoBadSize.into();
5292 }
5293 Ok(FLACSpecificBox { version, blocks })
5294 }
5295
5296 /// Parse `OpusSpecificBox`.
5297 fn read_dops<T: Read>(src: &mut BMFFBox<T>) -> Result<OpusSpecificBox> {
5298 let version = src.read_u8()?;
5299 if version != 0 {
5300 return Err(Error::Unsupported("unknown dOps (Opus) version"));
5301 }
5302
5303 let output_channel_count = src.read_u8()?;
5304 let pre_skip = be_u16(src)?;
5305 let input_sample_rate = be_u32(src)?;
5306 let output_gain = be_i16(src)?;
5307 let channel_mapping_family = src.read_u8()?;
5308
5309 let channel_mapping_table = if channel_mapping_family == 0 {
5310 None
5311 } else {
5312 let stream_count = src.read_u8()?;
5313 let coupled_count = src.read_u8()?;
5314 let channel_mapping = read_buf(src, output_channel_count.into())?;
5315
5316 Some(ChannelMappingTable {
5317 stream_count,
5318 coupled_count,
5319 channel_mapping,
5320 })
5321 };
5322
5323 // TODO(kinetik): validate field value ranges.
5324 Ok(OpusSpecificBox {
5325 version,
5326 output_channel_count,
5327 pre_skip,
5328 input_sample_rate,
5329 output_gain,
5330 channel_mapping_family,
5331 channel_mapping_table,
5332 })
5333 }
5334
5335 /// Re-serialize the Opus codec-specific config data as an `OpusHead` packet.
5336 ///
5337 /// Some decoders expect the initialization data in the format used by the
5338 /// Ogg and WebM encapsulations. To support this we prepend the `OpusHead`
5339 /// tag and byte-swap the data from big- to little-endian relative to the
5340 /// dOps box.
5341 pub fn serialize_opus_header<W: byteorder::WriteBytesExt + std::io::Write>(
5342 opus: &OpusSpecificBox,
5343 dst: &mut W,
5344 ) -> Result<()> {
5345 match dst.write(b"OpusHead") {
5346 Err(e) => return Err(Error::from(e)),
5347 Ok(bytes) => {
5348 if bytes != 8 {
5349 return Status::DopsOpusHeadWriteErr.into();
5350 }
5351 }
5352 }
5353 // In mp4 encapsulation, the version field is 0, but in ogg
5354 // it is 1. While decoders generally accept zero as well, write
5355 // out the version of the header we're supporting rather than
5356 // whatever we parsed out of mp4.
5357 dst.write_u8(1)?;
5358 dst.write_u8(opus.output_channel_count)?;
5359 dst.write_u16::<byteorder::LittleEndian>(opus.pre_skip)?;
5360 dst.write_u32::<byteorder::LittleEndian>(opus.input_sample_rate)?;
5361 dst.write_i16::<byteorder::LittleEndian>(opus.output_gain)?;
5362 dst.write_u8(opus.channel_mapping_family)?;
5363 match opus.channel_mapping_table {
5364 None => {}
5365 Some(ref table) => {
5366 dst.write_u8(table.stream_count)?;
5367 dst.write_u8(table.coupled_count)?;
5368 match dst.write(&table.channel_mapping) {
5369 Err(e) => return Err(Error::from(e)),
5370 Ok(bytes) => {
5371 if bytes != table.channel_mapping.len() {
5372 return Status::DopsChannelMappingWriteErr.into();
5373 }
5374 }
5375 }
5376 }
5377 };
5378 Ok(())
5379 }
5380
5381 /// Parse `ALACSpecificBox`.
5382 fn read_alac<T: Read>(src: &mut BMFFBox<T>) -> Result<ALACSpecificBox> {
5383 let (version, flags) = read_fullbox_extra(src)?;
5384 if version != 0 {
5385 return Err(Error::Unsupported("unknown alac (ALAC) version"));
5386 }
5387 if flags != 0 {
5388 return Status::AlacFlagsNonzero.into();
5389 }
5390
5391 let length = match src.bytes_left() {
5392 x @ 24 | x @ 48 => x,
5393 _ => {
5394 return Status::AlacBadMagicCookieSize.into();
5395 }
5396 };
5397 let data = read_buf(src, length)?;
5398
5399 Ok(ALACSpecificBox { version, data })
5400 }
5401
5402 /// Parse a Handler Reference Box.<br />
5403 /// See ISOBMFF (ISO 14496-12:2020) § 8.4.3<br />
5404 /// See [\[ISOBMFF\]: reserved (field = 0;) handling is ambiguous](https://github.com/MPEGGroup/FileFormat/issues/36)
5405 fn read_hdlr<T: Read>(src: &mut BMFFBox<T>, strictness: ParseStrictness) -> Result<HandlerBox> {
5406 if read_fullbox_version_no_flags(src)? != 0 {
5407 return Status::HdlrUnsupportedVersion.into();
5408 }
5409
5410 let pre_defined = be_u32(src)?;
5411 if pre_defined != 0 {
5412 fail_with_status_if(
5413 strictness == ParseStrictness::Strict,
5414 Status::HdlrPredefinedNonzero,
5415 )?;
5416 }
5417
5418 let handler_type = FourCC::from(be_u32(src)?);
5419
5420 for _ in 1..=3 {
5421 let reserved = be_u32(src)?;
5422 if reserved != 0 {
5423 fail_with_status_if(
5424 strictness == ParseStrictness::Strict,
5425 Status::HdlrReservedNonzero,
5426 )?;
5427 }
5428 }
5429
5430 match std::str::from_utf8(src.read_into_try_vec()?.as_slice()) {
5431 Ok(name) => {
5432 // `name` must be nul-terminated and any trailing bytes after the first nul ignored.
5433 // See https://github.com/MPEGGroup/FileFormat/issues/35
5434 if !name.bytes().any(|b| b == b'\0') {
5435 fail_with_status_if(
5436 strictness != ParseStrictness::Permissive,
5437 Status::HdlrNameNoNul,
5438 )?;
5439 }
5440 }
5441 Err(_) => fail_with_status_if(
5442 strictness != ParseStrictness::Permissive,
5443 Status::HdlrNameNotUtf8,
5444 )?,
5445 }
5446
5447 Ok(HandlerBox { handler_type })
5448 }
5449
5450 /// Parse an video description inside an stsd box.
5451 fn read_video_sample_entry<T: Read>(src: &mut BMFFBox<T>) -> Result<SampleEntry> {
5452 let name = src.get_header().name;
5453 let codec_type = match name {
5454 BoxType::AVCSampleEntry | BoxType::AVC3SampleEntry => CodecType::H264,
5455 BoxType::MP4VideoSampleEntry => CodecType::MP4V,
5456 BoxType::VP8SampleEntry => CodecType::VP8,
5457 BoxType::VP9SampleEntry => CodecType::VP9,
5458 BoxType::AV1SampleEntry => CodecType::AV1,
5459 BoxType::ProtectedVisualSampleEntry => CodecType::EncryptedVideo,
5460 BoxType::H263SampleEntry => CodecType::H263,
5461 BoxType::HEV1SampleEntry | BoxType::HVC1SampleEntry => CodecType::HEVC,
5462 _ => {
5463 debug!("Unsupported video codec, box {:?} found", name);
5464 CodecType::Unknown
5465 }
5466 };
5467
5468 // Skip uninteresting fields.
5469 skip(src, 6)?;
5470
5471 let data_reference_index = be_u16(src)?;
5472
5473 // Skip uninteresting fields.
5474 skip(src, 16)?;
5475
5476 let width = be_u16(src)?;
5477 let height = be_u16(src)?;
5478
5479 // Skip uninteresting fields.
5480 skip(src, 50)?;
5481
5482 // Skip clap/pasp/etc. for now.
5483 let mut codec_specific = None;
5484 let mut pixel_aspect_ratio = None;
5485 let mut protection_info = TryVec::new();
5486 let mut iter = src.box_iter();
5487 while let Some(mut b) = iter.next_box()? {
5488 match b.head.name {
5489 BoxType::AVCConfigurationBox => {
5490 if (name != BoxType::AVCSampleEntry
5491 && name != BoxType::AVC3SampleEntry
5492 && name != BoxType::ProtectedVisualSampleEntry)
5493 || codec_specific.is_some()
5494 {
5495 return Status::StsdBadVideoSampleEntry.into();
5496 }
5497 let avcc_size = b
5498 .head
5499 .size
5500 .checked_sub(b.head.offset)
5501 .expect("offset invalid");
5502 let avcc = read_buf(&mut b.content, avcc_size)?;
5503 debug!("{:?} (avcc)", avcc);
5504 // TODO(kinetik): Parse avcC box? For now we just stash the data.
5505 codec_specific = Some(VideoCodecSpecific::AVCConfig(avcc));
5506 }
5507 BoxType::H263SpecificBox => {
5508 if (name != BoxType::H263SampleEntry) || codec_specific.is_some() {
5509 return Status::StsdBadVideoSampleEntry.into();
5510 }
5511 let h263_dec_spec_struc_size = b
5512 .head
5513 .size
5514 .checked_sub(b.head.offset)
5515 .expect("offset invalid");
5516 let h263_dec_spec_struc = read_buf(&mut b.content, h263_dec_spec_struc_size)?;
5517 debug!("{:?} (h263DecSpecStruc)", h263_dec_spec_struc);
5518
5519 codec_specific = Some(VideoCodecSpecific::H263Config(h263_dec_spec_struc));
5520 }
5521 BoxType::VPCodecConfigurationBox => {
5522 // vpcC
5523 if (name != BoxType::VP8SampleEntry
5524 && name != BoxType::VP9SampleEntry
5525 && name != BoxType::ProtectedVisualSampleEntry)
5526 || codec_specific.is_some()
5527 {
5528 return Status::StsdBadVideoSampleEntry.into();
5529 }
5530 let vpcc = read_vpcc(&mut b)?;
5531 codec_specific = Some(VideoCodecSpecific::VPxConfig(vpcc));
5532 }
5533 BoxType::AV1CodecConfigurationBox => {
5534 if name != BoxType::AV1SampleEntry && name != BoxType::ProtectedVisualSampleEntry {
5535 return Status::StsdBadVideoSampleEntry.into();
5536 }
5537 let av1c = read_av1c(&mut b)?;
5538 codec_specific = Some(VideoCodecSpecific::AV1Config(av1c));
5539 }
5540 BoxType::ESDBox => {
5541 if name != BoxType::MP4VideoSampleEntry || codec_specific.is_some() {
5542 return Status::StsdBadVideoSampleEntry.into();
5543 }
5544 #[cfg(not(feature = "mp4v"))]
5545 {
5546 let (_, _) = read_fullbox_extra(&mut b.content)?;
5547 // Subtract 4 extra to offset the members of fullbox not
5548 // accounted for in head.offset
5549 let esds_size = b
5550 .head
5551 .size
5552 .checked_sub(b.head.offset + 4)
5553 .expect("offset invalid");
5554 let esds = read_buf(&mut b.content, esds_size)?;
5555 codec_specific = Some(VideoCodecSpecific::ESDSConfig(esds));
5556 }
5557 #[cfg(feature = "mp4v")]
5558 {
5559 // Read ES_Descriptor inside an esds box.
5560 // See ISOBMFF (ISO 14496-1:2010) § 7.2.6.5
5561 let esds = read_esds(&mut b)?;
5562 codec_specific =
5563 Some(VideoCodecSpecific::ESDSConfig(esds.decoder_specific_data));
5564 }
5565 }
5566 BoxType::ProtectionSchemeInfoBox => {
5567 if name != BoxType::ProtectedVisualSampleEntry {
5568 return Status::StsdBadVideoSampleEntry.into();
5569 }
5570 let sinf = read_sinf(&mut b)?;
5571 debug!("{:?} (sinf)", sinf);
5572 protection_info.push(sinf)?;
5573 }
5574 BoxType::HEVCConfigurationBox => {
5575 if (name != BoxType::HEV1SampleEntry
5576 && name != BoxType::HVC1SampleEntry
5577 && name != BoxType::ProtectedVisualSampleEntry)
5578 || codec_specific.is_some()
5579 {
5580 return Status::StsdBadVideoSampleEntry.into();
5581 }
5582 let hvcc_size = b
5583 .head
5584 .size
5585 .checked_sub(b.head.offset)
5586 .expect("offset invalid");
5587 let hvcc = read_buf(&mut b.content, hvcc_size)?;
5588 debug!("{:?} (hvcc)", hvcc);
5589 codec_specific = Some(VideoCodecSpecific::HEVCConfig(hvcc));
5590 }
5591 BoxType::PixelAspectRatioBox => {
5592 let pasp = read_pasp(&mut b)?;
5593 let aspect_ratio = pasp.h_spacing as f32 / pasp.v_spacing as f32;
5594 let is_valid_aspect_ratio = |value: f32| -> bool { value > 0.0 && value < 10.0 };
5595 // Only set pixel_aspect_ratio if it is valid
5596 if is_valid_aspect_ratio(aspect_ratio) {
5597 pixel_aspect_ratio = Some(aspect_ratio);
5598 }
5599 debug!("Parsed pasp box: {:?}, PAR {:?}", pasp, pixel_aspect_ratio);
5600 }
5601 _ => {
5602 debug!("Unsupported video codec, box {:?} found", b.head.name);
5603 skip_box_content(&mut b)?;
5604 }
5605 }
5606 check_parser_state!(b.content);
5607 }
5608
5609 Ok(
5610 codec_specific.map_or(SampleEntry::Unknown, |codec_specific| {
5611 SampleEntry::Video(VideoSampleEntry {
5612 codec_type,
5613 data_reference_index,
5614 width,
5615 height,
5616 codec_specific,
5617 protection_info,
5618 pixel_aspect_ratio,
5619 })
5620 }),
5621 )
5622 }
5623
5624 fn read_qt_wave_atom<T: Read>(src: &mut BMFFBox<T>) -> Result<ES_Descriptor> {
5625 let mut codec_specific = None;
5626 let mut iter = src.box_iter();
5627 while let Some(mut b) = iter.next_box()? {
5628 match b.head.name {
5629 BoxType::ESDBox => {
5630 let esds = read_esds(&mut b)?;
5631 codec_specific = Some(esds);
5632 }
5633 _ => skip_box_content(&mut b)?,
5634 }
5635 }
5636
5637 codec_specific.ok_or_else(|| Error::from(Status::EsdsBadAudioSampleEntry))
5638 }
5639
5640 /// Parse an audio description inside an stsd box.
5641 /// See ISOBMFF (ISO 14496-12:2020) § 12.2.3
5642 fn read_audio_sample_entry<T: Read>(src: &mut BMFFBox<T>) -> Result<SampleEntry> {
5643 let name = src.get_header().name;
5644
5645 // Skip uninteresting fields.
5646 skip(src, 6)?;
5647
5648 let data_reference_index = be_u16(src)?;
5649
5650 // XXX(kinetik): This is "reserved" in BMFF, but some old QT MOV variant
5651 // uses it, need to work out if we have to support it. Without checking
5652 // here and reading extra fields after samplerate (or bailing with an
5653 // error), the parser loses sync completely.
5654 let version = be_u16(src)?;
5655
5656 // Skip uninteresting fields.
5657 skip(src, 6)?;
5658
5659 let mut channelcount = u32::from(be_u16(src)?);
5660 let samplesize = be_u16(src)?;
5661
5662 // Skip uninteresting fields.
5663 skip(src, 4)?;
5664
5665 let mut samplerate = f64::from(be_u32(src)? >> 16); // 16.16 fixed point;
5666
5667 match version {
5668 0 => (),
5669 1 => {
5670 // Quicktime sound sample description version 1.
5671 // Skip uninteresting fields.
5672 skip(src, 16)?;
5673 }
5674 2 => {
5675 // Quicktime sound sample description version 2.
5676 skip(src, 4)?;
5677 samplerate = f64::from_bits(be_u64(src)?);
5678 channelcount = be_u32(src)?;
5679 skip(src, 20)?;
5680 }
5681 _ => {
5682 return Err(Error::Unsupported(
5683 "unsupported non-isom audio sample entry",
5684 ))
5685 }
5686 }
5687
5688 let (mut codec_type, mut codec_specific) = match name {
5689 BoxType::MP3AudioSampleEntry => (CodecType::MP3, Some(AudioCodecSpecific::MP3)),
5690 BoxType::LPCMAudioSampleEntry => (CodecType::LPCM, Some(AudioCodecSpecific::LPCM)),
5691 // Some mp4 file with AMR doesn't have AMRSpecificBox "damr" in followed while loop,
5692 // we use empty box by default.
5693 #[cfg(feature = "3gpp")]
5694 BoxType::AMRNBSampleEntry => (
5695 CodecType::AMRNB,
5696 Some(AudioCodecSpecific::AMRSpecificBox(Default::default())),
5697 ),
5698 #[cfg(feature = "3gpp")]
5699 BoxType::AMRWBSampleEntry => (
5700 CodecType::AMRWB,
5701 Some(AudioCodecSpecific::AMRSpecificBox(Default::default())),
5702 ),
5703 _ => (CodecType::Unknown, None),
5704 };
5705 let mut protection_info = TryVec::new();
5706 let mut iter = src.box_iter();
5707 while let Some(mut b) = iter.next_box()? {
5708 match b.head.name {
5709 BoxType::ESDBox => {
5710 if (name != BoxType::MP4AudioSampleEntry
5711 && name != BoxType::ProtectedAudioSampleEntry)
5712 || codec_specific.is_some()
5713 {
5714 return Status::StsdBadAudioSampleEntry.into();
5715 }
5716 let esds = read_esds(&mut b)?;
5717 codec_type = esds.audio_codec;
5718 codec_specific = Some(AudioCodecSpecific::ES_Descriptor(esds));
5719 }
5720 BoxType::FLACSpecificBox => {
5721 if (name != BoxType::FLACSampleEntry && name != BoxType::ProtectedAudioSampleEntry)
5722 || codec_specific.is_some()
5723 {
5724 return Status::StsdBadAudioSampleEntry.into();
5725 }
5726 let dfla = read_dfla(&mut b)?;
5727 codec_type = CodecType::FLAC;
5728 codec_specific = Some(AudioCodecSpecific::FLACSpecificBox(dfla));
5729 }
5730 BoxType::OpusSpecificBox => {
5731 if (name != BoxType::OpusSampleEntry && name != BoxType::ProtectedAudioSampleEntry)
5732 || codec_specific.is_some()
5733 {
5734 return Status::StsdBadAudioSampleEntry.into();
5735 }
5736 let dops = read_dops(&mut b)?;
5737 codec_type = CodecType::Opus;
5738 codec_specific = Some(AudioCodecSpecific::OpusSpecificBox(dops));
5739 }
5740 BoxType::ALACSpecificBox => {
5741 if name != BoxType::ALACSpecificBox || codec_specific.is_some() {
5742 return Status::StsdBadAudioSampleEntry.into();
5743 }
5744 let alac = read_alac(&mut b)?;
5745 codec_type = CodecType::ALAC;
5746 codec_specific = Some(AudioCodecSpecific::ALACSpecificBox(alac));
5747 }
5748 BoxType::QTWaveAtom => {
5749 let qt_esds = read_qt_wave_atom(&mut b)?;
5750 codec_type = qt_esds.audio_codec;
5751 codec_specific = Some(AudioCodecSpecific::ES_Descriptor(qt_esds));
5752 }
5753 BoxType::ProtectionSchemeInfoBox => {
5754 if name != BoxType::ProtectedAudioSampleEntry {
5755 return Status::StsdBadAudioSampleEntry.into();
5756 }
5757 let sinf = read_sinf(&mut b)?;
5758 debug!("{:?} (sinf)", sinf);
5759 codec_type = CodecType::EncryptedAudio;
5760 protection_info.push(sinf)?;
5761 }
5762 #[cfg(feature = "3gpp")]
5763 BoxType::AMRSpecificBox => {
5764 if codec_type != CodecType::AMRNB && codec_type != CodecType::AMRWB {
5765 return Status::StsdBadAudioSampleEntry.into();
5766 }
5767 let amr_dec_spec_struc_size = b
5768 .head
5769 .size
5770 .checked_sub(b.head.offset)
5771 .expect("offset invalid");
5772 let amr_dec_spec_struc = read_buf(&mut b.content, amr_dec_spec_struc_size)?;
5773 debug!("{:?} (AMRDecSpecStruc)", amr_dec_spec_struc);
5774 codec_specific = Some(AudioCodecSpecific::AMRSpecificBox(amr_dec_spec_struc));
5775 }
5776 _ => {
5777 debug!("Unsupported audio codec, box {:?} found", b.head.name);
5778 skip_box_content(&mut b)?;
5779 }
5780 }
5781 check_parser_state!(b.content);
5782 }
5783
5784 Ok(
5785 codec_specific.map_or(SampleEntry::Unknown, |codec_specific| {
5786 SampleEntry::Audio(AudioSampleEntry {
5787 codec_type,
5788 data_reference_index,
5789 channelcount,
5790 samplesize,
5791 samplerate,
5792 codec_specific,
5793 protection_info,
5794 })
5795 }),
5796 )
5797 }
5798
5799 /// Parse a stsd box.
5800 /// See ISOBMFF (ISO 14496-12:2020) § 8.5.2
5801 /// See MP4 (ISO 14496-14:2020) § 6.7.2
5802 fn read_stsd<T: Read>(src: &mut BMFFBox<T>, track: &Track) -> Result<SampleDescriptionBox> {
5803 let (_, flags) = read_fullbox_extra(src)?;
5804
5805 if flags != 0 {
5806 warn!(
5807 "Unexpected `flags` value for SampleDescriptionBox (stsd): {}",
5808 flags
5809 );
5810 }
5811
5812 let description_count = be_u32(src)?.to_usize();
5813 let mut descriptions = TryVec::with_capacity(description_count)?;
5814
5815 let mut iter = src.box_iter();
5816 while descriptions.len() < description_count {
5817 if let Some(mut b) = iter.next_box()? {
5818 let description = match track.track_type {
5819 TrackType::Video => read_video_sample_entry(&mut b),
5820 TrackType::Picture => read_video_sample_entry(&mut b),
5821 TrackType::AuxiliaryVideo => read_video_sample_entry(&mut b),
5822 TrackType::Audio => read_audio_sample_entry(&mut b),
5823 TrackType::Metadata => Err(Error::Unsupported("metadata track")),
5824 TrackType::Unknown => Err(Error::Unsupported("unknown track type")),
5825 };
5826 let description = match description {
5827 Ok(desc) => desc,
5828 Err(Error::Unsupported(_)) => {
5829 // read_{audio,video}_desc may have returned Unsupported
5830 // after partially reading the box content, so we can't
5831 // simply use skip_box_content here.
5832 let to_skip = b.bytes_left();
5833 skip(&mut b, to_skip)?;
5834 SampleEntry::Unknown
5835 }
5836 Err(e) => return Err(e),
5837 };
5838 descriptions.push(description)?;
5839 check_parser_state!(b.content);
5840 } else {
5841 break;
5842 }
5843 }
5844
5845 // Padding could be added in some contents.
5846 skip_box_remain(src)?;
5847
5848 Ok(SampleDescriptionBox { descriptions })
5849 }
5850
5851 fn read_sinf<T: Read>(src: &mut BMFFBox<T>) -> Result<ProtectionSchemeInfoBox> {
5852 let mut sinf = ProtectionSchemeInfoBox::default();
5853
5854 let mut iter = src.box_iter();
5855 while let Some(mut b) = iter.next_box()? {
5856 match b.head.name {
5857 BoxType::OriginalFormatBox => {
5858 sinf.original_format = FourCC::from(be_u32(&mut b)?);
5859 }
5860 BoxType::SchemeTypeBox => {
5861 sinf.scheme_type = Some(read_schm(&mut b)?);
5862 }
5863 BoxType::SchemeInformationBox => {
5864 // We only need tenc box in schi box so far.
5865 sinf.tenc = read_schi(&mut b)?;
5866 }
5867 _ => skip_box_content(&mut b)?,
5868 }
5869 check_parser_state!(b.content);
5870 }
5871
5872 Ok(sinf)
5873 }
5874
5875 fn read_schi<T: Read>(src: &mut BMFFBox<T>) -> Result<Option<TrackEncryptionBox>> {
5876 let mut tenc = None;
5877 let mut iter = src.box_iter();
5878 while let Some(mut b) = iter.next_box()? {
5879 match b.head.name {
5880 BoxType::TrackEncryptionBox => {
5881 if tenc.is_some() {
5882 return Status::SchiQuantity.into();
5883 }
5884 tenc = Some(read_tenc(&mut b)?);
5885 }
5886 _ => skip_box_content(&mut b)?,
5887 }
5888 }
5889
5890 Ok(tenc)
5891 }
5892
5893 fn read_tenc<T: Read>(src: &mut BMFFBox<T>) -> Result<TrackEncryptionBox> {
5894 let (version, _) = read_fullbox_extra(src)?;
5895
5896 // reserved byte
5897 skip(src, 1)?;
5898 // the next byte is used to signal the default pattern in version >= 1
5899 let (default_crypt_byte_block, default_skip_byte_block) = match version {
5900 0 => {
5901 skip(src, 1)?;
5902 (None, None)
5903 }
5904 _ => {
5905 let pattern_byte = src.read_u8()?;
5906 let crypt_bytes = pattern_byte >> 4;
5907 let skip_bytes = pattern_byte & 0x0f;
5908 (Some(crypt_bytes), Some(skip_bytes))
5909 }
5910 };
5911 let default_is_encrypted = src.read_u8()?;
5912 let default_iv_size = src.read_u8()?;
5913 let default_kid = read_buf(src, 16)?;
5914 // If default_is_encrypted == 1 && default_iv_size == 0 we expect a default_constant_iv
5915 let default_constant_iv = match (default_is_encrypted, default_iv_size) {
5916 (1, 0) => {
5917 let default_constant_iv_size = src.read_u8()?;
5918 Some(read_buf(src, default_constant_iv_size.into())?)
5919 }
5920 _ => None,
5921 };
5922
5923 Ok(TrackEncryptionBox {
5924 is_encrypted: default_is_encrypted,
5925 iv_size: default_iv_size,
5926 kid: default_kid,
5927 crypt_byte_block_count: default_crypt_byte_block,
5928 skip_byte_block_count: default_skip_byte_block,
5929 constant_iv: default_constant_iv,
5930 })
5931 }
5932
5933 fn read_schm<T: Read>(src: &mut BMFFBox<T>) -> Result<SchemeTypeBox> {
5934 // Flags can be used to signal presence of URI in the box, but we don't
5935 // use the URI so don't bother storing the flags.
5936 let (_, _) = read_fullbox_extra(src)?;
5937 let scheme_type = FourCC::from(be_u32(src)?);
5938 let scheme_version = be_u32(src)?;
5939 // Null terminated scheme URI may follow, but we don't use it right now.
5940 skip_box_remain(src)?;
5941 Ok(SchemeTypeBox {
5942 scheme_type,
5943 scheme_version,
5944 })
5945 }
5946
5947 /// Parse a metadata box inside a moov, trak, or mdia box.
5948 /// See ISOBMFF (ISO 14496-12:2020) § 8.10.1.
5949 fn read_udta<T: Read>(src: &mut BMFFBox<T>) -> Result<UserdataBox> {
5950 let mut iter = src.box_iter();
5951 let mut udta = UserdataBox { meta: None };
5952
5953 while let Some(mut b) = iter.next_box()? {
5954 match b.head.name {
5955 BoxType::MetadataBox => {
5956 let meta = read_meta(&mut b)?;
5957 udta.meta = Some(meta);
5958 }
5959 _ => skip_box_content(&mut b)?,
5960 };
5961 check_parser_state!(b.content);
5962 }
5963 Ok(udta)
5964 }
5965
5966 /// Parse the meta box
5967 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.1
5968 fn read_meta<T: Read>(src: &mut BMFFBox<T>) -> Result<MetadataBox> {
5969 let (_, _) = read_fullbox_extra(src)?;
5970 let mut iter = src.box_iter();
5971 let mut meta = MetadataBox::default();
5972 while let Some(mut b) = iter.next_box()? {
5973 match b.head.name {
5974 BoxType::MetadataItemListEntry => read_ilst(&mut b, &mut meta)?,
5975 #[cfg(feature = "meta-xml")]
5976 BoxType::MetadataXMLBox => read_xml_(&mut b, &mut meta)?,
5977 #[cfg(feature = "meta-xml")]
5978 BoxType::MetadataBXMLBox => read_bxml(&mut b, &mut meta)?,
5979 _ => skip_box_content(&mut b)?,
5980 };
5981 check_parser_state!(b.content);
5982 }
5983 Ok(meta)
5984 }
5985
5986 /// Parse a XML box inside a meta box
5987 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.2
5988 #[cfg(feature = "meta-xml")]
5989 fn read_xml_<T: Read>(src: &mut BMFFBox<T>, meta: &mut MetadataBox) -> Result<()> {
5990 if read_fullbox_version_no_flags(src)? != 0 {
5991 return Err(Error::Unsupported("unsupported XmlBox version"));
5992 }
5993 meta.xml = Some(XmlBox::StringXmlBox(src.read_into_try_vec()?));
5994 Ok(())
5995 }
5996
5997 /// Parse a Binary XML box inside a meta box
5998 /// See ISOBMFF (ISO 14496-12:2020) § 8.11.2
5999 #[cfg(feature = "meta-xml")]
6000 fn read_bxml<T: Read>(src: &mut BMFFBox<T>, meta: &mut MetadataBox) -> Result<()> {
6001 if read_fullbox_version_no_flags(src)? != 0 {
6002 return Err(Error::Unsupported("unsupported XmlBox version"));
6003 }
6004 meta.xml = Some(XmlBox::BinaryXmlBox(src.read_into_try_vec()?));
6005 Ok(())
6006 }
6007
6008 /// Parse a metadata box inside a udta box
6009 fn read_ilst<T: Read>(src: &mut BMFFBox<T>, meta: &mut MetadataBox) -> Result<()> {
6010 let mut iter = src.box_iter();
6011 while let Some(mut b) = iter.next_box()? {
6012 match b.head.name {
6013 BoxType::AlbumEntry => meta.album = read_ilst_string_data(&mut b)?,
6014 BoxType::ArtistEntry | BoxType::ArtistLowercaseEntry => {
6015 meta.artist = read_ilst_string_data(&mut b)?
6016 }
6017 BoxType::AlbumArtistEntry => meta.album_artist = read_ilst_string_data(&mut b)?,
6018 BoxType::CommentEntry => meta.comment = read_ilst_string_data(&mut b)?,
6019 BoxType::DateEntry => meta.year = read_ilst_string_data(&mut b)?,
6020 BoxType::TitleEntry => meta.title = read_ilst_string_data(&mut b)?,
6021 BoxType::CustomGenreEntry => {
6022 meta.genre = read_ilst_string_data(&mut b)?.map(Genre::CustomGenre)
6023 }
6024 BoxType::StandardGenreEntry => {
6025 meta.genre = read_ilst_u8_data(&mut b)?
6026 .and_then(|gnre| Some(Genre::StandardGenre(gnre.get(1).copied()?)))
6027 }
6028 BoxType::ComposerEntry => meta.composer = read_ilst_string_data(&mut b)?,
6029 BoxType::EncoderEntry => meta.encoder = read_ilst_string_data(&mut b)?,
6030 BoxType::EncodedByEntry => meta.encoded_by = read_ilst_string_data(&mut b)?,
6031 BoxType::CopyrightEntry => meta.copyright = read_ilst_string_data(&mut b)?,
6032 BoxType::GroupingEntry => meta.grouping = read_ilst_string_data(&mut b)?,
6033 BoxType::CategoryEntry => meta.category = read_ilst_string_data(&mut b)?,
6034 BoxType::KeywordEntry => meta.keyword = read_ilst_string_data(&mut b)?,
6035 BoxType::PodcastUrlEntry => meta.podcast_url = read_ilst_string_data(&mut b)?,
6036 BoxType::PodcastGuidEntry => meta.podcast_guid = read_ilst_string_data(&mut b)?,
6037 BoxType::DescriptionEntry => meta.description = read_ilst_string_data(&mut b)?,
6038 BoxType::LongDescriptionEntry => meta.long_description = read_ilst_string_data(&mut b)?,
6039 BoxType::LyricsEntry => meta.lyrics = read_ilst_string_data(&mut b)?,
6040 BoxType::TVNetworkNameEntry => meta.tv_network_name = read_ilst_string_data(&mut b)?,
6041 BoxType::TVEpisodeNameEntry => meta.tv_episode_name = read_ilst_string_data(&mut b)?,
6042 BoxType::TVShowNameEntry => meta.tv_show_name = read_ilst_string_data(&mut b)?,
6043 BoxType::PurchaseDateEntry => meta.purchase_date = read_ilst_string_data(&mut b)?,
6044 BoxType::RatingEntry => meta.rating = read_ilst_string_data(&mut b)?,
6045 BoxType::OwnerEntry => meta.owner = read_ilst_string_data(&mut b)?,
6046 BoxType::HDVideoEntry => meta.hd_video = read_ilst_bool_data(&mut b)?,
6047 BoxType::SortNameEntry => meta.sort_name = read_ilst_string_data(&mut b)?,
6048 BoxType::SortArtistEntry => meta.sort_artist = read_ilst_string_data(&mut b)?,
6049 BoxType::SortAlbumEntry => meta.sort_album = read_ilst_string_data(&mut b)?,
6050 BoxType::SortAlbumArtistEntry => {
6051 meta.sort_album_artist = read_ilst_string_data(&mut b)?
6052 }
6053 BoxType::SortComposerEntry => meta.sort_composer = read_ilst_string_data(&mut b)?,
6054 BoxType::TrackNumberEntry => {
6055 if let Some(trkn) = read_ilst_u8_data(&mut b)? {
6056 meta.track_number = trkn.get(3).copied();
6057 meta.total_tracks = trkn.get(5).copied();
6058 };
6059 }
6060 BoxType::DiskNumberEntry => {
6061 if let Some(disk) = read_ilst_u8_data(&mut b)? {
6062 meta.disc_number = disk.get(3).copied();
6063 meta.total_discs = disk.get(5).copied();
6064 };
6065 }
6066 BoxType::TempoEntry => {
6067 meta.beats_per_minute =
6068 read_ilst_u8_data(&mut b)?.and_then(|tmpo| tmpo.get(1).copied())
6069 }
6070 BoxType::CompilationEntry => meta.compilation = read_ilst_bool_data(&mut b)?,
6071 BoxType::AdvisoryEntry => {
6072 meta.advisory = read_ilst_u8_data(&mut b)?.and_then(|rtng| {
6073 Some(match rtng.first()? {
6074 2 => AdvisoryRating::Clean,
6075 0 => AdvisoryRating::Inoffensive,
6076 r => AdvisoryRating::Explicit(*r),
6077 })
6078 })
6079 }
6080 BoxType::MediaTypeEntry => {
6081 meta.media_type = read_ilst_u8_data(&mut b)?.and_then(|stik| {
6082 Some(match stik.first()? {
6083 0 => MediaType::Movie,
6084 1 => MediaType::Normal,
6085 2 => MediaType::AudioBook,
6086 5 => MediaType::WhackedBookmark,
6087 6 => MediaType::MusicVideo,
6088 9 => MediaType::ShortFilm,
6089 10 => MediaType::TVShow,
6090 11 => MediaType::Booklet,
6091 s => MediaType::Unknown(*s),
6092 })
6093 })
6094 }
6095 BoxType::PodcastEntry => meta.podcast = read_ilst_bool_data(&mut b)?,
6096 BoxType::TVSeasonNumberEntry => {
6097 meta.tv_season = read_ilst_u8_data(&mut b)?.and_then(|tvsn| tvsn.get(3).copied())
6098 }
6099 BoxType::TVEpisodeNumberEntry => {
6100 meta.tv_episode_number =
6101 read_ilst_u8_data(&mut b)?.and_then(|tves| tves.get(3).copied())
6102 }
6103 BoxType::GaplessPlaybackEntry => meta.gapless_playback = read_ilst_bool_data(&mut b)?,
6104 BoxType::CoverArtEntry => meta.cover_art = read_ilst_multiple_u8_data(&mut b).ok(),
6105 _ => skip_box_content(&mut b)?,
6106 };
6107 check_parser_state!(b.content);
6108 }
6109 Ok(())
6110 }
6111
6112 fn read_ilst_bool_data<T: Read>(src: &mut BMFFBox<T>) -> Result<Option<bool>> {
6113 Ok(read_ilst_u8_data(src)?.and_then(|d| Some(d.first()? == &1)))
6114 }
6115
6116 fn read_ilst_string_data<T: Read>(src: &mut BMFFBox<T>) -> Result<Option<TryString>> {
6117 read_ilst_u8_data(src)
6118 }
6119
6120 fn read_ilst_u8_data<T: Read>(src: &mut BMFFBox<T>) -> Result<Option<TryVec<u8>>> {
6121 // For all non-covr atoms, there must only be one data atom.
6122 Ok(read_ilst_multiple_u8_data(src)?.pop())
6123 }
6124
6125 fn read_ilst_multiple_u8_data<T: Read>(src: &mut BMFFBox<T>) -> Result<TryVec<TryVec<u8>>> {
6126 let mut iter = src.box_iter();
6127 let mut data = TryVec::new();
6128 while let Some(mut b) = iter.next_box()? {
6129 match b.head.name {
6130 BoxType::MetadataItemDataEntry => {
6131 data.push(read_ilst_data(&mut b)?)?;
6132 }
6133 _ => skip_box_content(&mut b)?,
6134 };
6135 check_parser_state!(b.content);
6136 }
6137 Ok(data)
6138 }
6139
6140 fn read_ilst_data<T: Read>(src: &mut BMFFBox<T>) -> Result<TryVec<u8>> {
6141 // Skip past the padding bytes
6142 skip(&mut src.content, src.head.offset)?;
6143 let size = src.content.limit();
6144 read_buf(&mut src.content, size)
6145 }
6146
6147 /// Skip a number of bytes that we don't care to parse.
6148 fn skip<T: Read>(src: &mut T, bytes: u64) -> Result<()> {
6149 std::io::copy(&mut src.take(bytes), &mut std::io::sink())?;
6150 Ok(())
6151 }
6152
6153 /// Read size bytes into a Vector or return error.
6154 fn read_buf<T: Read>(src: &mut T, size: u64) -> Result<TryVec<u8>> {
6155 let buf = src.take(size).read_into_try_vec()?;
6156 if buf.len().to_u64() != size {
6157 return Status::ReadBufErr.into();
6158 }
6159
6160 Ok(buf)
6161 }
6162
6163 fn be_i16<T: ReadBytesExt>(src: &mut T) -> Result<i16> {
6164 src.read_i16::<byteorder::BigEndian>().map_err(From::from)
6165 }
6166
6167 fn be_i32<T: ReadBytesExt>(src: &mut T) -> Result<i32> {
6168 src.read_i32::<byteorder::BigEndian>().map_err(From::from)
6169 }
6170
6171 fn be_i64<T: ReadBytesExt>(src: &mut T) -> Result<i64> {
6172 src.read_i64::<byteorder::BigEndian>().map_err(From::from)
6173 }
6174
6175 fn be_u16<T: ReadBytesExt>(src: &mut T) -> Result<u16> {
6176 src.read_u16::<byteorder::BigEndian>().map_err(From::from)
6177 }
6178
6179 fn be_u24<T: ReadBytesExt>(src: &mut T) -> Result<u32> {
6180 src.read_u24::<byteorder::BigEndian>().map_err(From::from)
6181 }
6182
6183 fn be_u32<T: ReadBytesExt>(src: &mut T) -> Result<u32> {
6184 src.read_u32::<byteorder::BigEndian>().map_err(From::from)
6185 }
6186
6187 fn be_u64<T: ReadBytesExt>(src: &mut T) -> Result<u64> {
6188 src.read_u64::<byteorder::BigEndian>().map_err(From::from)
6189 }
6190
6191 fn write_be_u32<T: WriteBytesExt>(des: &mut T, num: u32) -> Result<()> {
6192 des.write_u32::<byteorder::BigEndian>(num)
6193 .map_err(From::from)
6194 }
6195
6196 #[cfg(test)]
6197 mod media_data_box_tests {
6198 use super::*;
6199
6200 impl DataBox {
6201 fn at_offset(file_offset: u64, data: std::vec::Vec<u8>) -> Self {
6202 DataBox {
6203 metadata: DataBoxMetadata::Mdat { file_offset },
6204 data: data.into(),
6205 }
6206 }
6207 }
6208
6209 #[test]
6210 fn extent_with_length_before_mdat_returns_none() {
6211 let mdat = DataBox::at_offset(100, vec![1; 5]);
6212 let extent = Extent::WithLength { offset: 0, len: 2 };
6213
6214 assert!(mdat.get(&extent).is_none());
6215 }
6216
6217 #[test]
6218 fn extent_to_end_before_mdat_returns_none() {
6219 let mdat = DataBox::at_offset(100, vec![1; 5]);
6220 let extent = Extent::ToEnd { offset: 0 };
6221
6222 assert!(mdat.get(&extent).is_none());
6223 }
6224
6225 #[test]
6226 fn extent_with_length_crossing_front_mdat_boundary_returns_none() {
6227 let mdat = DataBox::at_offset(100, vec![1; 5]);
6228 let extent = Extent::WithLength { offset: 99, len: 3 };
6229
6230 assert!(mdat.get(&extent).is_none());
6231 }
6232
6233 #[test]
6234 fn extent_with_length_which_is_subset_of_mdat() {
6235 let mdat = DataBox::at_offset(100, vec![1; 5]);
6236 let extent = Extent::WithLength {
6237 offset: 101,
6238 len: 2,
6239 };
6240
6241 assert_eq!(mdat.get(&extent), Some(&[1, 1][..]));
6242 }
6243
6244 #[test]
6245 fn extent_to_end_which_is_subset_of_mdat() {
6246 let mdat = DataBox::at_offset(100, vec![1; 5]);
6247 let extent = Extent::ToEnd { offset: 101 };
6248
6249 assert_eq!(mdat.get(&extent), Some(&[1, 1, 1, 1][..]));
6250 }
6251
6252 #[test]
6253 fn extent_with_length_which_is_all_of_mdat() {
6254 let mdat = DataBox::at_offset(100, vec![1; 5]);
6255 let extent = Extent::WithLength {
6256 offset: 100,
6257 len: 5,
6258 };
6259
6260 assert_eq!(mdat.get(&extent), Some(mdat.data.as_slice()));
6261 }
6262
6263 #[test]
6264 fn extent_to_end_which_is_all_of_mdat() {
6265 let mdat = DataBox::at_offset(100, vec![1; 5]);
6266 let extent = Extent::ToEnd { offset: 100 };
6267
6268 assert_eq!(mdat.get(&extent), Some(mdat.data.as_slice()));
6269 }
6270
6271 #[test]
6272 fn extent_with_length_crossing_back_mdat_boundary_returns_none() {
6273 let mdat = DataBox::at_offset(100, vec![1; 5]);
6274 let extent = Extent::WithLength {
6275 offset: 103,
6276 len: 3,
6277 };
6278
6279 assert!(mdat.get(&extent).is_none());
6280 }
6281
6282 #[test]
6283 fn extent_with_length_after_mdat_returns_none() {
6284 let mdat = DataBox::at_offset(100, vec![1; 5]);
6285 let extent = Extent::WithLength {
6286 offset: 200,
6287 len: 2,
6288 };
6289
6290 assert!(mdat.get(&extent).is_none());
6291 }
6292
6293 #[test]
6294 fn extent_to_end_after_mdat_returns_none() {
6295 let mdat = DataBox::at_offset(100, vec![1; 5]);
6296 let extent = Extent::ToEnd { offset: 200 };
6297
6298 assert!(mdat.get(&extent).is_none());
6299 }
6300
6301 #[test]
6302 fn extent_with_length_which_overflows_usize() {
6303 let mdat = DataBox::at_offset(u64::MAX - 1, vec![1; 5]);
6304 let extent = Extent::WithLength {
6305 offset: u64::MAX,
6306 len: usize::MAX,
6307 };
6308
6309 assert!(mdat.get(&extent).is_none());
6310 }
6311
6312 // The end of the range would overflow `usize` if it were calculated, but
6313 // because the range end is unbounded, we don't calculate it.
6314 #[test]
6315 fn extent_to_end_which_overflows_usize() {
6316 let mdat = DataBox::at_offset(u64::MAX - 1, vec![1; 5]);
6317 let extent = Extent::ToEnd { offset: u64::MAX };
6318
6319 assert_eq!(mdat.get(&extent), Some(&[1, 1, 1, 1][..]));
6320 }
6321 }