go264

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: BSD-2-Clause Imports: 9 Imported by: 0

README

go264

H.264/AVC encoder and decoder in pure Go. No cgo, ever.

  • CGO-free. Builds and passes its full test suite with CGO_ENABLED=0 on every supported platform. No C toolchain, no shared-library link step.
  • Verified against a reference implementation. The decoder reproduces ffmpeg's output bit for bit on the checked-in conformance streams, and ffmpeg decodes the encoder's output bit for bit to what our own decoder produces. Both directions are measured, not assumed.
  • Hardware acceleration when present. The encoder and decoder probe for platform video engines at construction time and use them when available, falling back to the CPU path transparently. Bindings go through syscalls and dlopen, never cgo.

Status

Working today:

Area State
Decoder, High profile complete, bit-exact against ffmpeg on twenty-nine clips
Encoder, High profile the 8x8 transform, Intra_8x8 and the scaling matrices
Intra prediction all block sizes in both directions, 4x4, 8x8 and 16x16
Inter prediction all P partitions both directions, 8x8 sub-macroblocks, multiple references
B slices both directions: bi-prediction, spatial direct, output reordered by picture order count
Weighted prediction explicit for predictive slices, explicit and implicit for bi-predictive
Supplemental enhancement information recovery point, buffering period, picture timing and user data, both directions
CAVLC complete, both directions
CABAC complete in both directions; streams are 18 to 30 per cent smaller than CAVLC
In-loop deblocking filter complete, shared by encoder and decoder
Reference picture management sliding window and the memory management operations in both directions, including long-term references
Rate-distortion quantisation two to seven per cent of the bitrate at equal quality
Level selection from the picture size, the reference count, the bitrate and the buffer
Slices any count, encoded in parallel; ten times faster on twenty threads for 1.8 per cent more bits
Hardware acceleration encoding on Windows through Media Foundation, on Linux through NVENC and VA-API; decoding on Windows through Direct3D, nine times our own decoder at 1080p. No cgo on any path
Bitrate targeted rate control complete, and under a buffer model the long run rate never exceeds the request
Mode decision rate-distortion, with an early skip test that pays for itself six times over on screen content
SIMD kernels transformed differences, six-tap and bilinear interpolation, block matching, the 4x4 transform and quantisation
Scaling matrices resolved and applied in both directions; the JVT defaults save 8 to 18 per cent of the bits
Intra refresh a sweeping band of intra macroblocks, motion constrained so the refreshed area is never reinfected
Deblocking control on, off, or kept inside slices, with both offsets
Buffer model a coded picture buffer with a constant bitrate mode, announced to the decoder
Lossless transform bypass rejected explicitly, in both directions

See docs/ROADMAP.md for what comes next and why in that order, docs/PLAN.md for the phase breakdown and docs/ARCHITECTURE.md for the design.

Install

go get github.com/oops1/go.264

Library

enc, err := go264.NewEncoder(go264.EncoderConfig{
    Width:  1920,
    Height: 1080,
    FPSNum: 30, FPSDen: 1,
    GOPSize: 60,
    QP:      26,
})
if err != nil {
    return err
}
defer enc.Close()

packet, err := enc.Encode(i420Frame)
dec := go264.NewDecoder()
defer dec.Close()

frames, err := dec.Decode(annexB)
for _, f := range frames {
    i420 = f.AppendI420(i420[:0])
}

Encoder.Backend() and Decoder.Backend() report which implementation is actually in use, and ForceSoftware pins the CPU path for reproducibility.

Command line

go install github.com/oops1/go.264/cmd/go264@latest
go264 encode -s 1280x720 -qp 24 -gop 30 -i input.yuv -o output.264

Or aim at a bitrate instead of a fixed quantiser:

go264 encode -s 1280x720 -b 2500 -gop 30 -i input.yuv -o output.264
go264 decode -i input.264 -o output.yuv

Input and output default to standard input and output, so the tool composes with ffmpeg:

ffmpeg -i movie.mp4 -pix_fmt yuv420p -f rawvideo - | go264 encode -s 1280x720 -o out.264

Verification

Every numeric table taken from the specification is transcribed from an authoritative source and then validated structurally rather than trusted. For the CAVLC tables that means asserting each is a prefix free code whose Kraft sum is at or just below one, which caught seven wrong entries in one table and a chroma table whose sum exceeded one, an arithmetic impossibility for any prefix code.

The decoder is measured against frames ffmpeg produces from the same streams, sample for sample. The encoder is measured the other way: ffmpeg must decode its output to exactly what our own decoder produces. Assembly kernels are compared against their pure Go twins on randomised inputs.

The arithmetic decoder is held to the same standard from the other side. Its tests carry a CABAC encoder written from the specification and round trip randomised bin sequences through it, along with every syntax element the Main profile needs, so that a stream that fails to decode points at the surrounding code rather than at the arithmetic. Prediction and interpolation are compared against independent reference implementations written from the specification formulas rather than from the production code.

Testing

go test ./...

The conformance suite decodes the streams under testdata/conformance and compares every sample against frames produced by ffmpeg. testdata/regen.sh regenerates that corpus. Tests that shell out to ffmpeg skip themselves when it is not installed.

License

