avif

package module
v0.0.0-...-c232460 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 16 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

go-avif

libavif(1.1.0 以上)の共有ライブラリを purego で動的に読み込みます。

libavif のインストール(vcpkg)

vcpkg ならどの OS でも同じ手順です。

OS 共有ライブラリ トリプレット 置き場所($VCPKG_ROOT/installed/<トリプレット>/) 検索パス
Windows avif.dll x64-windows / arm64-windows bin PATH
Linux libavif.so x64-linux-dynamic / arm64-linux-dynamic lib LD_LIBRARY_PATH
macOS libavif.dylib arm64-osx-dynamic / x64-osx-dynamic(Intel) lib DYLD_LIBRARY_PATH
  • コーデック: 既定ではコーデックなしでビルドされ、エンコードもデコードもできません。libavif[aom,dav1d] のように feature を付けます(aom: エンコード・デコード、dav1d: 高速デコード、svt: SVT-AV1 エンコーダー)。
  • 共有ライブラリ: Linux / macOS の既定トリプレット(x64-linux、arm64-osx など)は静的ライブラリで purego から読めないため、*-dynamic を使います。x64-windows は最初から DLL です。

インストール後、置き場所を検索パスに追加します(永続化は ~/.bashrc / ~/.zshrc などで)。

Windows(Visual Studio / Build Tools の「C++ によるデスクトップ開発」が必要)

vcpkg install "libavif[aom,dav1d,svt]:x64-windows"
$env:PATH = "$env:VCPKG_ROOT\installed\x64-windows\bin;$env:PATH"   # 現在のセッションのみ
# ユーザー環境変数に永続的に追加(新しいターミナルから有効)
[Environment]::SetEnvironmentVariable("PATH", "$env:VCPKG_ROOT\installed\x64-windows\bin;" + [Environment]::GetEnvironmentVariable("PATH", "User"), "User")

bin には依存 DLL(aom.dll、dav1d.dll、libyuv.dll など)も入ります。配布時は実行ファイルと同じディレクトリに置けば PATH の設定は不要です。

Linux(Debian / Ubuntu の例)

sudo apt install build-essential cmake ninja-build pkg-config nasm python3 curl zip unzip tar git
vcpkg install "libavif[aom,dav1d]:x64-linux-dynamic"
export LD_LIBRARY_PATH="$VCPKG_ROOT/installed/x64-linux-dynamic/lib:$LD_LIBRARY_PATH"

macOS

xcode-select --install
brew install cmake ninja pkg-config nasm
vcpkg install "libavif[aom,dav1d]:arm64-osx-dynamic"
export DYLD_LIBRARY_PATH="$VCPKG_ROOT/installed/arm64-osx-dynamic/lib:$DYLD_LIBRARY_PATH"

DYLD_* は SIP により /bin/sh などのシステム付属プログラムを経由すると消えるため、シェルスクリプトや make ではスクリプト内で再度 export します。

SharpYUV を有効にする

vcpkg の libavif port には libsharpyuv の feature がないので追加します。

  1. $VCPKG_ROOT/ports/libavif/vcpkg.json の features に追加します。

    "sharpyuv": {
      "description": "Sharp RGB to YUV conversion",
      "dependencies": ["libwebp"]
    }
    
  2. 同じディレクトリの portfile.cmake で、if("svt" IN_LIST FEATURES) のブロックの後に追加します。

    if("sharpyuv" IN_LIST FEATURES)
        list(APPEND FEATURE_OPTIONS "-DAVIF_LIBSHARPYUV=SYSTEM")
    endif()
    
  3. sharpyuv を付けて再ビルドします。

    vcpkg install "libavif[aom,dav1d,svt,sharpyuv]:x64-windows" --recurse
    
インストールの確認

vcpkg list libavif に libavif、libavif[aom]、libavif[dav1d] の 3 行が出ればコーデック付きです。libavif だけなら feature を付けて vcpkg install をやり直します(再ビルドされます)。

次に、検索パスを設定したターミナルでリポジトリのルートから go test -count=1 -v . を実行し、すべて --- PASS なら読み込み・デコード・エンコードができています。ライブラリやコーデックがないとスキップではなく --- FAIL になります(libavif を使わないオプション検証・画素変換・構造体レイアウトのテストを除く)。原因は TestLibrary の出力でわかります(-v で libavif とコーデックのバージョンも出ます)。

