gaal

package module
v0.0.0-...-6d9b202 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 26 Imported by: 1 module, 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.

Documentation

Overview

Package gaal encodes and decodes media through the native codecs of the host platform, preferring hardware acceleration. It contains no C code.

H.264 and H.265 are never implemented or shipped by this module. They are only reached through codecs that are already on the system or, if Options.AllowDownload is set, through a binary fetched from its vendor at run time.

Streaming model

Every codec is a Stream: call Send with input, then call Receive until it returns ErrAgain. After Flush, Receive returns the remaining output and then io.EOF. Output comes from per-stream pools. Call Release on each output when finished with it, so a running stream does not allocate.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAgain     = errors.New("gaal: more input needed")
	ErrNoBackend = errors.New("gaal: no usable codec backend")
	ErrInvalid   = errors.New("gaal: invalid argument")
	// ErrCorrupt means the input data is damaged. The stream stays usable.
	ErrCorrupt = errors.New("gaal: corrupt input")
	ErrClosed  = errors.New("gaal: codec closed")
)

Errors returned by this package.

View Source
var ErrTimeout = errors.New("gaal: timed out waiting for output")

ErrTimeout is returned by ReceiveWait when no output arrived in time.

Functions

func AppendCompleteJPEG

func AppendCompleteJPEG(dst, b []byte) []byte

AppendCompleteJPEG appends b to dst, with the standard Huffman tables inserted before the first scan when JPEGNeedsTables(b). Anything else is appended unchanged.

func JPEGNeedsTables

func JPEGNeedsTables(b []byte) bool

JPEGNeedsTables reports whether b is a JPEG image without Huffman tables of its own before its first scan. It is false for an image that has them or that it cannot walk.

func ReceiveWait

func ReceiveWait[In, Out any](s Stream[In, Out], timeout time.Duration) (Out, error)

ReceiveWait is Receive that waits up to timeout for output.

Types

type AudioConfig

type AudioConfig struct {
	Codec      Codec
	SampleRate int // default 48000, or 8000 for PCMU and PCMA
	Channels   int // default 2, or 1 for PCMU and PCMA
	Bitrate    int // encoder only, bits per second, 0 means codec default
	// Extra is out-of-band codec setup for decoders, when the container carries
	// it: AudioSpecificConfig for AAC, the ALAC magic cookie, or the three Vorbis
	// headers in Xiph lacing.
	Extra []byte
}

AudioConfig configures an audio codec.

type AudioDecoder

type AudioDecoder = Stream[Packet, *AudioFrame]

Stream types.

type AudioEncoder

type AudioEncoder = Stream[*AudioFrame, *EncodedPacket]

Stream types.

type AudioFrame

type AudioFrame struct {
	Samples    []int16
	SampleRate int
	Channels   int
	PTS        time.Duration
	// contains filtered or unexported fields
}

AudioFrame is interleaved signed 16-bit PCM.

func (*AudioFrame) Release

func (f *AudioFrame) Release()

Release drops a reference. The frame must not be used after its last one.

func (*AudioFrame) Retain

func (f *AudioFrame) Retain()

Retain adds a reference, which needs a matching Release.

type BackendInfo

type BackendInfo struct {
	Name     string
	Codec    Codec
	Dir      Direction
	Hardware bool
}

BackendInfo describes one codec implementation.

type BitrateSetter

type BitrateSetter interface {
	SetBitrate(bps int) error
}

BitrateSetter is implemented by video encoders whose target bitrate can change while they run, for example to follow a receiver's bandwidth estimate. The change takes effect from the next frame sent, without a new keyframe and without reopening the codec.

SetBitrate returns ErrInvalid for a bitrate of zero or less, and an error that matches errors.ErrUnsupported when the backend cannot change its bitrate live. A stream from NewVideoEncoder always implements it and keeps the new bitrate for any backend it fails over to, even when the current backend reports ErrUnsupported.

type Codec

type Codec int

Codec identifies a media format.

const (
	H264 Codec = iota
	VP8
	JPEG
	Opus
	H265
	VP9
	AAC
	MP3
	FLAC
	Vorbis
	ALAC
	AC3
	PCMU // G.711 mu-law
	PCMA // G.711 A-law

	// MJPEG is a sequence of JPEG images, one per packet.
	MJPEG = JPEG
)

