heif

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: BSD-3-Clause Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

heif

A pure-Go reader for HEIF / HEIC still images (ISO/IEC 23008-12 on the ISO base media file format of ISO/IEC 14496-12). The HEVC pictures inside are decoded by go-avkit/h265. No cgo, no libheif.

import (
	"image"
	_ "github.com/go-images/heif" // registers the formats
)

img, format, err := image.Decode(r) // format is "heif"
cfg, format, err := image.DecodeConfig(r)

image.Decode finds HEIF by its ftyp box (brands heic, heix, hevc, hevx, heim, heis, hevm, hevs, mif1). The package also offers:

Function Purpose
Decode(r) the primary image as an image.Image
DecodeOptions(r, Options) the same with explicit Limits; returns a *Result with Image, ICCProfile, Nclx and HasAlpha
DecodeConfig(r) / DecodeConfigOptions size and colour model from the head of the file, without decoding any picture
DecodeWork(r, opts) the pixels decoding the primary image will process (every tile of a grid, however far it is cropped), from the head of the file: what a caller sets a budget against

The result is an *image.YCbCr or *image.Gray sharing the decoder's planes when nothing needs converting (8-bit, full-range BT.601, no transform), otherwise an *image.RGBA, *image.RGBA64, *image.Gray or *image.Gray16 (the 16-bit forms for deeper sources). Rotation (irot), mirroring (imir) and cropping (clap) are applied, so DecodeConfig reports the size after them. Grid items (grid), identity derivations (iden) and items stored in idat are supported. Colour conversion follows the nclx colour information (matrix, range); an ICC profile is returned, not applied.

imir: axis 0 swaps top and bottom, axis 1 swaps left and right, as libheif does. The irot direction (anti-clockwise) was checked against Apple's sips; sips cannot settle the mirror axis, so that one follows libheif.

Security

Input is untrusted. Every size is checked before anything is allocated from it.

res, err := heif.DecodeOptions(r, heif.Options{Limits: heif.Limits{
	MaxBytes:  64 << 20, // bytes read from r (default 256 MiB)
	MaxPixels: 1 << 24,  // pixels of any picture, coded or output (default 1<<26)
	MaxMemory: 256 << 20, // estimated bytes of a decode (default 320 MiB)
}})

MaxMemory is the memory bound of a decode, checked from the SPS before any picture is decoded (ErrImageTooLarge; DecodeWork applies the same check). The estimate is the HEVC planes of the largest coded picture plus the converted result, which are alive together (a crop or rotation is written as the pixels are converted, with no copy of the unturned picture), and for a grid the assembled canvas as well: 6 bytes a pixel for 8-bit 4:2:0 (4 for the result, 2 for the planes), up to 14 for 16-bit 4:4:4. At the default 320 MiB a 48 MP 8-bit 4:2:0 picture passes (about 256 MiB) and 16-bit 4:4:4 stops near 24 MP; an 8192x8192 picture needs MaxMemory raised, and so do 10-bit 4:2:2 stills above about 28 MP (12 bytes a pixel; 16-bit 4:4:4 stops near 24 MP). MaxMemory is an estimate of live data, not a heap bound: the peak heap, garbage included, is about 1.25 times it (about 400 MiB at the 320 MiB default; measured 437 MiB against an estimate of 352). Measured peak heap for a flat 8192x8192 file of 17 KB with MaxMemory 400 MiB: 239 MiB plain, 380 MiB turned by irot; 260 MiB for a 2x2 grid of 4096 tiles; 124 MiB for 8192x4320 at the default. The 16-bit 4:4:4 figure is computed, not measured. MaxMemory does not count the input: reading the file and assembling an item hold up to 2 times MaxBytes besides. MaxPixels still bounds the pixel count on its own (a value above 2^40 is lowered to 2^40).

The coded size comes from the SPS of the hvcC, not from ispe: an item whose parameter set does not state the size its ispe does is refused before any picture is decoded, and DecodeWork reports the coded size (a picture cropped by its conformance window counts as the whole coded picture, and every tile of a grid counts, up to four times MaxPixels).

