1use std::borrow::Cow;
28
29use rff_core::{Error, Result};
30
31pub 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 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
69pub 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
74struct 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub struct Limits {
159 pub max_items: u32,
161 pub max_extents: u32,
163 pub max_item_bytes: u64,
165 pub max_dimension: u32,
167 pub max_pixels: u64,
169 pub max_grid_tiles: u32,
171 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 max_pixels: 1 << 28,
184 max_grid_tiles: 65_536,
185 max_derivation_depth: 8,
186 }
187 }
188}
189
190#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct Location {
197 pub construction_method: u8,
199 pub base_offset: u64,
200 pub extents: Vec<(u64, u64)>,
202}
203
204#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct Item {
207 pub id: u32,
208 pub item_type: [u8; 4],
210 pub name: String,
211 pub content_type: Option<String>,
213 pub hidden: bool,
215 pub location: Option<Location>,
216 pub properties: Vec<(usize, bool)>,
219}
220
221#[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 Icc(&'a [u8]),
232}
233
234#[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 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#[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 fn trunc(self) -> i64 {
285 (self.0 / self.1) as i64
286 }
287 fn round(self) -> i64 {
289 ((self.0 + self.1 / 2) / self.1) as i64
290 }
291}
292
293fn 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#[derive(Debug, Clone, PartialEq, Eq)]
312pub enum Property<'a> {
313 Ispe {
315 width: u32,
316 height: u32,
317 },
318 HvcC(&'a [u8]),
320 Av1C(&'a [u8]),
322 Colr(Colour<'a>),
323 Irot(u8),
325 Imir(u8),
328 Clap(Clap),
329 Pixi(Vec<u8>),
331 AuxC {
333 aux_type: String,
334 subtype: &'a [u8],
335 },
336 Other([u8; 4]),
338}
339
340#[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#[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#[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#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct Overlay {
377 pub fill: [u16; 4],
379 pub output_width: u32,
380 pub output_height: u32,
381 pub offsets: Vec<(i32, i32)>,
383}
384
385impl<'a> HeifFile<'a> {
386 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()?; 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 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 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 pub fn item(&self, id: u32) -> Option<&Item> {
463 self.items.iter().find(|it| it.id == id)
464 }
465
466 pub fn primary_item(&self) -> Option<&Item> {
468 self.primary.and_then(|id| self.item(id))
469 }
470
471 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 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 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 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 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 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 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 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 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 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 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()?; 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()?; 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, }
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 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 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 *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
909pub 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
920pub 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
927pub fn is_alpha_urn(urn: &str) -> bool {
929 ALPHA_URNS.contains(&urn)
930}
931
932pub 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 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 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 [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 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 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 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 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 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 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 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}