Supported codecs.

func (Codec) String

func (c Codec) String() string

type CodecConfigurer

type CodecConfigurer interface {
	// CodecConfig returns the setup bytes for AudioConfig.Extra, or nil.
	CodecConfig() []byte
}

CodecConfigurer is implemented by audio encoders whose stream needs out-of-band setup, such as AAC's AudioSpecificConfig.

type ColorRange

type ColorRange uint8

ColorRange says how sample values map to black and white. gaal never converts samples to another range. It reports what a stream says and signals what the caller declares.

const (
	// RangeUnspecified means the stream does not say. Players then normally
	// assume limited range.
	RangeUnspecified ColorRange = iota
	RangeLimited                // luma 16-235
	RangeFull                   // luma 0-255
)

Color ranges.

func StreamRange

func StreamRange(c Codec, data []byte) ColorRange

StreamRange reports the color range declared by a compressed packet. It is RangeUnspecified when the packet does not say.

func (ColorRange) String

func (r ColorRange) String() string

type Direction

type Direction int

Direction says whether a backend decodes or encodes.

const (
	Decode Direction = iota
	Encode
)

Directions.

func (Direction) String

func (d Direction) String() string

type EncodedPacket

type EncodedPacket struct {
	Packet
	// contains filtered or unexported fields
}

EncodedPacket is pooled compressed output. Its embedded Packet can be passed directly to a decoder.

func (*EncodedPacket) Release

func (p *EncodedPacket) Release()

Release drops a reference. The packet must not be used after its last one.

func (*EncodedPacket) Retain

func (p *EncodedPacket) Retain()

Retain adds a reference, which needs a matching Release.

type FramePool

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

FramePool recycles video frames. Use it to capture encoder input without allocating. It is safe for concurrent use.

func (*FramePool) Get

func (p *FramePool) Get(width, height int, format PixelFormat) *VideoFrame

Get returns a frame with one reference. Its pixels are not cleared.

type HardwarePolicy

type HardwarePolicy int

HardwarePolicy controls which backends may be selected.

const (
	PreferHardware HardwarePolicy = iota // hardware first, then software
	RequireHardware
	RequireSoftware
)

Hardware policies.

type Library

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

Library selects codec backends according to its Options.

func New

func New(opts Options) *Library

New returns a Library. It does not load any codec.

func (*Library) Backends

func (l *Library) Backends(c Codec, d Direction) []BackendInfo

Backends lists the usable backends for a codec, best first.

func (*Library) DecodeJPEG

func (l *Library) DecodeJPEG(data []byte) (*VideoFrame, error)

DecodeJPEG decodes one image. The caller must Release the frame. It reuses the decoders of earlier calls, so calling it for every image of a stream costs about what a VideoDecoder does. Like every JPEG decoder of this package, it accepts images without Huffman tables, as Motion-JPEG sends them, and uses the standard ones (see AppendCompleteJPEG).

func (*Library) EncodeJPEG

func (l *Library) EncodeJPEG(f *VideoFrame, quality int) (*EncodedPacket, error)

EncodeJPEG encodes one image of even size. Quality is 1-100, and 0 selects the default. The caller must Release the packet.

func (*Library) NewAudioDecoder

func (l *Library) NewAudioDecoder(cfg AudioConfig) (AudioDecoder, error)

NewAudioDecoder opens the best available decoder for cfg.Codec.

func (*Library) NewAudioEncoder

func (l *Library) NewAudioEncoder(cfg AudioConfig) (AudioEncoder, error)

NewAudioEncoder opens the best available encoder for cfg.Codec.

func (*Library) NewVideoDecoder

func (l *Library) NewVideoDecoder(cfg VideoConfig) (VideoDecoder, error)

NewVideoDecoder opens the best available decoder for cfg.Codec.

An H.264 decoder never returns a picture it had to guess. Until the first IDR picture, and after a reference picture is lost (frame_num skips a value) until the next one, Send returns an error matching ErrCorrupt for each picture and passes it to no backend, so no picture comes out for it. The stream stays usable. Packets without a picture, such as parameter sets, are always passed on. Damage that a backend detects in a picture is also reported as ErrCorrupt where the backend says so.

JPEG images without Huffman tables, as Motion-JPEG sends them, are decoded with the standard tables.

func (*Library) NewVideoEncoder