出力 原因と対処
libavif is required by this test: cannot load library ... 共有ライブラリが見つかりません。検索パスを確認してください。
libavif is required by this test: minimum required libavif version is 1.1.0 古い libavif が先に見つかっています。vcpkg のディレクトリを先にしてください。
libavif was built without an AV1 encoder / decoder コーデックなしでビルドされています。feature を付けて入れ直してください。
  • libavif 1.4.0 未満では 1.4.0 の機能(DepthExtension、CreationTime など)、libsharpyuv なし(vcpkg の既定)では SharpYUV のテストをスキップします。
  • TestMatchesAvifenc は avifenc の出力とバイト単位で比較します。AV1 エンコーダーの出力はバージョンで変わるため、avifenc --version の 1 行目(libavif とコーデックのバージョン)が共有ライブラリと完全に一致するときだけ実行します。vcpkg は avifenc を入れないのでスキップされます。

自分のプログラムからは avif.Dynamic() で確認できます。

if err := avif.Dynamic(); err != nil {
    log.Fatal("共有ライブラリが見つかりません:", err)
}

使い方

import "github.com/f0reth/go-avif"

img, err := avif.Decode(f)     // AVIF → image.Image
ret, err := avif.DecodeAll(f)  // アニメーション AVIF: ret.Image は各フレーム、ret.Delay は各フレームの表示時間(秒)
err = avif.Encode(w, img, nil) // image.Image → AVIF(nil はデフォルト設定)
エンコードオプション

Options は avifenc と同じ設定・デフォルト値を持ち、nil やゼロ値のフィールドは avifenc のデフォルトになります。0 が意味を持つ Quality / QualityAlpha / Speed などはポインタなので new(80) のように指定します。

err := avif.Encode(w, img, &avif.Options{
    Quality:      new(80),             // -q 0〜100(100 で可逆、デフォルト: 60)
    QualityAlpha: new(90),             // --qalpha(デフォルト: Quality と同じ)
    Speed:        new(8),              // -s 0〜10 / avif.SpeedCodecDefault(デフォルト: 6)
    YUV:          avif.PixelFormat420, // -y auto|444|422|420|400(デフォルト: auto)
    Depth:        10,                  // -d 8|10|12(デフォルト: 8bit 画像は 8、16bit 画像は 12)
})
avifenc Options
-q, --qcolor / --qalpha Quality / QualityAlpha
-s, --speed Speed
-j, --jobs Jobs(0 = all)
-l, --lossless Lossless
-d, --depth D[,Dextension] Depth, DepthExtension
-y, --yuv YUV
-p, --premultiply Premultiply
--sharpyuv SharpYUV
--cicp, --nclx CICP
-r, --range Range
--target-size TargetSize
--progressive Progressive
-g, --grid Grid
-c, --codec Codec
--exif / --xmp / --icc Exif / XMP / ICC
--timescale, --fps Timescale
--creation-time / --modification-time CreationTime / ModificationTime
-k, --keyframe KeyframeInterval
--repetition-count RepetitionCount
--pasp / --crop / --clap PixelAspectRatio / Crop / CleanAperture
--irot / --imir / --clli Rotation / Mirror / ContentLightLevel
--tilerowslog2 / --tilecolslog2 / --autotiling TileRowsLog2 / TileColsLog2 / ManualTiling(デフォルトは自動タイル)
--scaling-mode ScalingMode
-a, --advanced Advanced

EncodeAll は複数の画像をアニメーション AVIF にします(avifenc に複数の入力を渡すのと同じ)。各フレームの表示時間は Delay(秒)を Timescale 単位に変換した値です。

err := avif.EncodeAll(w, &avif.AVIF{Image: frames, Delay: delays}, &avif.Options{Timescale: 30})

同じバージョンの libavif なら、image/png でデコードした画像を同じ設定でエンコードすると、avifenc に PNG を渡したのと同じ AVIF になります。ただし次の点が異なります。

  • PNG の色空間情報(sRGB / gAMA / cHRM / iCCP / cICP)や Exif / XMP は image.Image に含まれません。必要なら CICP / ICC / Exif / XMP で指定します(未指定時はチャンクなしの PNG と同じく sRGB)。
  • グレースケール+アルファの PNG は image/png が *image.NRGBA にするため、YUV auto では 400 でなく 444 になります。
  • --layered、--stdin、--input-format、--no-overwrite、--ignore-*、非推奨の --min / --max は非対応です。