BSD 2-Clause. See LICENSE.

Documentation

Index

Constants

View Source
const (
	DeblockingOn              = encoder.DeblockingOn
	DeblockingOff             = encoder.DeblockingOff
	DeblockingNotAcrossSlices = encoder.DeblockingNotAcrossSlices
)
View Source
const (
	ScalingMatrixFlat = encoder.ScalingMatrixFlat
	ScalingMatrixJVT  = encoder.ScalingMatrixJVT
)
View Source
const (
	MotionSearchFull = encoder.MotionSearchFull
	MotionSearchZero = encoder.MotionSearchZero
)
View Source
const (
	WeightedPredictionOff      = encoder.WeightedPredictionOff
	WeightedPredictionExplicit = encoder.WeightedPredictionExplicit
	WeightedPredictionImplicit = encoder.WeightedPredictionImplicit
)
View Source
const (
	DirectSpatial  = encoder.DirectSpatial
	DirectTemporal = encoder.DirectTemporal
)
View Source
const (
	ModeDecisionFast       = encoder.ModeDecisionFast
	ModeDecisionExhaustive = encoder.ModeDecisionExhaustive
)
View Source
const (
	RegionUnknown = encoder.RegionUnknown
	RegionFill    = encoder.RegionFill
	RegionText    = encoder.RegionText
	RegionImage   = encoder.RegionImage
)

Variables

View Source
var ErrClosed = errors.New("go264: use of a closed codec")
View Source
var ErrOverLimit = decoder.ErrOverLimit

Functions

func Backends

func Backends() []string

Types

type DeblockMode added in v1.2.0

type DeblockMode = encoder.DeblockMode

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

func NewDecoder

func NewDecoder() *Decoder

func NewDecoderWithConfig

func NewDecoderWithConfig(cfg DecoderConfig) *Decoder

func (*Decoder) Backend

func (d *Decoder) Backend() string

func (*Decoder) Close

func (d *Decoder) Close() error

func (*Decoder) Decode

func (d *Decoder) Decode(annexB []byte) ([]*Frame, error)

func (*Decoder) Flush

func (d *Decoder) Flush() ([]*Frame, error)

type DecoderConfig

type DecoderConfig struct {
	ForceSoftware bool

	Width  int
	Height int

	Limits DecoderLimits
}

type DecoderLimits added in v1.6.0

type DecoderLimits = decoder.Limits

type DirectMode added in v1.3.0

type DirectMode = encoder.DirectMode

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

func NewEncoder

func NewEncoder(cfg EncoderConfig) (*Encoder, error)

func (*Encoder) Backend

func (e *Encoder) Backend() string

func (*Encoder) Close

func (e *Encoder) Close() error

func (*Encoder) Encode

func (e *Encoder) Encode(i420 []byte) ([]byte, error)

func (*Encoder) EncodeFrame added in v1.1.0

func (e *Encoder) EncodeFrame(f *Frame, changed []image.Rectangle, regions []Region) ([]byte, error)

func (*Encoder) EncodeWithHints added in v1.2.0

func (e *Encoder) EncodeWithHints(i420 []byte, changed []image.Rectangle, regions []Region) ([]byte, error)

func (*Encoder) Flush added in v1.1.0

func (e *Encoder) Flush() ([]byte, error)

func (*Encoder) ForceKeyFrame added in v1.1.0

func (e *Encoder) ForceKeyFrame()

type EncoderConfig

type EncoderConfig struct {
	Width   int
	Height  int
	FPSNum  int
	FPSDen  int
	GOPSize int
	QP      int

	BitrateKbps int
	RefFrames   int
	BFrames     int

	LongTermReferences int

	CABAC         bool
	MotionSearch  MotionSearch
	ModeDecision  ModeDecision
	Slices        int
	Transform8x8  bool
	ScalingMatrix ScalingMatrix
	Trellis       bool
	ForceSoftware bool

	WeightedPrediction WeightedPrediction
	DirectMode         DirectMode

	IntraRefresh        int
	RepeatParameterSets bool

	Deblocking         DeblockMode
	DeblockAlphaOffset int
	DeblockBetaOffset  int

	VBVBufferKbits int
	VBVMaxrateKbps int
	CBR            bool
}

type Frame

type Frame struct {
	Y       []byte
	Cb      []byte
	Cr      []byte
	StrideY int
	StrideC int
	Width   int
	Height  int
}

func (*Frame) AppendI420

func (f *Frame) AppendI420(dst []byte) []byte

func (*Frame) I420Size

func (f *Frame) I420Size() int

type ModeDecision added in v1.2.0

type ModeDecision = encoder.ModeDecision

type MotionSearch added in v1.1.0

type MotionSearch = encoder.MotionSearch

type Region added in v1.1.0

type Region = encoder.Region

type RegionKind added in v1.1.0

type RegionKind = encoder.RegionKind

type ScalingMatrix added in v1.2.0

type ScalingMatrix = encoder.ScalingMatrix

type WeightedPrediction added in v1.3.0

type WeightedPrediction = encoder.WeightedPrediction

Directories

Path Synopsis
cmd
go264 command
hwaccel
vaapi module
internal
mc
nal

Jump to

Keyboard shortcuts

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