This document is the practical API reference for integrating heic_decoder in apps and automation.
- Decode HEIF/HEIC/AVIF to RGBA (
u8oru16storage). - Decode HEVC-coded HEIC/HEIF straight to RGB8 when alpha is not needed.
- Decode HEVC-coded HEIC within a memory budget to a size-capped, display-oriented sRGB RGB8 image (
decode_bounded), or with the smallest working memory at a lower speed (decode_bounded_tiny). - Decode from bytes,
Read,BufRead, and file paths. - Optional
imagecrate integration through hook registration. - Keep default decode output aligned with primary item transforms (
clap/irot/imir) and expose explicit EXIF orientation helpers.
default:std,parallel-gridandavif.image-integration: enablesheic_decoder::image_integrationmodule and hook APIs.avif(default): AVIF decoding through rav1d. Without it, AVIF decodes returnDecodeAvifError::DecoderUnavailable, theimagehooks leave files with theaviforavismajor brand to other decoders, and with default features off the crate builds for 32-bit targets without 64-bit atomics, such asxtensa-esp32s3-espidf. An AVIF whose major brand ismif1,msf1ormiafstill matches the HEIF content signatures, sowith_guessed_formathands it to this crate and the decode returnsDecoderUnavailable; opened by its.avifextension without content guessing, it reaches another registered AVIF decoder.
Cargo.toml:
[dependencies]
heic_decoder = { path = "../heic-decoder" }With image integration:
[dependencies]
heic_decoder = { path = "../heic-decoder", features = ["image-integration"] }
image = { version = "0.25", default-features = false, features = ["png"] }DecodeGuardrailsmax_input_bytes: Option<u64>max_pixels: Option<u64>max_temp_spool_bytes: Option<u64>temp_spool_directory: Option<PathBuf>
DecodedRgbaImagewidth,heightsource_bit_depthpixels: DecodedRgbaPixels(U8(Vec<u8>)orU16(Vec<u16>))icc_profile: Option<Vec<u8>>
DecodedRgbImagewidth,heightsource_bit_depthpixels: Vec<u8>(RGB8 interleaved)icc_profile: Option<Vec<u8>>
ExifOrientationHintexif_orientation: Option<u8>primary_item_has_orientation_transform: boolshould_apply_exif_orientation()orientation_to_apply()
DecodeError,DecodeErrorCategory,DecodeGuardrailError
Return type for RGBA decode functions:
Result<DecodedRgbaImage, DecodeError>decode_bytes_to_rgba_with_guardrails(input, guardrails)decode_read_to_rgba_with_guardrails(reader, guardrails)decode_bufread_to_rgba_with_guardrails(bufread, guardrails)decode_path_to_rgba_with_guardrails(path, guardrails)
Non-guardrailed convenience variants also exist (decode_*_to_rgba) and use DecodeGuardrails::default().
For callers that only need RGB, such as pipelines that would otherwise call
DynamicImage::into_rgb8 on the RGBA result:
decode_bytes_to_rgb8_with_guardrails(input, guardrails)decode_path_to_rgb8_with_guardrails(path, guardrails)
Both return Result<DecodedRgbImage, DecodeError>. decode_bytes_to_rgb8 and
decode_path_to_rgb8 use DecodeGuardrails::default(). There are no
Read/BufRead variants.
Contract:
- Only HEVC-coded primary items (
hvc1/hev1, or agridof them) are supported. AVIF and uncompressed (unci) HEIF return an error; use the RGBA entry points for those. - Calling RGB8 is an explicit request to drop alpha. Auxiliary alpha is not
decoded and no RGBA buffer is allocated. On large images this roughly halves
peak memory compared with decoding RGBA and then calling
into_rgb8. pixelsholdswidth * height * 3bytes, row-major with no padding. Primary item transforms (clap/irot/imir) are applied and EXIF orientation is not, as with RGBA.DecodedRgbImagehas no orientation helper.- Output is always 8-bit;
source_bit_depthreports the coded bit depth. - When the RGBA decode of the same input succeeds,
pixelsis byte-for-byte equal to that RGBA output converted withDynamicImage::into_rgb8. For high-bit-depth input this means each RGBA16 samplevbecomes(v + 128) / 257. icc_profilematches the RGBA output's.
decode_bytes_to_png_with_guardrails(input, output_path, guardrails)decode_read_to_png_with_guardrails(reader, output_path, guardrails)decode_bufread_to_png_with_guardrails(bufread, output_path, guardrails)decode_path_to_png_with_guardrails(input_path, output_path, guardrails)
Legacy aliases:
decode_file_to_rgba->decode_path_to_rgbadecode_file_to_png->decode_path_to_png
These are useful for tooling and specialized pipelines, but most applications should use the core entry points above.
decode_primary_avif_to_image(input)->Result<DecodedAvifImage, DecodeAvifError>ycbcr_rangeandycbcr_matrixcome from the item'scolrnclx property, or from the AV1 sequence header when the item has none, as in libheif. Earlier versions reported full range with unspecified coefficients when the item had no nclx property, and the RGBA decode converted such items that way.
assemble_primary_heic_hevc_stream(input)->Result<Vec<u8>, DecodeHeicError>decode_primary_heic_to_image(input)->Result<DecodedHeicImage, DecodeHeicError>decode_primary_heic_to_metadata(input)->Result<DecodedHeicImageMetadata, DecodeHeicError>decode_primary_uncompressed_to_image(input)->Result<DecodedUncompressedImage, DecodeUncompressedError>
Also note:
isobmffandsourcemodules are public and available for advanced use.- These low-level APIs expose more container/codec details and have a larger surface for malformed-input handling.
Assembled HEVC streams are decoded with fixed four-byte length-prefixed framing. Streams whose first NAL unit is 1 byte or 256-511 bytes long were previously re-detected as Annex B start-code data, which could decode hidden parameter sets embedded anywhere in the stream and bypass pixel limits; such streams now decode strictly by their length prefixes and either decode their visible parameter sets or fail cleanly.
Use this decision order:
- If you already have
&[u8], usedecode_bytes_to_rgba_with_guardrails. - If you have a file path, use
decode_path_to_rgba_with_guardrails. - If you have
Read/BufRead(non-seek stream), usedecode_read_to_rgba_with_guardrailsordecode_bufread_to_rgba_with_guardrails.
Important behavior:
Read/BufReadinputs are spooled once to a temporary file to enable random-access decode.Pathand seekable decode paths avoid full-file in-memory buffering.
Use explicit guardrails in production.
Example preset:
use heic_decoder::DecodeGuardrails;
let guardrails = DecodeGuardrails {
max_input_bytes: Some(128 * 1024 * 1024),
max_pixels: Some(64_000_000),
max_temp_spool_bytes: Some(128 * 1024 * 1024),
temp_spool_directory: None,
};Notes:
max_input_bytesapplies to all entry points.max_temp_spool_bytesprotects non-seekRead/BufReadingestion.max_pixelschecks AV1 and HEVC coded frame area before pixel decoding, including auxiliary alpha frames and HEIC grid tiles. Container dimensions and post-decode geometry checks still apply.- Auxiliary alpha must match the primary's visible geometry. Its coded frame,
including any conformance-window padding, counts against
max_pixelsand the decoded-byte allowance below, so cropping cannot hide an oversized coded frame. - HEVC preflight estimates decoded planes and normalized bitstream storage. The byte allowance is 12 bytes per allowed pixel plus 64 MiB, with the primary area limiting auxiliary frames and the composed output area limiting grids. A grid dimension covered by a single tile row or column counts as at least 512 pixels when tiles are stacked along the other dimension, matching the fixed tile span encoders use for narrow images. Every grid tile, including the first, and the sum of all tile estimates must fit this allowance. This estimate is not a process RSS limit.
Top-level errors are DecodeError. Use category() for stable handling:
use heic_decoder::{DecodeError, DecodeErrorCategory};
fn classify(err: &DecodeError) -> DecodeErrorCategory {
err.category()
}Stable categories:
IoParseMalformedInputUnsupportedFeatureResourceLimitDecoderBackendOutputEncoding
Typical policy mapping:
ResourceLimit: return413/ reject input.MalformedInputorParse: return422.UnsupportedFeature: return415.IoorDecoderBackend: retry/fallback/log depending on context.
Inspect storage and branch explicitly:
use heic_decoder::DecodedRgbaPixels;
match &decoded.pixels {
DecodedRgbaPixels::U8(p) => {
// p: &[u8], RGBA8 interleaved
}
DecodedRgbaPixels::U16(p) => {
// p: &[u16], RGBA16 interleaved
}
}Helpers on DecodedRgbaImage / DecodedRgbaPixels:
storage_bit_depth()as_rgba8(),as_rgba16()into_rgba8(),into_rgba16()apply_exif_orientation(exif_orientation)
Default decode behavior:
- Decode applies HEIF primary item transforms from
clap/irot/imir. - Decode does not implicitly apply EXIF orientation.
- This keeps output stable for libheif parity and avoids hidden double-rotation behavior.
Container transforms follow libheif when they would split chroma samples. libheif converts a 4:2:0 or 4:2:2 image to 4:4:4 with bilinear chroma before any of these, each judged at the size the image has when it applies:
- a
clapwith an odd left edge, or on 4:2:0 an odd top edge; - on 4:2:0, an anticlockwise 90°
irotof an odd width, a 180°irotwith either side odd, an anticlockwise 270°irotof an odd height, or animirwith either side odd; - on 4:2:2, any 90° or 270°
irot, a 180°irotof an odd height, or a left-rightimir(axis 1) of an odd width.
The HEVC and AVIF decode paths do the same. Transforms before the conversion
run on the subsampled planes in property order, as in libheif; for example, a 180°
irot of an odd-width 4:2:2 image rotates its half-width chroma planes without
converting them. If the coded colour is limited range, the conversion then
passes the image through RGB to full-range 4:4:4, as libheif does. The coded
stream's colour drives that conversion: the HEVC VUI, or the AV1 sequence
header's color_config. A colr nclx property replaces it only after all
transforms. The same applies to primary items, to grids as a whole,
and to the clean apertures of individual grid tiles. A grid whose tile crops
convert some tiles but not others is rejected with DecodedLayoutMismatch,
because its tiles no longer share one chroma format; libheif rejects it too.
For primary items and whole grids, the 4:4:4 image is built a few rows at a
time while converting to RGB, so it is never held at full size. A grid that
needs the conversion, or a transform of its subsampled planes, is first
assembled into one canvas, which stays in memory alongside the output, instead
of being converted tile by tile. An 8-bit AVIF item that needs the conversion
has its planes widened to 16-bit samples first, which doubles the memory they
take during the decode. Image edges use clamped interpolation,
matching libheif after its 2026-10 border fix. The pinned libheif 1.21.2
validator differs on output rows or columns that keep an edge of the converted
image.
Orientation APIs:
exif_orientation_hint(input_bytes)->ExifOrientationHintexif_orientation_hint_from_path(input_path)->Result<ExifOrientationHint, DecodeError>primary_exif_orientation(input_bytes)->Option<u8>primary_exif_orientation_from_path(input_path)->Result<Option<u8>, DecodeError>primary_item_has_orientation_transform(input_bytes)->boolpath_extension_is_heif(path)->boolpath_extension_is_heif_family(path)->boolDecodedRgbaImage::apply_exif_orientation(exif_orientation)->Result<DecodedRgbaImage, DecodeError>
Recommended pattern:
use heic_decoder::{decode_path_to_rgba, exif_orientation_hint};
use std::path::Path;
fn decode_with_explicit_orientation(path: &Path) -> Result<(), heic_decoder::DecodeError> {
let input = std::fs::read(path).map_err(heic_decoder::DecodeError::Io)?;
let hint = exif_orientation_hint(&input);
let decoded = decode_path_to_rgba(path)?;
let decoded = if let Some(orientation) = hint.orientation_to_apply() {
decoded.apply_exif_orientation(orientation)?
} else {
decoded
};
eprintln!("{}x{}", decoded.width, decoded.height);
Ok(())
}Path-only variant (no full input read, no image decode):
use heic_decoder::{exif_orientation_hint_from_path, path_extension_is_heif};
use std::path::Path;
fn orientation_to_apply(path: &Path) -> Result<Option<u8>, heic_decoder::DecodeError> {
if !path_extension_is_heif(path) {
return Ok(None);
}
Ok(exif_orientation_hint_from_path(path)?.orientation_to_apply())
}Requires image-integration feature.
Hook decodes buffer the entire encoded input in memory before decoding; in
exchange, pixels decode straight into the buffer image hands over, without
an additional full-frame owned RGBA allocation. Codec-native planes and a
single grid-tile scratch buffer may still be allocated.
register_image_decoder_hooks() caps the encoded input buffer at
DEFAULT_HOOK_MAX_INPUT_BYTES (128 MiB); register with explicit guardrails
to choose a different max_input_bytes bound (or None for unbounded).
use heic_decoder::DecodeGuardrails;
use heic_decoder::image_integration::register_image_decoder_hooks_with_guardrails;
let registration = register_image_decoder_hooks_with_guardrails(DecodeGuardrails {
max_input_bytes: Some(128 * 1024 * 1024),
max_pixels: Some(64_000_000),
max_temp_spool_bytes: Some(128 * 1024 * 1024),
temp_spool_directory: None,
});
assert!(registration.any_decoder_hook_registered());use image::ImageReader;
use heic_decoder::exif_orientation_hint;
use heic_decoder::image_integration::apply_exif_orientation_dynamic;
let bytes = std::fs::read("input.heic").map_err(image::ImageError::IoError)?;
let hint = exif_orientation_hint(&bytes);
let img = ImageReader::new(std::io::Cursor::new(&bytes))
.with_guessed_format()?
.decode()?;
let img = if let Some(orientation) = hint.orientation_to_apply() {
apply_exif_orientation_dynamic(img, orientation)
} else {
img
};The registered hook decoder also exposes the primary item's EXIF block through
the standard ImageDecoder::exif_metadata/ImageDecoder::orientation methods,
so generic image code (decoder.orientation() +
DynamicImage::apply_orientation) works without crate-specific helpers. EXIF
orientation stays unapplied in the pixels; applying it remains the caller's
choice. When the primary item carries irot/imir container transforms —
which decode does bake into the pixels — orientation() reports
NoTransforms (matching ExifOrientationHint::should_apply_exif_orientation)
so callers do not rotate twice; exif_metadata still returns the full block.
Under image-integration, DecodedRgbaImage provides conversion helpers:
into_image_buffer_with_metadata()into_image_buffer()into_dynamic_image_with_metadata()into_dynamic_image()
Metadata-preserving wrappers:
ImageBufferWithMetadataDynamicImageWithMetadata
Possible conversion failures:
ImageConversionError::SampleCountOverflowImageConversionError::SampleCountMismatch
Additional helper under image-integration:
apply_exif_orientation_dynamic(image, exif_orientation)
For reliable agent behavior:
- Always use
*_with_guardrailsAPIs for untrusted input. - Treat
Read/BufReadas temp-spooled random-access decode, not progressive decode. - Branch on
decoded.storage_bit_depth()and avoid implicit down-conversion. - Match
DecodeError::category()for stable retry/reject decisions. - Register image hooks exactly once during process startup.
- Keep guardrail values centralized in one config module for consistency.
use heic_decoder::{decode_path_to_rgba_with_guardrails, DecodeGuardrails};
use std::path::Path;
fn decode(path: &Path) -> Result<(), heic_decoder::DecodeError> {
let guardrails = DecodeGuardrails {
max_input_bytes: Some(128 * 1024 * 1024),
max_pixels: Some(64_000_000),
max_temp_spool_bytes: Some(128 * 1024 * 1024),
temp_spool_directory: None,
};
let decoded = decode_path_to_rgba_with_guardrails(path, guardrails)?;
eprintln!(
"decoded {}x{}, storage={}bit, source={}bit",
decoded.width,
decoded.height,
decoded.storage_bit_depth(),
decoded.source_bit_depth
);
Ok(())
}decode_bounded(BoundedInput, BoundedDecodeOptions) decodes a HEIC still image
to display-oriented sRGB RGB8 within a memory budget. It returns
Result<BoundedRgbImage, BoundedDecodeError>. The output is reduced with area
averaging so that neither side exceeds max_side (1 through 6000, default
6000), and original_dimensions is the display size before reduction.
max_memory_bytes (at least 64 KiB, default 128 MiB) caps the decoder-owned
memory that depends on the input. decoder-tracing disables bounded decoding.
The primary item may be a grid of uniform HEVC tiles or a single HEVC image
(hvc1/hev1). Every coded item must be opaque 8-, 10- or 12-bit 4:2:0 HEVC
with one IDR slice, and a pixi property must match the coded bit depth; WPP
is supported. A single image is decoded as a grid with one tile.
clap/irot/imir are applied, and Exif orientation applies when no
effective container orientation is present. When a container transform makes
libheif convert 4:2:0 chroma to 4:4:4 (the 4:2:0 rules under Container
transforms above), the output matches the regular decoders: bilinear chroma
with clamped edges, the limited-range round trip through RGB, and the colr
nclx override after all transforms, at the coded bit depth. The 4:4:4 samples
are built a band of rows at a time while each tile is converted to RGB, so no
full-size 4:4:4 image is held. Grid tiles are then converted in units shifted
one pixel up and left, so each unit needs only the last chroma row and column
of tiles decoded before it; those edges are kept in strips as wide as the
canvas. Clean apertures, rotations and mirrors on individual grid tiles are
refused. RGB matrix/TRC ICC profiles and SDR nclx colour with BT.709, BT.2020
or Display P3 primaries are converted to sRGB, and PQ or HLG colour is tone
mapped to sRGB as described below. Grayscale ICC profiles, lookup-table ICC
profiles without a PQ or HLG cicp tag, unprofiled wide-gamut SDR HEVC colour,
matrix coefficients 8, 11, 14 (ICtCp) or 16, PQ or HLG in the nclx or HEVC VUI
when higher-precedence colour says otherwise, alpha, and unknown required
auxiliaries return errors. Known depth, semantic matte, and gain-map
auxiliaries are ignored, so an Apple gain-map HDR photo decodes as its SDR base
image.
PQ (transfer 16) and HLG (transfer 18) are taken from the cicp tag of an RGB
ICC profile, whatever its other tags, otherwise from the container nclx,
otherwise, when the container has no colour, from the HEVC VUI. Their primaries
must be BT.709, BT.2020 or Display P3; unspecified primaries are treated as
BT.2020. Samples are converted to display light with 203 cd/m² as SDR reference
white: PQ directly, and HLG through the BT.2100 OOTF for a 1000 cd/m² display,
so 75% HLG is also 203 cd/m². The colour is converted to BT.709 primaries with
negative components clipped, and the BT.2390 EETF is applied to the largest
component so that the source peak becomes SDR white. The source peak is the
clli maximum content light level, otherwise the mdcv maximum mastering
luminance, each taken from the primary item or else its first tile, otherwise
1000 cd/m², limited to 203 through 10000 cd/m²; HLG always uses 1000 cd/m². A
clli or mdcv box of the wrong size or with a zero value is ignored, a
repeated one does not replace the first, and grid tiles may carry different
ones. With a 1000 cd/m² peak, light up to about 88 cd/m² is unchanged,
reference white encodes as 229 of 255, and brighter light rolls off to 255. The
output is sRGB-encoded without an ICC profile, and source_bit_depth reports
the coded bit depth. The other decode functions do not tone map: they return
the HDR samples with the container's embedded ICC profile or one made from its
nclx, so with no profile when only the HEVC VUI signals PQ or HLG.
Before any pixel decoding, preflight reads every coded item's headers and
reserves its reconstruction workspace, and admission then reserves the output
together with the largest tile workspace, which includes the 4:4:4 band
buffers when the conversion applies. Inputs that do not fit return
MemoryBudgetExceeded or LimitExceeded without decoding pixels. Grid tiles
decode one at a time, or concurrently with parallel-grid when the budget
allows. A single image's full-resolution reconstruction must fit the budget at
once, so a large non-grid image needs a larger budget than a grid of the same
size. Grid tile payloads are limited to 16 MiB; a single image's payload is
bounded by the budget and the 512 MiB input limit. Admission is conservative,
and allocator overhead and process RSS are not included.
decode_bounded_tiny(BoundedInput, BoundedDecodeOptions) takes the same
options as decode_bounded and returns the same BoundedRgbImage, with
identical pixels, for devices where memory matters more than speed. It decodes
one coded item at a time on the calling thread, a CTU row at a time, and
converts and reduces each row into the output straight away, so no tile or
image is held at full resolution. Besides the output, its working memory is a
few CTU rows of coded width, one row and one column of reduction sums, and for
WPP items a copy of the item's payload, an unescaped copy of its slice and four
bytes for each emulation prevention byte; other items are read from the input
as they are decoded. Preflight reads only each item's headers, and admission
reserves the output and the largest item workspace before any pixels are
decoded, so inputs that do not fit return MemoryBudgetExceeded. It also
decodes large single images whose full-resolution reconstruction does not fit
the budget, and it limits grid tile payloads only through the budget rather
than decode_bounded's 16 MiB per tile. It refuses some inputs that
decode_bounded decodes, with an error rather than different pixels: 10- and
12-bit items, PQ and HLG colour (which decode_bounded tone maps), VPS, SPS or
PPS carried in the item data instead of its hvcC, a PPS with HEVC tiles
enabled even for a single tile, grid tiles that differ in coded size or
conformance window, primary images above 256 million pixels, and grids of
several coded items that need the 4:4:4 chroma conversion. decoder-tracing
disables it.
rows::info(config, payload) and rows::decode_rows(config, payload, emit)
work on one HEVC coded item, such as a single grid tile. config is the
item's hvcC property payload and payload is its length-prefixed item data.
The item must be 8-bit 4:2:0 HEVC with one IDR slice; WPP is supported, HEVC
tiles are not. info does not repeat every check of decode_rows: it also
reports 10- and 12-bit items and items whose PPS enables a single HEVC tile,
which decode_rows refuses. Info reports the display and coded sizes, the
conformance window crop (left, right, top, bottom) and the colour signalling.
decode_rows calls emit with each Band from top to bottom. top and
rows count coded luma rows; luma holds rows rows of luma_stride
samples, and cb and cr hold the matching half-height chroma rows of
chroma_stride samples. Bands are one CTU tall, except possibly the last, and
borrow decoder buffers for the duration of the call. Errors are
BoundedDecodeError. No cropping, transforms, or colour conversion are
applied, and no memory budget is enforced: working memory is a copy of the
payload, four bytes for each emulation prevention byte removed from it, and a
few CTU rows of coded width. info prepares the slice the same way before it
returns.
Enable the incremental-experiment Cargo feature to use
decode_incremental_experiment(BoundedInput, BoundedDecodeOptions). It returns
(BoundedRgbImage, [u64; 3]); the diagnostic counters are reconstructed rows,
SAO edge components, and SAO band components across all coded items. This
feature and entry point are experimental. Existing decode functions retain
their behavior and do not select this path automatically.
The incremental path supports opaque 8-bit 4:2:0 HEVC still images with one IDR slice per coded item, including non-grid images and uniform grids whose individual tiles exceed the output cap. WPP, HEVC tiles, multiple slices, higher bit depths, PQ or HLG colour, alpha, other chroma formats, and unsupported color profiles return errors. The output is display-oriented sRGB RGB8, using area averaging when reduced, with a maximum side from 1 through 6000. Known depth, semantic matte, and gain-map auxiliaries may accompany the SDR base image; this does not apply their effects or provide HDR output.
Reconstruction, deblocking, and SAO finish in rolling bands before conversion
and reduction. Large coded images use a bounded two-thread pipeline. The
working state grows with coded width and CTU size, while output storage is
capped by max_side; it does not retain a full source raster or use temporary
files or repeated reconstruction. A caller's borrowed compressed input is
separate from decoder-owned memory. Admission is conservative and may reject
budgets smaller than its reserved workspace, including a worker stack.
Allocator overhead and process RSS are not the same as requested allocation
payloads. Use Path input when avoiding a caller-owned compressed input buffer
is also important.
This first subset retains limits of 16384 per coded side, 256 million display
pixels, bounded metadata, and a 64 KiB slice-header prefix. It applies
clap/irot/imir in property order and converts to 4:4:4 like
decode_bounded on a single coded image or a one-tile grid. Grids of several
coded items that need the 4:4:4 conversion return Unsupported. Exif
orientation applies when no effective container orientation is present.
decoder-tracing disables bounded decoding.