ベンチマーク

テストと同じ環境で実行します。

go test -run '^$' -bench . -benchmem .
go test -run '^$' -bench . -count 10 . > new.txt   # 変更前の old.txt と benchstat old.txt new.txt で比較

ns/op に加えて 1 秒あたりの処理画素数(Mpx/s、アニメーションは全フレーム分)を、BenchmarkEncode と BenchmarkConvert は出力サイズ(out-bytes)と 1 画素あたりのビット数(bpp)も出力します。BenchmarkEncode/speed* 以外は変換を含む全体を測るため SpeedFastest でエンコードします。

ベンチマーク 内容
BenchmarkDecode 8bit / 10bit の静止画、アニメーションの先頭フレームのデコード
BenchmarkDecodeConfig ヘッダーの解析のみ
BenchmarkDecodeAll アニメーション(500x360、17 フレーム)全体のデコード
BenchmarkEncode 512x512 の写真のエンコード。YUV 444/422/420/400、アルファ、10/12bit、可逆、品質 90、シングルスレッド、速度 10/8/6/0(0 は不可逆で最高圧縮率)
BenchmarkConvert PNG / JPEG から AVIF への変換(標準ライブラリでのデコードを含む)。768x512 の Kodak テスト画像(kodim23)と、それを品質 90 で JPEG にしたもの
BenchmarkEncodeAll アニメーション全体のエンコード
BenchmarkDecodeParallel / BenchmarkEncodeParallel 複数ゴルーチンからの同時デコード / エンコード(Jobs: 1)
BenchmarkRGBFromImage image.Image から libavif 用 RGB バッファへの Go 側の変換(画像の型ごと、libavif 不要)

Documentation

Overview

Package avif implements an AVIF image decoder/encoder based on libavif shared library used via purego (CGo-free).

Index

Constants

View Source
const (
	// DefaultQuality is the default color quality (avifenc -q). Maps to a quantizer (QP) of 25.
	DefaultQuality = 60
	// DefaultSpeed is the default encoder speed (avifenc -s).
	DefaultSpeed = 6
	// DefaultTimescale is the default timescale of image sequences (avifenc --timescale).
	DefaultTimescale = 30
)

Defaults of the encoding parameters. They are the same as the defaults of avifenc.

View Source
const (
	// QualityWorst is the worst quality.
	QualityWorst = 0
	// QualityBest is the best quality.
	QualityBest = 100
	// QualityLossless is the quality that implies lossless encoding.
	QualityLossless = 100

	// SpeedSlowest is the slowest encoder speed (best compression).
	SpeedSlowest = 0
	// SpeedFastest is the fastest encoder speed.
	SpeedFastest = 10
	// SpeedCodecDefault leaves the AV1 codec to its own default speed settings (avifenc -s default).
	SpeedCodecDefault = -1

	// RepetitionCountInfinite repeats an image sequence infinitely (avifenc --repetition-count infinite).
	RepetitionCountInfinite = -1
)

Special values of the encoding parameters.

View Source
const (
	ColorPrimariesBT709       = 1
	ColorPrimariesSRGB        = 1
	ColorPrimariesUnspecified = 2
	ColorPrimariesBT2020      = 9
	ColorPrimariesSMPTE432    = 12 // Display P3
)

Color primaries (ITU-T H.273). Only the most common values are listed.

View Source
const (
	TransferCharacteristicsBT709       = 1
	TransferCharacteristicsUnspecified = 2
	TransferCharacteristicsLinear      = 8
	TransferCharacteristicsSRGB        = 13
	TransferCharacteristicsPQ          = 16
	TransferCharacteristicsHLG         = 18
)

Transfer characteristics (ITU-T H.273). Only the most common values are listed.

View Source
const (
	MatrixCoefficientsIdentity    = 0
	MatrixCoefficientsBT709       = 1
	MatrixCoefficientsUnspecified = 2
	MatrixCoefficientsBT601       = 6
	MatrixCoefficientsBT2020NCL   = 9
	MatrixCoefficientsYCgCo       = 8
	MatrixCoefficientsYCgCoRe     = 16
	MatrixCoefficientsYCgCoRo     = 17
)

Matrix coefficients (ITU-T H.273). Only the most common values are listed.

Variables