func (l *Library) NewVideoEncoder(cfg VideoConfig) (VideoEncoder, error)

NewVideoEncoder opens the best available encoder for cfg.Codec.

func (*Library) Prepare

func (l *Library) Prepare(ctx context.Context, c Codec) error

Prepare downloads Cisco's OpenH264 binary into the cache so that H.264 can be opened on a system without a usable codec. It is the only function in this package that uses the network. It returns an error unless Options.AllowDownload is set, and it does nothing if a verified copy is already cached. The download is checked against SHA-256 values built into this package before it is decompressed or stored. Android and iOS are refused.

Applications that use this binary must meet Cisco's licence conditions, see http://www.openh264.org/BINARY_LICENSE.txt. Call Prepare on the end user's device, because the binary must not be bundled with the application. Let the user enable and disable it, which maps to Options.AllowDownload, and show "OpenH264 Video Codec provided by Cisco Systems, Inc." at that control. Reproduce the licence text with the application's licensing information.

type NoBackendError

type NoBackendError struct {
	Codec Codec
	Dir   Direction
	Tried []string // "backend: reason"
	Hint  string
}

NoBackendError explains why a codec could not be opened. It matches ErrNoBackend with errors.Is.

func (*NoBackendError) Error

func (e *NoBackendError) Error() string

func (*NoBackendError) Is

func (e *NoBackendError) Is(target error) bool

Is implements errors.Is.

type Options

type Options struct {
	Hardware HardwarePolicy
	// AllowDownload permits fetching a missing codec from its vendor.
	// Nothing is downloaded unless this is true.
	AllowDownload bool
	// CacheDir stores downloaded codecs. Empty means the user cache directory.
	CacheDir string
	// Backend restricts selection to the backend with this name.
	Backend string
}

Options configures a Library.

type Packet

type Packet struct {
	Data     []byte
	PTS      time.Duration
	Keyframe bool
}

Packet is compressed input. H.264 and H.265 use Annex B with one access unit per packet. VP8 and VP9 use one frame or superframe per packet. JPEG uses one image per packet. An empty Opus packet reports a lost packet, which the decoder conceals.

type PixelFormat

type PixelFormat int

PixelFormat is the memory layout of a VideoFrame.

const (
	I420 PixelFormat = iota // Y, U and V planes
	NV12                    // Y plane and interleaved UV in U, V is nil
)

Pixel formats. Hardware decoders output NV12 without conversion.

type ReorderReporter

type ReorderReporter interface {
	ReorderStats() ReorderStats
}

ReorderReporter is implemented by decoders opened with VideoConfig.LowDelay.

type ReorderStats

type ReorderStats struct {
	// Reordered counts pictures that precede, in output order, a picture
	// decoded before them. It stays zero for a stream without B-frames.
	Reordered uint64
	// Dropped counts pictures that were discarded because a later picture had
	// already been returned.
	Dropped uint64
	// Depth is the number of frames the decoder now holds back to restore
	// presentation order.
	Depth int
}

ReorderStats describes what a VideoConfig.LowDelay decoder found.

type Stream

type Stream[In, Out any] interface {
	// Send submits input. The stream does not keep In after Send returns.
	Send(In) error
	// Receive returns the next output, ErrAgain if more input is needed, or
	// io.EOF once a flushed stream is empty. The caller owns the output until
	// it calls Release.
	Receive() (Out, error)
	// Flush ends the input. Only Receive and Close are valid afterwards.
	Flush() error
	Close() error
	// Backend reports the implementation in use. It can change until the
	// first output is produced, because of failover.
	Backend() BackendInfo
}

Stream is a codec. It is not safe for concurrent use, but outputs may be used and released on any goroutine.

type VideoConfig

type VideoConfig struct {
	Codec         Codec
	Width, Height int // encoder only, must be even
	FPS           int // encoder only, default 30
	Bitrate       int // encoder only, bits per second, default 2 Mbit/s
	KeyframeEvery int // encoder only, in frames, default 2 seconds
	Quality       int // JPEG and MJPEG encoder only, 1-100, default 85
	// Range is signalled in the encoded stream, encoder only. It describes the
	// frames you send, which are not converted. Pass the Range of the first
	// decoded frame when re-encoding. VP8 cannot signal it and is limited range,
	// JPEG is always full range, and VP9 signals it in each keyframe.
	Range ColorRange
	// LowDelay, for decoders, returns every picture as soon as it is decoded, in
	// decoding order and with the PTS of its own packet, however many frames the
	// stream's parameter sets allow to be reordered. Use it for streams without
	// B-frames, such as most cameras. Should H.264 or H.265 pictures turn out to
	// be reordered, the decoder restores presentation order by holding frames
	// back and sorting them by PTS: pictures that arrive after a later one was
	// returned are dropped, and ReorderReporter counts what happened.
	LowDelay bool
}