The slice segments of a picture must be in increasing tile-scan order (CtbAddrRsToTs, H.265 6.5.1; the raster order without tiles), otherwise ErrInvalid.

Limits also bounds tiles, boxes, nesting depth, items and the decoder's memory (MaxTiles, MaxBoxes, MaxDepth, MaxItems, MaxDecoderBytes). A zero field takes the default. Refusals are named errors you can test with errors.Is: ErrNotHEIF, ErrTruncated, ErrInvalid, ErrUnsupported, ErrNoPrimaryItem, ErrCorrupt, ErrFileTooLarge, ErrImageTooLarge, ErrTooManyBoxes, ErrNestingTooDeep, ErrTooManyItems, ErrTooManyTiles. Overlapping iloc extents count against MaxBytes once each.

Tests: FuzzDecode with a committed corpus (testdata/fuzz/FuzzDecode), and TestBombs, which asserts a refusal with a small allocation for enormous declared sizes (CI runs it under GOMEMLIMIT=256MiB).

Not supported

Reported as ErrUnsupported, never silently wrong:

  • items that are not HEVC (AVC, AV1, JPEG, uncompressed) and moov image sequences;
  • alpha: HasAlpha reports an auxiliary alpha plane, which is not decoded;
  • HDR gain maps and other auxiliary images;
  • iloc construction method 2 (item offsets) and external data references;
  • essential properties the reader does not know.

Sources deeper than 8 bits decode (10 and 12 bit, 4:0:0, 4:2:0, 4:2:2, 4:4:4) to 16-bit output. Bit depths are those that go-avkit/h265 v0.24.0 decodes.

Checked against

  • grid decode is byte-identical to ffmpeg 9.0.2 on a 2x2 grid (TestGridMatchesFFmpeg);
  • a single image from Apple's HEIC encoder matches sips at 52 dB PSNR;
  • locally, 51 of the 64 Nokia HEIF conformance files decode; the others are image sequences without a meta box (11), an unknown essential property rref (1) and an AVC item (1), each refused with a named error (TestLocalFiles, run with HEIF_LOCAL_DIRS). Those files and libheif's example.heic have no licence that allows committing them, so they are used locally only.

The reference tool, libheif's heif-dec, was not installed when this was written, so there is no timing comparison against it yet. BenchmarkDecodeGrid and BenchmarkDecodeSmall (GOMAXPROCS=1 gotest -run XXX -bench Decode .) are the harness; they were not run for this first version because the machine was above the fleet's load limit.

Development

go test ./... runs everything; the package keeps 100% statement coverage (go run ./internal/covergate cover.out). internal/mkhevc makes the HEVC test streams with ffmpeg; internal/mkpng writes the reference PNGs.

BSD 3-Clause.

Documentation

Overview

Package heif reads HEIF/HEIC still images (ISO/IEC 23008-12 over the ISO base media file format of ISO/IEC 14496-12) in pure Go. The HEVC pictures are decoded by github.com/go-avkit/h265.

What it reads: the primary item of a file whose ftyp brands include heic, heix, hevc, hevx, heim, heis, mif1 or msf1, when that item is an hvc1 image, a grid of hvc1 tiles, or an identity (iden) of one of them, with the transformative properties irot, imir and clap applied in the order the file lists them. 8-bit and deeper (to 16-bit) 4:0:0, 4:2:0, 4:2:2 and 4:4:4 pictures are supported. Colour is converted with the matrix and range of the nclx colr property (BT.601 full range without one); the primaries and transfer characteristic are not applied, and an ICC profile is returned, not applied.

What it does not read: alpha auxiliary images (Result.HasAlpha says one exists), depth maps, HDR gain maps, overlays (iovl), thumbnails, image sequences, other codecs (AV1, JPEG, VVC), and items stored in another file.