View Source
var (
	ErrMemRead  = errors.New("avif: mem read failed")
	ErrMemWrite = errors.New("avif: mem write failed")
	ErrDecode   = errors.New("avif: decode failed")
	ErrEncode   = errors.New("avif: encode failed")
	ErrOptions  = errors.New("avif: invalid options")
)

Errors returned by this package, wrapped with details.

Functions

func Decode

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

Decode reads a AVIF image from r and returns it as an image.Image.

func DecodeConfig

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

DecodeConfig returns the color model and dimensions of a AVIF image without decoding the entire image.

func Dynamic

func Dynamic() error

Dynamic returns the error, if any, that makes the libavif shared library unusable.

func Encode

func Encode(w io.Writer, m image.Image, o *Options) error

Encode writes the image m to w with the given options; nil options mean the defaults. With the same options, the output is the same as the one of avifenc given m as a PNG file.

func EncodeAll

func EncodeAll(w io.Writer, a *AVIF, o *Options) error

EncodeAll writes the images in a to w as an image sequence (animated AVIF) with the given options; nil options mean the defaults. The display duration of each frame is a.Delay (in seconds) converted to Options.Timescale units; frames without a positive delay last one timescale unit. A single frame is encoded as a still image, like avifenc does with a single input.

Types

type AVIF

type AVIF struct {
	// Images, one per frame. Decoded images are *image.RGBA, or *image.RGBA64 when the bit depth
	// of the AVIF is greater than 8.
	Image []image.Image
	// Delay times, one per frame, in seconds.
	Delay []float64
}

AVIF represents the possibly multiple images stored in a AVIF file.

func DecodeAll

func DecodeAll(r io.Reader) (*AVIF, error)

DecodeAll reads a AVIF image from r and returns the sequential frames and timing information.

type CICP

type CICP struct {
	ColorPrimaries          uint16
	TransferCharacteristics uint16
	MatrixCoefficients      uint16
}

CICP holds the color primaries, transfer characteristics and matrix coefficients (avifenc --cicp P/T/M).

type CleanAperture

type CleanAperture struct {
	WidthN, WidthD       uint32
	HeightN, HeightD     uint32
	HorizOffN, HorizOffD uint32
	VertOffN, VertOffD   uint32
}

CleanAperture is the clap property (avifenc --clap WN,WD,HN,HD,HON,HOD,VON,VOD).

type ContentLightLevel

type ContentLightLevel struct {
	MaxCLL  uint16
	MaxPALL uint16
}

ContentLightLevel is the clli property (avifenc --clli MaxCLL,MaxPALL).

type Grid

type Grid struct {
	// Columns in [1,256].
	Cols int
	// Rows in [1,256].
	Rows int
}

Grid is the number of cells of a grid image (avifenc -g MxN).

type Options

