Skip to main content

rff_format/
heif.rs

1//! HEIF (ISO/IEC 23008-12) box parser: the item model shared by every
2//! HEIF-family container (HEIC, AVIF, ...).
3//!
4//! A HEIF still image is not a stream of samples but a small database of
5//! *items* described by the top-level `meta` box:
6//!
7//! * `iinf`/`infe` — what each item is (`hvc1`, `av01`, `grid`, `iden`,
8//!   `Exif`, `mime`, ...) and whether it is hidden;
9//! * `iloc` — where its bytes are (file extents, or the `idat` box);
10//! * `iprp` (`ipco` + `ipma`) — its properties: size (`ispe`), decoder
11//!   configuration (`hvcC`), colour (`colr`), transforms (`clap`, `irot`,
12//!   `imir`), auxiliary type (`auxC`), ...;
13//! * `iref` — how items relate: a grid's tiles (`dimg`), a thumbnail
14//!   (`thmb`), an alpha or depth plane (`auxl`), metadata (`cdsc`), a
15//!   premultiplied alpha (`prem`), predictive coding (`pred`);
16//! * `pitm` — which item is the primary image.
17//!
18//! [`HeifFile::parse`] reads all of it over a borrowed file buffer, copying
19//! nothing it can borrow, and with every count and size bounded by
20//! [`Limits`]: a malformed file returns an error, never a panic and never an
21//! allocation the file's own length does not justify.
22//!
23//! This module only *describes* the file. Decoding an item's bitstream is the
24//! job of the codec-specific crate (`rff-format-heif` for HEVC, the AVIF
25//! crates for AV1).
26
27use std::borrow::Cow;
28
29use rff_core::{Error, Result};
30
31// ===========================================================================
32// Box walking
33// ===========================================================================
34
35/// Parse sibling boxes at the top level of `buf` into `(type, payload)` pairs.
36/// Tolerates the 64-bit `largesize` form and the `size == 0` (to-end) form.
37/// A box whose declared size runs past `buf`, or ends before its own header,
38/// ends the walk (as FFmpeg's `mov_read_default` does).
39pub fn child_boxes(buf: &[u8]) -> Vec<([u8; 4], &[u8])> {
40    let mut out = Vec::new();
41    let mut i = 0;
42    while i + 8 <= buf.len() {
43        let size32 = u32::from_be_bytes([buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]) as usize;
44        let typ = [buf[i + 4], buf[i + 5], buf[i + 6], buf[i + 7]];
45        let (payload_start, box_end) = if size32 == 1 {
46            if i + 16 > buf.len() {
47                break;
48            }
49            let mut large = [0u8; 8];
50            large.copy_from_slice(&buf[i + 8..i + 16]);
51            let large = u64::from_be_bytes(large) as usize;
52            (i + 16, i.checked_add(large).unwrap_or(buf.len()))
53        } else if size32 == 0 {
54            (i + 8, buf.len())
55        } else {
56            (i + 8, i + size32)
57        };
58        // A size below the header's own (2-7, or a 64-bit size under 16) ends the box
59        // before its payload starts: stop there, as FFmpeg's mov_read_default does.
60        if box_end > buf.len() || box_end < payload_start {
61            break;
62        }
63        out.push((typ, &buf[payload_start..box_end]));
64        i = box_end;
65    }
66    out
67}
68
69/// The payload of the first box of type `typ` in a [`child_boxes`] list.
70pub fn find_box<'a>(boxes: &[([u8; 4], &'a [u8])], typ: &[u8; 4]) -> Option<&'a [u8]> {
71    boxes.iter().find(|(t, _)| t == typ).map(|(_, p)| *p)
72}
73
74/// A bounds-checked big-endian reader over one box payload. Every read past
75/// the end is an error naming the box, never a panic.
76struct Rd<'a> {
77    b: &'a [u8],
78    p: usize,
79    what: &'static str,
80}
81
82impl<'a> Rd<'a> {
83    fn new(b: &'a [u8], what: &'static str) -> Self {
84        Rd { b, p: 0, what }
85    }
86
87    fn short(&self) -> Error {
88        Error::invalid(format!("heif: truncated `{}`", self.what))
89    }
90
91    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
92        let end = self.p.checked_add(n).ok_or_else(|| self.short())?;
93        let s = self.b.get(self.p..end).ok_or_else(|| self.short())?;
94        self.p = end;
95        Ok(s)
96    }
97
98    fn u8(&mut self) -> Result<u8> {
99        Ok(self.take(1)?[0])
100    }
101
102    fn u16(&mut self) -> Result<u16> {
103        let s = self.take(2)?;
104        Ok(u16::from_be_bytes([s[0], s[1]]))
105    }
106
107    fn u32(&mut self) -> Result<u32> {
108        let s = self.take(4)?;
109        Ok(u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
110    }
111
112    /// An unsigned big-endian field of `n` bytes (0, 1, 2, 4 or 8). Zero
113    /// bytes reads as 0, which is how `iloc` encodes an absent field.
114    fn uint(&mut self, n: usize) -> Result<u64> {
115        if n > 8 {
116            return Err(Error::invalid(format!(
117                "heif: {}-byte field in `{}`",
118                n, self.what
119            )));
120        }
121        Ok(self.take(n)?.iter().fold(0u64, |v, &b| (v << 8) | b as u64))
122    }
123
124    fn fourcc(&mut self) -> Result<[u8; 4]> {
125        let s = self.take(4)?;
126        Ok([s[0], s[1], s[2], s[3]])
127    }
128
129    /// A NUL-terminated UTF-8 string. A missing terminator at the end of the
130    /// box is tolerated (some writers drop it on the last field).
131    fn cstr(&mut self) -> String {
132        let rest = &self.b[self.p.min(self.b.len())..];
133        let n = rest.iter().position(|&c| c == 0).unwrap_or(rest.len());
134        self.p = (self.p + n + 1).min(self.b.len());
135        String::from_utf8_lossy(&rest[..n]).into_owned()
136    }
137
138    fn rest(&self) -> &'a [u8] {
139        &self.b[self.p.min(self.b.len())..]
140    }
141
142    /// A FullBox header: `(version, flags)`.
143    fn full(&mut self) -> Result<(u8, u32)> {
144        let v = self.u32()?;
145        Ok(((v >> 24) as u8, v & 0x00ff_ffff))
146    }
147}
148
149// ===========================================================================
150// Limits
151// ===========================================================================
152
153/// Upper bounds the parser and decoders enforce on untrusted files. The
154/// defaults admit every real camera file (an iPhone 48 MP photo is a grid of
155/// 8×6 tiles, 8064×6048) with a wide margin, and refuse what only a hostile
156/// file would declare.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub struct Limits {
159    /// Items in `iinf` / `iloc` / `ipma` (each).
160    pub max_items: u32,
161    /// Extents per item in `iloc`.
162    pub max_extents: u32,
163    /// Bytes of one item's data (also bounded by the file's length).
164    pub max_item_bytes: u64,
165    /// Width or height of any image, after composition.
166    pub max_dimension: u32,
167    /// Pixels of any image (`width * height`), after composition.
168    pub max_pixels: u64,
169    /// Tiles of one `grid` (rows × columns; the format caps each at 256).
170    pub max_grid_tiles: u32,
171    /// Depth of derived-image chains (`iden` of `iden` of `grid` ...).
172    pub max_derivation_depth: u32,
173}
174
175impl Default for Limits {
176    fn default() -> Self {
177        Limits {
178            max_items: 65_536,
179            max_extents: 4_096,
180            max_item_bytes: 1 << 30,
181            max_dimension: 65_535,
182            // 2^28 = 268 M pixels (16384×16384); libheif's default is 2^30.
183            max_pixels: 1 << 28,
184            max_grid_tiles: 65_536,
185            max_derivation_depth: 8,
186        }
187    }
188}
189
190// ===========================================================================
191// The item model
192// ===========================================================================
193
194/// Where an item's bytes live (`iloc`).
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct Location {
197    /// 0 = file offsets, 1 = offsets into `idat`, 2 = into another item.
198    pub construction_method: u8,
199    pub base_offset: u64,
200    /// `(offset, length)` pairs; a length of 0 means "to the end".
201    pub extents: Vec<(u64, u64)>,
202}
203
204/// One entry of `iinf`.
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct Item {
207    pub id: u32,
208    /// `hvc1`, `av01`, `grid`, `iden`, `iovl`, `Exif`, `mime`, ...
209    pub item_type: [u8; 4],
210    pub name: String,
211    /// For `mime` items: the MIME type (`application/rdf+xml` for XMP).
212    pub content_type: Option<String>,
213    /// `infe` flag 1: not meant to be displayed on its own.
214    pub hidden: bool,
215    pub location: Option<Location>,
216    /// `(index into HeifFile::properties, essential)`, in `ipma` order —
217    /// which is the order transformative properties apply in.
218    pub properties: Vec<(usize, bool)>,
219}
220
221/// `colr`: an `nclx` code-point triple or an ICC profile.
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub enum Colour<'a> {
224    Nclx {
225        primaries: u16,
226        transfer: u16,
227        matrix: u16,
228        full_range: bool,
229    },
230    /// `rICC` (restricted) or `prof` (unrestricted) — the profile bytes.
231    Icc(&'a [u8]),
232}
233
234/// `clap`: a clean aperture as four rationals (ISO/IEC 14496-12 §12.1.4).
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub struct Clap {
237    pub width: (i64, i64),
238    pub height: (i64, i64),
239    pub horiz_off: (i64, i64),
240    pub vert_off: (i64, i64),
241}
242
243impl Clap {
244    /// The integer crop rectangle `(left, top, width, height)` this aperture
245    /// selects from a `w`x`h` image, computed exactly as libheif does: the
246    /// centre is `offset + (size - 1) / 2`, `left` truncates, `top`,
247    /// `right` and `bottom` round half up, and the result is clamped to the
248    /// image. `None` if a denominator is zero, the image is empty, or the
249    /// clamped rectangle is empty.
250    pub fn rect(&self, w: u32, h: u32) -> Option<(u32, u32, u32, u32)> {
251        if w == 0 || h == 0 {
252            return None;
253        }
254        let (l, r) = edges(self.width, self.horiz_off, w, false)?;
255        let (t, b) = edges(self.height, self.vert_off, h, true)?;
256        let (l, t) = (l.max(0), t.max(0));
257        let (r, b) = (r.min(w as i64 - 1), b.min(h as i64 - 1));
258        if l > r || t > b {
259            return None;
260        }
261        Some((l as u32, t as u32, (r - l + 1) as u32, (b - t + 1) as u32))
262    }
263}
264
265/// An exact rational with a positive denominator.
266#[derive(Clone, Copy)]
267struct Q(i128, i128);
268
269impl Q {
270    fn new(n: i64, d: i64) -> Option<Q> {
271        match d {
272            0 => None,
273            d if d < 0 => Some(Q(-(n as i128), -(d as i128))),
274            d => Some(Q(n as i128, d as i128)),
275        }
276    }
277    fn add(self, o: Q) -> Q {
278        Q(self.0 * o.1 + o.0 * self.1, self.1 * o.1)
279    }
280    fn sub(self, o: Q) -> Q {
281        Q(self.0 * o.1 - o.0 * self.1, self.1 * o.1)
282    }
283    /// C integer division: truncation toward zero (libheif `round_down`).
284    fn trunc(self) -> i64 {
285        (self.0 / self.1) as i64
286    }
287    /// `(n + d/2) / d`, truncated (libheif `round`).
288    fn round(self) -> i64 {
289        ((self.0 + self.1 / 2) / self.1) as i64
290    }
291}
292
293/// The two edges `(lo, hi)` of one clean-aperture axis, as libheif computes
294/// them (`lo` truncated on the horizontal axis, rounded on the vertical).
295fn edges(size: (i64, i64), off: (i64, i64), image: u32, round_lo: bool) -> Option<(i64, i64)> {
296    let size = Q::new(size.0, size.1)?;
297    let off = Q::new(off.0, off.1)?;
298    let one = Q(1, 1);
299    let pc = off.add(Q(image as i128 - 1, 2));
300    let half = {
301        let s = size.sub(one);
302        Q(s.0, s.1 * 2)
303    };
304    let lo_q = pc.sub(half);
305    let lo = if round_lo { lo_q.round() } else { lo_q.trunc() };
306    let hi = size.sub(one).add(Q(lo as i128, 1)).round();
307    Some((lo, hi))
308}
309
310/// One property of `ipco`. Payloads are borrowed from the file buffer.
311#[derive(Debug, Clone, PartialEq, Eq)]
312pub enum Property<'a> {
313    /// `ispe`: the image's width and height.
314    Ispe {
315        width: u32,
316        height: u32,
317    },
318    /// `hvcC`: the HEVC decoder configuration record, verbatim.
319    HvcC(&'a [u8]),
320    /// `av1C`: the AV1 codec configuration record, verbatim.
321    Av1C(&'a [u8]),
322    Colr(Colour<'a>),
323    /// `irot`: anti-clockwise rotation in units of 90 degrees (0-3).
324    Irot(u8),
325    /// `imir`: 0 = mirror about a vertical axis (left-right flip),
326    /// 1 = about a horizontal axis (top-bottom flip).
327    Imir(u8),
328    Clap(Clap),
329    /// `pixi`: bits per channel.
330    Pixi(Vec<u8>),
331    /// `auxC`: the auxiliary image's type URN (alpha, depth, ...).
332    AuxC {
333        aux_type: String,
334        subtype: &'a [u8],
335    },
336    /// Anything else, by box type.
337    Other([u8; 4]),
338}
339
340/// One reference of `iref`: `from` refers to each of `to`, with meaning
341/// `kind` (`dimg`, `thmb`, `auxl`, `cdsc`, `prem`, `pred`, `base`, ...).
342#[derive(Debug, Clone, PartialEq, Eq)]
343pub struct Reference {
344    pub kind: [u8; 4],
345    pub from: u32,
346    pub to: Vec<u32>,
347}
348
349/// A parsed HEIF file: brands, items, properties and references, borrowing
350/// the file buffer.
351#[derive(Debug, Clone)]
352pub struct HeifFile<'a> {
353    data: &'a [u8],
354    idat: &'a [u8],
355    pub major_brand: [u8; 4],
356    pub compatible_brands: Vec<[u8; 4]>,
357    pub handler: [u8; 4],
358    pub primary: Option<u32>,
359    pub items: Vec<Item>,
360    pub properties: Vec<Property<'a>>,
361    pub references: Vec<Reference>,
362    pub limits: Limits,
363}
364
365/// `grid` derived-image descriptor (ISO/IEC 23008-12 §6.6.2.3).
366#[derive(Debug, Clone, Copy, PartialEq, Eq)]
367pub struct Grid {
368    pub rows: u32,
369    pub columns: u32,
370    pub output_width: u32,
371    pub output_height: u32,
372}
373
374/// `iovl` derived-image descriptor (ISO/IEC 23008-12 §6.6.2.4).
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct Overlay {
377    /// Canvas fill, 16-bit R, G, B, A.
378    pub fill: [u16; 4],
379    pub output_width: u32,
380    pub output_height: u32,
381    /// `(x, y)` of each `dimg` input, in reference order.
382    pub offsets: Vec<(i32, i32)>,
383}
384
385impl<'a> HeifFile<'a> {
386    /// Parse the `ftyp` and top-level `meta` of a HEIF file held in memory.
387    pub fn parse(data: &'a [u8], limits: Limits) -> Result<HeifFile<'a>> {
388        let top = child_boxes(data);
389        let ftyp = find_box(&top, b"ftyp").ok_or_else(|| Error::invalid("heif: no `ftyp` box"))?;
390        let mut r = Rd::new(ftyp, "ftyp");
391        let major_brand = r.fourcc()?;
392        let _minor = r.u32()?;
393        let compatible_brands = r
394            .rest()
395            .chunks_exact(4)
396            .map(|c| [c[0], c[1], c[2], c[3]])
397            .collect();
398
399        let meta = find_box(&top, b"meta").ok_or_else(|| Error::invalid("heif: no `meta` box"))?;
400        let mut r = Rd::new(meta, "meta");
401        r.full()?;
402        let meta_children = child_boxes(r.rest());
403
404        let mut file = HeifFile {
405            data,
406            idat: find_box(&meta_children, b"idat").unwrap_or(&[]),
407            major_brand,
408            compatible_brands,
409            handler: [0; 4],
410            primary: None,
411            items: Vec::new(),
412            properties: Vec::new(),
413            references: Vec::new(),
414            limits,
415        };
416
417        if let Some(hdlr) = find_box(&meta_children, b"hdlr") {
418            let mut r = Rd::new(hdlr, "hdlr");
419            r.full()?;
420            r.u32()?; // pre_defined
421            file.handler = r.fourcc()?;
422        }
423        if let Some(pitm) = find_box(&meta_children, b"pitm") {
424            let mut r = Rd::new(pitm, "pitm");
425            let (v, _) = r.full()?;
426            file.primary = Some(if v == 0 { r.u16()? as u32 } else { r.u32()? });
427        }
428        if let Some(iinf) = find_box(&meta_children, b"iinf") {
429            file.items = parse_iinf(iinf, &limits)?;
430        }
431        if let Some(iloc) = find_box(&meta_children, b"iloc") {
432            for (id, loc) in parse_iloc(iloc, &limits)? {
433                // `iloc` may name items `iinf` does not; those are unreachable
434                // and ignored.
435                if let Some(it) = file.items.iter_mut().find(|it| it.id == id) {
436                    it.location = Some(loc);
437                }
438            }
439        }
440        if let Some(iref) = find_box(&meta_children, b"iref") {
441            file.references = parse_iref(iref, &limits)?;
442        }
443        if let Some(iprp) = find_box(&meta_children, b"iprp") {
444            let iprp = child_boxes(iprp);
445            if let Some(ipco) = find_box(&iprp, b"ipco") {
446                file.properties = child_boxes(ipco)
447                    .into_iter()
448                    .map(|(t, p)| parse_property(t, p))
449                    .collect::<Result<_>>()?;
450            }
451            // A file may split its associations over several `ipma` boxes.
452            for (t, p) in &iprp {
453                if t == b"ipma" {
454                    parse_ipma(p, &limits, &mut file)?;
455                }
456            }
457        }
458        Ok(file)
459    }
460
461    /// The item with `id`, if `iinf` declares one.
462    pub fn item(&self, id: u32) -> Option<&Item> {
463        self.items.iter().find(|it| it.id == id)
464    }
465
466    /// The primary item, if `pitm` names one that `iinf` declares.
467    pub fn primary_item(&self) -> Option<&Item> {
468        self.primary.and_then(|id| self.item(id))
469    }
470
471    /// Item `id`'s properties in `ipma` order, with their essential flag.
472    pub fn properties_of(&self, id: u32) -> impl Iterator<Item = (&Property<'a>, bool)> + '_ {
473        self.item(id)
474            .map(|it| it.properties.as_slice())
475            .unwrap_or(&[])
476            .iter()
477            .filter_map(|&(i, e)| self.properties.get(i).map(|p| (p, e)))
478    }
479
480    /// The first `ispe` of item `id`.
481    pub fn ispe(&self, id: u32) -> Option<(u32, u32)> {
482        self.properties_of(id).find_map(|(p, _)| match p {
483            Property::Ispe { width, height } => Some((*width, *height)),
484            _ => None,
485        })
486    }
487
488    /// The first `hvcC` of item `id`.
489    pub fn hvcc(&self, id: u32) -> Option<&'a [u8]> {
490        self.properties_of(id).find_map(|(p, _)| match p {
491            Property::HvcC(b) => Some(*b),
492            _ => None,
493        })
494    }
495
496    /// The `auxC` type URN of item `id`, if it is an auxiliary image.
497    pub fn aux_type(&self, id: u32) -> Option<&str> {
498        self.properties_of(id).find_map(|(p, _)| match p {
499            Property::AuxC { aux_type, .. } => Some(aux_type.as_str()),
500            _ => None,
501        })
502    }
503
504    /// Items `id` refers to with `kind`, in reference order.
505    pub fn refs_from(&self, id: u32, kind: &[u8; 4]) -> Vec<u32> {
506        self.references
507            .iter()
508            .filter(|r| r.from == id && &r.kind == kind)
509            .flat_map(|r| r.to.iter().copied())
510            .collect()
511    }
512
513    /// Items that refer to `id` with `kind` (e.g. the thumbnails of `id`
514    /// are the items with a `thmb` reference to it).
515    pub fn refs_to(&self, id: u32, kind: &[u8; 4]) -> Vec<u32> {
516        let mut out: Vec<u32> = self
517            .references
518            .iter()
519            .filter(|r| &r.kind == kind && r.to.contains(&id))
520            .map(|r| r.from)
521            .collect();
522        out.dedup();
523        out
524    }
525
526    /// Item `id`'s bytes: a borrow of the file (or `idat`) when it is one
527    /// extent, a concatenation when it is several.
528    pub fn item_data(&self, id: u32) -> Result<Cow<'a, [u8]>> {
529        let item = self
530            .item(id)
531            .ok_or_else(|| Error::invalid(format!("heif: no item {id}")))?;
532        let loc = item
533            .location
534            .as_ref()
535            .ok_or_else(|| Error::invalid(format!("heif: item {id} has no `iloc` entry")))?;
536        let src: &'a [u8] = match loc.construction_method {
537            0 => self.data,
538            1 => self.idat,
539            m => {
540                return Err(Error::unsupported(format!(
541                    "heif: item {id} uses iloc construction method {m}"
542                )))
543            }
544        };
545        let extent = |&(off, len): &(u64, u64)| -> Result<&'a [u8]> {
546            let start = loc
547                .base_offset
548                .checked_add(off)
549                .filter(|&s| s <= src.len() as u64)
550                .ok_or_else(|| Error::invalid(format!("heif: item {id} extent out of range")))?;
551            let end = if len == 0 {
552                src.len() as u64
553            } else {
554                start
555                    .checked_add(len)
556                    .filter(|&e| e <= src.len() as u64)
557                    .ok_or_else(|| Error::invalid(format!("heif: item {id} extent out of range")))?
558            };
559            Ok(&src[start as usize..end as usize])
560        };
561        let total: u64 = loc
562            .extents
563            .iter()
564            .map(|e| extent(e).map(|s| s.len() as u64))
565            .sum::<Result<u64>>()?;
566        if total > self.limits.max_item_bytes {
567            return Err(Error::invalid(format!(
568                "heif: item {id} is {total} bytes, over the {} byte limit",
569                self.limits.max_item_bytes
570            )));
571        }
572        match loc.extents.as_slice() {
573            [] => Ok(Cow::Borrowed(&[])),
574            [one] => Ok(Cow::Borrowed(extent(one)?)),
575            many => {
576                let mut v = Vec::with_capacity(total as usize);
577                for e in many {
578                    v.extend_from_slice(extent(e)?);
579                }
580                Ok(Cow::Owned(v))
581            }
582        }
583    }
584
585    /// Parse item `id` as a `grid` descriptor, checked against [`Limits`].
586    pub fn grid(&self, id: u32) -> Result<Grid> {
587        let data = self.item_data(id)?;
588        let mut r = Rd::new(&data, "grid");
589        let _version = r.u8()?;
590        let flags = r.u8()?;
591        let rows = r.u8()? as u32 + 1;
592        let columns = r.u8()? as u32 + 1;
593        let field = if flags & 1 != 0 { 4 } else { 2 };
594        let output_width = r.uint(field)? as u32;
595        let output_height = r.uint(field)? as u32;
596        if rows * columns > self.limits.max_grid_tiles {
597            return Err(Error::invalid(format!(
598                "heif: grid of {rows}x{columns} tiles is over the limit"
599            )));
600        }
601        self.check_size(output_width, output_height)?;
602        Ok(Grid {
603            rows,
604            columns,
605            output_width,
606            output_height,
607        })
608    }
609
610    /// Parse item `id` as an `iovl` descriptor, checked against [`Limits`].
611    pub fn overlay(&self, id: u32) -> Result<Overlay> {
612        let inputs = self.refs_from(id, b"dimg").len();
613        let data = self.item_data(id)?;
614        let mut r = Rd::new(&data, "iovl");
615        let _version = r.u8()?;
616        let flags = r.u8()?;
617        let mut fill = [0u16; 4];
618        for f in &mut fill {
619            *f = r.u16()?;
620        }
621        let field = if flags & 1 != 0 { 4 } else { 2 };
622        let output_width = r.uint(field)? as u32;
623        let output_height = r.uint(field)? as u32;
624        self.check_size(output_width, output_height)?;
625        let mut offsets = Vec::with_capacity(inputs.min(r.rest().len() / (2 * field)));
626        for _ in 0..inputs {
627            let (x, y) = if field == 4 {
628                (r.u32()? as i32, r.u32()? as i32)
629            } else {
630                (r.u16()? as i16 as i32, r.u16()? as i16 as i32)
631            };
632            offsets.push((x, y));
633        }
634        Ok(Overlay {
635            fill,
636            output_width,
637            output_height,
638            offsets,
639        })
640    }
641
642    /// Refuse an image size outside [`Limits`] (or empty).
643    pub fn check_size(&self, w: u32, h: u32) -> Result<()> {
644        if w == 0 || h == 0 {
645            return Err(Error::invalid(format!("heif: empty image {w}x{h}")));
646        }
647        if w > self.limits.max_dimension
648            || h > self.limits.max_dimension
649            || w as u64 * h as u64 > self.limits.max_pixels
650        {
651            return Err(Error::invalid(format!(
652                "heif: image {w}x{h} is over the size limit"
653            )));
654        }
655        Ok(())
656    }
657
658    /// True if the brands say this file holds HEIF still images (`mif1`,
659    /// `heic`, ...), as opposed to only image sequences (`msf1`).
660    pub fn has_brand(&self, brand: &[u8; 4]) -> bool {
661        &self.major_brand == brand || self.compatible_brands.contains(brand)
662    }
663}
664
665fn parse_iinf(p: &[u8], limits: &Limits) -> Result<Vec<Item>> {
666    let mut r = Rd::new(p, "iinf");
667    let (v, _) = r.full()?;
668    let count = if v == 0 { r.u16()? as u32 } else { r.u32()? };
669    if count > limits.max_items {
670        return Err(Error::invalid(format!(
671            "heif: {count} items is over the limit"
672        )));
673    }
674    let mut items = Vec::with_capacity((count as usize).min(r.rest().len() / 12));
675    for (t, infe) in child_boxes(r.rest()) {
676        if &t != b"infe" {
677            continue;
678        }
679        if items.len() as u32 >= count {
680            break;
681        }
682        let mut r = Rd::new(infe, "infe");
683        let (v, flags) = r.full()?;
684        let mut item = Item {
685            id: 0,
686            item_type: [0; 4],
687            name: String::new(),
688            content_type: None,
689            hidden: flags & 1 != 0,
690            location: None,
691            properties: Vec::new(),
692        };
693        match v {
694            0 | 1 => {
695                item.id = r.u16()? as u32;
696                r.u16()?; // protection index
697                item.name = r.cstr();
698                item.content_type = Some(r.cstr());
699            }
700            2 | 3 => {
701                item.id = if v == 2 { r.u16()? as u32 } else { r.u32()? };
702                r.u16()?; // protection index
703                item.item_type = r.fourcc()?;
704                item.name = r.cstr();
705                if &item.item_type == b"mime" {
706                    item.content_type = Some(r.cstr());
707                }
708            }
709            _ => continue, // a future version: unknown layout, skip the item
710        }
711        items.push(item);
712    }
713    Ok(items)
714}
715
716fn parse_iloc(p: &[u8], limits: &Limits) -> Result<Vec<(u32, Location)>> {
717    let mut r = Rd::new(p, "iloc");
718    let (v, _) = r.full()?;
719    if v > 2 {
720        return Err(Error::unsupported(format!("heif: iloc version {v}")));
721    }
722    let a = r.u8()?;
723    let b = r.u8()?;
724    let (offset_size, length_size) = ((a >> 4) as usize, (a & 15) as usize);
725    let base_offset_size = (b >> 4) as usize;
726    let index_size = if v >= 1 { (b & 15) as usize } else { 0 };
727    for s in [offset_size, length_size, base_offset_size, index_size] {
728        if !matches!(s, 0 | 4 | 8) {
729            return Err(Error::invalid(format!("heif: iloc field size {s}")));
730        }
731    }
732    let count = if v < 2 { r.u16()? as u32 } else { r.u32()? };
733    if count > limits.max_items {
734        return Err(Error::invalid(format!(
735            "heif: {count} iloc entries is over the limit"
736        )));
737    }
738    let mut out = Vec::with_capacity((count as usize).min(r.rest().len() / 6));
739    for _ in 0..count {
740        let id = if v < 2 { r.u16()? as u32 } else { r.u32()? };
741        let construction_method = if v >= 1 { (r.u16()? & 15) as u8 } else { 0 };
742        let data_ref = r.u16()?;
743        let base_offset = r.uint(base_offset_size)?;
744        let extent_count = r.u16()? as u32;
745        if extent_count > limits.max_extents {
746            return Err(Error::invalid(format!(
747                "heif: item {id} has {extent_count} extents, over the limit"
748            )));
749        }
750        let per = index_size + offset_size + length_size;
751        let mut extents =
752            Vec::with_capacity((extent_count as usize).min(r.rest().len() / per.max(1)));
753        for _ in 0..extent_count {
754            r.uint(index_size)?;
755            let off = r.uint(offset_size)?;
756            let len = r.uint(length_size)?;
757            extents.push((off, len));
758        }
759        if data_ref != 0 {
760            // Data in another file: not reachable from a single buffer.
761            continue;
762        }
763        out.push((
764            id,
765            Location {
766                construction_method,
767                base_offset,
768                extents,
769            },
770        ));
771    }
772    Ok(out)
773}
774
775fn parse_iref(p: &[u8], limits: &Limits) -> Result<Vec<Reference>> {
776    let mut r = Rd::new(p, "iref");
777    let (v, _) = r.full()?;
778    let mut out = Vec::new();
779    let mut total = 0u32;
780    for (kind, body) in child_boxes(r.rest()) {
781        let mut r = Rd::new(body, "iref");
782        let id = |r: &mut Rd| -> Result<u32> {
783            if v == 0 {
784                Ok(r.u16()? as u32)
785            } else {
786                r.u32()
787            }
788        };
789        let from = id(&mut r)?;
790        let n = r.u16()? as u32;
791        total = total.saturating_add(n);
792        if total > limits.max_items.saturating_mul(4) {
793            return Err(Error::invalid("heif: too many item references"));
794        }
795        let mut to = Vec::with_capacity(n as usize);
796        for _ in 0..n {
797            to.push(id(&mut r)?);
798        }
799        out.push(Reference { kind, from, to });
800    }
801    Ok(out)
802}
803
804fn parse_ipma(p: &[u8], limits: &Limits, file: &mut HeifFile) -> Result<()> {
805    let mut r = Rd::new(p, "ipma");
806    let (v, flags) = r.full()?;
807    let count = r.u32()?;
808    if count > limits.max_items {
809        return Err(Error::invalid(format!(
810            "heif: {count} ipma entries is over the limit"
811        )));
812    }
813    for _ in 0..count {
814        let id = if v < 1 { r.u16()? as u32 } else { r.u32()? };
815        let n = r.u8()?;
816        let mut props = Vec::with_capacity(n as usize);
817        for _ in 0..n {
818            let (essential, index) = if flags & 1 != 0 {
819                let x = r.u16()?;
820                (x & 0x8000 != 0, (x & 0x7fff) as usize)
821            } else {
822                let x = r.u8()?;
823                (x & 0x80 != 0, (x & 0x7f) as usize)
824            };
825            // Index 0 means "no property"; the rest are 1-based into ipco.
826            if index > 0 {
827                props.push((index - 1, essential));
828            }
829        }
830        if let Some(it) = file.items.iter_mut().find(|it| it.id == id) {
831            it.properties.extend(props);
832        }
833    }
834    Ok(())
835}
836
837fn parse_property<'a>(t: [u8; 4], p: &'a [u8]) -> Result<Property<'a>> {
838    Ok(match &t {
839        b"ispe" => {
840            let mut r = Rd::new(p, "ispe");
841            r.full()?;
842            Property::Ispe {
843                width: r.u32()?,
844                height: r.u32()?,
845            }
846        }
847        b"hvcC" => Property::HvcC(p),
848        b"av1C" => Property::Av1C(p),
849        b"colr" => {
850            let mut r = Rd::new(p, "colr");
851            match &r.fourcc()? {
852                b"nclx" => {
853                    let primaries = r.u16()?;
854                    let transfer = r.u16()?;
855                    let matrix = r.u16()?;
856                    let full_range = r.u8()? & 0x80 != 0;
857                    Property::Colr(Colour::Nclx {
858                        primaries,
859                        transfer,
860                        matrix,
861                        full_range,
862                    })
863                }
864                b"rICC" | b"prof" => Property::Colr(Colour::Icc(r.rest())),
865                _ => Property::Other(t),
866            }
867        }
868        b"irot" => Property::Irot(Rd::new(p, "irot").u8()? & 3),
869        b"imir" => Property::Imir(Rd::new(p, "imir").u8()? & 1),
870        b"clap" => {
871            let mut r = Rd::new(p, "clap");
872            let mut f = [0i64; 8];
873            for (i, x) in f.iter_mut().enumerate() {
874                let v = r.u32()?;
875                // Widths/heights and denominators are unsigned; the two
876                // offset numerators are signed.
877                *x = if i == 4 || i == 6 {
878                    v as i32 as i64
879                } else {
880                    v as i64
881                };
882            }
883            Property::Clap(Clap {
884                width: (f[0], f[1]),
885                height: (f[2], f[3]),
886                horiz_off: (f[4], f[5]),
887                vert_off: (f[6], f[7]),
888            })
889        }
890        b"pixi" => {
891            let mut r = Rd::new(p, "pixi");
892            r.full()?;
893            let n = r.u8()? as usize;
894            Property::Pixi(r.take(n)?.to_vec())
895        }
896        b"auxC" => {
897            let mut r = Rd::new(p, "auxC");
898            r.full()?;
899            let aux_type = r.cstr();
900            Property::AuxC {
901                aux_type,
902                subtype: r.rest(),
903            }
904        }
905        _ => Property::Other(t),
906    })
907}
908
909// ===========================================================================
910// Well-known auxiliary-image types
911// ===========================================================================
912
913/// `auxC` URNs that mark an alpha plane.
914pub const ALPHA_URNS: &[&str] = &[
915    "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha",
916    "urn:mpeg:hevc:2015:auxid:1",
917    "urn:mpeg:avc:2015:auxid:1",
918];
919
920/// `auxC` URNs that mark a depth map.
921pub const DEPTH_URNS: &[&str] = &[
922    "urn:mpeg:mpegB:cicp:systems:auxiliary:depth",
923    "urn:mpeg:hevc:2015:auxid:2",
924    "urn:mpeg:avc:2015:auxid:2",
925];
926
927/// True if `urn` is an alpha `auxC` type.
928pub fn is_alpha_urn(urn: &str) -> bool {
929    ALPHA_URNS.contains(&urn)
930}
931
932/// True if `urn` is a depth `auxC` type.
933pub fn is_depth_urn(urn: &str) -> bool {
934    DEPTH_URNS.contains(&urn)
935}
936
937#[cfg(test)]
938mod tests {
939    use super::*;
940
941    fn bx(t: &[u8; 4], body: &[u8]) -> Vec<u8> {
942        let mut v = ((8 + body.len()) as u32).to_be_bytes().to_vec();
943        v.extend_from_slice(t);
944        v.extend_from_slice(body);
945        v
946    }
947
948    fn full(t: &[u8; 4], ver: u8, flags: u32, body: &[u8]) -> Vec<u8> {
949        let mut b = vec![ver];
950        b.extend_from_slice(&flags.to_be_bytes()[1..]);
951        b.extend_from_slice(body);
952        bx(t, &b)
953    }
954
955    /// A minimal two-item file: a 2x1 grid (in `idat`) over two `hvc1`
956    /// tiles, one with a thumbnail and an Exif item.
957    fn sample() -> Vec<u8> {
958        let mut infe = Vec::new();
959        for (id, t, hidden) in [
960            (1u16, b"grid", 0u32),
961            (2, b"hvc1", 1),
962            (3, b"hvc1", 1),
963            (4, b"Exif", 0),
964        ] {
965            let mut b = id.to_be_bytes().to_vec();
966            b.extend_from_slice(&[0, 0]);
967            b.extend_from_slice(t);
968            b.push(0);
969            infe.extend_from_slice(&full(b"infe", 2, hidden, &b));
970        }
971        let mut iinf = 4u16.to_be_bytes().to_vec();
972        iinf.extend_from_slice(&infe);
973        let iinf = full(b"iinf", 0, 0, &iinf);
974
975        let grid = [0u8, 0, 0, 1, 0, 100, 0, 50];
976        let idat = bx(b"idat", &grid);
977
978        // iloc v1: offset 4, length 4, base 0, index 0.
979        let mut il = vec![0x44, 0x00];
980        il.extend_from_slice(&4u16.to_be_bytes());
981        let entry = |id: u16, cm: u16, off: u32, len: u32| {
982            let mut e = id.to_be_bytes().to_vec();
983            e.extend_from_slice(&cm.to_be_bytes());
984            e.extend_from_slice(&0u16.to_be_bytes());
985            e.extend_from_slice(&1u16.to_be_bytes());
986            e.extend_from_slice(&off.to_be_bytes());
987            e.extend_from_slice(&len.to_be_bytes());
988            e
989        };
990        il.extend_from_slice(&entry(1, 1, 0, 8));
991        il.extend_from_slice(&entry(2, 0, 0, 4));
992        il.extend_from_slice(&entry(3, 0, 4, 4));
993        il.extend_from_slice(&entry(4, 0, 8, 0));
994        let iloc = full(b"iloc", 1, 0, &il);
995
996        let mut dimg = 1u16.to_be_bytes().to_vec();
997        dimg.extend_from_slice(&2u16.to_be_bytes());
998        dimg.extend_from_slice(&2u16.to_be_bytes());
999        dimg.extend_from_slice(&3u16.to_be_bytes());
1000        let mut cdsc = 4u16.to_be_bytes().to_vec();
1001        cdsc.extend_from_slice(&1u16.to_be_bytes());
1002        cdsc.extend_from_slice(&1u16.to_be_bytes());
1003        let iref = full(
1004            b"iref",
1005            0,
1006            0,
1007            &[bx(b"dimg", &dimg), bx(b"cdsc", &cdsc)].concat(),
1008        );
1009
1010        let ispe = full(
1011            b"ispe",
1012            0,
1013            0,
1014            &[&100u32.to_be_bytes()[..], &50u32.to_be_bytes()].concat(),
1015        );
1016        let irot = bx(b"irot", &[1]);
1017        let ipco = bx(b"ipco", &[ispe, irot].concat());
1018        let mut ipma = 1u32.to_be_bytes().to_vec();
1019        ipma.extend_from_slice(&1u16.to_be_bytes());
1020        ipma.extend_from_slice(&[2, 1, 0x82]);
1021        let ipma = full(b"ipma", 0, 0, &ipma);
1022        let iprp = bx(b"iprp", &[ipco, ipma].concat());
1023
1024        let pitm = full(b"pitm", 0, 0, &1u16.to_be_bytes());
1025        let meta = full(
1026            b"meta",
1027            0,
1028            0,
1029            &[pitm, iinf, iloc, iref, iprp, idat].concat(),
1030        );
1031        let ftyp = bx(b"ftyp", b"heic\0\0\0\0mif1heic");
1032        let head = [ftyp, meta].concat();
1033        // The file-offset extents above are relative to the file start, so
1034        // place the mdat bytes at offset 0..12 by prefixing... instead, put
1035        // them after the head and rebase: here we just append and let the
1036        // test read item 4 (to-end) to prove the length-0 rule.
1037        [head, bx(b"mdat", b"AAAABBBBexif")].concat()
1038    }
1039
1040    #[test]
1041    fn parses_items_refs_properties() {
1042        let data = sample();
1043        let f = HeifFile::parse(&data, Limits::default()).unwrap();
1044        assert_eq!(&f.major_brand, b"heic");
1045        assert!(f.has_brand(b"mif1"));
1046        assert_eq!(f.primary, Some(1));
1047        assert_eq!(f.items.len(), 4);
1048        assert!(f.item(2).unwrap().hidden);
1049        assert_eq!(f.refs_from(1, b"dimg"), vec![2, 3]);
1050        assert_eq!(f.refs_to(1, b"cdsc"), vec![4]);
1051        assert_eq!(f.ispe(1), Some((100, 50)));
1052        let props: Vec<_> = f.properties_of(1).collect();
1053        assert_eq!(props.len(), 2);
1054        assert_eq!(props[1], (&Property::Irot(1), true));
1055        let g = f.grid(1).unwrap();
1056        assert_eq!(
1057            (g.rows, g.columns, g.output_width, g.output_height),
1058            (1, 2, 100, 50)
1059        );
1060        // File-offset extents: item 2 is bytes 0..4 of the file (the ftyp
1061        // size field), item 4 runs from offset 8 to the end.
1062        assert_eq!(&f.item_data(2).unwrap()[..], &data[0..4]);
1063        assert_eq!(f.item_data(4).unwrap().len(), data.len() - 8);
1064    }
1065
1066    #[test]
1067    fn truncation_is_an_error_at_every_length() {
1068        let data = sample();
1069        for n in 0..data.len() {
1070            // Never a panic; a short buffer may still parse (boxes past the
1071            // end are dropped), but every accessor must stay in bounds.
1072            if let Ok(f) = HeifFile::parse(&data[..n], Limits::default()) {
1073                for it in &f.items {
1074                    let _ = f.item_data(it.id);
1075                    let _ = f.grid(it.id);
1076                    let _ = f.overlay(it.id);
1077                }
1078            }
1079        }
1080    }
1081
1082    #[test]
1083    fn hostile_counts_are_refused_not_allocated() {
1084        // iinf claiming 4 billion items.
1085        let iinf = full(b"iinf", 1, 0, &u32::MAX.to_be_bytes());
1086        let meta = full(b"meta", 0, 0, &iinf);
1087        let data = [bx(b"ftyp", b"heic\0\0\0\0"), meta].concat();
1088        assert!(HeifFile::parse(&data, Limits::default()).is_err());
1089        // iloc with a 3-byte offset field.
1090        let iloc = full(b"iloc", 0, 0, &[0x34, 0x00, 0, 0]);
1091        let meta = full(b"meta", 0, 0, &iloc);
1092        let data = [bx(b"ftyp", b"heic\0\0\0\0"), meta].concat();
1093        assert!(HeifFile::parse(&data, Limits::default()).is_err());
1094    }
1095
1096    #[test]
1097    fn clap_rect_matches_libheif_rounding() {
1098        // Centred 300x300 crop of a 1280x720 image.
1099        let c = Clap {
1100            width: (300, 1),
1101            height: (300, 1),
1102            horiz_off: (0, 1),
1103            vert_off: (0, 1),
1104        };
1105        assert_eq!(c.rect(1280, 720), Some((490, 210, 300, 300)));
1106        // A zero denominator is refused; an over-wide aperture is clamped
1107        // to the image, as libheif does.
1108        let bad = Clap {
1109            width: (300, 0),
1110            ..c
1111        };
1112        assert_eq!(bad.rect(1280, 720), None);
1113        let big = Clap {
1114            width: (2000, 1),
1115            ..c
1116        };
1117        assert_eq!(big.rect(1280, 720), Some((0, 210, 1280, 300)));
1118        // Odd: a 3-wide aperture centred in a 4-wide image.
1119        let odd = Clap {
1120            width: (3, 1),
1121            height: (1, 1),
1122            horiz_off: (0, 1),
1123            vert_off: (0, 1),
1124        };
1125        assert_eq!(odd.rect(4, 1), Some((0, 0, 3, 1)));
1126    }
1127}