The input is untrusted: see Limits.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotHEIF: the data is not a HEIF file (no ftyp box with a still-image brand).
	ErrNotHEIF = errors.New("heif: not a HEIF still-image file")
	// ErrTruncated: a box, a field or an item's data runs past the end of its container.
	ErrTruncated = errors.New("heif: truncated data")
	// ErrInvalid: the file breaks the format (a size, offset, reference or count that
	// cannot be right).
	ErrInvalid = errors.New("heif: invalid file")
	// ErrUnsupported: the file is valid but uses something this reader does not decode
	// (an item type other than hvc1, grid and iden, an overlay, a matrix, an essential
	// property it does not know).
	ErrUnsupported = errors.New("heif: unsupported feature")
	// ErrNoPrimaryItem: the file has no primary item, or it is not an image.
	ErrNoPrimaryItem = errors.New("heif: no primary image item")
	// ErrCorrupt: the HEVC bitstream of an item could not be decoded.
	ErrCorrupt = errors.New("heif: the HEVC bitstream could not be decoded")

	// ErrFileTooLarge: the file is longer than Limits.MaxBytes.
	ErrFileTooLarge = errors.New("heif: file larger than the limit")
	// ErrImageTooLarge: an image (a tile, a grid, the result) has more pixels than
	// Limits.MaxPixels, or its buffers cannot be addressed on this platform.
	ErrImageTooLarge = errors.New("heif: image larger than the limit")
	// ErrTooManyBoxes: the file holds more than Limits.MaxBoxes boxes.
	ErrTooManyBoxes = errors.New("heif: too many boxes")
	// ErrNestingTooDeep: boxes nest deeper than Limits.MaxDepth, or items derive from
	// one another deeper than that.
	ErrNestingTooDeep = errors.New("heif: boxes or derivations nested too deeply")
	// ErrTooManyItems: more than Limits.MaxItems items (or item entries).
	ErrTooManyItems = errors.New("heif: too many items")
	// ErrTooManyTiles: a grid has more than Limits.MaxTiles tiles.
	ErrTooManyTiles = errors.New("heif: too many tiles")
)

Errors of the reader. Every error returned by this package wraps one of them (test with errors.Is); the text after the colon says where.

Functions

func Decode

func Decode(r io.Reader) (image.Image, error)

Decode reads the primary image of a HEIF file with the default limits.

func DecodeConfig

func DecodeConfig(r io.Reader) (image.Config, error)

DecodeConfig returns the size and colour model of the primary image without decoding it; only the boxes up to meta are read.

func DecodeConfigOptions

func DecodeConfigOptions(r io.Reader, o Options) (image.Config, error)

DecodeConfigOptions is DecodeConfig under the given options.

func DecodeWork

func DecodeWork(r io.Reader, o Options) (int64, error)

DecodeWork is the number of pixels the decoder processes to read the primary image, from the head of the file and without decoding any picture. It is what a caller sets a budget against: a grid decodes every tile in full, so a grid of large tiles cropped to a sliver costs far more than the size DecodeConfig reports.

Types

type Limits