type Options struct {
	// Quality for color in [0,100] where 100 is lossless (avifenc -q). Default: 60.
	Quality *int
	// Quality for alpha in [0,100] where 100 is lossless (avifenc --qalpha). Default: same as Quality.
	QualityAlpha *int
	// Encoder speed in [0,10] where 0 is the slowest and 10 the fastest, or SpeedCodecDefault
	// (avifenc -s). Default: 6.
	Speed *int

	// Number of worker threads (avifenc -j). 0 uses as many as possible (default).
	Jobs int
	// Encode losslessly (avifenc -l): sets quality to 100 and the matrix coefficients to identity
	// unless CICP is given.
	Lossless bool
	// Output bit depth per channel: 8, 10 or 12 (avifenc -d). 0 means 8 for 8-bit images and 12
	// for 16-bit images (default).
	Depth int
	// Bit depth of a hidden image stored next to the primary one to reach 16-bit depth at decoding
	// (avifenc -d D,Dextension): 4 (with Depth 12) or 8 (with Depth 8 or 12). Requires libavif 1.4.0.
	DepthExtension int
	// YUV format (avifenc -y). Default: auto.
	YUV PixelFormat
	// Premultiply color by the alpha channel and signal this in the AVIF (avifenc -p).
	Premultiply bool
	// Use sharp RGB to YUV420 conversion (avifenc --sharpyuv). Requires libavif built with libsharpyuv.
	SharpYUV bool
	// CICP values (avifenc --cicp). nil means: 1/13/6 (sRGB) if no ICC profile is given,
	// 2/2/6 otherwise; matrix coefficients are 0 (identity) when Lossless is set.
	CICP *CICP
	// YUV range (avifenc -r). Default: full.
	Range Range
	// Target file size in bytes (avifenc --target-size). The qualities that are not explicitly set are
	// searched to get the closest output size. 0 disables it.
	TargetSize int
	// Encode a simple layered image supporting progressive rendering (avifenc --progressive).
	Progressive bool
	// Encode a single-image grid AVIF by splitting the image into Cols x Rows cells (avifenc -g).
	Grid *Grid
	// AV1 codec to use, such as "aom", "rav1e" or "svt" (avifenc -c). Default: chosen by libavif.
	Codec string
	// Exif metadata payload (avifenc --exif).
	Exif []byte
	// XMP metadata payload (avifenc --xmp).
	XMP []byte
	// ICC profile payload (avifenc --icc).
	ICC []byte
	// Timescale for image sequences (avifenc --timescale). Default: 30.
	Timescale uint64
	// Creation time for image sequences in seconds since the Unix epoch (avifenc --creation-time).
	// 0 uses the modification time. Requires libavif 1.4.0 when not 0.
	CreationTime uint64
	// Modification time for image sequences in seconds since the Unix epoch
	// (avifenc --modification-time). 0 uses the current time. Requires libavif 1.4.0 when not 0.
	ModificationTime uint64
	// Maximum keyframe interval for image sequences (avifenc -k). 0 disables it (default).
	KeyframeInterval int
	// Number of times an image sequence is repeated, or RepetitionCountInfinite
	// (avifenc --repetition-count). Default: infinite.
	RepetitionCount *int
	// Pixel aspect ratio property (avifenc --pasp).
	PixelAspectRatio *PixelAspectRatio
	// Clean aperture property calculated from a crop rectangle (avifenc --crop).
	Crop *image.Rectangle
	// Clean aperture property (avifenc --clap).
	CleanAperture *CleanAperture
	// Rotation property in [0,3]: makes (90 * Rotation) degree rotation anti-clockwise (avifenc --irot).
	Rotation *int
	// Mirroring property: 0 = top-to-bottom, 1 = left-to-right (avifenc --imir).
	Mirror *int
	// Content light level information property (avifenc --clli).
	ContentLightLevel *ContentLightLevel

	// Log2 of the number of tile rows in [0,6] (avifenc --tilerowslog2). Setting it switches to manual tiling.
	TileRowsLog2 int
	// Log2 of the number of tile columns in [0,6] (avifenc --tilecolslog2). Setting it switches to manual tiling.
	TileColsLog2 int
	// Use TileRowsLog2 and TileColsLog2 even when both are 0, instead of automatic tiling (default).
	ManualTiling bool
	// Frame scaling mode (avifenc --scaling-mode). Default: 1/1.
	ScalingMode *ScalingMode
	// Advanced codec-specific key/value options (avifenc -a KEY=VALUE),
	// e.g. {"tune": "ssim", "c:sharpness": "2"}.
	Advanced map[string]string
}

Options are the encoding parameters. They mirror the options of avifenc. The zero value of every field means "use the avifenc default". Fields that accept 0 as a meaningful value are pointers, e.g. Quality: new(80).

type PixelAspectRatio

type PixelAspectRatio struct {
	HSpacing uint32
	VSpacing uint32
}

PixelAspectRatio is the pasp property (avifenc --pasp H,V).

type PixelFormat

type PixelFormat int

PixelFormat is the YUV format of the encoded image (avifenc -y).

const (
	// PixelFormatAuto uses YUV400 for grayscale images (*image.Gray, *image.Gray16) and YUV444
	// for all other images, like avifenc does for PNG input.
	PixelFormatAuto PixelFormat = iota
	PixelFormat444
	PixelFormat422
	PixelFormat420
	PixelFormat400
)

Pixel formats.

type Range

type Range int

Range is the YUV range of the encoded image (avifenc -r).

const (
	// RangeFull is the full range (default).
	RangeFull Range = iota
	// RangeLimited is the limited (studio) range.
	RangeLimited
)

YUV ranges.

type ScalingMode

type ScalingMode struct {
	N uint32
	// Denominator. 0 is treated as 1.
	D uint32
}

ScalingMode is the frame (layer) scaling mode N/D (avifenc --scaling-mode N[/D]).

Jump to

Keyboard shortcuts

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