VideoConfig configures a video codec. Decoders only need Codec.

type VideoDecoder

type VideoDecoder = Stream[Packet, *VideoFrame]

Stream types.

type VideoEncoder

type VideoEncoder = Stream[*VideoFrame, *EncodedPacket]

Stream types.

type VideoFrame

type VideoFrame struct {
	Width, Height     int
	Format            PixelFormat
	Y, U, V           []byte
	YStride, UVStride int
	PTS               time.Duration
	// Range is the color range of the samples. Decoders set it from the stream.
	// gaal does not convert samples between ranges.
	Range ColorRange
	// ForceKeyframe asks an encoder to make this frame a keyframe.
	ForceKeyframe bool
	// contains filtered or unexported fields
}

VideoFrame is a raw picture.

func NewVideoFrame

func NewVideoFrame(width, height int, format PixelFormat) *VideoFrame

NewVideoFrame allocates a tightly packed frame outside any pool.

func (*VideoFrame) CopyTo

func (f *VideoFrame) CopyTo(dst *VideoFrame) error

CopyTo copies pixels and timing into dst, which must have the same size and format.

func (*VideoFrame) Release

func (f *VideoFrame) Release()

Release drops a reference. The frame must not be used after its last one.

func (*VideoFrame) Retain

func (f *VideoFrame) Retain()

Retain adds a reference, which needs a matching Release.

func (*VideoFrame) ToI420

func (f *VideoFrame) ToI420(dst *VideoFrame) error

ToI420 writes this frame into dst, an I420 frame of the same size.

type Waiter

type Waiter interface {
	// Wait returns when output may be ready or the timeout passes.
	Wait(timeout time.Duration)
}

Waiter is implemented by streams whose output arrives asynchronously, so a caller can sleep instead of polling Receive.

Directories

Path Synopsis
Package camera captures video from the platform's native camera API without C code: V4L2 on Linux and the NDK Camera2 API on Android.
Package camera captures video from the platform's native camera API without C code: V4L2 on Linux and the NDK Camera2 API on Android.
Package display shows gaal.VideoFrame pictures in a native window with as little latency and CPU as the platform allows.
Package display shows gaal.VideoFrame pictures in a native window with as little latency and CPU as the platform allows.
examples
display command
Command display opens a window and shows a moving test pattern.
Command display opens a window and shows a moving test pattern.
e2e
Package e2e runs a live camera through two encode and decode generations with a drawing step between them, then shows the result.
Package e2e runs a live camera through two encode and decode generations with a drawing step between them, then shows the result.
e2e/cmd/e2e command
Command e2e shows a camera through the full encode, draw and decode pipeline.
Command e2e shows a camera through the full encode, draw and decode pipeline.
rtsp-probe command
Command rtsp-probe connects to an RTSP stream, directly or through ONVIF, and prints stream details, frame rate, jitter, loss and decode latency.
Command rtsp-probe connects to an RTSP stream, directly or through ONVIF, and prints stream details, frame rate, jitter, loss and decode latency.
internal
dl
Package dl loads native shared libraries and binds their symbols without any C code in this module.
Package dl loads native shared libraries and binds their symbols without any C code in this module.
Package onvif is a small read-only ONVIF client: WS-Discovery, device capabilities and services, media profiles and stream URIs, for Media1 and Media2 devices.
Package onvif is a small read-only ONVIF client: WS-Discovery, device capabilities and services, media profiles and stream URIs, for Media1 and Media2 devices.
Package rtsp is a client for live RTSP cameras, written in pure Go.
Package rtsp is a client for live RTSP cameras, written in pure Go.
rtsptest
Package rtsptest is a small scriptable RTSP server for tests.
Package rtsptest is a small scriptable RTSP server for tests.

Jump to

Keyboard shortcuts

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