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