Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ craft-ecproj-format = { path = "crates/ecproj-format" }
craft-font-catalog = { path = "crates/font-catalog" }
craft-font-manager = { path = "crates/font-manager" }
craft-font-store = { path = "crates/font-store" }
craft-heif = { path = "crates/heif" }
craft-fonts-build = { path = "crates/fonts-build" }
craft-i18n = { path = "crates/i18n" }
craft-jpeg = { path = "crates/jpeg" }
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ craft-<name> = { git = "https://github.com/storytold/craft-libs", rev = "<commit
- [`craft-fonts-build`](crates/fonts-build/README.md): embeds the optional craft-fonts faces
from an app's `build.rs` (`CRAFT_FONTS_DIR`, `CRAFT_FONTS_REQUIRED`, script filters) as a table
of `EmbeddedFace`s. No dependencies; the app picks the faces.
- [`craft-heif`](crates/heif/README.md): optional HEIF/HEIC still-image decoder, from LightCraft:
heic-rs reads the container and HEVC pictures, and this crate converts to 16-bit RGB to match
libheif (VUI range and matrix, chroma upsampling, `imir`, ICC on grid tiles). Also orientation,
alpha, EXIF/XMP and thumbnails. It never panics, and apps put it behind a non-default feature.
- [`craft-i18n`](crates/i18n/README.md): translations over the embedded craft-i18n catalogs:
lookup with fallback (`pt-br` → `pt` → English), plurals, language names, the system locale and
a pseudo locale. The catalogs stay a fully optional build input; apps keep `tl!` and their
Expand Down
27 changes: 27 additions & 0 deletions crates/heif/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[package]
name = "craft-heif"
description = "Optional HEIF/HEIC still-image decoder: heic-rs for the container and HEVC, libheif-matching colour conversion, panic-guarded."
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true

[dependencies]
# Pure Rust, no unsafe. Pinned exactly: a young, single-owner crate that parses untrusted files;
# moving the pin is a reviewed change (re-run these tests and each app's HEIF corpus tests).
# heic-rs was chosen over the other permissive candidates (heif-oxide's HEVC decoder, rust_h265, follows FFmpeg's (LGPL)
# code structure; gamut-heic has no HEVC decoder of its own).
heic-rs = { version = "=0.1.4", default-features = false, features = ["std"] }

# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"] }
rayon = { workspace = true }

[features]
# `craft_heif::testdata`: lossless synthetic HEIF files, for the tests of the crates above.
testdata = []

[lints]
workspace = true
47 changes: 47 additions & 0 deletions crates/heif/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# craft-heif

An optional HEIF / HEIC decoder for iPhone and Mac photos, shared by LightCraft and PhotoCraft. It was moved from
LightCraft's `lightcraft-heif`. [`heic-rs`](https://github.com/tbraun96/heic-rs)
(pure Rust, no `unsafe`, MIT OR Apache-2.0, written from the H.265 / HEIF specifications) reads the
container and reconstructs the HEVC pictures; this crate turns them into 16-bit RGB itself so the
result matches libheif to within one code value:

- the colour description is the item's `colr nclx` (or its first tile's), else the HEVC VUI
(iPhones: full range), else the H.265 defaults; an unspecified matrix is BT.601. heic-rs alone
assumes BT.709 limited range, about 8 code values off on every iPhone photo;
- chroma is upsampled by nearest neighbour, or centred bilinear when a `clap` starts on an odd
pixel, as libheif does;
- `imir` axis 0 flips top and bottom, as libheif writes and reads it (heic-rs names it the other way);
- a grid's ICC profile may sit on its tiles.

Single pictures and grid-tiled photos, 4:2:0 and monochrome, 8- to 10-bit, alpha auxiliary images
(other auxiliary images — HDR gain maps, depth — are ignored), the container's rotation/mirror/crop,
ICC, EXIF and XMP, and the file's thumbnail item. 4:2:2 and 4:4:4 (Canon/Sony "HIF") are refused
with `Error::Unsupported`: heic-rs 0.1.1 loses sync on them. Read-only.

```rust
let info = craft_heif::probe(&bytes)?; // size, depth, alpha: check limits first
let img = craft_heif::decode(&bytes, &craft_heif::Options::default())?;
// img.width, img.height, img.has_alpha, img.bit_depth, img.data (RGB/RGBA u16), img.colour, img.icc, img.exif, img.xmp
let thumb = craft_heif::decode_thumbnail(&bytes, 256, &Default::default())?; // Option<Decoded>
```

