Skip to main content

zenavif_parse/
lib.rs

1#![deny(unsafe_code)]
2#![allow(clippy::missing_safety_doc)]
3//! AVIF container parser (ISOBMFF/MIAF demuxer).
4//!
5//! Extracts AV1 payloads, alpha channels, grid tiles, animation frames,
6//! and container metadata from AVIF files. Written in safe Rust with
7//! fallible allocations throughout.
8//!
9//! The primary API is [`AvifParser`], which performs zero-copy parsing by
10//! recording byte offsets and resolving data on demand.
11//!
12//! A legacy eager API ([`read_avif`]) is available behind the `eager` feature flag.
13
14// This Source Code Form is subject to the terms of the Mozilla Public
15// License, v. 2.0. If a copy of the MPL was not distributed with this
16// file, You can obtain one at https://mozilla.org/MPL/2.0/.
17
18use arrayvec::ArrayVec;
19use log::{debug, warn};
20
21use bitreader::BitReader;
22use byteorder::ReadBytesExt;
23use fallible_collections::{TryClone, TryReserveError};
24use std::borrow::Cow;
25use std::convert::{TryFrom, TryInto as _};
26
27use std::io::{Read, Take};
28use std::num::NonZeroU32;
29use std::ops::{Range, RangeFrom};
30
31mod obu;
32
33mod boxes;
34use crate::boxes::{BoxType, FourCC};
35
36/// This crate can be used from C.
37#[cfg(feature = "c_api")]
38pub mod c_api;
39
40pub use enough::{Stop, StopReason, Unstoppable};
41
42// Arbitrary buffer size limit used for raw read_bufs on a box.
43// const BUF_SIZE_LIMIT: u64 = 10 * 1024 * 1024;
44
45/// A trait to indicate a type can be infallibly converted to `u64`.
46/// This should only be implemented for infallible conversions, so only unsigned types are valid.
47trait ToU64 {
48    fn to_u64(self) -> u64;
49}
50
51/// Infallible: usize always fits in u64.
52impl ToU64 for usize {
53    fn to_u64(self) -> u64 {
54        const _: () = assert!(std::mem::size_of::<usize>() <= std::mem::size_of::<u64>());
55        self as u64
56    }
57}
58
59/// A trait to indicate a type can be infallibly converted to `usize`.
60/// This should only be implemented for infallible conversions, so only unsigned types are valid.
61pub(crate) trait ToUsize {
62    fn to_usize(self) -> usize;
63}
64
65/// Infallible widening cast: `$from_type` always fits in `usize`.
66macro_rules! impl_to_usize_from {
67    ( $from_type:ty ) => {
68        impl ToUsize for $from_type {
69            fn to_usize(self) -> usize {
70                const _: () = assert!(std::mem::size_of::<$from_type>() <= std::mem::size_of::<usize>());
71                self as usize
72            }
73        }
74    };
75}
76
77impl_to_usize_from!(u8);
78impl_to_usize_from!(u16);
79impl_to_usize_from!(u32);
80
81/// Indicate the current offset (i.e., bytes already read) in a reader
82trait Offset {
83    fn offset(&self) -> u64;
84}
85
86/// Wraps a reader to track the current offset
87struct OffsetReader<'a, T> {
88    reader: &'a mut T,
89    offset: u64,
90}
91
92impl<'a, T> OffsetReader<'a, T> {
93    fn new(reader: &'a mut T) -> Self {
94        Self { reader, offset: 0 }
95    }
96}
97
98impl<T> Offset for OffsetReader<'_, T> {
99    fn offset(&self) -> u64 {
100        self.offset
101    }
102}
103
104impl<T: Read> Read for OffsetReader<'_, T> {
105    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
106        let bytes_read = self.reader.read(buf)?;
107        self.offset = self
108            .offset
109            .checked_add(bytes_read.to_u64())
110            .ok_or(Error::Unsupported("total bytes read too large for offset type"))?;
111        Ok(bytes_read)
112    }
113}
114
115pub(crate) type TryVec<T> = fallible_collections::TryVec<T>;
116pub(crate) type TryString = fallible_collections::TryVec<u8>;
117
118// To ensure we don't use stdlib allocating types by accident
119#[allow(dead_code)]
120struct Vec;
121#[allow(dead_code)]
122struct Box;
123#[allow(dead_code)]
124struct HashMap;
125#[allow(dead_code)]
126struct String;
127
128/// Describes parser failures.
129///
130/// This enum wraps the standard `io::Error` type, unified with
131/// our own parser error states and those of crates we use.
132#[derive(Debug)]
133pub enum Error {
134    /// Parse error caused by corrupt or malformed data.
135    InvalidData(&'static str),
136    /// Parse error caused by limited parser support rather than invalid data.
137    Unsupported(&'static str),
138    /// Reflect `std::io::ErrorKind::UnexpectedEof` for short data.
139    UnexpectedEOF,
140    /// Propagate underlying errors from `std::io`.
141    Io(std::io::Error),
142    /// `read_mp4` terminated without detecting a moov box.
143    NoMoov,
144    /// Out of memory
145    OutOfMemory,
146    /// Resource limit exceeded during parsing
147    ResourceLimitExceeded(&'static str),
148    /// Operation was stopped/cancelled
149    Stopped(enough::StopReason),
150}
151
152impl std::fmt::Display for Error {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        let msg = match self {
155            Self::InvalidData(s) | Self::Unsupported(s) | Self::ResourceLimitExceeded(s) => s,
156            Self::UnexpectedEOF => "EOF",
157            Self::Io(err) => return err.fmt(f),
158            Self::NoMoov => "Missing Moov box",
159            Self::OutOfMemory => "OOM",
160            Self::Stopped(reason) => return write!(f, "Stopped: {}", reason),
161        };
162        f.write_str(msg)
163    }
164}
165
166impl std::error::Error for Error {}
167
168impl From<bitreader::BitReaderError> for Error {
169    #[cold]
170    #[cfg_attr(debug_assertions, track_caller)]
171    fn from(err: bitreader::BitReaderError) -> Self {
172        log::warn!("bitreader: {err}");
173        debug_assert!(!matches!(err, bitreader::BitReaderError::TooManyBitsForType { .. })); // bug
174        Self::InvalidData("truncated bits")
175    }
176}
177
178impl From<std::io::Error> for Error {
179    fn from(err: std::io::Error) -> Self {
180        match err.kind() {
181            std::io::ErrorKind::UnexpectedEof => Self::UnexpectedEOF,
182            _ => Self::Io(err),
183        }
184    }
185}
186
187impl From<std::string::FromUtf8Error> for Error {
188    fn from(_: std::string::FromUtf8Error) -> Self {
189        Self::InvalidData("invalid utf8")
190    }
191}
192
193impl From<std::num::TryFromIntError> for Error {
194    fn from(_: std::num::TryFromIntError) -> Self {
195        Self::Unsupported("integer conversion failed")
196    }
197}
198
199impl From<Error> for std::io::Error {
200    fn from(err: Error) -> Self {
201        let kind = match err {
202            Error::InvalidData(_) => std::io::ErrorKind::InvalidData,
203            Error::UnexpectedEOF => std::io::ErrorKind::UnexpectedEof,
204            Error::Io(io_err) => return io_err,
205            _ => std::io::ErrorKind::Other,
206        };
207        Self::new(kind, err)
208    }
209}
210
211impl From<TryReserveError> for Error {
212    fn from(_: TryReserveError) -> Self {
213        Self::OutOfMemory
214    }
215}
216
217impl From<enough::StopReason> for Error {
218    fn from(reason: enough::StopReason) -> Self {
219        Self::Stopped(reason)
220    }
221}
222
223/// Result shorthand using our Error enum.
224pub type Result<T, E = Error> = std::result::Result<T, E>;
225
226/// Basic ISO box structure.
227///
228/// mp4 files are a sequence of possibly-nested 'box' structures.  Each box
229/// begins with a header describing the length of the box's data and a
230/// four-byte box type which identifies the type of the box. Together these
231/// are enough to interpret the contents of that section of the file.
232///
233/// See ISO 14496-12:2015 § 4.2
234#[derive(Debug, Clone, Copy)]
235struct BoxHeader {
236    /// Box type.
237    name: BoxType,
238    /// Size of the box in bytes.
239    size: u64,
240    /// Offset to the start of the contained data (or header size).
241    offset: u64,
242    /// Uuid for extended type.
243    #[allow(unused)]
244    uuid: Option<[u8; 16]>,
245}
246
247impl BoxHeader {
248    /// 4-byte size + 4-byte type
249    const MIN_SIZE: u64 = 8;
250    /// 4-byte size + 4-byte type + 16-byte size
251    const MIN_LARGE_SIZE: u64 = 16;
252}
253
254/// File type box 'ftyp'.
255#[derive(Debug)]
256#[allow(unused)]
257struct FileTypeBox {
258    major_brand: FourCC,
259    minor_version: u32,
260    compatible_brands: TryVec<FourCC>,
261}
262
263// Handler reference box 'hdlr'
264#[derive(Debug)]
265#[allow(unused)]
266struct HandlerBox {
267    handler_type: FourCC,
268}
269
270/// AV1 codec configuration from the `av1C` property box.
271///
272/// Contains the AV1 codec parameters as signaled in the container.
273/// See AV1-ISOBMFF § 2.3.
274#[derive(Debug, Clone, PartialEq, Eq)]
275pub struct AV1Config {
276    /// AV1 seq_profile (0=Main, 1=High, 2=Professional)
277    pub profile: u8,
278    /// AV1 seq_level_idx for operating point 0
279    pub level: u8,
280    /// AV1 seq_tier for operating point 0
281    pub tier: u8,
282    /// Bit depth (8, 10, or 12)
283    pub bit_depth: u8,
284    /// True if monochrome (no chroma planes)
285    pub monochrome: bool,
286    /// Chroma subsampling X (1 = horizontally subsampled)
287    pub chroma_subsampling_x: u8,
288    /// Chroma subsampling Y (1 = vertically subsampled)
289    pub chroma_subsampling_y: u8,
290    /// Chroma sample position (0=unknown, 1=vertical, 2=colocated)
291    pub chroma_sample_position: u8,
292}
293
294/// Colour information from the `colr` property box.
295///
296/// Can be either CICP-based (`nclx`) or an ICC profile (`rICC`/`prof`).
297/// See ISOBMFF § 12.1.5.
298#[derive(Debug, Clone, PartialEq, Eq)]
299pub enum ColorInformation {
300    /// CICP-based color information (colour_type = 'nclx')
301    Nclx {
302        /// Colour primaries (ITU-T H.273 Table 2)
303        color_primaries: u16,
304        /// Transfer characteristics (ITU-T H.273 Table 3)
305        transfer_characteristics: u16,
306        /// Matrix coefficients (ITU-T H.273 Table 4)
307        matrix_coefficients: u16,
308        /// True if full range (0-255 for 8-bit), false if limited/studio range
309        full_range: bool,
310    },
311    /// ICC profile (colour_type = 'rICC' or 'prof')
312    IccProfile(std::vec::Vec<u8>),
313}
314
315/// Image rotation from the `irot` property box.
316///
317/// Specifies a counter-clockwise rotation to apply after decoding.
318/// See ISOBMFF § 12.1.4.
319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
320pub struct ImageRotation {
321    /// Rotation angle in degrees counter-clockwise: 0, 90, 180, or 270.
322    pub angle: u16,
323}
324
325/// Image mirror from the `imir` property box.
326///
327/// Specifies a mirror (flip) axis to apply after rotation.
328/// See ISOBMFF § 12.1.4.
329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330pub struct ImageMirror {
331    /// Mirror axis: 0 = top-to-bottom (vertical axis, left-right flip),
332    /// 1 = left-to-right (horizontal axis, top-bottom flip).
333    pub axis: u8,
334}
335
336/// Clean aperture from the `clap` property box.
337///
338/// Defines a crop rectangle as a centered region. All values are
339/// stored as exact rationals (numerator/denominator).
340/// See ISOBMFF § 12.1.4.
341#[derive(Debug, Clone, Copy, PartialEq, Eq)]
342pub struct CleanAperture {
343    /// Width of the clean aperture (numerator)
344    pub width_n: u32,
345    /// Width of the clean aperture (denominator)
346    pub width_d: u32,
347    /// Height of the clean aperture (numerator)
348    pub height_n: u32,
349    /// Height of the clean aperture (denominator)
350    pub height_d: u32,
351    /// Horizontal offset of the clean aperture center (numerator, signed)
352    pub horiz_off_n: i32,
353    /// Horizontal offset of the clean aperture center (denominator)
354    pub horiz_off_d: u32,
355    /// Vertical offset of the clean aperture center (numerator, signed)
356    pub vert_off_n: i32,
357    /// Vertical offset of the clean aperture center (denominator)
358    pub vert_off_d: u32,
359}
360
361/// Pixel aspect ratio from the `pasp` property box.
362///
363/// For AVIF, the spec requires this to be 1:1 if present.
364/// See ISOBMFF § 12.1.4.
365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366pub struct PixelAspectRatio {
367    /// Horizontal spacing
368    pub h_spacing: u32,
369    /// Vertical spacing
370    pub v_spacing: u32,
371}
372
373/// Content light level info from the `clli` property box.
374///
375/// HDR metadata for display mapping.
376/// See ISOBMFF § 12.1.5 / ITU-T H.274.
377#[derive(Debug, Clone, Copy, PartialEq, Eq)]
378pub struct ContentLightLevel {
379    /// Maximum content light level (cd/m²)
380    pub max_content_light_level: u16,
381    /// Maximum picture average light level (cd/m²)
382    pub max_pic_average_light_level: u16,
383}
384
385/// Mastering display colour volume from the `mdcv` property box.
386///
387/// HDR metadata describing the mastering display's color volume.
388/// See ISOBMFF § 12.1.5 / SMPTE ST 2086.
389#[derive(Debug, Clone, Copy, PartialEq, Eq)]
390pub struct MasteringDisplayColourVolume {
391    /// Display primaries: [(x, y); 3] in 0.00002 units (CIE 1931)
392    /// Order: green, blue, red (per SMPTE ST 2086)
393    pub primaries: [(u16, u16); 3],
394    /// White point (x, y) in 0.00002 units
395    pub white_point: (u16, u16),
396    /// Maximum display luminance in 0.0001 cd/m² units
397    pub max_luminance: u32,
398    /// Minimum display luminance in 0.0001 cd/m² units
399    pub min_luminance: u32,
400}
401
402/// Content colour volume from the `cclv` property box.
403///
404/// Describes the colour volume of the content. Derived from H.265 D.2.40 /
405/// ITU-T H.274. All fields are optional, controlled by presence flags.
406/// See ISOBMFF § 12.1.5.
407#[derive(Debug, Clone, Copy, PartialEq, Eq)]
408pub struct ContentColourVolume {
409    /// Content colour primaries (x, y) for 3 primaries, as signed i32.
410    /// Present only if `ccv_primaries_present_flag` was set.
411    pub primaries: Option<[(i32, i32); 3]>,
412    /// Minimum luminance value. Present only if flag was set.
413    pub min_luminance: Option<u32>,
414    /// Maximum luminance value. Present only if flag was set.
415    pub max_luminance: Option<u32>,
416    /// Average luminance value. Present only if flag was set.
417    pub avg_luminance: Option<u32>,
418}
419
420/// Ambient viewing environment from the `amve` property box.
421///
422/// Describes the ambient viewing conditions under which the content
423/// was authored. See ISOBMFF § 12.1.5 / H.265 D.2.39.
424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
425pub struct AmbientViewingEnvironment {
426    /// Ambient illuminance in units of 1/10000 cd/m²
427    pub ambient_illuminance: u32,
428    /// Ambient light x chromaticity (CIE 1931), units of 1/50000
429    pub ambient_light_x: u16,
430    /// Ambient light y chromaticity (CIE 1931), units of 1/50000
431    pub ambient_light_y: u16,
432}
433
434/// Per-channel gain map parameters from ISO 21496-1.
435///
436/// Each field is a rational number (numerator/denominator pair) describing
437/// how to apply the gain map for this channel.
438#[derive(Debug, Clone, Copy, PartialEq, Eq)]
439pub struct GainMapChannel {
440    /// Minimum gain map value (numerator).
441    pub gain_map_min_n: i32,
442    /// Minimum gain map value (denominator).
443    pub gain_map_min_d: u32,
444    /// Maximum gain map value (numerator).
445    pub gain_map_max_n: i32,
446    /// Maximum gain map value (denominator).
447    pub gain_map_max_d: u32,
448    /// Gamma curve parameter (numerator).
449    pub gamma_n: u32,
450    /// Gamma curve parameter (denominator).
451    pub gamma_d: u32,
452    /// Base image offset (numerator).
453    pub base_offset_n: i32,
454    /// Base image offset (denominator).
455    pub base_offset_d: u32,
456    /// Alternate image offset (numerator).
457    pub alternate_offset_n: i32,
458    /// Alternate image offset (denominator).
459    pub alternate_offset_d: u32,
460}
461
462/// Gain map metadata from a ToneMapImage (`tmap`) derived image item.
463///
464/// Describes how to apply a gain map to convert between SDR and HDR
465/// renditions. The gain map is a separate AV1-encoded image that, combined
466/// with this metadata, allows reconstructing an HDR image from the SDR base.
467///
468/// See ISO 21496-1:2025 for the full specification.
469#[derive(Debug, Clone, PartialEq, Eq)]
470pub struct GainMapMetadata {
471    /// If true, each RGB channel has independent gain map parameters.
472    /// If false, `channels[0]` applies to all three channels.
473    pub is_multichannel: bool,
474    /// If true, the gain map is encoded in the base image's colour space.
475    /// If false, it's in the alternate image's colour space.
476    pub use_base_colour_space: bool,
477    /// Base HDR headroom (numerator).
478    pub base_hdr_headroom_n: u32,
479    /// Base HDR headroom (denominator).
480    pub base_hdr_headroom_d: u32,
481    /// Alternate HDR headroom (numerator).
482    pub alternate_hdr_headroom_n: u32,
483    /// Alternate HDR headroom (denominator).
484    pub alternate_hdr_headroom_d: u32,
485    /// Per-channel parameters. For single-channel mode, only index 0 is
486    /// meaningful (indices 1 and 2 are copies of index 0).
487    pub channels: [GainMapChannel; 3],
488}
489
490/// Operating point selector from the `a1op` property box.
491///
492/// Selects which AV1 operating point to decode for multi-operating-point images.
493/// See AVIF § 4.3.4.
494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
495pub struct OperatingPointSelector {
496    /// Operating point index (0..31)
497    pub op_index: u8,
498}
499
500/// Layer selector from the `lsel` property box.
501///
502/// Selects which spatial layer to render for layered/progressive images.
503/// See HEIF (ISO 23008-12).
504#[derive(Debug, Clone, Copy, PartialEq, Eq)]
505pub struct LayerSelector {
506    /// Layer ID to render (0-3), or 0xFFFF for all layers (progressive)
507    pub layer_id: u16,
508}
509
510/// AV1 layered image indexing from the `a1lx` property box.
511///
512/// Provides byte sizes for the first 3 layers so decoders can seek
513/// to a specific layer without parsing the full bitstream.
514/// See AVIF § 4.3.6.
515#[derive(Debug, Clone, Copy, PartialEq, Eq)]
516pub struct AV1LayeredImageIndexing {
517    /// Byte sizes of layers 0, 1, 2. The last layer's size is implicit
518    /// (total item size minus the sum of these three).
519    pub layer_sizes: [u32; 3],
520}
521
522/// Options for parsing AVIF files
523///
524/// Prefer using [`DecodeConfig::lenient()`] with [`AvifParser`] instead.
525#[derive(Debug, Clone, Copy)]
526#[derive(Default)]
527pub struct ParseOptions {
528    /// Enable lenient parsing mode
529    ///
530    /// When true, non-critical validation errors (like non-zero flags in boxes
531    /// that expect zero flags) will be ignored instead of returning errors.
532    /// This allows parsing of slightly malformed but otherwise valid AVIF files.
533    ///
534    /// Default: false (strict validation)
535    pub lenient: bool,
536}
537
538/// Configuration for parsing AVIF files with resource limits and validation options
539///
540/// Provides fine-grained control over resource consumption during AVIF parsing,
541/// allowing defensive parsing against malicious or malformed files.
542///
543/// Resource limits are checked **before** allocations occur, preventing out-of-memory
544/// conditions from malicious files that claim unrealistic dimensions or counts.
545///
546/// # Examples
547///
548/// ```rust
549/// use zenavif_parse::DecodeConfig;
550///
551/// // Default limits (suitable for most apps)
552/// let config = DecodeConfig::default();
553///
554/// // Strict limits for untrusted input
555/// let config = DecodeConfig::default()
556///     .with_peak_memory_limit(100_000_000)  // 100MB
557///     .with_total_megapixels_limit(64)       // 64MP max
558///     .with_max_animation_frames(100);       // 100 frames
559///
560/// // No limits (backwards compatible with read_avif)
561/// let config = DecodeConfig::unlimited();
562/// ```
563#[derive(Debug, Clone)]
564pub struct DecodeConfig {
565    /// Maximum peak heap memory usage in bytes.
566    /// Default: 1GB (1,000,000,000 bytes)
567    pub peak_memory_limit: Option<u64>,
568
569    /// Maximum total megapixels for grid images.
570    /// Default: 512 megapixels
571    pub total_megapixels_limit: Option<u32>,
572
573    /// Maximum number of animation frames.
574    /// Default: 10,000 frames
575    pub max_animation_frames: Option<u32>,
576
577    /// Maximum number of grid tiles.
578    /// Default: 1,000 tiles
579    pub max_grid_tiles: Option<u32>,
580
581    /// Enable lenient parsing mode.
582    /// Default: false (strict validation)
583    pub lenient: bool,
584}
585
586impl Default for DecodeConfig {
587    fn default() -> Self {
588        Self {
589            peak_memory_limit: Some(1_000_000_000),
590            total_megapixels_limit: Some(512),
591            max_animation_frames: Some(10_000),
592            max_grid_tiles: Some(1_000),
593            lenient: false,
594        }
595    }
596}
597
598impl DecodeConfig {
599    /// Create a configuration with no resource limits.
600    ///
601    /// Equivalent to the behavior of `read_avif()` before resource limits were added.
602    pub fn unlimited() -> Self {
603        Self {
604            peak_memory_limit: None,
605            total_megapixels_limit: None,
606            max_animation_frames: None,
607            max_grid_tiles: None,
608            lenient: false,
609        }
610    }
611
612    /// Set the peak memory limit in bytes
613    pub fn with_peak_memory_limit(mut self, bytes: u64) -> Self {
614        self.peak_memory_limit = Some(bytes);
615        self
616    }
617
618    /// Set the total megapixels limit for grid images
619    pub fn with_total_megapixels_limit(mut self, megapixels: u32) -> Self {
620        self.total_megapixels_limit = Some(megapixels);
621        self
622    }
623
624    /// Set the maximum animation frame count
625    pub fn with_max_animation_frames(mut self, frames: u32) -> Self {
626        self.max_animation_frames = Some(frames);
627        self
628    }
629
630    /// Set the maximum grid tile count
631    pub fn with_max_grid_tiles(mut self, tiles: u32) -> Self {
632        self.max_grid_tiles = Some(tiles);
633        self
634    }
635
636    /// Enable lenient parsing mode
637    pub fn lenient(mut self, lenient: bool) -> Self {
638        self.lenient = lenient;
639        self
640    }
641}
642
643/// Grid configuration for tiled/grid-based AVIF images
644#[derive(Debug, Clone, PartialEq)]
645/// Grid image configuration
646///
647/// For tiled/grid AVIF images, this describes the grid layout.
648/// Grid images are composed of multiple AV1 image items (tiles) arranged in a rectangular grid.
649///
650/// ## Grid Layout Determination
651///
652/// Grid layout can be specified in two ways:
653/// 1. **Explicit ImageGrid property box** - contains rows, columns, and output dimensions
654/// 2. **Calculated from ispe properties** - when no ImageGrid box exists, dimensions are
655///    calculated by dividing the grid item's dimensions by a tile's dimensions
656///
657/// ## Output Dimensions
658///
659/// - `output_width` and `output_height` may be 0, indicating the decoder should calculate
660///   them from the tile dimensions
661/// - When non-zero, they specify the exact output dimensions of the composed image
662pub struct GridConfig {
663    /// Number of tile rows (1-256)
664    pub rows: u8,
665    /// Number of tile columns (1-256)
666    pub columns: u8,
667    /// Output width in pixels (0 = calculate from tiles)
668    pub output_width: u32,
669    /// Output height in pixels (0 = calculate from tiles)
670    pub output_height: u32,
671}
672
673/// Frame information for animated AVIF
674#[cfg(feature = "eager")]
675#[deprecated(since = "1.5.0", note = "Use `AvifParser::frame()` which returns `FrameRef` instead")]
676#[derive(Debug)]
677pub struct AnimationFrame {
678    /// AV1 bitstream data for this frame
679    pub data: TryVec<u8>,
680    /// Duration in milliseconds (0 if unknown)
681    pub duration_ms: u32,
682}
683
684/// Animation configuration for animated AVIF (avis brand)
685#[cfg(feature = "eager")]
686#[deprecated(since = "1.5.0", note = "Use `AvifParser::animation_info()` and `AvifParser::frames()` instead")]
687#[derive(Debug)]
688#[allow(deprecated)]
689pub struct AnimationConfig {
690    /// Number of times to loop (0 = infinite)
691    pub loop_count: u32,
692    /// All frames in the animation
693    pub frames: TryVec<AnimationFrame>,
694}
695
696// Internal structures for animation parsing
697
698#[derive(Debug)]
699struct MovieHeader {
700    _timescale: u32,
701    _duration: u64,
702}
703
704#[derive(Debug)]
705struct MediaHeader {
706    timescale: u32,
707    _duration: u64,
708}
709
710#[derive(Debug)]
711struct TimeToSampleEntry {
712    sample_count: u32,
713    sample_delta: u32,
714}
715
716#[derive(Debug)]
717struct SampleToChunkEntry {
718    first_chunk: u32,
719    samples_per_chunk: u32,
720    _sample_description_index: u32,
721}
722
723#[derive(Debug)]
724struct SampleTable {
725    time_to_sample: TryVec<TimeToSampleEntry>,
726    sample_sizes: TryVec<u32>,
727    /// Precomputed byte offset for each sample, derived from
728    /// sample_to_chunk + chunk_offsets + sample_sizes during parsing.
729    sample_offsets: TryVec<u64>,
730}
731
732/// A track reference entry (e.g., auxl, cdsc) parsed from a `tref` sub-box.
733#[derive(Debug)]
734struct TrackReference {
735    reference_type: FourCC,
736    track_ids: TryVec<u32>,
737}
738
739/// Codec properties extracted from a `stsd` VisualSampleEntry.
740#[derive(Debug, Clone, Default)]
741struct TrackCodecConfig {
742    av1_config: Option<AV1Config>,
743    color_info: Option<ColorInformation>,
744}
745
746/// Parsed data from a single track box (`trak`).
747#[derive(Debug)]
748struct ParsedTrack {
749    track_id: u32,
750    handler_type: FourCC,
751    media_timescale: u32,
752    sample_table: SampleTable,
753    references: TryVec<TrackReference>,
754    loop_count: u32,
755    codec_config: TrackCodecConfig,
756}
757
758/// Paired color + optional alpha animation data after track association.
759struct ParsedAnimationData {
760    color_timescale: u32,
761    color_sample_table: SampleTable,
762    alpha_timescale: Option<u32>,
763    alpha_sample_table: Option<SampleTable>,
764    loop_count: u32,
765    color_codec_config: TrackCodecConfig,
766}
767
768#[cfg(feature = "eager")]
769#[deprecated(since = "1.5.0", note = "Use `AvifParser` for zero-copy parsing instead")]
770#[derive(Debug, Default)]
771#[allow(deprecated)]
772pub struct AvifData {
773    /// AV1 data for the color channels.
774    ///
775    /// The collected data indicated by the `pitm` box, See ISO 14496-12:2015 § 8.11.4
776    pub primary_item: TryVec<u8>,
777    /// AV1 data for alpha channel.
778    ///
779    /// Associated alpha channel for the primary item, if any
780    pub alpha_item: Option<TryVec<u8>>,
781    /// If true, divide RGB values by the alpha value.
782    ///
783    /// See `prem` in MIAF § 7.3.5.2
784    pub premultiplied_alpha: bool,
785
786    /// Grid configuration for tiled images.
787    ///
788    /// If present, the image is a grid and `grid_tiles` contains the tile data.
789    /// Grid layout is determined either from an explicit ImageGrid property box or
790    /// calculated from ispe (Image Spatial Extents) properties.
791    ///
792    /// ## Example
793    ///
794    /// ```no_run
795    /// #[allow(deprecated)]
796    /// use std::fs::File;
797    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
798    /// #[allow(deprecated)]
799    /// let data = zenavif_parse::read_avif(&mut File::open("image.avif")?)?;
800    ///
801    /// if let Some(grid) = data.grid_config {
802    ///     println!("Grid: {}×{} tiles", grid.rows, grid.columns);
803    ///     println!("Output: {}×{}", grid.output_width, grid.output_height);
804    ///     println!("Tile count: {}", data.grid_tiles.len());
805    /// }
806    /// # Ok(())
807    /// # }
808    /// ```
809    pub grid_config: Option<GridConfig>,
810
811    /// AV1 payloads for grid image tiles.
812    ///
813    /// Empty for non-grid images. For grid images, contains one entry per tile.
814    ///
815    /// **Tile ordering:** Tiles are guaranteed to be in the correct order for grid assembly,
816    /// sorted by their dimgIdx (reference index). This is row-major order: tiles in the first
817    /// row from left to right, then the second row, etc.
818    pub grid_tiles: TryVec<TryVec<u8>>,
819
820    /// Animation configuration (for animated AVIF with avis brand)
821    ///
822    /// When present, primary_item contains the first frame
823    pub animation: Option<AnimationConfig>,
824
825    /// AV1 codec configuration from the container's `av1C` property.
826    pub av1_config: Option<AV1Config>,
827
828    /// Colour information from the container's `colr` property.
829    pub color_info: Option<ColorInformation>,
830
831    /// Image rotation from the container's `irot` property.
832    pub rotation: Option<ImageRotation>,
833
834    /// Image mirror from the container's `imir` property.
835    pub mirror: Option<ImageMirror>,
836
837    /// Clean aperture (crop) from the container's `clap` property.
838    pub clean_aperture: Option<CleanAperture>,
839
840    /// Pixel aspect ratio from the container's `pasp` property.
841    pub pixel_aspect_ratio: Option<PixelAspectRatio>,
842
843    /// Content light level from the container's `clli` property.
844    pub content_light_level: Option<ContentLightLevel>,
845
846    /// Mastering display colour volume from the container's `mdcv` property.
847    pub mastering_display: Option<MasteringDisplayColourVolume>,
848
849    /// Content colour volume from the container's `cclv` property.
850    pub content_colour_volume: Option<ContentColourVolume>,
851
852    /// Ambient viewing environment from the container's `amve` property.
853    pub ambient_viewing: Option<AmbientViewingEnvironment>,
854
855    /// Operating point selector from the container's `a1op` property.
856    pub operating_point: Option<OperatingPointSelector>,
857
858    /// Layer selector from the container's `lsel` property.
859    pub layer_selector: Option<LayerSelector>,
860
861    /// AV1 layered image indexing from the container's `a1lx` property.
862    pub layered_image_indexing: Option<AV1LayeredImageIndexing>,
863
864    /// EXIF metadata from a `cdsc`-linked `Exif` item.
865    ///
866    /// Raw EXIF data (TIFF header onwards), with the 4-byte AVIF offset prefix stripped.
867    pub exif: Option<TryVec<u8>>,
868
869    /// XMP metadata from a `cdsc`-linked `mime` item.
870    ///
871    /// Raw XMP/XML data as UTF-8.
872    pub xmp: Option<TryVec<u8>>,
873
874    /// Gain map metadata from a `tmap` derived image item.
875    pub gain_map_metadata: Option<GainMapMetadata>,
876
877    /// AV1-encoded gain map image data.
878    pub gain_map_item: Option<TryVec<u8>>,
879
880    /// Color information for the alternate (HDR) rendition from the `tmap` item.
881    pub gain_map_color_info: Option<ColorInformation>,
882
883    /// Major brand from the `ftyp` box (e.g., `*b"avif"` or `*b"avis"`).
884    pub major_brand: [u8; 4],
885
886    /// Compatible brands from the `ftyp` box.
887    pub compatible_brands: std::vec::Vec<[u8; 4]>,
888}
889
890// # Memory Usage
891//
892// This implementation loads all image data into owned vectors (`TryVec<u8>`), which has
893// memory implications depending on the file type:
894//
895// - **Static images**: Single copy of compressed data (~5-50KB typical)
896//   - `primary_item`: compressed AV1 data
897//   - `alpha_item`: compressed alpha data (if present)
898//
899// - **Grid images**: All tiles loaded (~100KB-2MB for large grids)
900//   - `grid_tiles`: one compressed tile per grid cell
901//
902// - **Animated images**: All frames loaded eagerly (⚠️ HIGH MEMORY)
903//   - Internal mdat boxes: ~500KB for 95-frame video
904//   - Extracted frames: ~500KB duplicated in `animation.frames[].data`
905//   - **Total: ~2× file size in memory**
906//
907// For large animated files, consider using a streaming approach or processing frames
908// individually rather than loading the entire `AvifData` structure.
909
910#[cfg(feature = "eager")]
911#[allow(deprecated)]
912impl AvifData {
913    #[deprecated(since = "1.5.0", note = "Use `AvifParser::from_reader()` instead")]
914    pub fn from_reader<R: Read>(reader: &mut R) -> Result<Self> {
915        read_avif(reader)
916    }
917
918    /// Parses AV1 data to get basic properties of the opaque channel
919    pub fn primary_item_metadata(&self) -> Result<AV1Metadata> {
920        AV1Metadata::parse_av1_bitstream(&self.primary_item)
921    }
922
923    /// Parses AV1 data to get basic properties about the alpha channel, if any
924    pub fn alpha_item_metadata(&self) -> Result<Option<AV1Metadata>> {
925        self.alpha_item.as_deref().map(AV1Metadata::parse_av1_bitstream).transpose()
926    }
927}
928
929/// AV1 sequence header metadata parsed from an OBU bitstream.
930///
931/// See [`AvifParser::primary_metadata()`] and [`AV1Metadata::parse_av1_bitstream()`].
932#[non_exhaustive]
933#[derive(Debug, Clone)]
934pub struct AV1Metadata {
935    /// Should be true for non-animated AVIF
936    pub still_picture: bool,
937    pub max_frame_width: NonZeroU32,
938    pub max_frame_height: NonZeroU32,
939    /// 8, 10, or 12
940    pub bit_depth: u8,
941    /// 0, 1 or 2 for the level of complexity
942    pub seq_profile: u8,
943    /// Horizontal and vertical. `false` is full-res.
944    pub chroma_subsampling: (bool, bool),
945    pub monochrome: bool,
946}
947
948impl AV1Metadata {
949    /// Parses raw AV1 bitstream (OBU sequence header) only.
950    ///
951    /// This is for the bare image payload from an encoder, not an AVIF/HEIF file.
952    /// To parse AVIF files, see [`AvifParser::from_reader()`].
953    #[inline(never)]
954    pub fn parse_av1_bitstream(obu_bitstream: &[u8]) -> Result<Self> {
955        let h = obu::parse_obu(obu_bitstream)?;
956        Ok(Self {
957            still_picture: h.still_picture,
958            max_frame_width: h.max_frame_width,
959            max_frame_height: h.max_frame_height,
960            bit_depth: h.color.bit_depth,
961            seq_profile: h.seq_profile,
962            chroma_subsampling: h.color.chroma_subsampling,
963            monochrome: h.color.monochrome,
964        })
965    }
966}
967
968/// A single frame from an animated AVIF, with zero-copy when possible.
969///
970/// The `data` field is `Cow::Borrowed` when the frame lives in a single
971/// contiguous mdat extent, and `Cow::Owned` when extents must be concatenated.
972pub struct FrameRef<'a> {
973    pub data: Cow<'a, [u8]>,
974    /// Alpha channel data for this frame, if the animation has a separate alpha track.
975    pub alpha_data: Option<Cow<'a, [u8]>>,
976    pub duration_ms: u32,
977}
978
979/// Byte range of a media data box within the file.
980struct MdatBounds {
981    offset: u64,
982    length: u64,
983}
984
985/// Where an item's data lives: construction method + extent ranges.
986struct ItemExtents {
987    construction_method: ConstructionMethod,
988    extents: TryVec<ExtentRange>,
989}
990
991/// Zero-copy AVIF parser backed by a borrowed or owned byte buffer.
992///
993/// `AvifParser` records byte offsets during parsing but does **not** copy
994/// mdat payload data. Data access methods return `Cow<[u8]>` — borrowed
995/// when the item is a single contiguous extent, owned when extents must
996/// be concatenated.
997///
998/// # Constructors
999///
1000/// | Method | Lifetime | Zero-copy? |
1001/// |--------|----------|------------|
1002/// | [`from_bytes`](Self::from_bytes) | `'data` | Yes — borrows the slice |
1003/// | [`from_owned`](Self::from_owned) | `'static` | Within the owned buffer |
1004/// | [`from_reader`](Self::from_reader) | `'static` | Reads all, then owned |
1005///
1006/// # Example
1007///
1008/// ```no_run
1009/// use zenavif_parse::AvifParser;
1010///
1011/// let bytes = std::fs::read("image.avif")?;
1012/// let parser = AvifParser::from_bytes(&bytes)?;
1013/// let primary = parser.primary_data()?; // Cow::Borrowed for single-extent
1014/// # Ok::<(), Box<dyn std::error::Error>>(())
1015/// ```
1016pub struct AvifParser<'data> {
1017    raw: Cow<'data, [u8]>,
1018    mdat_bounds: TryVec<MdatBounds>,
1019    idat: Option<TryVec<u8>>,
1020    primary: ItemExtents,
1021    alpha: Option<ItemExtents>,
1022    grid_config: Option<GridConfig>,
1023    tiles: TryVec<ItemExtents>,
1024    animation_data: Option<AnimationParserData>,
1025    premultiplied_alpha: bool,
1026    av1_config: Option<AV1Config>,
1027    color_info: Option<ColorInformation>,
1028    rotation: Option<ImageRotation>,
1029    mirror: Option<ImageMirror>,
1030    clean_aperture: Option<CleanAperture>,
1031    pixel_aspect_ratio: Option<PixelAspectRatio>,
1032    content_light_level: Option<ContentLightLevel>,
1033    mastering_display: Option<MasteringDisplayColourVolume>,
1034    content_colour_volume: Option<ContentColourVolume>,
1035    ambient_viewing: Option<AmbientViewingEnvironment>,
1036    operating_point: Option<OperatingPointSelector>,
1037    layer_selector: Option<LayerSelector>,
1038    layered_image_indexing: Option<AV1LayeredImageIndexing>,
1039    exif_item: Option<ItemExtents>,
1040    xmp_item: Option<ItemExtents>,
1041    gain_map_metadata: Option<GainMapMetadata>,
1042    gain_map: Option<ItemExtents>,
1043    gain_map_color_info: Option<ColorInformation>,
1044    major_brand: [u8; 4],
1045    compatible_brands: std::vec::Vec<[u8; 4]>,
1046}
1047
1048struct AnimationParserData {
1049    media_timescale: u32,
1050    sample_table: SampleTable,
1051    alpha_media_timescale: Option<u32>,
1052    alpha_sample_table: Option<SampleTable>,
1053    loop_count: u32,
1054    codec_config: TrackCodecConfig,
1055}
1056
1057/// Animation metadata from [`AvifParser`]
1058#[derive(Debug, Clone, Copy)]
1059pub struct AnimationInfo {
1060    pub frame_count: usize,
1061    pub loop_count: u32,
1062    /// Whether animation has a separate alpha track.
1063    pub has_alpha: bool,
1064    /// Media timescale (ticks per second) for the color track.
1065    pub timescale: u32,
1066}
1067
1068/// Parsed structure from the box-level parse pass (no mdat data).
1069struct ParsedStructure {
1070    /// `None` for pure AVIF sequences (`avis` brand) that have only `moov`+`mdat`.
1071    meta: Option<AvifInternalMeta>,
1072    mdat_bounds: TryVec<MdatBounds>,
1073    animation_data: Option<ParsedAnimationData>,
1074    major_brand: [u8; 4],
1075    compatible_brands: std::vec::Vec<[u8; 4]>,
1076}
1077
1078impl<'data> AvifParser<'data> {
1079    // ========================================
1080    // Constructors
1081    // ========================================
1082
1083    /// Parse AVIF from a borrowed byte slice (true zero-copy).
1084    ///
1085    /// The returned parser borrows `data` — single-extent items will be
1086    /// returned as `Cow::Borrowed` slices into this buffer.
1087    pub fn from_bytes(data: &'data [u8]) -> Result<Self> {
1088        Self::from_bytes_with_config(data, &DecodeConfig::unlimited(), &Unstoppable)
1089    }
1090
1091    /// Parse AVIF from a borrowed byte slice with resource limits.
1092    pub fn from_bytes_with_config(
1093        data: &'data [u8],
1094        config: &DecodeConfig,
1095        stop: &dyn Stop,
1096    ) -> Result<Self> {
1097        let parsed = Self::parse_raw(data, config, stop)?;
1098        Self::build(Cow::Borrowed(data), parsed, config)
1099    }
1100
1101    /// Parse AVIF from an owned buffer.
1102    ///
1103    /// The returned parser owns the data — single-extent items will still
1104    /// be returned as `Cow::Borrowed` slices (borrowing from the internal buffer).
1105    pub fn from_owned(data: std::vec::Vec<u8>) -> Result<AvifParser<'static>> {
1106        AvifParser::from_owned_with_config(data, &DecodeConfig::unlimited(), &Unstoppable)
1107    }
1108
1109    /// Parse AVIF from an owned buffer with resource limits.
1110    pub fn from_owned_with_config(
1111        data: std::vec::Vec<u8>,
1112        config: &DecodeConfig,
1113        stop: &dyn Stop,
1114    ) -> Result<AvifParser<'static>> {
1115        let parsed = AvifParser::parse_raw(&data, config, stop)?;
1116        AvifParser::build(Cow::Owned(data), parsed, config)
1117    }
1118
1119    /// Parse AVIF from a reader (reads all bytes, then parses).
1120    pub fn from_reader<R: Read>(reader: &mut R) -> Result<AvifParser<'static>> {
1121        AvifParser::from_reader_with_config(reader, &DecodeConfig::unlimited(), &Unstoppable)
1122    }
1123
1124    /// Parse AVIF from a reader with resource limits.
1125    pub fn from_reader_with_config<R: Read>(
1126        reader: &mut R,
1127        config: &DecodeConfig,
1128        stop: &dyn Stop,
1129    ) -> Result<AvifParser<'static>> {
1130        let mut buf = std::vec::Vec::new();
1131        reader.read_to_end(&mut buf)?;
1132        AvifParser::from_owned_with_config(buf, config, stop)
1133    }
1134
1135    // ========================================
1136    // Internal: parse pass (records offsets, no mdat copy)
1137    // ========================================
1138
1139    /// Parse the AVIF box structure from raw bytes, recording mdat offsets
1140    /// without copying mdat content.
1141    fn parse_raw(data: &[u8], config: &DecodeConfig, stop: &dyn Stop) -> Result<ParsedStructure> {
1142        let parse_opts = ParseOptions { lenient: config.lenient };
1143        let mut cursor = std::io::Cursor::new(data);
1144        let mut f = OffsetReader::new(&mut cursor);
1145        let mut iter = BoxIter::new(&mut f);
1146
1147        // 'ftyp' box must occur first; see ISO 14496-12:2015 § 4.3.1
1148        let (major_brand, compatible_brands) = if let Some(mut b) = iter.next_box()? {
1149            if b.head.name == BoxType::FileTypeBox {
1150                let ftyp = read_ftyp(&mut b)?;
1151                if ftyp.major_brand != b"avif" && ftyp.major_brand != b"avis" {
1152                    return Err(Error::InvalidData("ftyp must be 'avif' or 'avis'"));
1153                }
1154                let major = ftyp.major_brand.value;
1155                let compat = ftyp.compatible_brands.iter().map(|b| b.value).collect();
1156                (major, compat)
1157            } else {
1158                return Err(Error::InvalidData("'ftyp' box must occur first"));
1159            }
1160        } else {
1161            return Err(Error::InvalidData("'ftyp' box must occur first"));
1162        };
1163
1164        let mut meta = None;
1165        let mut mdat_bounds = TryVec::new();
1166        let mut animation_data: Option<ParsedAnimationData> = None;
1167
1168        while let Some(mut b) = iter.next_box()? {
1169            stop.check()?;
1170
1171            match b.head.name {
1172                BoxType::MetadataBox => {
1173                    if meta.is_some() {
1174                        return Err(Error::InvalidData(
1175                            "There should be zero or one meta boxes per ISO 14496-12:2015 § 8.11.1.1",
1176                        ));
1177                    }
1178                    meta = Some(read_avif_meta(&mut b, &parse_opts)?);
1179                }
1180                BoxType::MovieBox => {
1181                    let tracks = read_moov(&mut b)?;
1182                    if !tracks.is_empty() {
1183                        animation_data = Some(associate_tracks(tracks)?);
1184                    }
1185                }
1186                BoxType::MediaDataBox => {
1187                    if b.bytes_left() > 0 {
1188                        let offset = b.offset();
1189                        let length = b.bytes_left();
1190                        mdat_bounds.push(MdatBounds { offset, length })?;
1191                    }
1192                    // Skip the content — we'll slice into raw later
1193                    skip_box_content(&mut b)?;
1194                }
1195                _ => skip_box_content(&mut b)?,
1196            }
1197
1198            check_parser_state(&b.head, &b.content)?;
1199        }
1200
1201        // meta is required for still images, but pure AVIF sequences (avis brand)
1202        // can have only moov+mdat with no meta box.
1203        if meta.is_none() && animation_data.is_none() {
1204            return Err(Error::InvalidData("missing meta"));
1205        }
1206
1207        Ok(ParsedStructure { meta, mdat_bounds, animation_data, major_brand, compatible_brands })
1208    }
1209
1210    /// Build an AvifParser from raw bytes + parsed structure.
1211    fn build(raw: Cow<'data, [u8]>, parsed: ParsedStructure, config: &DecodeConfig) -> Result<Self> {
1212        let tracker = ResourceTracker::new(config);
1213
1214        // Store animation metadata if present
1215        let animation_data = if let Some(anim) = parsed.animation_data {
1216            tracker.validate_animation_frames(anim.color_sample_table.sample_sizes.len() as u32)?;
1217            Some(AnimationParserData {
1218                media_timescale: anim.color_timescale,
1219                sample_table: anim.color_sample_table,
1220                alpha_media_timescale: anim.alpha_timescale,
1221                alpha_sample_table: anim.alpha_sample_table,
1222                loop_count: anim.loop_count,
1223                codec_config: anim.color_codec_config,
1224            })
1225        } else {
1226            None
1227        };
1228
1229        // Pure sequence (no meta box): only animation methods will work.
1230        // Use codec config from the color track's stsd if available.
1231        let Some(meta) = parsed.meta else {
1232            let track_config = animation_data.as_ref()
1233                .map(|a| a.codec_config.clone())
1234                .unwrap_or_default();
1235            return Ok(Self {
1236                raw,
1237                mdat_bounds: parsed.mdat_bounds,
1238                idat: None,
1239                primary: ItemExtents { construction_method: ConstructionMethod::File, extents: TryVec::new() },
1240                alpha: None,
1241                grid_config: None,
1242                tiles: TryVec::new(),
1243                animation_data,
1244                premultiplied_alpha: false,
1245                av1_config: track_config.av1_config,
1246                color_info: track_config.color_info,
1247                rotation: None,
1248                mirror: None,
1249                clean_aperture: None,
1250                pixel_aspect_ratio: None,
1251                content_light_level: None,
1252                mastering_display: None,
1253                content_colour_volume: None,
1254                ambient_viewing: None,
1255                operating_point: None,
1256                layer_selector: None,
1257                layered_image_indexing: None,
1258                exif_item: None,
1259                xmp_item: None,
1260                gain_map_metadata: None,
1261                gain_map: None,
1262                gain_map_color_info: None,
1263                major_brand: parsed.major_brand,
1264                compatible_brands: parsed.compatible_brands,
1265            });
1266        };
1267
1268        // Get primary item extents
1269        let primary = Self::get_item_extents(&meta, meta.primary_item_id)?;
1270
1271        // Find alpha item and get its extents
1272        let alpha_item_id = meta
1273            .item_references
1274            .iter()
1275            .filter(|iref| {
1276                iref.to_item_id == meta.primary_item_id
1277                    && iref.from_item_id != meta.primary_item_id
1278                    && iref.item_type == b"auxl"
1279            })
1280            .map(|iref| iref.from_item_id)
1281            .find(|&item_id| {
1282                meta.properties.iter().any(|prop| {
1283                    prop.item_id == item_id
1284                        && match &prop.property {
1285                            ItemProperty::AuxiliaryType(urn) => {
1286                                urn.type_subtype().0 == b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha"
1287                            }
1288                            _ => false,
1289                        }
1290                })
1291            });
1292
1293        let alpha = alpha_item_id
1294            .map(|id| Self::get_item_extents(&meta, id))
1295            .transpose()?;
1296
1297        // Check for premultiplied alpha
1298        let premultiplied_alpha = alpha_item_id.is_some_and(|alpha_id| {
1299            meta.item_references.iter().any(|iref| {
1300                iref.from_item_id == meta.primary_item_id
1301                    && iref.to_item_id == alpha_id
1302                    && iref.item_type == b"prem"
1303            })
1304        });
1305
1306        // Find EXIF/XMP items linked via cdsc references to the primary item
1307        let mut exif_item = None;
1308        let mut xmp_item = None;
1309        for iref in meta.item_references.iter() {
1310            if iref.to_item_id != meta.primary_item_id || iref.item_type != b"cdsc" {
1311                continue;
1312            }
1313            let desc_item_id = iref.from_item_id;
1314            let Some(info) = meta.item_infos.iter().find(|i| i.item_id == desc_item_id) else {
1315                continue;
1316            };
1317            if info.item_type == b"Exif" && exif_item.is_none() {
1318                exif_item = Some(Self::get_item_extents(&meta, desc_item_id)?);
1319            } else if info.item_type == b"mime" && xmp_item.is_none() {
1320                xmp_item = Some(Self::get_item_extents(&meta, desc_item_id)?);
1321            }
1322        }
1323
1324        // Check if primary item is a grid (tiled image)
1325        let is_grid = meta
1326            .item_infos
1327            .iter()
1328            .find(|x| x.item_id == meta.primary_item_id)
1329            .is_some_and(|info| info.item_type == b"grid");
1330
1331        // Extract grid configuration and tile extents if this is a grid
1332        let (grid_config, tiles) = if is_grid {
1333            let mut tiles_with_index: TryVec<(u32, u16)> = TryVec::new();
1334            for iref in meta.item_references.iter() {
1335                if iref.from_item_id == meta.primary_item_id && iref.item_type == b"dimg" {
1336                    tiles_with_index.push((iref.to_item_id, iref.reference_index))?;
1337                }
1338            }
1339
1340            tracker.validate_grid_tiles(tiles_with_index.len() as u32)?;
1341            tiles_with_index.sort_by_key(|&(_, idx)| idx);
1342
1343            let mut tile_extents = TryVec::new();
1344            for (tile_id, _) in tiles_with_index.iter() {
1345                tile_extents.push(Self::get_item_extents(&meta, *tile_id)?)?;
1346            }
1347
1348            let mut tile_ids = TryVec::new();
1349            for (tile_id, _) in tiles_with_index.iter() {
1350                tile_ids.push(*tile_id)?;
1351            }
1352
1353            let grid_config = Self::calculate_grid_config(&meta, &tile_ids)?;
1354
1355            // AVIF 1.2: transformative properties SHALL NOT be on grid tile items
1356            for (tile_id, _) in tiles_with_index.iter() {
1357                for prop in meta.properties.iter() {
1358                    if prop.item_id == *tile_id {
1359                        match &prop.property {
1360                            ItemProperty::Rotation(_)
1361                            | ItemProperty::Mirror(_)
1362                            | ItemProperty::CleanAperture(_) => {
1363                                warn!("grid tile {} has a transformative property (irot/imir/clap), violating AVIF spec", tile_id);
1364                            }
1365                            _ => {}
1366                        }
1367                    }
1368                }
1369            }
1370
1371            (Some(grid_config), tile_extents)
1372        } else {
1373            (None, TryVec::new())
1374        };
1375
1376        // Detect gain map (tmap derived image item)
1377        let (gain_map_metadata, gain_map, gain_map_color_info) = {
1378            let tmap_item = meta.item_infos.iter()
1379                .find(|info| info.item_type == b"tmap");
1380
1381            if let Some(tmap_info) = tmap_item {
1382                let tmap_id = tmap_info.item_id;
1383
1384                // Find dimg references FROM tmap TO its inputs
1385                let mut inputs: TryVec<(u32, u16)> = TryVec::new();
1386                for iref in meta.item_references.iter() {
1387                    if iref.from_item_id == tmap_id && iref.item_type == b"dimg" {
1388                        inputs.push((iref.to_item_id, iref.reference_index))?;
1389                    }
1390                }
1391                inputs.sort_by_key(|&(_, idx)| idx);
1392
1393                if inputs.len() >= 2 {
1394                    let base_item_id = inputs[0].0;
1395                    let gmap_item_id = inputs[1].0;
1396
1397                    if base_item_id == meta.primary_item_id {
1398                        // Read tmap item's data payload (ToneMapImage)
1399                        let tmap_extents = Self::get_item_extents(&meta, tmap_id)?;
1400                        let tmap_data = Self::resolve_extents_from_raw(
1401                            raw.as_ref(), &parsed.mdat_bounds, &tmap_extents,
1402                        )?;
1403                        let metadata = parse_tone_map_image(&tmap_data)?;
1404
1405                        // Get gain map image extents
1406                        let gmap_extents = Self::get_item_extents(&meta, gmap_item_id)?;
1407
1408                        // Get alternate color info from tmap item's properties
1409                        let alt_color = meta.properties.iter().find_map(|p| {
1410                            if p.item_id == tmap_id {
1411                                match &p.property {
1412                                    ItemProperty::ColorInformation(c) => Some(c.clone()),
1413                                    _ => None,
1414                                }
1415                            } else {
1416                                None
1417                            }
1418                        });
1419
1420                        (Some(metadata), Some(gmap_extents), alt_color)
1421                    } else {
1422                        (None, None, None)
1423                    }
1424                } else {
1425                    (None, None, None)
1426                }
1427            } else {
1428                (None, None, None)
1429            }
1430        };
1431
1432        // Extract properties for the primary item
1433        macro_rules! find_prop {
1434            ($variant:ident) => {
1435                meta.properties.iter().find_map(|p| {
1436                    if p.item_id == meta.primary_item_id {
1437                        match &p.property {
1438                            ItemProperty::$variant(c) => Some(c.clone()),
1439                            _ => None,
1440                        }
1441                    } else {
1442                        None
1443                    }
1444                })
1445            };
1446        }
1447
1448        let track_config = animation_data.as_ref().map(|a| &a.codec_config);
1449        let av1_config = find_prop!(AV1Config)
1450            .or_else(|| track_config.and_then(|c| c.av1_config.clone()));
1451        let color_info = find_prop!(ColorInformation)
1452            .or_else(|| track_config.and_then(|c| c.color_info.clone()));
1453        let rotation = find_prop!(Rotation);
1454        let mirror = find_prop!(Mirror);
1455        let clean_aperture = find_prop!(CleanAperture);
1456        let pixel_aspect_ratio = find_prop!(PixelAspectRatio);
1457        let content_light_level = find_prop!(ContentLightLevel);
1458        let mastering_display = find_prop!(MasteringDisplayColourVolume);
1459        let content_colour_volume = find_prop!(ContentColourVolume);
1460        let ambient_viewing = find_prop!(AmbientViewingEnvironment);
1461        let operating_point = find_prop!(OperatingPointSelector);
1462        let layer_selector = find_prop!(LayerSelector);
1463        let layered_image_indexing = find_prop!(AV1LayeredImageIndexing);
1464
1465        // Clone idat
1466        let idat = if let Some(ref idat_data) = meta.idat {
1467            let mut cloned = TryVec::new();
1468            cloned.extend_from_slice(idat_data)?;
1469            Some(cloned)
1470        } else {
1471            None
1472        };
1473
1474        Ok(Self {
1475            raw,
1476            mdat_bounds: parsed.mdat_bounds,
1477            idat,
1478            primary,
1479            alpha,
1480            grid_config,
1481            tiles,
1482            animation_data,
1483            premultiplied_alpha,
1484            av1_config,
1485            color_info,
1486            rotation,
1487            mirror,
1488            clean_aperture,
1489            pixel_aspect_ratio,
1490            content_light_level,
1491            mastering_display,
1492            content_colour_volume,
1493            ambient_viewing,
1494            operating_point,
1495            layer_selector,
1496            layered_image_indexing,
1497            exif_item,
1498            xmp_item,
1499            gain_map_metadata,
1500            gain_map,
1501            gain_map_color_info,
1502            major_brand: parsed.major_brand,
1503            compatible_brands: parsed.compatible_brands,
1504        })
1505    }
1506
1507    // ========================================
1508    // Internal helpers
1509    // ========================================
1510
1511    /// Get item extents (construction method + ranges) from metadata.
1512    fn get_item_extents(meta: &AvifInternalMeta, item_id: u32) -> Result<ItemExtents> {
1513        let item = meta
1514            .iloc_items
1515            .iter()
1516            .find(|item| item.item_id == item_id)
1517            .ok_or(Error::InvalidData("item not found in iloc"))?;
1518
1519        let mut extents = TryVec::new();
1520        for extent in &item.extents {
1521            extents.push(extent.extent_range.clone())?;
1522        }
1523        Ok(ItemExtents {
1524            construction_method: item.construction_method,
1525            extents,
1526        })
1527    }
1528
1529    /// Resolve file-based item extents from a raw buffer during `build()`,
1530    /// before `self` exists. Returns owned data (small payloads like tmap).
1531    fn resolve_extents_from_raw(
1532        raw: &[u8],
1533        mdat_bounds: &[MdatBounds],
1534        item: &ItemExtents,
1535    ) -> Result<std::vec::Vec<u8>> {
1536        if item.construction_method != ConstructionMethod::File {
1537            return Err(Error::Unsupported("tmap item must use file construction method"));
1538        }
1539        let mut data = std::vec::Vec::new();
1540        for extent in &item.extents {
1541            let file_offset = extent.start();
1542            let start = usize::try_from(file_offset)?;
1543            let end = match extent {
1544                ExtentRange::WithLength(range) => {
1545                    let len = range.end.checked_sub(range.start)
1546                        .ok_or(Error::InvalidData("extent range start > end"))?;
1547                    start.checked_add(usize::try_from(len)?)
1548                        .ok_or(Error::InvalidData("extent end overflow"))?
1549                }
1550                ExtentRange::ToEnd(_) => {
1551                    // Find the mdat that contains this offset
1552                    let mut found_end = raw.len();
1553                    for mdat in mdat_bounds {
1554                        if file_offset >= mdat.offset && file_offset < mdat.offset + mdat.length {
1555                            found_end = usize::try_from(mdat.offset + mdat.length)?;
1556                            break;
1557                        }
1558                    }
1559                    found_end
1560                }
1561            };
1562            let slice = raw.get(start..end)
1563                .ok_or(Error::InvalidData("tmap extent out of bounds"))?;
1564            data.extend_from_slice(slice);
1565        }
1566        Ok(data)
1567    }
1568
1569    /// Resolve an item's data from the raw buffer, returning `Cow::Borrowed`
1570    /// for single-extent file items and `Cow::Owned` for multi-extent or idat.
1571    fn resolve_item(&self, item: &ItemExtents) -> Result<Cow<'_, [u8]>> {
1572        match item.construction_method {
1573            ConstructionMethod::Idat => self.resolve_idat_extents(&item.extents),
1574            ConstructionMethod::File => self.resolve_file_extents(&item.extents),
1575            ConstructionMethod::Item => Err(Error::Unsupported("construction_method 'item' not supported")),
1576        }
1577    }
1578
1579    /// Resolve file-based extents from the raw buffer.
1580    fn resolve_file_extents(&self, extents: &[ExtentRange]) -> Result<Cow<'_, [u8]>> {
1581        let raw = self.raw.as_ref();
1582
1583        // Fast path: single extent → borrow directly from raw
1584        if extents.len() == 1 {
1585            let extent = &extents[0];
1586            let (start, end) = self.extent_byte_range(extent)?;
1587            let slice = raw.get(start..end).ok_or(Error::InvalidData("extent out of bounds in raw buffer"))?;
1588            return Ok(Cow::Borrowed(slice));
1589        }
1590
1591        // Multi-extent: concatenate into owned buffer
1592        let mut data = TryVec::new();
1593        for extent in extents {
1594            let (start, end) = self.extent_byte_range(extent)?;
1595            let slice = raw.get(start..end).ok_or(Error::InvalidData("extent out of bounds in raw buffer"))?;
1596            data.extend_from_slice(slice)?;
1597        }
1598        Ok(Cow::Owned(data.into_iter().collect()))
1599    }
1600
1601    /// Convert an ExtentRange to a (start, end) byte range within the raw buffer.
1602    fn extent_byte_range(&self, extent: &ExtentRange) -> Result<(usize, usize)> {
1603        let file_offset = extent.start();
1604        let start = usize::try_from(file_offset)?;
1605
1606        match extent {
1607            ExtentRange::WithLength(range) => {
1608                let len = range.end.checked_sub(range.start)
1609                    .ok_or(Error::InvalidData("extent range start > end"))?;
1610                let end = start.checked_add(usize::try_from(len)?)
1611                    .ok_or(Error::InvalidData("extent end overflow"))?;
1612                Ok((start, end))
1613            }
1614            ExtentRange::ToEnd(_) => {
1615                // Find the mdat that contains this offset and use its bounds
1616                for mdat in &self.mdat_bounds {
1617                    if file_offset >= mdat.offset && file_offset < mdat.offset + mdat.length {
1618                        let end = usize::try_from(mdat.offset + mdat.length)?;
1619                        return Ok((start, end));
1620                    }
1621                }
1622                // Fall back to end of raw buffer
1623                Ok((start, self.raw.len()))
1624            }
1625        }
1626    }
1627
1628    /// Resolve idat-based extents.
1629    fn resolve_idat_extents(&self, extents: &[ExtentRange]) -> Result<Cow<'_, [u8]>> {
1630        let idat_data = self.idat.as_ref()
1631            .ok_or(Error::InvalidData("idat box missing but construction_method is Idat"))?;
1632
1633        if extents.len() == 1 {
1634            let extent = &extents[0];
1635            let start = usize::try_from(extent.start())?;
1636            let slice = match extent {
1637                ExtentRange::WithLength(range) => {
1638                    let len = usize::try_from(range.end - range.start)?;
1639                    idat_data.get(start..start + len)
1640                        .ok_or(Error::InvalidData("idat extent out of bounds"))?
1641                }
1642                ExtentRange::ToEnd(_) => {
1643                    idat_data.get(start..)
1644                        .ok_or(Error::InvalidData("idat extent out of bounds"))?
1645                }
1646            };
1647            return Ok(Cow::Borrowed(slice));
1648        }
1649
1650        // Multi-extent idat: concatenate
1651        let mut data = TryVec::new();
1652        for extent in extents {
1653            let start = usize::try_from(extent.start())?;
1654            let slice = match extent {
1655                ExtentRange::WithLength(range) => {
1656                    let len = usize::try_from(range.end - range.start)?;
1657                    idat_data.get(start..start + len)
1658                        .ok_or(Error::InvalidData("idat extent out of bounds"))?
1659                }
1660                ExtentRange::ToEnd(_) => {
1661                    idat_data.get(start..)
1662                        .ok_or(Error::InvalidData("idat extent out of bounds"))?
1663                }
1664            };
1665            data.extend_from_slice(slice)?;
1666        }
1667        Ok(Cow::Owned(data.into_iter().collect()))
1668    }
1669
1670    /// Resolve a single animation frame from the raw buffer.
1671    fn resolve_frame(&self, index: usize) -> Result<FrameRef<'_>> {
1672        let anim = self.animation_data.as_ref()
1673            .ok_or(Error::InvalidData("not an animated AVIF"))?;
1674
1675        if index >= anim.sample_table.sample_sizes.len() {
1676            return Err(Error::InvalidData("frame index out of bounds"));
1677        }
1678
1679        let duration_ms = self.calculate_frame_duration(&anim.sample_table, anim.media_timescale, index)?;
1680        let (offset, size) = self.calculate_sample_location(&anim.sample_table, index)?;
1681
1682        let start = usize::try_from(offset)?;
1683        let end = start.checked_add(size as usize)
1684            .ok_or(Error::InvalidData("frame end overflow"))?;
1685
1686        let raw = self.raw.as_ref();
1687        let slice = raw.get(start..end)
1688            .ok_or(Error::InvalidData("frame not found in raw buffer"))?;
1689
1690        // Resolve alpha frame if alpha track exists and has this index
1691        let alpha_data = if let Some(ref alpha_st) = anim.alpha_sample_table {
1692            let alpha_timescale = anim.alpha_media_timescale.unwrap_or(anim.media_timescale);
1693            if index < alpha_st.sample_sizes.len() {
1694                let (a_offset, a_size) = self.calculate_sample_location(alpha_st, index)?;
1695                let a_start = usize::try_from(a_offset)?;
1696                let a_end = a_start.checked_add(a_size as usize)
1697                    .ok_or(Error::InvalidData("alpha frame end overflow"))?;
1698                let a_slice = raw.get(a_start..a_end)
1699                    .ok_or(Error::InvalidData("alpha frame not found in raw buffer"))?;
1700                let _ = alpha_timescale; // timescale used for duration, which comes from color track
1701                Some(Cow::Borrowed(a_slice))
1702            } else {
1703                warn!("alpha track has fewer frames than color track (index {})", index);
1704                None
1705            }
1706        } else {
1707            None
1708        };
1709
1710        Ok(FrameRef {
1711            data: Cow::Borrowed(slice),
1712            alpha_data,
1713            duration_ms,
1714        })
1715    }
1716
1717    /// Calculate grid configuration from metadata.
1718    fn calculate_grid_config(meta: &AvifInternalMeta, tile_ids: &[u32]) -> Result<GridConfig> {
1719        // Try explicit grid property first
1720        for prop in &meta.properties {
1721            if prop.item_id == meta.primary_item_id
1722                && let ItemProperty::ImageGrid(grid) = &prop.property {
1723                    return Ok(grid.clone());
1724                }
1725        }
1726
1727        // Fall back to ispe calculation
1728        let grid_dims = meta
1729            .properties
1730            .iter()
1731            .find(|p| p.item_id == meta.primary_item_id)
1732            .and_then(|p| match &p.property {
1733                ItemProperty::ImageSpatialExtents(e) => Some(e),
1734                _ => None,
1735            });
1736
1737        let tile_dims = tile_ids.first().and_then(|&tile_id| {
1738            meta.properties
1739                .iter()
1740                .find(|p| p.item_id == tile_id)
1741                .and_then(|p| match &p.property {
1742                    ItemProperty::ImageSpatialExtents(e) => Some(e),
1743                    _ => None,
1744                })
1745        });
1746
1747        if let (Some(grid), Some(tile)) = (grid_dims, tile_dims)
1748            && tile.width != 0
1749                && tile.height != 0
1750                && grid.width % tile.width == 0
1751                && grid.height % tile.height == 0
1752            {
1753                let columns = grid.width / tile.width;
1754                let rows = grid.height / tile.height;
1755
1756                if columns <= 255 && rows <= 255 {
1757                    return Ok(GridConfig {
1758                        rows: rows as u8,
1759                        columns: columns as u8,
1760                        output_width: grid.width,
1761                        output_height: grid.height,
1762                    });
1763                }
1764            }
1765
1766        let tile_count = tile_ids.len();
1767        Ok(GridConfig {
1768            rows: tile_count.min(255) as u8,
1769            columns: 1,
1770            output_width: 0,
1771            output_height: 0,
1772        })
1773    }
1774
1775    /// Calculate frame duration from sample table.
1776    fn calculate_frame_duration(
1777        &self,
1778        st: &SampleTable,
1779        timescale: u32,
1780        index: usize,
1781    ) -> Result<u32> {
1782        let mut current_sample = 0;
1783        for entry in &st.time_to_sample {
1784            if current_sample + entry.sample_count as usize > index {
1785                let duration_ms = if timescale > 0 {
1786                    ((entry.sample_delta as u64) * 1000) / (timescale as u64)
1787                } else {
1788                    0
1789                };
1790                return Ok(duration_ms as u32);
1791            }
1792            current_sample += entry.sample_count as usize;
1793        }
1794        Ok(0)
1795    }
1796
1797    /// Look up precomputed sample location (offset and size) from sample table.
1798    fn calculate_sample_location(&self, st: &SampleTable, index: usize) -> Result<(u64, u32)> {
1799        let offset = *st
1800            .sample_offsets
1801            .get(index)
1802            .ok_or(Error::InvalidData("sample index out of bounds"))?;
1803        let size = *st
1804            .sample_sizes
1805            .get(index)
1806            .ok_or(Error::InvalidData("sample index out of bounds"))?;
1807        Ok((offset, size))
1808    }
1809
1810    // ========================================
1811    // Public data access API (one way each)
1812    // ========================================
1813
1814    /// Get primary item data.
1815    ///
1816    /// Returns `Cow::Borrowed` for single-extent items, `Cow::Owned` for multi-extent.
1817    pub fn primary_data(&self) -> Result<Cow<'_, [u8]>> {
1818        self.resolve_item(&self.primary)
1819    }
1820
1821    /// Get alpha item data, if present.
1822    pub fn alpha_data(&self) -> Option<Result<Cow<'_, [u8]>>> {
1823        self.alpha.as_ref().map(|item| self.resolve_item(item))
1824    }
1825
1826    /// Get grid tile data by index.
1827    pub fn tile_data(&self, index: usize) -> Result<Cow<'_, [u8]>> {
1828        let item = self.tiles.get(index)
1829            .ok_or(Error::InvalidData("tile index out of bounds"))?;
1830        self.resolve_item(item)
1831    }
1832
1833    /// Get a single animation frame by index.
1834    pub fn frame(&self, index: usize) -> Result<FrameRef<'_>> {
1835        self.resolve_frame(index)
1836    }
1837
1838    /// Iterate over all animation frames.
1839    pub fn frames(&self) -> FrameIterator<'_> {
1840        let count = self
1841            .animation_info()
1842            .map(|info| info.frame_count)
1843            .unwrap_or(0);
1844        FrameIterator { parser: self, index: 0, count }
1845    }
1846
1847    // ========================================
1848    // Metadata (no data access)
1849    // ========================================
1850
1851    /// Get animation metadata (if animated).
1852    pub fn animation_info(&self) -> Option<AnimationInfo> {
1853        self.animation_data.as_ref().map(|data| AnimationInfo {
1854            frame_count: data.sample_table.sample_sizes.len(),
1855            loop_count: data.loop_count,
1856            has_alpha: data.alpha_sample_table.is_some(),
1857            timescale: data.media_timescale,
1858        })
1859    }
1860
1861    /// Get grid configuration (if grid image).
1862    pub fn grid_config(&self) -> Option<&GridConfig> {
1863        self.grid_config.as_ref()
1864    }
1865
1866    /// Get number of grid tiles.
1867    pub fn grid_tile_count(&self) -> usize {
1868        self.tiles.len()
1869    }
1870
1871    /// Check if alpha channel uses premultiplied alpha.
1872    pub fn premultiplied_alpha(&self) -> bool {
1873        self.premultiplied_alpha
1874    }
1875
1876    /// Get the AV1 codec configuration for the primary item, if present.
1877    ///
1878    /// This is parsed from the `av1C` property box in the container.
1879    pub fn av1_config(&self) -> Option<&AV1Config> {
1880        self.av1_config.as_ref()
1881    }
1882
1883    /// Get colour information for the primary item, if present.
1884    ///
1885    /// This is parsed from the `colr` property box in the container.
1886    /// For CICP/nclx values, this is the authoritative source and may
1887    /// differ from values in the AV1 bitstream sequence header.
1888    pub fn color_info(&self) -> Option<&ColorInformation> {
1889        self.color_info.as_ref()
1890    }
1891
1892    /// Get rotation for the primary item, if present.
1893    pub fn rotation(&self) -> Option<&ImageRotation> {
1894        self.rotation.as_ref()
1895    }
1896
1897    /// Get mirror for the primary item, if present.
1898    pub fn mirror(&self) -> Option<&ImageMirror> {
1899        self.mirror.as_ref()
1900    }
1901
1902    /// Get clean aperture (crop) for the primary item, if present.
1903    pub fn clean_aperture(&self) -> Option<&CleanAperture> {
1904        self.clean_aperture.as_ref()
1905    }
1906
1907    /// Get pixel aspect ratio for the primary item, if present.
1908    pub fn pixel_aspect_ratio(&self) -> Option<&PixelAspectRatio> {
1909        self.pixel_aspect_ratio.as_ref()
1910    }
1911
1912    /// Get content light level info for the primary item, if present.
1913    pub fn content_light_level(&self) -> Option<&ContentLightLevel> {
1914        self.content_light_level.as_ref()
1915    }
1916
1917    /// Get mastering display colour volume for the primary item, if present.
1918    pub fn mastering_display(&self) -> Option<&MasteringDisplayColourVolume> {
1919        self.mastering_display.as_ref()
1920    }
1921
1922    /// Get content colour volume for the primary item, if present.
1923    pub fn content_colour_volume(&self) -> Option<&ContentColourVolume> {
1924        self.content_colour_volume.as_ref()
1925    }
1926
1927    /// Get ambient viewing environment for the primary item, if present.
1928    pub fn ambient_viewing(&self) -> Option<&AmbientViewingEnvironment> {
1929        self.ambient_viewing.as_ref()
1930    }
1931
1932    /// Get operating point selector for the primary item, if present.
1933    pub fn operating_point(&self) -> Option<&OperatingPointSelector> {
1934        self.operating_point.as_ref()
1935    }
1936
1937    /// Get layer selector for the primary item, if present.
1938    pub fn layer_selector(&self) -> Option<&LayerSelector> {
1939        self.layer_selector.as_ref()
1940    }
1941
1942    /// Get AV1 layered image indexing for the primary item, if present.
1943    pub fn layered_image_indexing(&self) -> Option<&AV1LayeredImageIndexing> {
1944        self.layered_image_indexing.as_ref()
1945    }
1946
1947    /// Get EXIF metadata for the primary item, if present.
1948    ///
1949    /// Returns raw EXIF data (TIFF header onwards), with the 4-byte AVIF offset prefix stripped.
1950    pub fn exif(&self) -> Option<Result<Cow<'_, [u8]>>> {
1951        self.exif_item.as_ref().map(|item| {
1952            let raw = self.resolve_item(item)?;
1953            // AVIF EXIF items start with a 4-byte big-endian offset to the TIFF header
1954            if raw.len() <= 4 {
1955                return Err(Error::InvalidData("EXIF item too short"));
1956            }
1957            let offset = u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]) as usize;
1958            let start = 4 + offset;
1959            if start >= raw.len() {
1960                return Err(Error::InvalidData("EXIF offset exceeds item size"));
1961            }
1962            match raw {
1963                Cow::Borrowed(slice) => Ok(Cow::Borrowed(&slice[start..])),
1964                Cow::Owned(vec) => Ok(Cow::Owned(vec[start..].to_vec())),
1965            }
1966        })
1967    }
1968
1969    /// Get XMP metadata for the primary item, if present.
1970    ///
1971    /// Returns raw XMP/XML data.
1972    pub fn xmp(&self) -> Option<Result<Cow<'_, [u8]>>> {
1973        self.xmp_item.as_ref().map(|item| self.resolve_item(item))
1974    }
1975
1976    /// Gain map metadata, if a `tmap` derived image item is present.
1977    ///
1978    /// Describes how to apply a gain map to reconstruct an HDR rendition
1979    /// from the SDR base image. See ISO 21496-1.
1980    pub fn gain_map_metadata(&self) -> Option<&GainMapMetadata> {
1981        self.gain_map_metadata.as_ref()
1982    }
1983
1984    /// Gain map image data (AV1-encoded), if present.
1985    pub fn gain_map_data(&self) -> Option<Result<Cow<'_, [u8]>>> {
1986        self.gain_map.as_ref().map(|item| self.resolve_item(item))
1987    }
1988
1989    /// Color information for the alternate (typically HDR) rendition.
1990    ///
1991    /// This comes from the `tmap` item's `colr` property and describes
1992    /// the colour space of the tone-mapped output.
1993    pub fn gain_map_color_info(&self) -> Option<&ColorInformation> {
1994        self.gain_map_color_info.as_ref()
1995    }
1996
1997    /// Get the major brand from the `ftyp` box (e.g., `*b"avif"` or `*b"avis"`).
1998    pub fn major_brand(&self) -> &[u8; 4] {
1999        &self.major_brand
2000    }
2001
2002    /// Get the compatible brands from the `ftyp` box.
2003    pub fn compatible_brands(&self) -> &[[u8; 4]] {
2004        &self.compatible_brands
2005    }
2006
2007    /// Parse AV1 metadata from the primary item.
2008    pub fn primary_metadata(&self) -> Result<AV1Metadata> {
2009        let data = self.primary_data()?;
2010        AV1Metadata::parse_av1_bitstream(&data)
2011    }
2012
2013    /// Parse AV1 metadata from the alpha item, if present.
2014    pub fn alpha_metadata(&self) -> Option<Result<AV1Metadata>> {
2015        self.alpha.as_ref().map(|item| {
2016            let data = self.resolve_item(item)?;
2017            AV1Metadata::parse_av1_bitstream(&data)
2018        })
2019    }
2020
2021    // ========================================
2022    // Conversion
2023    // ========================================
2024
2025    /// Convert to [`AvifData`] (eagerly loads all frames and tiles).
2026    ///
2027    /// Provided for migration from the eager API. Prefer using `AvifParser`
2028    /// methods directly.
2029    #[cfg(feature = "eager")]
2030    #[deprecated(since = "1.5.0", note = "Use AvifParser methods directly instead of converting to AvifData")]
2031    #[allow(deprecated)]
2032    pub fn to_avif_data(&self) -> Result<AvifData> {
2033        let primary_data = self.primary_data()?;
2034        let mut primary_item = TryVec::new();
2035        primary_item.extend_from_slice(&primary_data)?;
2036
2037        let alpha_item = match self.alpha_data() {
2038            Some(Ok(data)) => {
2039                let mut v = TryVec::new();
2040                v.extend_from_slice(&data)?;
2041                Some(v)
2042            }
2043            Some(Err(e)) => return Err(e),
2044            None => None,
2045        };
2046
2047        let mut grid_tiles = TryVec::new();
2048        for i in 0..self.grid_tile_count() {
2049            let data = self.tile_data(i)?;
2050            let mut v = TryVec::new();
2051            v.extend_from_slice(&data)?;
2052            grid_tiles.push(v)?;
2053        }
2054
2055        let animation = if let Some(info) = self.animation_info() {
2056            let mut frames = TryVec::new();
2057            for i in 0..info.frame_count {
2058                let frame_ref = self.frame(i)?;
2059                let mut data = TryVec::new();
2060                data.extend_from_slice(&frame_ref.data)?;
2061                frames.push(AnimationFrame { data, duration_ms: frame_ref.duration_ms })?;
2062            }
2063            Some(AnimationConfig {
2064                loop_count: info.loop_count,
2065                frames,
2066            })
2067        } else {
2068            None
2069        };
2070
2071        Ok(AvifData {
2072            primary_item,
2073            alpha_item,
2074            premultiplied_alpha: self.premultiplied_alpha,
2075            grid_config: self.grid_config.clone(),
2076            grid_tiles,
2077            animation,
2078            av1_config: self.av1_config.clone(),
2079            color_info: self.color_info.clone(),
2080            rotation: self.rotation,
2081            mirror: self.mirror,
2082            clean_aperture: self.clean_aperture,
2083            pixel_aspect_ratio: self.pixel_aspect_ratio,
2084            content_light_level: self.content_light_level,
2085            mastering_display: self.mastering_display,
2086            content_colour_volume: self.content_colour_volume,
2087            ambient_viewing: self.ambient_viewing,
2088            operating_point: self.operating_point,
2089            layer_selector: self.layer_selector,
2090            layered_image_indexing: self.layered_image_indexing,
2091            exif: self.exif().and_then(|r| r.ok()).map(|c| {
2092                let mut v = TryVec::new();
2093                let _ = v.extend_from_slice(&c);
2094                v
2095            }),
2096            xmp: self.xmp().and_then(|r| r.ok()).map(|c| {
2097                let mut v = TryVec::new();
2098                let _ = v.extend_from_slice(&c);
2099                v
2100            }),
2101            gain_map_metadata: self.gain_map_metadata.clone(),
2102            gain_map_item: self.gain_map_data().and_then(|r| r.ok()).map(|c| {
2103                let mut v = TryVec::new();
2104                let _ = v.extend_from_slice(&c);
2105                v
2106            }),
2107            gain_map_color_info: self.gain_map_color_info.clone(),
2108            major_brand: self.major_brand,
2109            compatible_brands: self.compatible_brands.clone(),
2110        })
2111    }
2112}
2113
2114/// Iterator over animation frames.
2115///
2116/// Created by [`AvifParser::frames()`]. Yields [`FrameRef`] on demand.
2117pub struct FrameIterator<'a> {
2118    parser: &'a AvifParser<'a>,
2119    index: usize,
2120    count: usize,
2121}
2122
2123impl<'a> Iterator for FrameIterator<'a> {
2124    type Item = Result<FrameRef<'a>>;
2125
2126    fn next(&mut self) -> Option<Self::Item> {
2127        if self.index >= self.count {
2128            return None;
2129        }
2130        let result = self.parser.frame(self.index);
2131        self.index += 1;
2132        Some(result)
2133    }
2134
2135    fn size_hint(&self) -> (usize, Option<usize>) {
2136        let remaining = self.count.saturating_sub(self.index);
2137        (remaining, Some(remaining))
2138    }
2139}
2140
2141impl ExactSizeIterator for FrameIterator<'_> {
2142    fn len(&self) -> usize {
2143        self.count.saturating_sub(self.index)
2144    }
2145}
2146
2147struct AvifInternalMeta {
2148    item_references: TryVec<SingleItemTypeReferenceBox>,
2149    properties: TryVec<AssociatedProperty>,
2150    primary_item_id: u32,
2151    iloc_items: TryVec<ItemLocationBoxItem>,
2152    item_infos: TryVec<ItemInfoEntry>,
2153    idat: Option<TryVec<u8>>,
2154    #[allow(dead_code)] // Parsed for future altr group support
2155    entity_groups: TryVec<EntityGroup>,
2156}
2157
2158/// A Media Data Box
2159/// See ISO 14496-12:2015 § 8.1.1
2160#[cfg(feature = "eager")]
2161struct MediaDataBox {
2162    /// Offset of `data` from the beginning of the file. See `ConstructionMethod::File`
2163    offset: u64,
2164    data: TryVec<u8>,
2165}
2166
2167#[cfg(feature = "eager")]
2168impl MediaDataBox {
2169    /// Check whether the beginning of `extent` is within the bounds of the `MediaDataBox`.
2170    /// We assume extents to not cross box boundaries. If so, this will cause an error
2171    /// in `read_extent`.
2172    fn contains_extent(&self, extent: &ExtentRange) -> bool {
2173        if self.offset <= extent.start() {
2174            let start_offset = extent.start() - self.offset;
2175            start_offset < self.data.len().to_u64()
2176        } else {
2177            false
2178        }
2179    }
2180
2181    /// Check whether `extent` covers the `MediaDataBox` exactly.
2182    fn matches_extent(&self, extent: &ExtentRange) -> bool {
2183        if self.offset == extent.start() {
2184            match extent {
2185                ExtentRange::WithLength(range) => {
2186                    if let Some(end) = self.offset.checked_add(self.data.len().to_u64()) {
2187                        end == range.end
2188                    } else {
2189                        false
2190                    }
2191                },
2192                ExtentRange::ToEnd(_) => true,
2193            }
2194        } else {
2195            false
2196        }
2197    }
2198
2199    /// Copy the range specified by `extent` to the end of `buf` or return an error if the range
2200    /// is not fully contained within `MediaDataBox`.
2201    fn read_extent(&self, extent: &ExtentRange, buf: &mut TryVec<u8>) -> Result<()> {
2202        let start_offset = extent
2203            .start()
2204            .checked_sub(self.offset)
2205            .ok_or(Error::InvalidData("mdat does not contain extent"))?;
2206        let slice = match extent {
2207            ExtentRange::WithLength(range) => {
2208                let range_len = range
2209                    .end
2210                    .checked_sub(range.start)
2211                    .ok_or(Error::InvalidData("range start > end"))?;
2212                let end = start_offset
2213                    .checked_add(range_len)
2214                    .ok_or(Error::InvalidData("extent end overflow"))?;
2215                self.data.get(start_offset.try_into()?..end.try_into()?)
2216            },
2217            ExtentRange::ToEnd(_) => self.data.get(start_offset.try_into()?..),
2218        };
2219        let slice = slice.ok_or(Error::InvalidData("extent crosses box boundary"))?;
2220        buf.extend_from_slice(slice)?;
2221        Ok(())
2222    }
2223
2224}
2225
2226/// Used for 'infe' boxes within 'iinf' boxes
2227/// See ISO 14496-12:2015 § 8.11.6
2228/// Only versions {2, 3} are supported
2229#[derive(Debug)]
2230struct ItemInfoEntry {
2231    item_id: u32,
2232    item_type: FourCC,
2233}
2234
2235/// See ISO 14496-12:2015 § 8.11.12
2236#[derive(Debug)]
2237struct SingleItemTypeReferenceBox {
2238    item_type: FourCC,
2239    from_item_id: u32,
2240    to_item_id: u32,
2241    /// Index of this reference within the list of references of the same type from the same item
2242    /// (0-based). This is the dimgIdx for grid tiles.
2243    reference_index: u16,
2244}
2245
2246/// Potential sizes (in bytes) of variable-sized fields of the 'iloc' box
2247/// See ISO 14496-12:2015 § 8.11.3
2248#[derive(Debug)]
2249enum IlocFieldSize {
2250    Zero,
2251    Four,
2252    Eight,
2253}
2254
2255impl IlocFieldSize {
2256    const fn to_bits(&self) -> u8 {
2257        match self {
2258            Self::Zero => 0,
2259            Self::Four => 32,
2260            Self::Eight => 64,
2261        }
2262    }
2263}
2264
2265impl TryFrom<u8> for IlocFieldSize {
2266    type Error = Error;
2267
2268    fn try_from(value: u8) -> Result<Self> {
2269        match value {
2270            0 => Ok(Self::Zero),
2271            4 => Ok(Self::Four),
2272            8 => Ok(Self::Eight),
2273            _ => Err(Error::InvalidData("value must be in the set {0, 4, 8}")),
2274        }
2275    }
2276}
2277
2278#[derive(PartialEq)]
2279enum IlocVersion {
2280    Zero,
2281    One,
2282    Two,
2283}
2284
2285impl TryFrom<u8> for IlocVersion {
2286    type Error = Error;
2287
2288    fn try_from(value: u8) -> Result<Self> {
2289        match value {
2290            0 => Ok(Self::Zero),
2291            1 => Ok(Self::One),
2292            2 => Ok(Self::Two),
2293            _ => Err(Error::Unsupported("unsupported version in 'iloc' box")),
2294        }
2295    }
2296}
2297
2298/// Used for 'iloc' boxes
2299/// See ISO 14496-12:2015 § 8.11.3
2300/// `base_offset` is omitted since it is integrated into the ranges in `extents`
2301/// `data_reference_index` is omitted, since only 0 (i.e., this file) is supported
2302#[derive(Debug)]
2303struct ItemLocationBoxItem {
2304    item_id: u32,
2305    construction_method: ConstructionMethod,
2306    /// Unused for `ConstructionMethod::Idat`
2307    extents: TryVec<ItemLocationBoxExtent>,
2308}
2309
2310#[derive(Clone, Copy, Debug, PartialEq)]
2311enum ConstructionMethod {
2312    File,
2313    Idat,
2314    #[allow(dead_code)] // TODO: see https://github.com/mozilla/mp4parse-rust/issues/196
2315    Item,
2316}
2317
2318/// `extent_index` is omitted since it's only used for `ConstructionMethod::Item` which
2319/// is currently not implemented.
2320#[derive(Clone, Debug)]
2321struct ItemLocationBoxExtent {
2322    extent_range: ExtentRange,
2323}
2324
2325#[derive(Clone, Debug)]
2326enum ExtentRange {
2327    WithLength(Range<u64>),
2328    ToEnd(RangeFrom<u64>),
2329}
2330
2331impl ExtentRange {
2332    const fn start(&self) -> u64 {
2333        match self {
2334            Self::WithLength(r) => r.start,
2335            Self::ToEnd(r) => r.start,
2336        }
2337    }
2338}
2339
2340/// See ISO 14496-12:2015 § 4.2
2341struct BMFFBox<'a, T> {
2342    head: BoxHeader,
2343    content: Take<&'a mut T>,
2344}
2345
2346impl<T: Read> BMFFBox<'_, T> {
2347    fn read_into_try_vec(&mut self) -> std::io::Result<TryVec<u8>> {
2348        let limit = self.content.limit();
2349        // For size=0 boxes, size is set to u64::MAX, but after subtracting offset
2350        // (8 or 16 bytes), the limit will be slightly less. Check for values very
2351        // close to u64::MAX to detect these cases.
2352        let mut vec = if limit >= u64::MAX - BoxHeader::MIN_LARGE_SIZE {
2353            // Unknown size (size=0 box), read without pre-allocation
2354            std::vec::Vec::new()
2355        } else {
2356            let mut v = std::vec::Vec::new();
2357            v.try_reserve_exact(limit as usize)
2358                .map_err(|_| std::io::ErrorKind::OutOfMemory)?;
2359            v
2360        };
2361        self.content.read_to_end(&mut vec)?; // The default impl
2362        Ok(vec.into())
2363    }
2364}
2365
2366#[test]
2367fn box_read_to_end() {
2368    let tmp = &mut b"1234567890".as_slice();
2369    let mut src = BMFFBox {
2370        head: BoxHeader { name: BoxType::FileTypeBox, size: 5, offset: 0, uuid: None },
2371        content: <_ as Read>::take(tmp, 5),
2372    };
2373    let buf = src.read_into_try_vec().unwrap();
2374    assert_eq!(buf.len(), 5);
2375    assert_eq!(buf, b"12345".as_ref());
2376}
2377
2378#[test]
2379fn box_read_to_end_oom() {
2380    let tmp = &mut b"1234567890".as_slice();
2381    let mut src = BMFFBox {
2382        head: BoxHeader { name: BoxType::FileTypeBox, size: 5, offset: 0, uuid: None },
2383        // Use a very large value to trigger OOM, but not near u64::MAX (which indicates size=0 boxes)
2384        content: <_ as Read>::take(tmp, u64::MAX / 2),
2385    };
2386    assert!(src.read_into_try_vec().is_err());
2387}
2388
2389struct BoxIter<'a, T> {
2390    src: &'a mut T,
2391}
2392
2393impl<T: Read> BoxIter<'_, T> {
2394    fn new(src: &mut T) -> BoxIter<'_, T> {
2395        BoxIter { src }
2396    }
2397
2398    fn next_box(&mut self) -> Result<Option<BMFFBox<'_, T>>> {
2399        let r = read_box_header(self.src);
2400        match r {
2401            Ok(h) => Ok(Some(BMFFBox {
2402                head: h,
2403                content: self.src.take(h.size - h.offset),
2404            })),
2405            Err(Error::UnexpectedEOF) => Ok(None),
2406            Err(e) => Err(e),
2407        }
2408    }
2409}
2410
2411impl<T: Read> Read for BMFFBox<'_, T> {
2412    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
2413        self.content.read(buf)
2414    }
2415}
2416
2417impl<T: Offset> Offset for BMFFBox<'_, T> {
2418    fn offset(&self) -> u64 {
2419        self.content.get_ref().offset()
2420    }
2421}
2422
2423impl<T: Read> BMFFBox<'_, T> {
2424    fn bytes_left(&self) -> u64 {
2425        self.content.limit()
2426    }
2427
2428    const fn get_header(&self) -> &BoxHeader {
2429        &self.head
2430    }
2431
2432    fn box_iter(&mut self) -> BoxIter<'_, Self> {
2433        BoxIter::new(self)
2434    }
2435}
2436
2437impl<T> Drop for BMFFBox<'_, T> {
2438    fn drop(&mut self) {
2439        if self.content.limit() > 0 {
2440            let name: FourCC = From::from(self.head.name);
2441            debug!("Dropping {} bytes in '{}'", self.content.limit(), name);
2442        }
2443    }
2444}
2445
2446/// Read and parse a box header.
2447///
2448/// Call this first to determine the type of a particular mp4 box
2449/// and its length. Used internally for dispatching to specific
2450/// parsers for the internal content, or to get the length to
2451/// skip unknown or uninteresting boxes.
2452///
2453/// See ISO 14496-12:2015 § 4.2
2454fn read_box_header<T: ReadBytesExt>(src: &mut T) -> Result<BoxHeader> {
2455    let size32 = be_u32(src)?;
2456    let name = BoxType::from(be_u32(src)?);
2457    let size = match size32 {
2458        // valid only for top-level box and indicates it's the last box in the file.  usually mdat.
2459        0 => {
2460            // Size=0 means box extends to EOF (ISOBMFF spec allows this for last box)
2461            u64::MAX
2462        },
2463        1 => {
2464            let size64 = be_u64(src)?;
2465            if size64 < BoxHeader::MIN_LARGE_SIZE {
2466                return Err(Error::InvalidData("malformed wide size"));
2467            }
2468            size64
2469        },
2470        _ => {
2471            if u64::from(size32) < BoxHeader::MIN_SIZE {
2472                return Err(Error::InvalidData("malformed size"));
2473            }
2474            u64::from(size32)
2475        },
2476    };
2477    let mut offset = match size32 {
2478        1 => BoxHeader::MIN_LARGE_SIZE,
2479        _ => BoxHeader::MIN_SIZE,
2480    };
2481    let uuid = if name == BoxType::UuidBox {
2482        if size >= offset + 16 {
2483            let mut buffer = [0u8; 16];
2484            let count = src.read(&mut buffer)?;
2485            offset += count.to_u64();
2486            if count == 16 {
2487                Some(buffer)
2488            } else {
2489                debug!("malformed uuid (short read), skipping");
2490                None
2491            }
2492        } else {
2493            debug!("malformed uuid, skipping");
2494            None
2495        }
2496    } else {
2497        None
2498    };
2499    if offset > size {
2500        return Err(Error::InvalidData("box header offset exceeds size"));
2501    }
2502    Ok(BoxHeader { name, size, offset, uuid })
2503}
2504
2505/// Parse the extra header fields for a full box.
2506fn read_fullbox_extra<T: ReadBytesExt>(src: &mut T) -> Result<(u8, u32)> {
2507    let version = src.read_u8()?;
2508    let flags_a = src.read_u8()?;
2509    let flags_b = src.read_u8()?;
2510    let flags_c = src.read_u8()?;
2511    Ok((
2512        version,
2513        u32::from(flags_a) << 16 | u32::from(flags_b) << 8 | u32::from(flags_c),
2514    ))
2515}
2516
2517// Parse the extra fields for a full box whose flag fields must be zero.
2518fn read_fullbox_version_no_flags<T: ReadBytesExt>(src: &mut T, options: &ParseOptions) -> Result<u8> {
2519    let (version, flags) = read_fullbox_extra(src)?;
2520
2521    if flags != 0 && !options.lenient {
2522        return Err(Error::Unsupported("expected flags to be 0"));
2523    }
2524
2525    Ok(version)
2526}
2527
2528/// Skip over the entire contents of a box.
2529fn skip_box_content<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<()> {
2530    // Skip the contents of unknown chunks.
2531    let to_skip = {
2532        let header = src.get_header();
2533        debug!("{header:?} (skipped)");
2534        header
2535            .size
2536            .checked_sub(header.offset)
2537            .ok_or(Error::InvalidData("header offset > size"))?
2538    };
2539    assert_eq!(to_skip, src.bytes_left());
2540    skip(src, to_skip)
2541}
2542
2543/// Skip over the remain data of a box.
2544fn skip_box_remain<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<()> {
2545    let remain = {
2546        let header = src.get_header();
2547        let len = src.bytes_left();
2548        debug!("remain {len} (skipped) in {header:?}");
2549        len
2550    };
2551    skip(src, remain)
2552}
2553
2554struct ResourceTracker<'a> {
2555    config: &'a DecodeConfig,
2556    #[cfg(feature = "eager")]
2557    current_memory: u64,
2558    #[cfg(feature = "eager")]
2559    peak_memory: u64,
2560}
2561
2562impl<'a> ResourceTracker<'a> {
2563    fn new(config: &'a DecodeConfig) -> Self {
2564        Self {
2565            config,
2566            #[cfg(feature = "eager")]
2567            current_memory: 0,
2568            #[cfg(feature = "eager")]
2569            peak_memory: 0,
2570        }
2571    }
2572
2573    #[cfg(feature = "eager")]
2574    fn reserve(&mut self, bytes: u64) -> Result<()> {
2575        self.current_memory = self.current_memory.saturating_add(bytes);
2576        self.peak_memory = self.peak_memory.max(self.current_memory);
2577
2578        if let Some(limit) = self.config.peak_memory_limit
2579            && self.peak_memory > limit {
2580                return Err(Error::ResourceLimitExceeded("peak memory limit exceeded"));
2581            }
2582
2583        Ok(())
2584    }
2585
2586    #[cfg(feature = "eager")]
2587    fn release(&mut self, bytes: u64) {
2588        self.current_memory = self.current_memory.saturating_sub(bytes);
2589    }
2590
2591    #[cfg(feature = "eager")]
2592    fn validate_total_megapixels(&self, width: u32, height: u32) -> Result<()> {
2593        if let Some(limit) = self.config.total_megapixels_limit {
2594            let megapixels = (width as u64)
2595                .checked_mul(height as u64)
2596                .ok_or(Error::InvalidData("dimension overflow"))?
2597                / 1_000_000;
2598
2599            if megapixels > limit as u64 {
2600                return Err(Error::ResourceLimitExceeded("total megapixels limit exceeded"));
2601            }
2602        }
2603
2604        Ok(())
2605    }
2606
2607    fn validate_animation_frames(&self, count: u32) -> Result<()> {
2608        if let Some(limit) = self.config.max_animation_frames
2609            && count > limit {
2610                return Err(Error::ResourceLimitExceeded("animation frame count limit exceeded"));
2611            }
2612
2613        Ok(())
2614    }
2615
2616    fn validate_grid_tiles(&self, count: u32) -> Result<()> {
2617        if let Some(limit) = self.config.max_grid_tiles
2618            && count > limit {
2619                return Err(Error::ResourceLimitExceeded("grid tile count limit exceeded"));
2620            }
2621
2622        Ok(())
2623    }
2624}
2625
2626/// Read the contents of an AVIF file with resource limits and cancellation support
2627///
2628/// This is the primary parsing function with full control over resource limits
2629/// and cooperative cancellation via the [`Stop`] trait.
2630///
2631/// # Arguments
2632///
2633/// * `f` - Reader for the AVIF file
2634/// * `config` - Resource limits and parsing options
2635/// * `stop` - Cancellation token (use [`Unstoppable`] if not needed)
2636#[cfg(feature = "eager")]
2637#[deprecated(since = "1.5.0", note = "Use `AvifParser::from_reader_with_config()` instead")]
2638#[allow(deprecated)]
2639pub fn read_avif_with_config<T: Read>(
2640    f: &mut T,
2641    config: &DecodeConfig,
2642    stop: &dyn Stop,
2643) -> Result<AvifData> {
2644    let mut tracker = ResourceTracker::new(config);
2645    let mut f = OffsetReader::new(f);
2646
2647    let mut iter = BoxIter::new(&mut f);
2648
2649    // 'ftyp' box must occur first; see ISO 14496-12:2015 § 4.3.1
2650    let (major_brand, compatible_brands) = if let Some(mut b) = iter.next_box()? {
2651        if b.head.name == BoxType::FileTypeBox {
2652            let ftyp = read_ftyp(&mut b)?;
2653            // Accept both 'avif' (single-frame) and 'avis' (animated) brands
2654            if ftyp.major_brand != b"avif" && ftyp.major_brand != b"avis" {
2655                warn!("major_brand: {}", ftyp.major_brand);
2656                return Err(Error::InvalidData("ftyp must be 'avif' or 'avis'"));
2657            }
2658            let major = ftyp.major_brand.value;
2659            let compat = ftyp.compatible_brands.iter().map(|b| b.value).collect();
2660            (major, compat)
2661        } else {
2662            return Err(Error::InvalidData("'ftyp' box must occur first"));
2663        }
2664    } else {
2665        return Err(Error::InvalidData("'ftyp' box must occur first"));
2666    };
2667
2668    let mut meta = None;
2669    let mut mdats = TryVec::new();
2670    let mut animation_data: Option<ParsedAnimationData> = None;
2671
2672    let parse_opts = ParseOptions { lenient: config.lenient };
2673
2674    while let Some(mut b) = iter.next_box()? {
2675        stop.check()?;
2676
2677        match b.head.name {
2678            BoxType::MetadataBox => {
2679                if meta.is_some() {
2680                    return Err(Error::InvalidData("There should be zero or one meta boxes per ISO 14496-12:2015 § 8.11.1.1"));
2681                }
2682                meta = Some(read_avif_meta(&mut b, &parse_opts)?);
2683            },
2684            BoxType::MovieBox => {
2685                let tracks = read_moov(&mut b)?;
2686                if !tracks.is_empty() {
2687                    animation_data = Some(associate_tracks(tracks)?);
2688                }
2689            },
2690            BoxType::MediaDataBox => {
2691                if b.bytes_left() > 0 {
2692                    let offset = b.offset();
2693                    let size = b.bytes_left();
2694                    tracker.reserve(size)?;
2695                    let data = b.read_into_try_vec()?;
2696                    tracker.release(size);
2697                    mdats.push(MediaDataBox { offset, data })?;
2698                }
2699            },
2700            _ => skip_box_content(&mut b)?,
2701        }
2702
2703        check_parser_state(&b.head, &b.content)?;
2704    }
2705
2706    // meta is required for still images; pure sequences can have only moov+mdat
2707    if meta.is_none() && animation_data.is_none() {
2708        return Err(Error::InvalidData("missing meta"));
2709    }
2710    let Some(meta) = meta else {
2711        // Pure sequence: return minimal AvifData with no items
2712        return Ok(AvifData {
2713            ..Default::default()
2714        });
2715    };
2716
2717    // Check if primary item is a grid (tiled image)
2718    let is_grid = meta
2719        .item_infos
2720        .iter()
2721        .find(|x| x.item_id == meta.primary_item_id)
2722        .is_some_and(|info| {
2723            let is_g = info.item_type == b"grid";
2724            if is_g {
2725                log::debug!("Grid image detected: primary_item_id={}", meta.primary_item_id);
2726            }
2727            is_g
2728        });
2729
2730    // Extract grid configuration if this is a grid image
2731    let mut grid_config = if is_grid {
2732        meta.properties
2733            .iter()
2734            .find(|prop| {
2735                prop.item_id == meta.primary_item_id
2736                    && matches!(prop.property, ItemProperty::ImageGrid(_))
2737            })
2738            .and_then(|prop| match &prop.property {
2739                ItemProperty::ImageGrid(config) => {
2740                    log::debug!("Grid: found explicit ImageGrid property: {:?}", config);
2741                    Some(config.clone())
2742                },
2743                _ => None,
2744            })
2745    } else {
2746        None
2747    };
2748
2749    // Find tile item IDs if this is a grid
2750    let tile_item_ids: TryVec<u32> = if is_grid {
2751        // Collect tiles with their reference index
2752        let mut tiles_with_index: TryVec<(u32, u16)> = TryVec::new();
2753        for iref in meta.item_references.iter() {
2754            // Grid items reference tiles via "dimg" (derived image) type
2755            if iref.from_item_id == meta.primary_item_id && iref.item_type == b"dimg" {
2756                tiles_with_index.push((iref.to_item_id, iref.reference_index))?;
2757            }
2758        }
2759
2760        // Validate tile count
2761        tracker.validate_grid_tiles(tiles_with_index.len() as u32)?;
2762
2763        // Sort tiles by reference_index to get correct grid order
2764        tiles_with_index.sort_by_key(|&(_, idx)| idx);
2765
2766        // Extract just the IDs in sorted order
2767        let mut ids = TryVec::new();
2768        for (tile_id, _) in tiles_with_index.iter() {
2769            ids.push(*tile_id)?;
2770        }
2771
2772        // No logging here - too verbose for production
2773
2774        // If no ImageGrid property found, calculate grid layout from ispe dimensions
2775        if grid_config.is_none() && !ids.is_empty() {
2776            // Try to calculate grid dimensions from ispe properties
2777            let grid_dims = meta.properties.iter()
2778                .find(|p| p.item_id == meta.primary_item_id)
2779                .and_then(|p| match &p.property {
2780                    ItemProperty::ImageSpatialExtents(e) => Some(e),
2781                    _ => None,
2782                });
2783
2784            let tile_dims = ids.first().and_then(|&tile_id| {
2785                meta.properties.iter()
2786                    .find(|p| p.item_id == tile_id)
2787                    .and_then(|p| match &p.property {
2788                        ItemProperty::ImageSpatialExtents(e) => Some(e),
2789                        _ => None,
2790                    })
2791            });
2792
2793            if let (Some(grid), Some(tile)) = (grid_dims, tile_dims) {
2794                // Validate grid output dimensions
2795                tracker.validate_total_megapixels(grid.width, grid.height)?;
2796
2797                // Validate tile dimensions are non-zero (already validated in read_ispe, but defensive)
2798                if tile.width == 0 || tile.height == 0 {
2799                    log::warn!("Grid: tile has zero dimensions, using fallback");
2800                } else if grid.width % tile.width == 0 && grid.height % tile.height == 0 {
2801                    // Calculate grid layout: grid_dims ÷ tile_dims
2802                    let columns = grid.width / tile.width;
2803                    let rows = grid.height / tile.height;
2804
2805                    // Validate grid dimensions fit in u8 (max 255×255 grid)
2806                    if columns > 255 || rows > 255 {
2807                        log::warn!("Grid: calculated dimensions {}×{} exceed 255, using fallback", rows, columns);
2808                    } else {
2809                        log::debug!("Grid: calculated {}×{} layout from ispe dimensions", rows, columns);
2810                        grid_config = Some(GridConfig {
2811                            rows: rows as u8,
2812                            columns: columns as u8,
2813                            output_width: grid.width,
2814                            output_height: grid.height,
2815                        });
2816                    }
2817                } else {
2818                    log::warn!("Grid: dimension mismatch - grid {}×{} not evenly divisible by tile {}×{}, using fallback",
2819                              grid.width, grid.height, tile.width, tile.height);
2820                }
2821            }
2822
2823            // Fallback: if calculation failed or ispe not available, use N×1 inference
2824            if grid_config.is_none() {
2825                log::debug!("Grid: using fallback {}×1 layout inference", ids.len());
2826                grid_config = Some(GridConfig {
2827                    rows: ids.len() as u8,  // Changed: vertical stack
2828                    columns: 1,              // Changed: single column
2829                    output_width: 0,  // Will be calculated from tiles
2830                    output_height: 0, // Will be calculated from tiles
2831                });
2832            }
2833        }
2834
2835        ids
2836    } else {
2837        TryVec::new()
2838    };
2839
2840    let alpha_item_id = meta
2841        .item_references
2842        .iter()
2843        // Auxiliary image for the primary image
2844        .filter(|iref| {
2845            iref.to_item_id == meta.primary_item_id
2846                && iref.from_item_id != meta.primary_item_id
2847                && iref.item_type == b"auxl"
2848        })
2849        .map(|iref| iref.from_item_id)
2850        // which has the alpha property
2851        .find(|&item_id| {
2852            meta.properties.iter().any(|prop| {
2853                prop.item_id == item_id
2854                    && match &prop.property {
2855                        ItemProperty::AuxiliaryType(urn) => {
2856                            urn.type_subtype().0 == b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha"
2857                        }
2858                        _ => false,
2859                    }
2860            })
2861        });
2862
2863    // Extract properties for the primary item
2864    macro_rules! find_prop {
2865        ($variant:ident) => {
2866            meta.properties.iter().find_map(|p| {
2867                if p.item_id == meta.primary_item_id {
2868                    match &p.property {
2869                        ItemProperty::$variant(c) => Some(c.clone()),
2870                        _ => None,
2871                    }
2872                } else {
2873                    None
2874                }
2875            })
2876        };
2877    }
2878
2879    let av1_config = find_prop!(AV1Config);
2880    let color_info = find_prop!(ColorInformation);
2881    let rotation = find_prop!(Rotation);
2882    let mirror = find_prop!(Mirror);
2883    let clean_aperture = find_prop!(CleanAperture);
2884    let pixel_aspect_ratio = find_prop!(PixelAspectRatio);
2885    let content_light_level = find_prop!(ContentLightLevel);
2886    let mastering_display = find_prop!(MasteringDisplayColourVolume);
2887    let content_colour_volume = find_prop!(ContentColourVolume);
2888    let ambient_viewing = find_prop!(AmbientViewingEnvironment);
2889    let operating_point = find_prop!(OperatingPointSelector);
2890    let layer_selector = find_prop!(LayerSelector);
2891    let layered_image_indexing = find_prop!(AV1LayeredImageIndexing);
2892
2893    let mut context = AvifData {
2894        premultiplied_alpha: alpha_item_id.is_some_and(|alpha_item_id| {
2895            meta.item_references.iter().any(|iref| {
2896                iref.from_item_id == meta.primary_item_id
2897                    && iref.to_item_id == alpha_item_id
2898                    && iref.item_type == b"prem"
2899            })
2900        }),
2901        av1_config,
2902        color_info,
2903        rotation,
2904        mirror,
2905        clean_aperture,
2906        pixel_aspect_ratio,
2907        content_light_level,
2908        mastering_display,
2909        content_colour_volume,
2910        ambient_viewing,
2911        operating_point,
2912        layer_selector,
2913        layered_image_indexing,
2914        major_brand,
2915        compatible_brands,
2916        ..Default::default()
2917    };
2918
2919    // Helper to extract item data from either mdat or idat
2920    let mut extract_item_data = |loc: &ItemLocationBoxItem, buf: &mut TryVec<u8>| -> Result<()> {
2921        match loc.construction_method {
2922            ConstructionMethod::File => {
2923                for extent in loc.extents.iter() {
2924                    let mut found = false;
2925                    for mdat in mdats.iter_mut() {
2926                        if mdat.matches_extent(&extent.extent_range) {
2927                            buf.append(&mut mdat.data)?;
2928                            found = true;
2929                            break;
2930                        } else if mdat.contains_extent(&extent.extent_range) {
2931                            mdat.read_extent(&extent.extent_range, buf)?;
2932                            found = true;
2933                            break;
2934                        }
2935                    }
2936                    if !found {
2937                        return Err(Error::InvalidData("iloc contains an extent that is not in mdat"));
2938                    }
2939                }
2940                Ok(())
2941            },
2942            ConstructionMethod::Idat => {
2943                let idat_data = meta.idat.as_ref().ok_or(Error::InvalidData("idat box missing but construction_method is Idat"))?;
2944                for extent in loc.extents.iter() {
2945                    match &extent.extent_range {
2946                        ExtentRange::WithLength(range) => {
2947                            let start = usize::try_from(range.start).map_err(|_| Error::InvalidData("extent start too large"))?;
2948                            let end = usize::try_from(range.end).map_err(|_| Error::InvalidData("extent end too large"))?;
2949                            if end > idat_data.len() {
2950                                return Err(Error::InvalidData("extent exceeds idat size"));
2951                            }
2952                            buf.extend_from_slice(&idat_data[start..end]).map_err(|_| Error::OutOfMemory)?;
2953                        },
2954                        ExtentRange::ToEnd(range) => {
2955                            let start = usize::try_from(range.start).map_err(|_| Error::InvalidData("extent start too large"))?;
2956                            if start >= idat_data.len() {
2957                                return Err(Error::InvalidData("extent start exceeds idat size"));
2958                            }
2959                            buf.extend_from_slice(&idat_data[start..]).map_err(|_| Error::OutOfMemory)?;
2960                        },
2961                    }
2962                }
2963                Ok(())
2964            },
2965            ConstructionMethod::Item => {
2966                Err(Error::Unsupported("construction_method 'item' not supported"))
2967            },
2968        }
2969    };
2970
2971    // load data of relevant items
2972    // For grid images, we need to load tiles in the order specified by iref
2973    if is_grid {
2974        // Extract each tile in order
2975        for (idx, &tile_id) in tile_item_ids.iter().enumerate() {
2976            if idx % 16 == 0 {
2977                stop.check()?;
2978            }
2979
2980            let mut tile_data = TryVec::new();
2981
2982            if let Some(loc) = meta.iloc_items.iter().find(|loc| loc.item_id == tile_id) {
2983                extract_item_data(loc, &mut tile_data)?;
2984            } else {
2985                return Err(Error::InvalidData("grid tile not found in iloc"));
2986            }
2987
2988            context.grid_tiles.push(tile_data)?;
2989        }
2990
2991        // Set grid_config in context
2992        context.grid_config = grid_config;
2993    } else {
2994        // Standard single-frame AVIF: load primary_item and optional alpha_item
2995        for loc in meta.iloc_items.iter() {
2996            let item_data = if loc.item_id == meta.primary_item_id {
2997                &mut context.primary_item
2998            } else if Some(loc.item_id) == alpha_item_id {
2999                context.alpha_item.get_or_insert_with(TryVec::new)
3000            } else {
3001                continue;
3002            };
3003
3004            extract_item_data(loc, item_data)?;
3005        }
3006    }
3007
3008    // Extract EXIF and XMP items linked via cdsc references to the primary item
3009    for iref in meta.item_references.iter() {
3010        if iref.to_item_id != meta.primary_item_id || iref.item_type != b"cdsc" {
3011            continue;
3012        }
3013        let desc_item_id = iref.from_item_id;
3014        let Some(info) = meta.item_infos.iter().find(|i| i.item_id == desc_item_id) else {
3015            continue;
3016        };
3017        if info.item_type == b"Exif" {
3018            if let Some(loc) = meta.iloc_items.iter().find(|l| l.item_id == desc_item_id) {
3019                let mut raw = TryVec::new();
3020                extract_item_data(loc, &mut raw)?;
3021                // AVIF EXIF items start with a 4-byte big-endian offset to the TIFF header
3022                if raw.len() > 4 {
3023                    let offset = u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]) as usize;
3024                    let start = 4 + offset;
3025                    if start < raw.len() {
3026                        let mut exif = TryVec::new();
3027                        exif.extend_from_slice(&raw[start..])?;
3028                        context.exif = Some(exif);
3029                    }
3030                }
3031            }
3032        } else if info.item_type == b"mime"
3033            && let Some(loc) = meta.iloc_items.iter().find(|l| l.item_id == desc_item_id)
3034        {
3035            let mut xmp = TryVec::new();
3036            extract_item_data(loc, &mut xmp)?;
3037            context.xmp = Some(xmp);
3038        }
3039    }
3040
3041    // Extract gain map (tmap derived image item)
3042    if let Some(tmap_info) = meta.item_infos.iter().find(|info| info.item_type == b"tmap") {
3043        let tmap_id = tmap_info.item_id;
3044
3045        let mut inputs: TryVec<(u32, u16)> = TryVec::new();
3046        for iref in meta.item_references.iter() {
3047            if iref.from_item_id == tmap_id && iref.item_type == b"dimg" {
3048                inputs.push((iref.to_item_id, iref.reference_index))?;
3049            }
3050        }
3051        inputs.sort_by_key(|&(_, idx)| idx);
3052
3053        if inputs.len() >= 2 && inputs[0].0 == meta.primary_item_id {
3054            let gmap_item_id = inputs[1].0;
3055
3056            // Read tmap item payload
3057            if let Some(loc) = meta.iloc_items.iter().find(|l| l.item_id == tmap_id) {
3058                let mut tmap_data = TryVec::new();
3059                extract_item_data(loc, &mut tmap_data)?;
3060                if let Ok(metadata) = parse_tone_map_image(&tmap_data) {
3061                    context.gain_map_metadata = Some(metadata);
3062                }
3063            }
3064
3065            // Read gain map image data
3066            if let Some(loc) = meta.iloc_items.iter().find(|l| l.item_id == gmap_item_id) {
3067                let mut gmap_data = TryVec::new();
3068                extract_item_data(loc, &mut gmap_data)?;
3069                context.gain_map_item = Some(gmap_data);
3070            }
3071
3072            // Get alternate color info from tmap item's properties
3073            context.gain_map_color_info = meta.properties.iter().find_map(|p| {
3074                if p.item_id == tmap_id {
3075                    match &p.property {
3076                        ItemProperty::ColorInformation(c) => Some(c.clone()),
3077                        _ => None,
3078                    }
3079                } else {
3080                    None
3081                }
3082            });
3083        }
3084    }
3085
3086    // Extract animation frames if this is an animated AVIF
3087    if let Some(anim) = animation_data {
3088        let frame_count = anim.color_sample_table.sample_sizes.len() as u32;
3089        tracker.validate_animation_frames(frame_count)?;
3090
3091        log::debug!("Animation: extracting frames (media_timescale={})", anim.color_timescale);
3092        match extract_animation_frames(&anim.color_sample_table, anim.color_timescale, &mut mdats) {
3093            Ok(frames) => {
3094                if !frames.is_empty() {
3095                    log::debug!("Animation: extracted {} frames", frames.len());
3096                    context.animation = Some(AnimationConfig {
3097                        loop_count: anim.loop_count,
3098                        frames,
3099                    });
3100                }
3101            }
3102            Err(e) => {
3103                log::warn!("Animation: failed to extract frames: {}", e);
3104            }
3105        }
3106    }
3107
3108    Ok(context)
3109}
3110
3111/// Read the contents of an AVIF file with custom parsing options
3112///
3113/// Uses unlimited resource limits for backwards compatibility.
3114///
3115/// # Arguments
3116///
3117/// * `f` - Reader for the AVIF file
3118/// * `options` - Parsing options (e.g., lenient mode)
3119#[cfg(feature = "eager")]
3120#[deprecated(since = "1.5.0", note = "Use `AvifParser::from_reader_with_config()` with `DecodeConfig::lenient()` instead")]
3121#[allow(deprecated)]
3122pub fn read_avif_with_options<T: Read>(f: &mut T, options: &ParseOptions) -> Result<AvifData> {
3123    let config = DecodeConfig::unlimited().lenient(options.lenient);
3124    read_avif_with_config(f, &config, &Unstoppable)
3125}
3126
3127/// Read the contents of an AVIF file
3128///
3129/// Metadata is accumulated and returned in [`AvifData`] struct.
3130/// Uses strict validation and unlimited resource limits by default.
3131///
3132/// For resource limits, use [`read_avif_with_config`].
3133/// For lenient parsing, use [`read_avif_with_options`].
3134#[cfg(feature = "eager")]
3135#[deprecated(since = "1.5.0", note = "Use `AvifParser::from_reader()` instead")]
3136#[allow(deprecated)]
3137pub fn read_avif<T: Read>(f: &mut T) -> Result<AvifData> {
3138    read_avif_with_options(f, &ParseOptions::default())
3139}
3140
3141/// An entity group from a GroupsListBox (`grpl`).
3142///
3143/// See ISO 14496-12:2024 § 8.15.3.
3144#[allow(dead_code)] // Parsed for future altr group support
3145struct EntityGroup {
3146    group_type: FourCC,
3147    group_id: u32,
3148    entity_ids: TryVec<u32>,
3149}
3150
3151/// Parse a GroupsListBox (`grpl`).
3152///
3153/// Each child box is an EntityToGroupBox with a grouping type given by its box type.
3154/// See ISO 14496-12:2024 § 8.15.3.
3155fn read_grpl<T: Read + Offset>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<EntityGroup>> {
3156    let mut groups = TryVec::new();
3157    let mut iter = src.box_iter();
3158    while let Some(mut b) = iter.next_box()? {
3159        let group_type = FourCC::from(u32::from(b.head.name));
3160        // Read version and flags (not validated per spec flexibility)
3161        let _version = b.read_u8()?;
3162        let mut flags_buf = [0u8; 3];
3163        b.read_exact(&mut flags_buf)?;
3164
3165        let group_id = be_u32(&mut b)?;
3166        let num_entities = be_u32(&mut b)?;
3167
3168        let mut entity_ids = TryVec::new();
3169        for _ in 0..num_entities {
3170            entity_ids.push(be_u32(&mut b)?)?;
3171        }
3172
3173        groups.push(EntityGroup {
3174            group_type,
3175            group_id,
3176            entity_ids,
3177        })?;
3178
3179        skip_box_remain(&mut b)?;
3180        check_parser_state(&b.head, &b.content)?;
3181    }
3182    Ok(groups)
3183}
3184
3185/// Parse a ToneMapImage (`tmap`) item payload into gain map metadata.
3186///
3187/// See ISO 21496-1:2025 for the payload format.
3188fn parse_tone_map_image(data: &[u8]) -> Result<GainMapMetadata> {
3189    let mut cursor = std::io::Cursor::new(data);
3190
3191    // version (u8) — must be 0
3192    let version = cursor.read_u8()?;
3193    if version != 0 {
3194        return Err(Error::Unsupported("tmap version"));
3195    }
3196
3197    // minimum_version (u16 BE) — must be 0
3198    let minimum_version = be_u16(&mut cursor)?;
3199    if minimum_version > 0 {
3200        return Err(Error::Unsupported("tmap minimum version"));
3201    }
3202
3203    // writer_version (u16 BE) — informational, must be >= minimum_version
3204    let writer_version = be_u16(&mut cursor)?;
3205    if writer_version < minimum_version {
3206        return Err(Error::InvalidData("tmap writer_version < minimum_version"));
3207    }
3208
3209    // Flags byte: is_multichannel (bit 7), use_base_colour_space (bit 6), reserved (bits 0-5)
3210    let flags = cursor.read_u8()?;
3211    let is_multichannel = (flags & 0x80) != 0;
3212    let use_base_colour_space = (flags & 0x40) != 0;
3213
3214    // base_hdr_headroom and alternate_hdr_headroom
3215    let base_hdr_headroom_n = be_u32(&mut cursor)?;
3216    let base_hdr_headroom_d = be_u32(&mut cursor)?;
3217    let alternate_hdr_headroom_n = be_u32(&mut cursor)?;
3218    let alternate_hdr_headroom_d = be_u32(&mut cursor)?;
3219
3220    let channel_count = if is_multichannel { 3 } else { 1 };
3221    let mut channels = [GainMapChannel {
3222        gain_map_min_n: 0, gain_map_min_d: 0,
3223        gain_map_max_n: 0, gain_map_max_d: 0,
3224        gamma_n: 0, gamma_d: 0,
3225        base_offset_n: 0, base_offset_d: 0,
3226        alternate_offset_n: 0, alternate_offset_d: 0,
3227    }; 3];
3228
3229    for ch in channels.iter_mut().take(channel_count) {
3230        ch.gain_map_min_n = be_i32(&mut cursor)?;
3231        ch.gain_map_min_d = be_u32(&mut cursor)?;
3232        ch.gain_map_max_n = be_i32(&mut cursor)?;
3233        ch.gain_map_max_d = be_u32(&mut cursor)?;
3234        ch.gamma_n = be_u32(&mut cursor)?;
3235        ch.gamma_d = be_u32(&mut cursor)?;
3236        ch.base_offset_n = be_i32(&mut cursor)?;
3237        ch.base_offset_d = be_u32(&mut cursor)?;
3238        ch.alternate_offset_n = be_i32(&mut cursor)?;
3239        ch.alternate_offset_d = be_u32(&mut cursor)?;
3240    }
3241
3242    // Copy channel 0 to channels 1 and 2 if single-channel
3243    if !is_multichannel {
3244        channels[1] = channels[0];
3245        channels[2] = channels[0];
3246    }
3247
3248    Ok(GainMapMetadata {
3249        is_multichannel,
3250        use_base_colour_space,
3251        base_hdr_headroom_n,
3252        base_hdr_headroom_d,
3253        alternate_hdr_headroom_n,
3254        alternate_hdr_headroom_d,
3255        channels,
3256    })
3257}
3258
3259/// Parse a metadata box in the context of an AVIF
3260/// Currently requires the primary item to be an av01 item type and generates
3261/// an error otherwise.
3262/// See ISO 14496-12:2015 § 8.11.1
3263fn read_avif_meta<T: Read + Offset>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<AvifInternalMeta> {
3264    let version = read_fullbox_version_no_flags(src, options)?;
3265
3266    if version != 0 {
3267        return Err(Error::Unsupported("unsupported meta version"));
3268    }
3269
3270    let mut primary_item_id = None;
3271    let mut item_infos = None;
3272    let mut iloc_items = None;
3273    let mut item_references = TryVec::new();
3274    let mut properties = TryVec::new();
3275    let mut idat = None;
3276    let mut entity_groups = TryVec::new();
3277
3278    let mut iter = src.box_iter();
3279    while let Some(mut b) = iter.next_box()? {
3280        match b.head.name {
3281            BoxType::ItemInfoBox => {
3282                if item_infos.is_some() {
3283                    return Err(Error::InvalidData("There should be zero or one iinf boxes per ISO 14496-12:2015 § 8.11.6.1"));
3284                }
3285                item_infos = Some(read_iinf(&mut b, options)?);
3286            },
3287            BoxType::ItemLocationBox => {
3288                if iloc_items.is_some() {
3289                    return Err(Error::InvalidData("There should be zero or one iloc boxes per ISO 14496-12:2015 § 8.11.3.1"));
3290                }
3291                iloc_items = Some(read_iloc(&mut b, options)?);
3292            },
3293            BoxType::PrimaryItemBox => {
3294                if primary_item_id.is_some() {
3295                    return Err(Error::InvalidData("There should be zero or one iloc boxes per ISO 14496-12:2015 § 8.11.4.1"));
3296                }
3297                primary_item_id = Some(read_pitm(&mut b, options)?);
3298            },
3299            BoxType::ImageReferenceBox => {
3300                item_references.append(&mut read_iref(&mut b, options)?)?;
3301            },
3302            BoxType::ImagePropertiesBox => {
3303                properties = read_iprp(&mut b, options)?;
3304            },
3305            BoxType::ItemDataBox => {
3306                if idat.is_some() {
3307                    return Err(Error::InvalidData("There should be zero or one idat boxes"));
3308                }
3309                idat = Some(b.read_into_try_vec()?);
3310            },
3311            BoxType::GroupsListBox => {
3312                entity_groups.append(&mut read_grpl(&mut b)?)?;
3313            },
3314            BoxType::HandlerBox => {
3315                let hdlr = read_hdlr(&mut b)?;
3316                if hdlr.handler_type != b"pict" {
3317                    warn!("hdlr handler_type: {}", hdlr.handler_type);
3318                    return Err(Error::InvalidData("meta handler_type must be 'pict' for AVIF"));
3319                }
3320            },
3321            _ => skip_box_content(&mut b)?,
3322        }
3323
3324        check_parser_state(&b.head, &b.content)?;
3325    }
3326
3327    let primary_item_id = primary_item_id.ok_or(Error::InvalidData("Required pitm box not present in meta box"))?;
3328
3329    let item_infos = item_infos.ok_or(Error::InvalidData("iinf missing"))?;
3330
3331    if let Some(item_info) = item_infos.iter().find(|x| x.item_id == primary_item_id) {
3332        // Allow both "av01" (standard single-frame) and "grid" (tiled) types
3333        if item_info.item_type != b"av01" && item_info.item_type != b"grid" {
3334            warn!("primary_item_id type: {}", item_info.item_type);
3335            return Err(Error::InvalidData("primary_item_id type is not av01 or grid"));
3336        }
3337    } else {
3338        return Err(Error::InvalidData("primary_item_id not present in iinf box"));
3339    }
3340
3341    Ok(AvifInternalMeta {
3342        properties,
3343        item_references,
3344        primary_item_id,
3345        iloc_items: iloc_items.ok_or(Error::InvalidData("iloc missing"))?,
3346        item_infos,
3347        idat,
3348        entity_groups,
3349    })
3350}
3351
3352/// Parse a Handler Reference Box
3353/// See ISO 14496-12:2015 § 8.4.3
3354fn read_hdlr<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<HandlerBox> {
3355    let (_version, _flags) = read_fullbox_extra(src)?;
3356    // pre_defined (4 bytes)
3357    skip(src, 4)?;
3358    // handler_type (4 bytes)
3359    let handler_type = be_u32(src)?;
3360    // reserved (3 × 4 bytes) + name (variable) — skip the rest
3361    skip_box_remain(src)?;
3362    Ok(HandlerBox {
3363        handler_type: FourCC::from(handler_type),
3364    })
3365}
3366
3367/// Parse a Primary Item Box
3368/// See ISO 14496-12:2015 § 8.11.4
3369fn read_pitm<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<u32> {
3370    let version = read_fullbox_version_no_flags(src, options)?;
3371
3372    let item_id = match version {
3373        0 => be_u16(src)?.into(),
3374        1 => be_u32(src)?,
3375        _ => return Err(Error::Unsupported("unsupported pitm version")),
3376    };
3377
3378    Ok(item_id)
3379}
3380
3381/// Parse an Item Information Box
3382/// See ISO 14496-12:2015 § 8.11.6
3383fn read_iinf<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<TryVec<ItemInfoEntry>> {
3384    let version = read_fullbox_version_no_flags(src, options)?;
3385
3386    match version {
3387        0 | 1 => (),
3388        _ => return Err(Error::Unsupported("unsupported iinf version")),
3389    }
3390
3391    let entry_count = if version == 0 {
3392        be_u16(src)?.to_usize()
3393    } else {
3394        be_u32(src)?.to_usize()
3395    };
3396    let mut item_infos = TryVec::with_capacity(entry_count)?;
3397
3398    let mut iter = src.box_iter();
3399    while let Some(mut b) = iter.next_box()? {
3400        if b.head.name != BoxType::ItemInfoEntry {
3401            return Err(Error::InvalidData("iinf box should contain only infe boxes"));
3402        }
3403
3404        item_infos.push(read_infe(&mut b)?)?;
3405
3406        check_parser_state(&b.head, &b.content)?;
3407    }
3408
3409    Ok(item_infos)
3410}
3411
3412/// Parse an Item Info Entry
3413/// See ISO 14496-12:2015 § 8.11.6.2
3414fn read_infe<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ItemInfoEntry> {
3415    // According to the standard, it seems the flags field should be 0, but
3416    // at least one sample AVIF image has a nonzero value.
3417    let (version, _) = read_fullbox_extra(src)?;
3418
3419    // mif1 brand (see ISO 23008-12:2017 § 10.2.1) only requires v2 and 3
3420    let item_id = match version {
3421        2 => be_u16(src)?.into(),
3422        3 => be_u32(src)?,
3423        _ => return Err(Error::Unsupported("unsupported version in 'infe' box")),
3424    };
3425
3426    let item_protection_index = be_u16(src)?;
3427
3428    if item_protection_index != 0 {
3429        return Err(Error::Unsupported("protected items (infe.item_protection_index != 0) are not supported"));
3430    }
3431
3432    let item_type = FourCC::from(be_u32(src)?);
3433    debug!("infe item_id {item_id} item_type: {item_type}");
3434
3435    // There are some additional fields here, but they're not of interest to us
3436    skip_box_remain(src)?;
3437
3438    Ok(ItemInfoEntry { item_id, item_type })
3439}
3440
3441fn read_iref<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<TryVec<SingleItemTypeReferenceBox>> {
3442    let mut item_references = TryVec::new();
3443    let version = read_fullbox_version_no_flags(src, options)?;
3444    if version > 1 {
3445        return Err(Error::Unsupported("iref version"));
3446    }
3447
3448    let mut iter = src.box_iter();
3449    while let Some(mut b) = iter.next_box()? {
3450        let from_item_id = if version == 0 {
3451            be_u16(&mut b)?.into()
3452        } else {
3453            be_u32(&mut b)?
3454        };
3455        let reference_count = be_u16(&mut b)?;
3456        for reference_index in 0..reference_count {
3457            let to_item_id = if version == 0 {
3458                be_u16(&mut b)?.into()
3459            } else {
3460                be_u32(&mut b)?
3461            };
3462            if from_item_id == to_item_id {
3463                return Err(Error::InvalidData("from_item_id and to_item_id must be different"));
3464            }
3465            item_references.push(SingleItemTypeReferenceBox {
3466                item_type: b.head.name.into(),
3467                from_item_id,
3468                to_item_id,
3469                reference_index,
3470            })?;
3471        }
3472        check_parser_state(&b.head, &b.content)?;
3473    }
3474    Ok(item_references)
3475}
3476
3477/// Properties that MUST be marked essential when associated with an item.
3478/// See AVIF § 2.3.2.1.1 (a1op), HEIF § 6.5.11.1 (lsel), MIAF § 7.3.9 (clap, irot, imir).
3479const MUST_BE_ESSENTIAL: &[&[u8; 4]] = &[b"a1op", b"lsel", b"clap", b"irot", b"imir"];
3480
3481/// Properties that MUST NOT be marked essential when associated with an item.
3482/// See AVIF § 2.3.2.3.2 (a1lx).
3483const MUST_NOT_BE_ESSENTIAL: &[&[u8; 4]] = &[b"a1lx"];
3484
3485fn read_iprp<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<TryVec<AssociatedProperty>> {
3486    let mut iter = src.box_iter();
3487    let mut properties = TryVec::new();
3488    let mut associations = TryVec::new();
3489
3490    while let Some(mut b) = iter.next_box()? {
3491        match b.head.name {
3492            BoxType::ItemPropertyContainerBox => {
3493                properties = read_ipco(&mut b, options)?;
3494            },
3495            BoxType::ItemPropertyAssociationBox => {
3496                associations = read_ipma(&mut b)?;
3497            },
3498            _ => return Err(Error::InvalidData("unexpected ipco child")),
3499        }
3500    }
3501
3502    let mut associated = TryVec::new();
3503    for a in associations {
3504        let index = match a.property_index {
3505            0 => {
3506                // property_index 0 means no association; essential must also be 0
3507                if a.essential {
3508                    return Err(Error::InvalidData(
3509                        "ipma property_index 0 must not be marked essential",
3510                    ));
3511                }
3512                continue;
3513            }
3514            x => x as usize - 1,
3515        };
3516
3517        let Some(entry) = properties.get(index) else {
3518            continue;
3519        };
3520
3521        let is_supported = entry.property != ItemProperty::Unsupported;
3522        let fourcc_bytes = &entry.fourcc.value;
3523
3524        if is_supported {
3525            // Validate essential flag for known property types
3526            if a.essential && MUST_NOT_BE_ESSENTIAL.contains(&fourcc_bytes) {
3527                warn!("item {} has {} marked essential (spec forbids it)", a.item_id, entry.fourcc);
3528                if !options.lenient {
3529                    return Err(Error::InvalidData(
3530                        "property must not be marked essential",
3531                    ));
3532                }
3533            }
3534            if !a.essential && MUST_BE_ESSENTIAL.contains(&fourcc_bytes) {
3535                warn!("item {} has {} not marked essential (spec requires it)", a.item_id, entry.fourcc);
3536                if !options.lenient {
3537                    return Err(Error::InvalidData(
3538                        "property must be marked essential",
3539                    ));
3540                }
3541            }
3542
3543            associated.push(AssociatedProperty {
3544                item_id: a.item_id,
3545                property: entry.property.try_clone()?,
3546            })?;
3547        } else if a.essential {
3548            // Unknown property marked essential — this item cannot be correctly processed
3549            warn!(
3550                "item {} has unsupported property {} marked essential; item will be unusable",
3551                a.item_id, entry.fourcc
3552            );
3553            if !options.lenient {
3554                return Err(Error::Unsupported(
3555                    "unsupported property marked as essential",
3556                ));
3557            }
3558        }
3559        // Unknown non-essential properties are silently skipped (they're optional)
3560    }
3561    Ok(associated)
3562}
3563
3564/// Image spatial extents (dimensions)
3565#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3566pub(crate) struct ImageSpatialExtents {
3567    pub(crate) width: u32,
3568    pub(crate) height: u32,
3569}
3570
3571#[derive(Debug, PartialEq)]
3572pub(crate) enum ItemProperty {
3573    Channels(ArrayVec<u8, 16>),
3574    AuxiliaryType(AuxiliaryTypeProperty),
3575    ImageSpatialExtents(ImageSpatialExtents),
3576    ImageGrid(GridConfig),
3577    AV1Config(AV1Config),
3578    ColorInformation(ColorInformation),
3579    Rotation(ImageRotation),
3580    Mirror(ImageMirror),
3581    CleanAperture(CleanAperture),
3582    PixelAspectRatio(PixelAspectRatio),
3583    ContentLightLevel(ContentLightLevel),
3584    MasteringDisplayColourVolume(MasteringDisplayColourVolume),
3585    ContentColourVolume(ContentColourVolume),
3586    AmbientViewingEnvironment(AmbientViewingEnvironment),
3587    OperatingPointSelector(OperatingPointSelector),
3588    LayerSelector(LayerSelector),
3589    AV1LayeredImageIndexing(AV1LayeredImageIndexing),
3590    Unsupported,
3591}
3592
3593impl TryClone for ItemProperty {
3594    fn try_clone(&self) -> Result<Self, TryReserveError> {
3595        Ok(match self {
3596            Self::Channels(val) => Self::Channels(val.clone()),
3597            Self::AuxiliaryType(val) => Self::AuxiliaryType(val.try_clone()?),
3598            Self::ImageSpatialExtents(val) => Self::ImageSpatialExtents(*val),
3599            Self::ImageGrid(val) => Self::ImageGrid(val.clone()),
3600            Self::AV1Config(val) => Self::AV1Config(val.clone()),
3601            Self::ColorInformation(val) => Self::ColorInformation(val.clone()),
3602            Self::Rotation(val) => Self::Rotation(*val),
3603            Self::Mirror(val) => Self::Mirror(*val),
3604            Self::CleanAperture(val) => Self::CleanAperture(*val),
3605            Self::PixelAspectRatio(val) => Self::PixelAspectRatio(*val),
3606            Self::ContentLightLevel(val) => Self::ContentLightLevel(*val),
3607            Self::MasteringDisplayColourVolume(val) => Self::MasteringDisplayColourVolume(*val),
3608            Self::ContentColourVolume(val) => Self::ContentColourVolume(*val),
3609            Self::AmbientViewingEnvironment(val) => Self::AmbientViewingEnvironment(*val),
3610            Self::OperatingPointSelector(val) => Self::OperatingPointSelector(*val),
3611            Self::LayerSelector(val) => Self::LayerSelector(*val),
3612            Self::AV1LayeredImageIndexing(val) => Self::AV1LayeredImageIndexing(*val),
3613            Self::Unsupported => Self::Unsupported,
3614        })
3615    }
3616}
3617
3618struct Association {
3619    item_id: u32,
3620    essential: bool,
3621    property_index: u16,
3622}
3623
3624pub(crate) struct AssociatedProperty {
3625    pub item_id: u32,
3626    pub property: ItemProperty,
3627}
3628
3629fn read_ipma<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<Association>> {
3630    let (version, flags) = read_fullbox_extra(src)?;
3631
3632    let mut associations = TryVec::new();
3633
3634    let entry_count = be_u32(src)?;
3635    for _ in 0..entry_count {
3636        let item_id = if version == 0 {
3637            be_u16(src)?.into()
3638        } else {
3639            be_u32(src)?
3640        };
3641        let association_count = src.read_u8()?;
3642        for _ in 0..association_count {
3643            let num_association_bytes = if flags & 1 == 1 { 2 } else { 1 };
3644            let association = &mut [0; 2][..num_association_bytes];
3645            src.read_exact(association)?;
3646            let mut association = BitReader::new(association);
3647            let essential = association.read_bool()?;
3648            let property_index = association.read_u16(association.remaining().try_into()?)?;
3649            associations.push(Association {
3650                item_id,
3651                essential,
3652                property_index,
3653            })?;
3654        }
3655    }
3656    Ok(associations)
3657}
3658
3659/// A parsed property with its box FourCC, for essential flag validation.
3660struct IndexedProperty {
3661    fourcc: FourCC,
3662    property: ItemProperty,
3663}
3664
3665fn read_ipco<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<TryVec<IndexedProperty>> {
3666    let mut properties = TryVec::new();
3667
3668    let mut iter = src.box_iter();
3669    while let Some(mut b) = iter.next_box()? {
3670        let fourcc: FourCC = b.head.name.into();
3671        // Must push for every property to have correct index for them
3672        let prop = match b.head.name {
3673            BoxType::PixelInformationBox => ItemProperty::Channels(read_pixi(&mut b, options)?),
3674            BoxType::AuxiliaryTypeProperty => ItemProperty::AuxiliaryType(read_auxc(&mut b, options)?),
3675            BoxType::ImageSpatialExtentsBox => ItemProperty::ImageSpatialExtents(read_ispe(&mut b, options)?),
3676            BoxType::ImageGridBox => ItemProperty::ImageGrid(read_grid(&mut b, options)?),
3677            BoxType::AV1CodecConfigurationBox => ItemProperty::AV1Config(read_av1c(&mut b)?),
3678            BoxType::ColorInformationBox => {
3679                match read_colr(&mut b) {
3680                    Ok(colr) => ItemProperty::ColorInformation(colr),
3681                    Err(_) => ItemProperty::Unsupported,
3682                }
3683            },
3684            BoxType::ImageRotationBox => ItemProperty::Rotation(read_irot(&mut b)?),
3685            BoxType::ImageMirrorBox => ItemProperty::Mirror(read_imir(&mut b)?),
3686            BoxType::CleanApertureBox => ItemProperty::CleanAperture(read_clap(&mut b)?),
3687            BoxType::PixelAspectRatioBox => ItemProperty::PixelAspectRatio(read_pasp(&mut b)?),
3688            BoxType::ContentLightLevelBox => ItemProperty::ContentLightLevel(read_clli(&mut b)?),
3689            BoxType::MasteringDisplayColourVolumeBox => ItemProperty::MasteringDisplayColourVolume(read_mdcv(&mut b)?),
3690            BoxType::ContentColourVolumeBox => ItemProperty::ContentColourVolume(read_cclv(&mut b)?),
3691            BoxType::AmbientViewingEnvironmentBox => ItemProperty::AmbientViewingEnvironment(read_amve(&mut b)?),
3692            BoxType::OperatingPointSelectorBox => ItemProperty::OperatingPointSelector(read_a1op(&mut b)?),
3693            BoxType::LayerSelectorBox => ItemProperty::LayerSelector(read_lsel(&mut b)?),
3694            BoxType::AV1LayeredImageIndexingBox => ItemProperty::AV1LayeredImageIndexing(read_a1lx(&mut b)?),
3695            _ => {
3696                skip_box_remain(&mut b)?;
3697                ItemProperty::Unsupported
3698            },
3699        };
3700        properties.push(IndexedProperty { fourcc, property: prop })?;
3701    }
3702    Ok(properties)
3703}
3704
3705fn read_pixi<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<ArrayVec<u8, 16>> {
3706    let version = read_fullbox_version_no_flags(src, options)?;
3707    if version != 0 {
3708        return Err(Error::Unsupported("pixi version"));
3709    }
3710
3711    let num_channels = usize::from(src.read_u8()?);
3712    let mut channels = ArrayVec::new();
3713    channels.extend((0..num_channels.min(channels.capacity())).map(|_| 0));
3714    debug_assert_eq!(num_channels, channels.len());
3715    src.read_exact(&mut channels).map_err(|_| Error::InvalidData("invalid num_channels"))?;
3716
3717    // In lenient mode, skip any extra bytes (e.g., extended_pixi.avif has 6 extra bytes)
3718    if options.lenient && src.bytes_left() > 0 {
3719        skip(src, src.bytes_left())?;
3720    }
3721
3722    check_parser_state(&src.head, &src.content)?;
3723    Ok(channels)
3724}
3725
3726#[derive(Debug, PartialEq)]
3727struct AuxiliaryTypeProperty {
3728    aux_data: TryString,
3729}
3730
3731impl AuxiliaryTypeProperty {
3732    #[must_use]
3733    fn type_subtype(&self) -> (&[u8], &[u8]) {
3734        let split = self.aux_data.iter().position(|&b| b == b'\0')
3735            .map(|pos| self.aux_data.split_at(pos));
3736        if let Some((aux_type, rest)) = split {
3737            (aux_type, &rest[1..])
3738        } else {
3739            (&self.aux_data, &[])
3740        }
3741    }
3742}
3743
3744impl TryClone for AuxiliaryTypeProperty {
3745    fn try_clone(&self) -> Result<Self, TryReserveError> {
3746        Ok(Self {
3747            aux_data: self.aux_data.try_clone()?,
3748        })
3749    }
3750}
3751
3752fn read_auxc<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<AuxiliaryTypeProperty> {
3753    let version = read_fullbox_version_no_flags(src, options)?;
3754    if version != 0 {
3755        return Err(Error::Unsupported("auxC version"));
3756    }
3757
3758    let aux_data = src.read_into_try_vec()?;
3759
3760    Ok(AuxiliaryTypeProperty { aux_data })
3761}
3762
3763/// Parse an AV1 Codec Configuration property box
3764/// See AV1-ISOBMFF § 2.3
3765fn read_av1c<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<AV1Config> {
3766    // av1C is NOT a FullBox — it has no version/flags
3767    let byte0 = src.read_u8()?;
3768    let marker = byte0 >> 7;
3769    let version = byte0 & 0x7F;
3770
3771    if marker != 1 {
3772        return Err(Error::InvalidData("av1C marker must be 1"));
3773    }
3774    if version != 1 {
3775        return Err(Error::Unsupported("av1C version must be 1"));
3776    }
3777
3778    let byte1 = src.read_u8()?;
3779    let profile = byte1 >> 5;
3780    let level = byte1 & 0x1F;
3781
3782    let byte2 = src.read_u8()?;
3783    let tier = byte2 >> 7;
3784    let high_bitdepth = (byte2 >> 6) & 1;
3785    let twelve_bit = (byte2 >> 5) & 1;
3786    let monochrome = (byte2 >> 4) & 1 != 0;
3787    let chroma_subsampling_x = (byte2 >> 3) & 1;
3788    let chroma_subsampling_y = (byte2 >> 2) & 1;
3789    let chroma_sample_position = byte2 & 0x03;
3790
3791    let byte3 = src.read_u8()?;
3792    // byte3: 3 bits reserved, 1 bit initial_presentation_delay_present, 4 bits delay/reserved
3793    // Not needed for image decoding.
3794    let _ = byte3;
3795
3796    let bit_depth = if high_bitdepth != 0 {
3797        if twelve_bit != 0 { 12 } else { 10 }
3798    } else {
3799        8
3800    };
3801
3802    // Skip any configOBUs (remainder of box)
3803    skip_box_remain(src)?;
3804
3805    Ok(AV1Config {
3806        profile,
3807        level,
3808        tier,
3809        bit_depth,
3810        monochrome,
3811        chroma_subsampling_x,
3812        chroma_subsampling_y,
3813        chroma_sample_position,
3814    })
3815}
3816
3817/// Parse a Colour Information property box
3818/// See ISOBMFF § 12.1.5
3819fn read_colr<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ColorInformation> {
3820    // colr is NOT a FullBox — no version/flags
3821    let colour_type = be_u32(src)?;
3822
3823    match &colour_type.to_be_bytes() {
3824        b"nclx" => {
3825            let color_primaries = be_u16(src)?;
3826            let transfer_characteristics = be_u16(src)?;
3827            let matrix_coefficients = be_u16(src)?;
3828            let full_range_byte = src.read_u8()?;
3829            let full_range = (full_range_byte >> 7) != 0;
3830            // Skip any remaining bytes
3831            skip_box_remain(src)?;
3832            Ok(ColorInformation::Nclx {
3833                color_primaries,
3834                transfer_characteristics,
3835                matrix_coefficients,
3836                full_range,
3837            })
3838        }
3839        b"rICC" | b"prof" => {
3840            let icc_data = src.read_into_try_vec()?;
3841            Ok(ColorInformation::IccProfile(icc_data.to_vec()))
3842        }
3843        _ => {
3844            skip_box_remain(src)?;
3845            Err(Error::Unsupported("unsupported colr colour_type"))
3846        }
3847    }
3848}
3849
3850/// Parse an Image Rotation property box.
3851/// See ISOBMFF § 12.1.4. NOT a FullBox.
3852fn read_irot<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ImageRotation> {
3853    let byte = src.read_u8()?;
3854    let angle_code = byte & 0x03;
3855    let angle = match angle_code {
3856        0 => 0,
3857        1 => 90,
3858        2 => 180,
3859        _ => 270, // angle_code & 0x03 can only be 0..=3
3860    };
3861    skip_box_remain(src)?;
3862    Ok(ImageRotation { angle })
3863}
3864
3865/// Parse an Image Mirror property box.
3866/// See ISOBMFF § 12.1.4. NOT a FullBox.
3867fn read_imir<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ImageMirror> {
3868    let byte = src.read_u8()?;
3869    let axis = byte & 0x01;
3870    skip_box_remain(src)?;
3871    Ok(ImageMirror { axis })
3872}
3873
3874/// Parse a Clean Aperture property box.
3875/// See ISOBMFF § 12.1.4. NOT a FullBox.
3876fn read_clap<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<CleanAperture> {
3877    let width_n = be_u32(src)?;
3878    let width_d = be_u32(src)?;
3879    let height_n = be_u32(src)?;
3880    let height_d = be_u32(src)?;
3881    let horiz_off_n = be_i32(src)?;
3882    let horiz_off_d = be_u32(src)?;
3883    let vert_off_n = be_i32(src)?;
3884    let vert_off_d = be_u32(src)?;
3885    // Validate denominators are non-zero
3886    if width_d == 0 || height_d == 0 || horiz_off_d == 0 || vert_off_d == 0 {
3887        return Err(Error::InvalidData("clap denominator cannot be zero"));
3888    }
3889    skip_box_remain(src)?;
3890    Ok(CleanAperture {
3891        width_n, width_d,
3892        height_n, height_d,
3893        horiz_off_n, horiz_off_d,
3894        vert_off_n, vert_off_d,
3895    })
3896}
3897
3898/// Parse a Pixel Aspect Ratio property box.
3899/// See ISOBMFF § 12.1.4. NOT a FullBox.
3900fn read_pasp<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<PixelAspectRatio> {
3901    let h_spacing = be_u32(src)?;
3902    let v_spacing = be_u32(src)?;
3903    skip_box_remain(src)?;
3904    Ok(PixelAspectRatio { h_spacing, v_spacing })
3905}
3906
3907/// Parse a Content Light Level Info property box.
3908/// See ISOBMFF § 12.1.5 / ITU-T H.274. NOT a FullBox.
3909fn read_clli<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ContentLightLevel> {
3910    let max_content_light_level = be_u16(src)?;
3911    let max_pic_average_light_level = be_u16(src)?;
3912    skip_box_remain(src)?;
3913    Ok(ContentLightLevel {
3914        max_content_light_level,
3915        max_pic_average_light_level,
3916    })
3917}
3918
3919/// Parse a Mastering Display Colour Volume property box.
3920/// See ISOBMFF § 12.1.5 / SMPTE ST 2086. NOT a FullBox.
3921fn read_mdcv<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<MasteringDisplayColourVolume> {
3922    // 3 primaries, each (x, y) as u16
3923    let primaries = [
3924        (be_u16(src)?, be_u16(src)?),
3925        (be_u16(src)?, be_u16(src)?),
3926        (be_u16(src)?, be_u16(src)?),
3927    ];
3928    let white_point = (be_u16(src)?, be_u16(src)?);
3929    let max_luminance = be_u32(src)?;
3930    let min_luminance = be_u32(src)?;
3931    skip_box_remain(src)?;
3932    Ok(MasteringDisplayColourVolume {
3933        primaries,
3934        white_point,
3935        max_luminance,
3936        min_luminance,
3937    })
3938}
3939
3940/// Parse a Content Colour Volume property box.
3941/// See ISOBMFF § 12.1.5 / H.265 D.2.40. NOT a FullBox.
3942fn read_cclv<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<ContentColourVolume> {
3943    let flags = src.read_u8()?;
3944    let primaries_present = flags & 0x20 != 0;
3945    let min_lum_present = flags & 0x10 != 0;
3946    let max_lum_present = flags & 0x08 != 0;
3947    let avg_lum_present = flags & 0x04 != 0;
3948
3949    let primaries = if primaries_present {
3950        Some([
3951            (be_i32(src)?, be_i32(src)?),
3952            (be_i32(src)?, be_i32(src)?),
3953            (be_i32(src)?, be_i32(src)?),
3954        ])
3955    } else {
3956        None
3957    };
3958
3959    let min_luminance = if min_lum_present { Some(be_u32(src)?) } else { None };
3960    let max_luminance = if max_lum_present { Some(be_u32(src)?) } else { None };
3961    let avg_luminance = if avg_lum_present { Some(be_u32(src)?) } else { None };
3962
3963    skip_box_remain(src)?;
3964    Ok(ContentColourVolume {
3965        primaries,
3966        min_luminance,
3967        max_luminance,
3968        avg_luminance,
3969    })
3970}
3971
3972/// Parse an Ambient Viewing Environment property box.
3973/// See ISOBMFF § 12.1.5 / H.265 D.2.39. NOT a FullBox.
3974fn read_amve<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<AmbientViewingEnvironment> {
3975    let ambient_illuminance = be_u32(src)?;
3976    let ambient_light_x = be_u16(src)?;
3977    let ambient_light_y = be_u16(src)?;
3978    skip_box_remain(src)?;
3979    Ok(AmbientViewingEnvironment {
3980        ambient_illuminance,
3981        ambient_light_x,
3982        ambient_light_y,
3983    })
3984}
3985
3986/// Parse an Operating Point Selector property box.
3987/// See AVIF § 4.3.4. NOT a FullBox.
3988fn read_a1op<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<OperatingPointSelector> {
3989    let op_index = src.read_u8()?;
3990    if op_index > 31 {
3991        return Err(Error::InvalidData("a1op op_index must be 0..31"));
3992    }
3993    skip_box_remain(src)?;
3994    Ok(OperatingPointSelector { op_index })
3995}
3996
3997/// Parse a Layer Selector property box.
3998/// See HEIF (ISO 23008-12). NOT a FullBox.
3999fn read_lsel<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<LayerSelector> {
4000    let layer_id = be_u16(src)?;
4001    skip_box_remain(src)?;
4002    Ok(LayerSelector { layer_id })
4003}
4004
4005/// Parse an AV1 Layered Image Indexing property box.
4006/// See AVIF § 4.3.6. NOT a FullBox.
4007fn read_a1lx<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<AV1LayeredImageIndexing> {
4008    let flags = src.read_u8()?;
4009    let large_size = flags & 0x01 != 0;
4010    let layer_sizes = if large_size {
4011        [be_u32(src)?, be_u32(src)?, be_u32(src)?]
4012    } else {
4013        [u32::from(be_u16(src)?), u32::from(be_u16(src)?), u32::from(be_u16(src)?)]
4014    };
4015    skip_box_remain(src)?;
4016    Ok(AV1LayeredImageIndexing { layer_sizes })
4017}
4018
4019/// Parse an Image Spatial Extents property box
4020/// See ISO/IEC 23008-12:2017 § 6.5.3
4021fn read_ispe<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<ImageSpatialExtents> {
4022    let _version = read_fullbox_version_no_flags(src, options)?;
4023    // Version is always 0 for ispe
4024
4025    let width = be_u32(src)?;
4026    let height = be_u32(src)?;
4027
4028    // Validate dimensions are non-zero (0×0 images are invalid)
4029    if width == 0 || height == 0 {
4030        return Err(Error::InvalidData("ispe dimensions cannot be zero"));
4031    }
4032
4033    Ok(ImageSpatialExtents { width, height })
4034}
4035
4036/// Parse a Movie Header box (mvhd)
4037/// See ISO/IEC 14496-12:2015 § 8.2.2
4038fn read_mvhd<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<MovieHeader> {
4039    let version = src.read_u8()?;
4040    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
4041
4042    let (timescale, duration) = if version == 1 {
4043        let _creation_time = be_u64(src)?;
4044        let _modification_time = be_u64(src)?;
4045        let timescale = be_u32(src)?;
4046        let duration = be_u64(src)?;
4047        (timescale, duration)
4048    } else {
4049        let _creation_time = be_u32(src)?;
4050        let _modification_time = be_u32(src)?;
4051        let timescale = be_u32(src)?;
4052        let duration = be_u32(src)?;
4053        (timescale, duration as u64)
4054    };
4055
4056    // Skip rest of mvhd (rate, volume, matrix, etc.)
4057    skip_box_remain(src)?;
4058
4059    Ok(MovieHeader { _timescale: timescale, _duration: duration })
4060}
4061
4062/// Parse a Media Header box (mdhd)
4063/// See ISO/IEC 14496-12:2015 § 8.4.2
4064fn read_mdhd<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<MediaHeader> {
4065    let version = src.read_u8()?;
4066    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
4067
4068    let (timescale, duration) = if version == 1 {
4069        let _creation_time = be_u64(src)?;
4070        let _modification_time = be_u64(src)?;
4071        let timescale = be_u32(src)?;
4072        let duration = be_u64(src)?;
4073        (timescale, duration)
4074    } else {
4075        let _creation_time = be_u32(src)?;
4076        let _modification_time = be_u32(src)?;
4077        let timescale = be_u32(src)?;
4078        let duration = be_u32(src)?;
4079        (timescale, duration as u64)
4080    };
4081
4082    // Skip language and pre_defined
4083    skip_box_remain(src)?;
4084
4085    Ok(MediaHeader { timescale, _duration: duration })
4086}
4087
4088/// Parse Time To Sample box (stts)
4089/// See ISO/IEC 14496-12:2015 § 8.6.1.2
4090fn read_stts<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<TimeToSampleEntry>> {
4091    let _version = src.read_u8()?;
4092    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
4093    let entry_count = be_u32(src)?;
4094
4095    let mut entries = TryVec::new();
4096    for _ in 0..entry_count {
4097        entries.push(TimeToSampleEntry {
4098            sample_count: be_u32(src)?,
4099            sample_delta: be_u32(src)?,
4100        })?;
4101    }
4102
4103    Ok(entries)
4104}
4105
4106/// Parse Sample To Chunk box (stsc)
4107/// See ISO/IEC 14496-12:2015 § 8.7.4
4108fn read_stsc<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<SampleToChunkEntry>> {
4109    let _version = src.read_u8()?;
4110    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
4111    let entry_count = be_u32(src)?;
4112
4113    let mut entries = TryVec::new();
4114    for _ in 0..entry_count {
4115        entries.push(SampleToChunkEntry {
4116            first_chunk: be_u32(src)?,
4117            samples_per_chunk: be_u32(src)?,
4118            _sample_description_index: be_u32(src)?,
4119        })?;
4120    }
4121
4122    Ok(entries)
4123}
4124
4125/// Parse Sample Size box (stsz)
4126/// See ISO/IEC 14496-12:2015 § 8.7.3
4127fn read_stsz<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<u32>> {
4128    let _version = src.read_u8()?;
4129    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
4130    let sample_size = be_u32(src)?;
4131    let sample_count = be_u32(src)?;
4132
4133    let mut sizes = TryVec::new();
4134    if sample_size == 0 {
4135        // Variable sizes - read each one
4136        for _ in 0..sample_count {
4137            sizes.push(be_u32(src)?)?;
4138        }
4139    } else {
4140        // Constant size for all samples
4141        for _ in 0..sample_count {
4142            sizes.push(sample_size)?;
4143        }
4144    }
4145
4146    Ok(sizes)
4147}
4148
4149/// Parse Chunk Offset box (stco or co64)
4150/// See ISO/IEC 14496-12:2015 § 8.7.5
4151fn read_chunk_offsets<T: Read>(src: &mut BMFFBox<'_, T>, is_64bit: bool) -> Result<TryVec<u64>> {
4152    let _version = src.read_u8()?;
4153    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
4154    let entry_count = be_u32(src)?;
4155
4156    let mut offsets = TryVec::new();
4157    for _ in 0..entry_count {
4158        let offset = if is_64bit {
4159            be_u64(src)?
4160        } else {
4161            be_u32(src)? as u64
4162        };
4163        offsets.push(offset)?;
4164    }
4165
4166    Ok(offsets)
4167}
4168
4169/// Parse Sample Description box (stsd) to extract codec config from VisualSampleEntry.
4170/// See ISO/IEC 14496-12:2015 § 8.5.2
4171///
4172/// For AVIF sequences, the VisualSampleEntry is `av01` which contains sub-boxes
4173/// like `av1C` (codec config) and `colr` (color info), similar to ipco properties.
4174fn read_stsd<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TrackCodecConfig> {
4175    let _version = src.read_u8()?;
4176    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
4177    let entry_count = be_u32(src)?;
4178
4179    let mut config = TrackCodecConfig::default();
4180
4181    // Parse first entry only (AVIF tracks have one sample description)
4182    let mut iter = src.box_iter();
4183    for _ in 0..entry_count {
4184        let Some(mut entry_box) = iter.next_box()? else {
4185            break;
4186        };
4187
4188        // Check if this is an av01 VisualSampleEntry
4189        if entry_box.head.name != BoxType::AV1SampleEntry {
4190            skip_box_remain(&mut entry_box)?;
4191            continue;
4192        }
4193
4194        // Skip VisualSampleEntry fixed fields (78 bytes total):
4195        //   reserved[6] + data_ref_index[2] + pre_defined[2] + reserved[2] +
4196        //   pre_defined[12] + width[2] + height[2] + horiz_res[4] + vert_res[4] +
4197        //   reserved[4] + frame_count[2] + compressorname[32] + depth[2] + pre_defined[2]
4198        const VISUAL_SAMPLE_ENTRY_SIZE: u64 = 78;
4199        if entry_box.bytes_left() < VISUAL_SAMPLE_ENTRY_SIZE {
4200            skip_box_remain(&mut entry_box)?;
4201            continue;
4202        }
4203        skip(&mut entry_box, VISUAL_SAMPLE_ENTRY_SIZE)?;
4204
4205        // Parse sub-boxes within the VisualSampleEntry for av1C and colr
4206        let mut sub_iter = entry_box.box_iter();
4207        while let Some(mut sub_box) = sub_iter.next_box()? {
4208            match sub_box.head.name {
4209                BoxType::AV1CodecConfigurationBox => {
4210                    config.av1_config = Some(read_av1c(&mut sub_box)?);
4211                }
4212                BoxType::ColorInformationBox => {
4213                    if let Ok(colr) = read_colr(&mut sub_box) {
4214                        config.color_info = Some(colr);
4215                    } else {
4216                        skip_box_remain(&mut sub_box)?;
4217                    }
4218                }
4219                _ => {
4220                    skip_box_remain(&mut sub_box)?;
4221                }
4222            }
4223        }
4224
4225        // Only need the first av01 entry
4226        if config.av1_config.is_some() {
4227            break;
4228        }
4229    }
4230
4231    Ok(config)
4232}
4233
4234/// Parse Sample Table box (stbl)
4235/// See ISO/IEC 14496-12:2015 § 8.5
4236fn read_stbl<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<(SampleTable, TrackCodecConfig)> {
4237    let mut time_to_sample = TryVec::new();
4238    let mut sample_to_chunk = TryVec::new();
4239    let mut sample_sizes = TryVec::new();
4240    let mut chunk_offsets = TryVec::new();
4241    let mut codec_config = TrackCodecConfig::default();
4242
4243    let mut iter = src.box_iter();
4244    while let Some(mut b) = iter.next_box()? {
4245        match b.head.name {
4246            BoxType::SampleDescriptionBox => {
4247                codec_config = read_stsd(&mut b)?;
4248            }
4249            BoxType::TimeToSampleBox => {
4250                time_to_sample = read_stts(&mut b)?;
4251            }
4252            BoxType::SampleToChunkBox => {
4253                sample_to_chunk = read_stsc(&mut b)?;
4254            }
4255            BoxType::SampleSizeBox => {
4256                sample_sizes = read_stsz(&mut b)?;
4257            }
4258            BoxType::ChunkOffsetBox => {
4259                chunk_offsets = read_chunk_offsets(&mut b, false)?;
4260            }
4261            BoxType::ChunkLargeOffsetBox => {
4262                chunk_offsets = read_chunk_offsets(&mut b, true)?;
4263            }
4264            _ => {
4265                skip_box_remain(&mut b)?;
4266            }
4267        }
4268    }
4269
4270    // Precompute per-sample byte offsets from sample_to_chunk + chunk_offsets + sample_sizes.
4271    // This flattens the ISOBMFF indirection into a simple array for O(1) frame lookup.
4272    let mut sample_offsets = TryVec::new();
4273    let mut sample_idx = 0usize;
4274    for (i, entry) in sample_to_chunk.iter().enumerate() {
4275        let next_first_chunk = sample_to_chunk
4276            .get(i + 1)
4277            .map(|e| e.first_chunk)
4278            .unwrap_or(u32::MAX);
4279
4280        for chunk_no in entry.first_chunk..next_first_chunk {
4281            if chunk_no == 0 {
4282                break;
4283            }
4284            let co_idx = (chunk_no - 1) as usize;
4285            let chunk_offset = match chunk_offsets.get(co_idx) {
4286                Some(&o) => o,
4287                None => break,
4288            };
4289
4290            let mut offset = chunk_offset;
4291            for _ in 0..entry.samples_per_chunk {
4292                if sample_idx >= sample_sizes.len() {
4293                    break;
4294                }
4295                sample_offsets.push(offset)?;
4296                offset += *sample_sizes.get(sample_idx)
4297                    .ok_or(Error::InvalidData("sample index mismatch"))? as u64;
4298                sample_idx += 1;
4299            }
4300        }
4301    }
4302
4303    Ok((SampleTable {
4304        time_to_sample,
4305        sample_sizes,
4306        sample_offsets,
4307    }, codec_config))
4308}
4309
4310/// Parse Track Header box (tkhd)
4311/// See ISO/IEC 14496-12:2015 § 8.3.2
4312fn read_tkhd<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<u32> {
4313    let version = src.read_u8()?;
4314    let _flags = [src.read_u8()?, src.read_u8()?, src.read_u8()?];
4315
4316    let track_id = if version == 1 {
4317        let _creation_time = be_u64(src)?;
4318        let _modification_time = be_u64(src)?;
4319        let track_id = be_u32(src)?;
4320        let _reserved = be_u32(src)?;
4321        let _duration = be_u64(src)?;
4322        track_id
4323    } else {
4324        let _creation_time = be_u32(src)?;
4325        let _modification_time = be_u32(src)?;
4326        let track_id = be_u32(src)?;
4327        let _reserved = be_u32(src)?;
4328        let _duration = be_u32(src)?;
4329        track_id
4330    };
4331
4332    // Skip rest (reserved, layer, alternate_group, volume, matrix, width, height)
4333    skip_box_remain(src)?;
4334    Ok(track_id)
4335}
4336
4337/// Parse Track Reference box (tref)
4338/// See ISO/IEC 14496-12:2015 § 8.3.3
4339///
4340/// Contains sub-boxes typed by FourCC (e.g., `auxl`, `cdsc`), each with a list of track IDs.
4341fn read_tref<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<TrackReference>> {
4342    let mut refs = TryVec::new();
4343    let mut iter = src.box_iter();
4344    while let Some(mut b) = iter.next_box()? {
4345        let reference_type = FourCC::from(u32::from(b.head.name));
4346        let bytes_left = b.bytes_left();
4347        if bytes_left < 4 || bytes_left % 4 != 0 {
4348            skip_box_remain(&mut b)?;
4349            continue;
4350        }
4351        let count = bytes_left / 4;
4352        let mut track_ids = TryVec::new();
4353        for _ in 0..count {
4354            track_ids.push(be_u32(&mut b)?)?;
4355        }
4356        refs.push(TrackReference { reference_type, track_ids })?;
4357    }
4358    Ok(refs)
4359}
4360
4361/// Parse Edit List box (elst) to extract loop count from flags.
4362/// See ISO/IEC 14496-12:2015 § 8.6.6
4363///
4364/// Returns the loop count: flags bit 0 set = infinite looping (0), otherwise 1.
4365fn read_elst<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<u32> {
4366    let (version, flags) = read_fullbox_extra(src)?;
4367
4368    let entry_count = be_u32(src)?;
4369    // Skip all entries
4370    let entry_size: u64 = if version == 1 { 20 } else { 12 };
4371    skip(src, entry_count as u64 * entry_size)?;
4372    skip_box_remain(src)?;
4373
4374    // Bit 0 of flags: repeat (1 = infinite loop → loop_count=0, 0 = play once → loop_count=1)
4375    if flags & 1 != 0 {
4376        Ok(0) // infinite
4377    } else {
4378        Ok(1) // play once
4379    }
4380}
4381
4382/// Parse animation from moov box.
4383/// Returns all parsed tracks.
4384fn read_moov<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<TryVec<ParsedTrack>> {
4385    let mut tracks = TryVec::new();
4386
4387    let mut iter = src.box_iter();
4388    while let Some(mut b) = iter.next_box()? {
4389        match b.head.name {
4390            BoxType::MovieHeaderBox => {
4391                let _mvhd = read_mvhd(&mut b)?;
4392            }
4393            BoxType::TrackBox => {
4394                if let Some(track) = read_trak(&mut b)? {
4395                    tracks.push(track)?;
4396                }
4397            }
4398            _ => {
4399                skip_box_remain(&mut b)?;
4400            }
4401        }
4402    }
4403
4404    Ok(tracks)
4405}
4406
4407/// Parse track box (trak).
4408/// Returns a ParsedTrack if this track has a valid sample table.
4409fn read_trak<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<Option<ParsedTrack>> {
4410    let mut track_id = 0u32;
4411    let mut references = TryVec::new();
4412    let mut loop_count = 1u32; // default: play once
4413    let mut mdia_result: Option<(FourCC, u32, SampleTable, TrackCodecConfig)> = None;
4414
4415    let mut iter = src.box_iter();
4416    while let Some(mut b) = iter.next_box()? {
4417        match b.head.name {
4418            BoxType::TrackHeaderBox => {
4419                track_id = read_tkhd(&mut b)?;
4420            }
4421            BoxType::TrackReferenceBox => {
4422                references = read_tref(&mut b)?;
4423            }
4424            BoxType::EditBox => {
4425                // Parse edts to find elst
4426                let mut edts_iter = b.box_iter();
4427                while let Some(mut eb) = edts_iter.next_box()? {
4428                    if eb.head.name == BoxType::EditListBox {
4429                        loop_count = read_elst(&mut eb)?;
4430                    } else {
4431                        skip_box_remain(&mut eb)?;
4432                    }
4433                }
4434            }
4435            BoxType::MediaBox => {
4436                mdia_result = read_mdia(&mut b)?;
4437            }
4438            _ => {
4439                skip_box_remain(&mut b)?;
4440            }
4441        }
4442    }
4443
4444    if let Some((handler_type, media_timescale, sample_table, codec_config)) = mdia_result {
4445        Ok(Some(ParsedTrack {
4446            track_id,
4447            handler_type,
4448            media_timescale,
4449            sample_table,
4450            references,
4451            loop_count,
4452            codec_config,
4453        }))
4454    } else {
4455        Ok(None)
4456    }
4457}
4458
4459/// Parse media box (mdia).
4460/// Returns (handler_type, media_timescale, sample_table, codec_config) if valid.
4461fn read_mdia<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<Option<(FourCC, u32, SampleTable, TrackCodecConfig)>> {
4462    let mut media_timescale = 1000; // default
4463    let mut handler_type = FourCC::default();
4464    let mut stbl_result: Option<(SampleTable, TrackCodecConfig)> = None;
4465
4466    let mut iter = src.box_iter();
4467    while let Some(mut b) = iter.next_box()? {
4468        match b.head.name {
4469            BoxType::MediaHeaderBox => {
4470                let mdhd = read_mdhd(&mut b)?;
4471                media_timescale = mdhd.timescale;
4472            }
4473            BoxType::HandlerBox => {
4474                let hdlr = read_hdlr(&mut b)?;
4475                handler_type = hdlr.handler_type;
4476            }
4477            BoxType::MediaInformationBox => {
4478                stbl_result = read_minf(&mut b)?;
4479            }
4480            _ => {
4481                skip_box_remain(&mut b)?;
4482            }
4483        }
4484    }
4485
4486    if let Some((stbl, codec_config)) = stbl_result {
4487        Ok(Some((handler_type, media_timescale, stbl, codec_config)))
4488    } else {
4489        Ok(None)
4490    }
4491}
4492
4493/// Associate parsed tracks into color + optional alpha animation data.
4494///
4495/// - Color track: first with handler `pict` (fallback: first track with a sample table)
4496/// - Alpha track: handler `auxv` with `tref/auxl` referencing color's track_id
4497/// - Audio tracks (handler `soun`) are skipped
4498fn associate_tracks(tracks: TryVec<ParsedTrack>) -> Result<ParsedAnimationData> {
4499    // Find color track: first with handler_type == "pict"
4500    let color_idx = tracks
4501        .iter()
4502        .position(|t| t.handler_type == b"pict")
4503        .or_else(|| {
4504            // Fallback: first track that isn't audio
4505            tracks.iter().position(|t| t.handler_type != b"soun")
4506        })
4507        .ok_or(Error::InvalidData("no color track found in moov"))?;
4508
4509    let color_track = tracks.get(color_idx)
4510        .ok_or(Error::InvalidData("color track index out of bounds"))?;
4511    let color_track_id = color_track.track_id;
4512
4513    // Find alpha track: handler_type == "auxv" with tref/auxl referencing color track
4514    let alpha_idx = tracks.iter().position(|t| {
4515        t.handler_type == b"auxv"
4516            && t.references.iter().any(|r| {
4517                r.reference_type == b"auxl"
4518                    && r.track_ids.iter().any(|&id| id == color_track_id)
4519            })
4520    });
4521
4522    if let Some(ai) = alpha_idx {
4523        let alpha_track = tracks.get(ai)
4524            .ok_or(Error::InvalidData("alpha track index out of bounds"))?;
4525        let color_track = tracks.get(color_idx)
4526            .ok_or(Error::InvalidData("color track index out of bounds"))?;
4527        let alpha_frames = alpha_track.sample_table.sample_sizes.len();
4528        let color_frames = color_track.sample_table.sample_sizes.len();
4529        if alpha_frames != color_frames {
4530            warn!(
4531                "alpha track has {} frames but color track has {} frames",
4532                alpha_frames, color_frames
4533            );
4534        }
4535    }
4536
4537    // Destructure — we need to consume the vec
4538    // Convert to a std vec so we can remove by index
4539    let mut tracks_vec: std::vec::Vec<ParsedTrack> = tracks.into_iter().collect();
4540
4541    // Remove alpha first if it has a higher index to avoid shifting
4542    let (color_track, alpha_track) = if let Some(ai) = alpha_idx {
4543        if ai > color_idx {
4544            let alpha = tracks_vec.remove(ai);
4545            let color = tracks_vec.remove(color_idx);
4546            (color, Some(alpha))
4547        } else {
4548            let color = tracks_vec.remove(color_idx);
4549            let alpha = tracks_vec.remove(ai);
4550            (color, Some(alpha))
4551        }
4552    } else {
4553        let color = tracks_vec.remove(color_idx);
4554        (color, None)
4555    };
4556
4557    let (alpha_timescale, alpha_sample_table) = match alpha_track {
4558        Some(t) => (Some(t.media_timescale), Some(t.sample_table)),
4559        None => (None, None),
4560    };
4561
4562    Ok(ParsedAnimationData {
4563        color_timescale: color_track.media_timescale,
4564        color_codec_config: color_track.codec_config,
4565        color_sample_table: color_track.sample_table,
4566        alpha_timescale,
4567        alpha_sample_table,
4568        loop_count: color_track.loop_count,
4569    })
4570}
4571
4572/// Parse media information box (minf)
4573fn read_minf<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<Option<(SampleTable, TrackCodecConfig)>> {
4574    let mut iter = src.box_iter();
4575    while let Some(mut b) = iter.next_box()? {
4576        if b.head.name == BoxType::SampleTableBox {
4577            return Ok(Some(read_stbl(&mut b)?));
4578        } else {
4579            skip_box_remain(&mut b)?;
4580        }
4581    }
4582    Ok(None)
4583}
4584
4585/// Extract animation frames using sample table
4586#[cfg(feature = "eager")]
4587#[allow(deprecated)]
4588fn extract_animation_frames(
4589    sample_table: &SampleTable,
4590    media_timescale: u32,
4591    mdats: &mut [MediaDataBox],
4592) -> Result<TryVec<AnimationFrame>> {
4593    let mut frames = TryVec::new();
4594
4595    // Calculate frame durations from time-to-sample
4596    let mut frame_durations = TryVec::new();
4597    for entry in &sample_table.time_to_sample {
4598        for _ in 0..entry.sample_count {
4599            let duration_ms = if media_timescale > 0 {
4600                ((entry.sample_delta as u64) * 1000) / (media_timescale as u64)
4601            } else {
4602                0
4603            };
4604            frame_durations.push(duration_ms as u32)?;
4605        }
4606    }
4607
4608    // Extract each frame using precomputed sample offsets
4609    for i in 0..sample_table.sample_sizes.len() {
4610        let sample_offset = *sample_table.sample_offsets.get(i)
4611            .ok_or(Error::InvalidData("sample offset index out of bounds"))?;
4612        let sample_size = *sample_table.sample_sizes.get(i)
4613            .ok_or(Error::InvalidData("sample size index out of bounds"))?;
4614        let duration_ms = frame_durations.get(i).copied().unwrap_or(0);
4615
4616        let mut frame_data = TryVec::new();
4617        let mut found = false;
4618
4619        for mdat in mdats.iter_mut() {
4620            let range = ExtentRange::WithLength(Range {
4621                start: sample_offset,
4622                end: sample_offset + sample_size as u64,
4623            });
4624
4625            if mdat.contains_extent(&range) {
4626                mdat.read_extent(&range, &mut frame_data)?;
4627                found = true;
4628                break;
4629            }
4630        }
4631
4632        if !found {
4633            log::warn!("Animation frame {} not found in mdat", i);
4634        }
4635
4636        frames.push(AnimationFrame {
4637            data: frame_data,
4638            duration_ms,
4639        })?;
4640    }
4641
4642    Ok(frames)
4643}
4644
4645/// Parse an ImageGrid property box
4646/// See ISO/IEC 23008-12:2017 § 6.6.2.3
4647fn read_grid<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<GridConfig> {
4648    let version = read_fullbox_version_no_flags(src, options)?;
4649    if version > 0 {
4650        return Err(Error::Unsupported("grid version > 0"));
4651    }
4652
4653    let flags_byte = src.read_u8()?;
4654    let rows = src.read_u8()?;
4655    let columns = src.read_u8()?;
4656
4657    // flags & 1 determines field size: 0 = 16-bit, 1 = 32-bit
4658    let (output_width, output_height) = if flags_byte & 1 == 0 {
4659        // 16-bit fields
4660        (u32::from(be_u16(src)?), u32::from(be_u16(src)?))
4661    } else {
4662        // 32-bit fields
4663        (be_u32(src)?, be_u32(src)?)
4664    };
4665
4666    Ok(GridConfig {
4667        rows,
4668        columns,
4669        output_width,
4670        output_height,
4671    })
4672}
4673
4674/// Parse an item location box inside a meta box
4675/// See ISO 14496-12:2015 § 8.11.3
4676fn read_iloc<T: Read>(src: &mut BMFFBox<'_, T>, options: &ParseOptions) -> Result<TryVec<ItemLocationBoxItem>> {
4677    let version: IlocVersion = read_fullbox_version_no_flags(src, options)?.try_into()?;
4678
4679    let iloc = src.read_into_try_vec()?;
4680    let mut iloc = BitReader::new(&iloc);
4681
4682    let offset_size: IlocFieldSize = iloc.read_u8(4)?.try_into()?;
4683    let length_size: IlocFieldSize = iloc.read_u8(4)?.try_into()?;
4684    let base_offset_size: IlocFieldSize = iloc.read_u8(4)?.try_into()?;
4685
4686    let index_size: Option<IlocFieldSize> = match version {
4687        IlocVersion::One | IlocVersion::Two => Some(iloc.read_u8(4)?.try_into()?),
4688        IlocVersion::Zero => {
4689            let _reserved = iloc.read_u8(4)?;
4690            None
4691        },
4692    };
4693
4694    let item_count = match version {
4695        IlocVersion::Zero | IlocVersion::One => iloc.read_u32(16)?,
4696        IlocVersion::Two => iloc.read_u32(32)?,
4697    };
4698
4699    let mut items = TryVec::with_capacity(item_count.to_usize())?;
4700
4701    for _ in 0..item_count {
4702        let item_id = match version {
4703            IlocVersion::Zero | IlocVersion::One => iloc.read_u32(16)?,
4704            IlocVersion::Two => iloc.read_u32(32)?,
4705        };
4706
4707        // The spec isn't entirely clear how an `iloc` should be interpreted for version 0,
4708        // which has no `construction_method` field. It does say:
4709        // "For maximum compatibility, version 0 of this box should be used in preference to
4710        //  version 1 with `construction_method==0`, or version 2 when possible."
4711        // We take this to imply version 0 can be interpreted as using file offsets.
4712        let construction_method = match version {
4713            IlocVersion::Zero => ConstructionMethod::File,
4714            IlocVersion::One | IlocVersion::Two => {
4715                let _reserved = iloc.read_u16(12)?;
4716                match iloc.read_u16(4)? {
4717                    0 => ConstructionMethod::File,
4718                    1 => ConstructionMethod::Idat,
4719                    2 => return Err(Error::Unsupported("construction_method 'item_offset' is not supported")),
4720                    _ => return Err(Error::InvalidData("construction_method is taken from the set 0, 1 or 2 per ISO 14496-12:2015 § 8.11.3.3")),
4721                }
4722            },
4723        };
4724
4725        let data_reference_index = iloc.read_u16(16)?;
4726
4727        if data_reference_index != 0 {
4728            return Err(Error::Unsupported("external file references (iloc.data_reference_index != 0) are not supported"));
4729        }
4730
4731        let base_offset = iloc.read_u64(base_offset_size.to_bits())?;
4732        let extent_count = iloc.read_u16(16)?;
4733
4734        if extent_count < 1 {
4735            return Err(Error::InvalidData("extent_count must have a value 1 or greater per ISO 14496-12:2015 § 8.11.3.3"));
4736        }
4737
4738        let mut extents = TryVec::with_capacity(extent_count.to_usize())?;
4739
4740        for _ in 0..extent_count {
4741            // Parsed but currently ignored, see `ItemLocationBoxExtent`
4742            let _extent_index = match &index_size {
4743                None | Some(IlocFieldSize::Zero) => None,
4744                Some(index_size) => {
4745                    debug_assert!(version == IlocVersion::One || version == IlocVersion::Two);
4746                    Some(iloc.read_u64(index_size.to_bits())?)
4747                },
4748            };
4749
4750            // Per ISO 14496-12:2015 § 8.11.3.1:
4751            // "If the offset is not identified (the field has a length of zero), then the
4752            //  beginning of the source (offset 0) is implied"
4753            // This behavior will follow from BitReader::read_u64(0) -> 0.
4754            let extent_offset = iloc.read_u64(offset_size.to_bits())?;
4755            let extent_length = iloc.read_u64(length_size.to_bits())?;
4756
4757            // "If the length is not specified, or specified as zero, then the entire length of
4758            //  the source is implied" (ibid)
4759            let start = base_offset
4760                .checked_add(extent_offset)
4761                .ok_or(Error::InvalidData("offset calculation overflow"))?;
4762            let extent_range = if extent_length == 0 {
4763                ExtentRange::ToEnd(RangeFrom { start })
4764            } else {
4765                let end = start
4766                    .checked_add(extent_length)
4767                    .ok_or(Error::InvalidData("end calculation overflow"))?;
4768                ExtentRange::WithLength(Range { start, end })
4769            };
4770
4771            extents.push(ItemLocationBoxExtent { extent_range })?;
4772        }
4773
4774        items.push(ItemLocationBoxItem { item_id, construction_method, extents })?;
4775    }
4776
4777    if iloc.remaining() == 0 {
4778        Ok(items)
4779    } else {
4780        Err(Error::InvalidData("invalid iloc size"))
4781    }
4782}
4783
4784/// Parse an ftyp box.
4785/// See ISO 14496-12:2015 § 4.3
4786fn read_ftyp<T: Read>(src: &mut BMFFBox<'_, T>) -> Result<FileTypeBox> {
4787    let major = be_u32(src)?;
4788    let minor = be_u32(src)?;
4789    let bytes_left = src.bytes_left();
4790    if !bytes_left.is_multiple_of(4) {
4791        return Err(Error::InvalidData("invalid ftyp size"));
4792    }
4793    // Is a brand_count of zero valid?
4794    let brand_count = bytes_left / 4;
4795    let mut brands = TryVec::with_capacity(brand_count.try_into()?)?;
4796    for _ in 0..brand_count {
4797        brands.push(be_u32(src)?.into())?;
4798    }
4799    Ok(FileTypeBox {
4800        major_brand: From::from(major),
4801        minor_version: minor,
4802        compatible_brands: brands,
4803    })
4804}
4805
4806#[cfg_attr(debug_assertions, track_caller)]
4807fn check_parser_state<T>(header: &BoxHeader, left: &Take<T>) -> Result<(), Error> {
4808    let limit = left.limit();
4809    // Allow fully consumed boxes, or size=0 boxes (where original size was u64::MAX)
4810    if limit == 0 || header.size == u64::MAX {
4811        Ok(())
4812    } else {
4813        debug_assert_eq!(0, limit, "bad parser state bytes left");
4814        Err(Error::InvalidData("unread box content or bad parser sync"))
4815    }
4816}
4817
4818/// Skip a number of bytes that we don't care to parse.
4819fn skip<T: Read>(src: &mut T, bytes: u64) -> Result<()> {
4820    std::io::copy(&mut src.take(bytes), &mut std::io::sink())?;
4821    Ok(())
4822}
4823
4824fn be_u16<T: ReadBytesExt>(src: &mut T) -> Result<u16> {
4825    src.read_u16::<byteorder::BigEndian>().map_err(From::from)
4826}
4827
4828fn be_u32<T: ReadBytesExt>(src: &mut T) -> Result<u32> {
4829    src.read_u32::<byteorder::BigEndian>().map_err(From::from)
4830}
4831
4832fn be_i32<T: ReadBytesExt>(src: &mut T) -> Result<i32> {
4833    src.read_i32::<byteorder::BigEndian>().map_err(From::from)
4834}
4835
4836fn be_u64<T: ReadBytesExt>(src: &mut T) -> Result<u64> {
4837    src.read_u64::<byteorder::BigEndian>().map_err(From::from)
4838}