type Limits struct {
	// MaxBytes is the longest file read (default 256 MiB). It also bounds the bytes
	// one item may assemble from its extents.
	MaxBytes int64
	// MaxPixels is the most pixels of one image: a tile, a grid, the decoded base image
	// and the result (default 1<<26, which holds a 48-megapixel photo and 8192x8192).
	//
	// It sets the memory of a decode: the planes of the HEVC decoder and the converted
	// image are alive together, 1.5 bytes a pixel for the planes of an 8-bit 4:2:0 picture
	// and 4 for its RGBA result, 5.5 bytes a pixel live at the peak. MaxMemory bounds
	// that product; MaxPixels bounds the size of a picture (a value above 2^40 is
	// lowered to 2^40).
	MaxPixels int64
	// MaxMemory is the most live data a decode may need, estimated before anything is
	// decoded from the parameter sets (default 320 MiB): the planes of the coded picture
	// (1.5 bytes a pixel for 8-bit 4:2:0, 6 for 16-bit 4:4:4; a grid holds those of one
	// tile and of the assembled picture) plus the converted result (4 bytes a pixel, 8
	// for 16 bits, 1 or 2 for grey). It is an estimate of live data, not a bound of the
	// heap: the peak heap, the garbage the collector has not yet taken included, is about
	// 1.25 times MaxMemory (measured 437 MiB against an estimate of 352, so about 400 MiB
	// at the 320 MiB default). It does not count the input: reading the file and
	// assembling an item hold up to 2 times MaxBytes besides. At the default a
	// 48-megapixel 8-bit 4:2:0 photo (about 250 MiB) is decoded, 8192x8192 8-bit 4:2:0
	// (352 MiB) is not, 10-bit 4:2:2 (12 bytes a pixel) stops at about 28 megapixels and
	// 16-bit 4:4:4 (14) at about 24. DecodeWork applies the same check.
	MaxMemory int64
	// MaxTiles is the most tiles of one grid (default 4096).
	MaxTiles int
	// MaxBoxes is the most boxes of the file, nested ones included (default 65536).
	MaxBoxes int
	// MaxDepth is the deepest box nesting, and the longest chain of derived items
	// (default 8).
	MaxDepth int
	// MaxItems is the most items, references and property associations the reader
	// accepts in one box (default 16384).
	MaxItems int
	// MaxDecoderBytes bounds the memory of the HEVC decoder's picture buffer, as the
	// decoder estimates it for the pictures the stream states: 9 bytes a luma sample of a
	// 4:2:0 picture, for each of the pictures its buffer may hold (default 4 GiB, which
	// holds the 4 pictures an x265 stream states at 8192x8192). An item holds one picture
	// and one decoder is alive at a time, so what is allocated is that of one picture.
	// It is the limit of the file, not of each tile.
	MaxDecoderBytes int64
}

Limits bound what an untrusted file can make the reader read, count or allocate. A zero field stands for its default.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits are the limits a zero Limits stands for.

type Nclx

type Nclx = nclx

Nclx is a colour description by code points (ITU-T H.273): colour primaries, transfer characteristics, matrix coefficients and range.

type Options

type Options struct {
	Limits Limits
}

Options configure Decode.

type Result

type Result struct {
	// Image is the primary image, transformations applied. It is an *image.YCbCr or
	// *image.Gray sharing the HEVC decoder's planes when no transformation applies
	// and the picture is 8-bit full-range BT.601, else an *image.RGBA, *image.RGBA64,
	// *image.Gray or *image.Gray16.
	Image image.Image
	// ICCProfile is the colr ICC profile of the primary item, as stored (nil if none).
	ICCProfile []byte
	// Nclx is the nclx colr property of the primary item (nil if none).
	Nclx *Nclx
	// HasAlpha says an alpha plane is attached to the primary item; it is not decoded.
	HasAlpha bool
}

Result is a decoded file.

func DecodeOptions

func DecodeOptions(r io.Reader, o Options) (*Result, error)

DecodeOptions reads the primary image of a HEIF file under the given options.

Directories

Path Synopsis
internal
covergate command
Command covergate reads a Go coverage profile and exits 1 unless every statement of it was executed.
Command covergate reads a Go coverage profile and exits 1 unless every statement of it was executed.
mkhevc command
Command mkhevc encodes one intra picture of each pixel format the tests need with ffmpeg's libx265: mkhevc <source.png> <dir> writes <dir>/<pix_fmt>.hevc, Annex B streams that the tests wrap in HEIF items.
Command mkhevc encodes one intra picture of each pixel format the tests need with ffmpeg's libx265: mkhevc <source.png> <dir> writes <dir>/<pix_fmt>.hevc, Annex B streams that the tests wrap in HEIF items.
mkpng command
Command mkpng writes the synthetic source images the testdata HEIC files are made from: mkpng <dir> writes small.png (67x45, odd sizes) and big.png (1100x700, which an encoder splits into a grid), each an asymmetric pattern so a rotation or mirror shows.
Command mkpng writes the synthetic source images the testdata HEIC files are made from: mkpng <dir> writes small.png (67x45, odd sizes) and big.png (1100x700, which an encoder splits into a grid), each an asymmetric pattern so a rotation or mirror shows.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址