Errors are `Error::Unsupported` (image sequences, overlays, 4:2:2/4:4:4, …), `Error::Limit` or
`Error::Malformed`. It never panics: every call into heic-rs runs under `catch_unwind`, and a panic
inside it (PhotoCraft's fuzzing found two in 0.1.1) becomes `Error::Malformed`.

Feature `testdata` exposes `craft_heif::testdata`: lossless synthetic HEIF files (PCM-coded
32 × 32 HEVC pictures, grids, every property above) for the tests of the crates above.

## Why it is a separate, optional crate

- **A young decoder.** heic-rs is new and has a single maintainer. It is pinned exactly
(`=0.1.4`); moving the pin is a reviewed change (re-run the crate tests and each app's HEIF tests,
e.g. `cargo test -p lightcraft-codecs --features heif`). The other permissive candidates were
rejected: heif-oxide's HEVC decoder (rust_h265) follows FFmpeg's (LGPL) code structure, and
gamut-heic has no HEVC decoder of its own.
- **HEVC patents are a distributor's call.** Apps use this crate only behind a non-default
`heif` feature, which their release packages enable. Without it, HEIC files are still
recognised, and opening one gives a clear "HEIC/HEIF support isn't included in this build" error.

The crate depends on no other Craft crate.
122 changes: 122 additions & 0 deletions crates/heif/src/census.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
//! Caps on the container's metadata boxes, counted before heic-rs touches the file.
//!
//! heic-rs 0.1.4 (pinned `=0.1.4`) has no aggregate work budget inside its container parsing:
//! every `ipma` association entry rescans the vector of already-seen item ids (quadratic in
//! the number of entries), and an `iloc` extent using construction method 2 reconstructs its
//! source item afresh for every extent that references it, with no shared cache. Legitimate
//! phone-photo metadata never comes near these caps — real corpora keep both well under a few
//! kilobytes — so anything above them is hostile or corrupt and is refused before the
//! countable CPU work happens.
//!
//! [`depth_boxes`] stops silently at structural blips: heic-rs's own parser reports those
//! better than this walk could, and an `ipma` box past the cap is caught wherever it parses.

use heic_rs::boxes::BoxIter;

use crate::Error;

/// The largest `ipma` box (item ↔ property associations) payload accepted, 64 KiB. An entry
/// costs at least 3 bytes, so this bounds heic-rs's per-entry rescan of earlier item ids to
/// ~21 000 entries ≈ 220 million comparisons: long enough to be annoying, never minutes.
const MAX_IPMA_BYTES: usize = 64 << 10;

/// The largest `iloc` box (item locations) payload accepted, 64 KiB. An extent costs at least
/// 12 bytes, so this bounds both the parse itself and how many extents a
/// construction-method-2 reconstruction chain can visit.
const MAX_ILOC_BYTES: usize = 64 << 10;

/// Falls through unless the container declares more `ipma` or `iloc` payload than a
/// legitimate phone photo ever does.
pub fn cap(bytes: &[u8]) -> Result<(), Error> {
let mut c = Census::default();
depth_boxes(&mut c, BoxIter::new(bytes), 0);
if c.ipma > MAX_IPMA_BYTES {
return Err(Error::Limit(format!("the image carries {} bytes of property associations, over the {MAX_IPMA_BYTES}-byte cap", c.ipma)));
}
if c.iloc > MAX_ILOC_BYTES {
return Err(Error::Limit(format!("the image carries {} bytes of item locations, over the {MAX_ILOC_BYTES}-byte cap", c.iloc)));
}
Ok(())
}

/// The metadata-box payload sizes seen so far.
#[derive(Default)]
struct Census {
ipma: usize,
iloc: usize,
}

/// Walks boxes, adding the payload sizes of those named in [`Census`].
///
/// Only `meta` and `iprp` (the two nesting boxes the metadata is built from) are descended
/// into, no deeper than that depth, so a nested-box trick can't hide a box from the count.
fn depth_boxes(c: &mut Census, boxes: BoxIter<'_>, depth: u32) {
if depth > 3 {
return;
}
for b in boxes {
// A structural error stops the walk; `heic_rs::probe` reports it properly afterwards.
let Ok(b) = b else { return };
if b.is(b"ipma") {
c.ipma = c.ipma.saturating_add(b.payload.len());
} else if b.is(b"iloc") {
c.iloc = c.iloc.saturating_add(b.payload.len());
} else if b.is(b"meta") {
// `meta` is a FullBox: version and flags sit between its header and its children.
if b.payload.len() >= 4 {
depth_boxes(c, BoxIter::new(&b.payload[4..]), depth + 1);
}
} else if b.is(b"iprp") {
depth_boxes(c, b.children(), depth + 1);
}
}
}

#[cfg(test)]
mod tests {
use super::*;

/// Assembles ftyp + meta(version/flags + iprp(ipco, ipma)) by hand; only the structure
/// the census walks matters, no item is ever defined.
fn file_with(ipma_payload: &[u8]) -> Vec<u8> {
let mut out = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic".to_vec();
let mut iprp = Vec::new();
iprp.extend(box_of(b"ipco", b""));
iprp.extend(box_of(b"ipma", ipma_payload));
let mut meta = vec![0u8, 0, 0, 0]; // version 0, flags 0
meta.extend(box_of(b"iprp", &iprp));
out.extend(box_of(b"meta", &meta));
out
}

fn box_of(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(8 + body.len());
let size = u32::try_from(8 + body.len()).expect("test box fits in u32");
out.extend_from_slice(&size.to_be_bytes());
out.extend_from_slice(kind);
out.extend_from_slice(body);
out
}

#[test]
fn an_oversized_ipma_is_refused() {
// 40 000 entries of 6 bytes: 240 KiB of ipma, far over the cap, and quadratic if
// parsed (each entry rescans the earlier item ids in heic-rs 0.1.4).
let mut ipma = Vec::new();
for _ in 0..40_000u32 {
ipma.extend_from_slice(&[0u8, 0, 0, 0, 0, 0]);
}
let bytes = file_with(&ipma);
let r = crate::probe(&bytes).map(|_| ());
assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("associations")), "{r:?}");
}

#[test]
fn a_undersized_ipma_is_untouched_by_the_caps() {
// The same shape with a normal ipma (two entries): the caps pass, and whatever error
// follows must not come from them.
let bytes = file_with(&[0, 0, 4, 1, 1, 2, 0, 0]);
let r = crate::probe(&bytes);
assert!(!matches!(r, Err(Error::Limit(ref m)) if m.contains("cap")), "{r:?}");
}
}
Loading
Loading