codec

package
v0.1.0-alpha.2 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 13 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.

Documentation

Overview

Package codec defines the decoder and encoder contracts: descriptors that declare what an implementation can do, factories that open it, and the caller-owned result buffers that keep decode/encode allocation-free. It also carries the codec spec grammar recipes use — codec.Opus(...), codec.VP9(codec.Bitrate(...)), codec.Control(fn) — and the per-runtime registry external codec adapters plug into.

Index

Constants

View Source
const (
	Mono   = 1
	Stereo = 2
)

Audio channel-count shorthands.

Variables

View Source
var (
	// ErrNilResult reports a nil result buffer handed to DecodeInto/EncodeInto.
	ErrNilResult = errors.New("codec: nil result")
	// ErrNilDecoder reports a nil decoder where one is required.
	ErrNilDecoder = errors.New("codec: nil decoder")
	// ErrNilEncoder reports a nil encoder where one is required.
	ErrNilEncoder = errors.New("codec: nil encoder")
	// ErrClosed reports a call on a closed decoder or encoder.
	ErrClosed = errors.New("codec: closed")
	// ErrOutputBufferTooSmall reports a caller-owned output buffer without the
	// capacity the operation needs; grow the buffer or the configured bounds.
	ErrOutputBufferTooSmall = errors.New("codec: output buffer too small")
	// ErrResultFull reports a result slice at its DecodeBounds capacity.
	ErrResultFull = errors.New("codec: result capacity full")
	// ErrUnavailable reports a codec whose descriptor is registered but whose
	// implementation is not (no factory).
	ErrUnavailable = errors.New("codec: unavailable")
	// ErrUnsupportedCodecSwitch reports a mid-stream codec change the decoder
	// cannot rebind to.
	ErrUnsupportedCodecSwitch = errors.New("codec: unsupported codec switch")
	// ErrUnsupportedFormat reports a sample or pixel format the codec cannot
	// consume or produce.
	ErrUnsupportedFormat = errors.New("codec: unsupported format")
	// ErrUnsupportedSampleRate reports an audio rate outside the codec's
	// supported set.
	ErrUnsupportedSampleRate = errors.New("codec: unsupported sample rate")
)

Codec sentinels, matched with errors.Is.

View Source
var (
	KnobBitrate     = Knob{Name: knobBitrate, Type: KnobInt, Min: 1000, Max: 2_000_000_000, Live: true, Help: "target bitrate in bits per second (2M, 800k)"}
	KnobRateControl = Knob{Name: "rc", Type: KnobEnum, Values: []string{"cbr", "vbr", "cq", "cqp"}, Help: "rate control: constant or variable bitrate, constant quality (quality), or constant quantizer (qp)"}
	KnobQuality     = Knob{Name: "quality", Type: KnobInt, Min: 0, Max: 100, Help: "constant-quality target, 0 to 100, higher is better"}
	KnobQP          = Knob{Name: "qp", Type: KnobInt, Min: 0, Max: 255, Help: "constant quantizer, in the codec's own scale"}
	KnobSpeed       = Knob{Name: "speed", Type: KnobInt, Min: 0, Max: 10, Help: "encoder effort, 0 slowest and best to 10 fastest"}
	KnobThreads     = Knob{Name: "threads", Type: KnobInt, Min: 0, Max: 256, Help: "worker threads; 0 picks per core"}
	KnobTune        = Knob{Name: "tune", Type: KnobEnum, Values: []string{"camera", "screen", "film", "animation", "grain", "latency"}, Help: "content tuning"}
	KnobGOP         = Knob{Name: knobGOP, Type: KnobInt, Min: 0, Max: 1 << 20, Help: "frames between keyframes (codec.KeyframeInterval)"}
	KnobRealtime    = Knob{Name: knobRealtime, Type: KnobBool, Help: "low-latency mode; on by default for realtime work"}
)

The common knobs. A backend that takes bitrate, rate control, quality, a quantizer, speed, threads, tuning, a keyframe interval, or a low-latency mode declares these, narrowing the values or range to what it honors, so a recipe's settings mean the same whichever backend serves them, and selection skips a backend that cannot honor one.

View Source
var ErrInvalidSetting = errors.New("codec: invalid setting")

ErrInvalidSetting reports a codec setting a backend does not take, or a value outside what it accepts.

View Source
var ErrNotFound = errors.New("codec: not found")

ErrNotFound reports a codec id (or id+mode) with no registered descriptor.

Functions

func BackendList

func BackendList(descriptors []Descriptor) string

BackendList names descriptors' backends for display, each with its kind: "videotoolbox (hardware), openh264 (lib)".

func BitrateMetadata

func BitrateMetadata(bitsPerSecond int) av.Metadata

BitrateMetadata builds the event metadata that carries a live encoder bitrate retarget: av.MetadataBitrate holding the rate as a decimal string in bits per second. It is the encoding half of EventBitrate, so producers and encoders agree on the wire form of av.EventBitrateChanged.

func EventBitrate

func EventBitrate(event *av.Event) (int, bool)

EventBitrate extracts the requested bitrate in bits per second from an av.EventBitrateChanged event. It reports false when the event carries no positive decimal av.MetadataBitrate entry, so an encoder can reject a malformed retarget explicitly instead of applying garbage.

func KnobScope

func KnobScope(key string) (string, bool)

KnobScope reports the backend a setting key is scoped to: openh264 for openh264.rc and for the raw openh264-params.

Types

type BackendInfo

type BackendInfo struct {
	Name    string
	Kind    BackendKind
	Module  string
	Package string
	Status  string
	// Notice is the attribution the backend's license asks a program to
	// show (Explain prints it). Unavailable is why a backend whose Status is
	// not active cannot serve, with the fix.
	Notice      string
	Unavailable error
}

BackendInfo identifies the implementation behind a descriptor. Name is its identity within the codec (h264/videotoolbox, av1/goav1): a registry holds many backends per codec, one per name, and registering a name again replaces it. Kind ranks the backend for automatic selection; Module and Package make it traceable in Explain.

func (BackendInfo) Label

func (b BackendInfo) Label() string

Label is the backend's display name: its name and, when declared, its kind in parentheses, as Describe and Explain show it.

type BackendKind

type BackendKind string

BackendKind is what a backend runs on, which ranks it when a request names no backend: hardware first, then shared libraries, then pure Go. A backend without a kind (an application's own factory) ranks ahead of all three.

const (
	// KindHardware is a hardware codec reached through the OS, such as
	// VideoToolbox.
	KindHardware BackendKind = "hardware"
	// KindLib is a software codec in a shared library or OS framework bound at
	// run time, such as OpenH264.
	KindLib BackendKind = "lib"
	// KindGo is a pure-Go codec.
	KindGo BackendKind = "go"
)

The backend kinds.

type Capabilities

type Capabilities struct {
	SampleFormats []string
	PixelFormats  []string
	// SampleRates lists the audio rates the codec accepts; empty means any.
	// Planning refuses other rates with the .Resample(...) fix instead of
	// letting the encoder fail at open.
	SampleRates []int
	// BitDepths lists the sample bit depths the backend codes; empty means 8.
	BitDepths []int
	// MaxWidth and MaxHeight bound the video geometry the backend accepts.
	MaxWidth    int
	MaxHeight   int
	RTPPayloads []string
	BuildTags   []string
}

Capabilities carries concrete media compatibility details. Codec identity, media type, supported modes, realtime status, and experimental status live on Descriptor so each fact has one owner. Backend selection filters on these fields; an empty list or a zero bound accepts anything.

type Choice

type Choice struct {
	Descriptor Descriptor
	// Decoder is set for ModeDecode and Encoder for ModeEncode.
	Decoder      DecoderFactory
	Encoder      EncoderFactory
	Reason       string
	Alternatives []Descriptor
}

Choice is the backend Select picked for a Need, why it was picked, and the other backends that would serve the need too, in preference order.

type ControlRequest

type ControlRequest struct {
	Type     ControlType
	StreamID av.StreamID
	Reason   string
}

ControlRequest is an upstream ask a decoder emits while decoding — most commonly a keyframe request after unrecoverable loss.

func (*ControlRequest) Reset

func (r *ControlRequest) Reset()

Reset clears the request for reuse.

type ControlType

type ControlType string

ControlType names a decoder's upstream ask.

const (
	ControlRequestKeyframe ControlType = "request_keyframe"
)

ControlRequestKeyframe asks the producer for a keyframe so decoding can resynchronize.

type DecodeBounds

type DecodeBounds struct {
	// MaxFramesPerInput bounds decoded frames emitted from one DecodeInto call.
	MaxFramesPerInput int
	// MaxEventsPerInput bounds events emitted from one DecodeInto call.
	MaxEventsPerInput int
	// MaxRequestsPerInput bounds control requests emitted from one DecodeInto call.
	MaxRequestsPerInput int
	// MaxPayloadBytes bounds one encoded input payload.
	MaxPayloadBytes int
	// MaxRetainedBytes bounds data a decoder may keep across DecodeInto calls,
	// such as a partial realtime video fragment.
	MaxRetainedBytes int
	// MaxWidth and MaxHeight bound video output geometry when known before open.
	MaxWidth  int
	MaxHeight int
}

DecodeBounds caps a decoder's per-call output and retained memory so allocation stays provable up front; zero fields take the adapter defaults through WithDefaults.

func (DecodeBounds) WithDefaults

func (b DecodeBounds) WithDefaults(defaults DecodeBounds) DecodeBounds

WithDefaults fills every unset (zero) bound from defaults and returns the result.

type DecodeConfig

type DecodeConfig struct {
	Stream     av.Stream
	Realtime   bool
	LowLatency bool
	Resilience ResiliencePolicy
	Bounds     DecodeBounds
	Settings   Settings
	// OpaqueState carries adapter-specific, caller-owned state. Adapter
	// packages must document the concrete type before reading it.
	OpaqueState any
}

DecodeConfig is everything a decoder needs at open: the stream's declared parameters, latency/resilience policy, output bounds, and settings.

type DecodeResult

type DecodeResult struct {
	Frames   []av.Frame
	Events   []av.Event
	Requests []ControlRequest
}

DecodeResult is the caller-owned output buffer DecodeInto/FlushInto append to: decoded frames, emitted events, and control requests. Reusing one result across calls keeps decode allocation-free.

Plane bytes may be the decoder's own memory, valid until its next call (reused output, reference pictures): the stage copies those once into a pooled buffer before publishing. Planes from av.NewBuffer pass their one reference to the stage without a copy; a decoder that keeps such a plane for itself retains it first.

func (*DecodeResult) Reset

func (r *DecodeResult) Reset()

Reset clears the result for reuse, keeping allocated capacity.

type DecodeStateFactory

type DecodeStateFactory interface {
	NewDecodeState(context.Context, DecodeConfig) (any, error)
}

DecodeStateFactory is an optional extension for decoder factories that can provision adapter-specific state for high-level runtimes. Low-level callers may still pass DecodeConfig.OpaqueState directly when they need exact control.

type Decoder

type Decoder interface {
	Descriptor() Descriptor
	Open(context.Context, DecodeConfig) error
	DecodeInto(context.Context, *av.Packet, *DecodeResult) error
	FlushInto(context.Context, *DecodeResult) error
	HandleEvent(context.Context, *av.Event) error
	Close() error
}

Decoder turns packets into frames through caller-owned result buffers. DecodeInto may emit zero or more frames per packet; FlushInto drains buffered output at end of stream; HandleEvent reacts to in-band events (discontinuities reset state).

type DecoderFactory

type DecoderFactory interface {
	NewDecoder(context.Context, DecodeConfig) (Decoder, error)
}

DecoderFactory opens decoders for a registered descriptor; registries hold factories so nothing allocates until a chain actually decodes.

type DecoderStage

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

DecoderStage adapts a Decoder into a pipeline.Stage: packets decode into frames, events reach the decoder (codec changes are validated against the opened stream), and decoder control requests surface as events.

func NewDecoderStage

func NewDecoderStage(config DecoderStageConfig) (*DecoderStage, error)

NewDecoderStage wraps an opened decoder as a stage; the decoder is required.

func (*DecoderStage) Close

func (s *DecoderStage) Close() error

Close closes the wrapped decoder once.

func (*DecoderStage) DescribeNode

func (s *DecoderStage) DescribeNode() pipeline.NodeSpec

DescribeNode reports the stage's spec entry for Describe.

func (*DecoderStage) Handle

func (s *DecoderStage) Handle(ctx context.Context, msg *pipeline.Message, emitter pipeline.Emitter) error

Handle decodes one packet message into frames (events pass to the decoder first), emitting results downstream.

func (*DecoderStage) Name

func (s *DecoderStage) Name() string

Name returns the stage's node name.

type DecoderStageConfig

type DecoderStageConfig struct {
	Name string
	// Detail is optional graph-rendering context for humans.
	Detail string
	// InputStream is the stream this decoder was opened for. When set, codec
	// change events that switch that stream to another codec fail explicitly.
	InputStream av.Stream
	// Decoder receives packets and events and writes decoded frames into Result.
	Decoder Decoder
	// Result is caller-owned scratch. Its slice capacities define how many
	// frames, events, and control requests can be emitted per input message.
	Result DecodeResult
	// DropInputEvents suppresses forwarding upstream events after the decoder
	// has observed them. By default, events stay visible downstream.
	DropInputEvents bool
}

DecoderStageConfig configures a DecoderStage: the opened decoder, the caller-owned result scratch bounding per-message output, and event behavior.

type Descriptor

type Descriptor struct {
	ID           av.CodecID
	Name         string
	Type         av.MediaType
	Modes        []Mode
	Profiles     []string
	Realtime     bool
	Experimental bool
	Capabilities Capabilities
	Backend      BackendInfo
	// Knobs are the settings the backend takes (see Knob); nil leaves its
	// settings unchecked. RawKnobs check its raw parameters; nil passes
	// them to the backend as given.
	Knobs    []Knob
	RawKnobs []Knob
}

Descriptor identifies a codec implementation and what it can do: identity, media type, supported modes, and concrete capabilities. Registries key on it, and the planner's compatibility checks read it before anything is allocated or opened. Realtime declares low-latency support: among otherwise equal backends, realtime work selects one that declares it.

func (Descriptor) Check

func (d Descriptor) Check(need Need) error

Check reports why the descriptor's declared capabilities cannot serve need, or nil when they can. It reads capabilities only: not the backend name, the mode, or whether a factory is registered.

func (Descriptor) Knob

func (d Descriptor) Knob(name string) (Knob, bool)

Knob returns the descriptor's knob called name.

func (Descriptor) ResolveKnobs

func (d Descriptor) ResolveKnobs(s Settings, lowLatency bool) (KnobValues, error)

ResolveKnobs checks s against the descriptor's knobs and returns their values: the typed common settings first, then each codec.Setting, then the backend's raw parameters; lowLatency defaults the realtime knob. Settings scoped to another backend are skipped. A descriptor that declares no knobs accepts its settings unchecked, as the values of their names.

func (Descriptor) Supports

func (d Descriptor) Supports(mode Mode) bool

Supports reports whether the descriptor lists the given mode.

type EncodeConfig

type EncodeConfig struct {
	Stream     av.Stream
	Parameters av.CodecParameters
	Realtime   bool
	LowLatency bool
	Settings   Settings
}

EncodeConfig is everything an encoder needs at open: the input stream, the target codec parameters, latency mode, and settings.

type EncodeResult

type EncodeResult struct {
	Packets []av.Packet
	Events  []av.Event
}

EncodeResult is the caller-owned output buffer EncodeInto/FlushInto append to: encoded packets and emitted events. Reusing one result across calls keeps encode allocation-free. Payload lifetimes follow DecodeResult's.

func (*EncodeResult) Reset

func (r *EncodeResult) Reset()

Reset clears the result for reuse, keeping allocated capacity.

type Encoder

type Encoder interface {
	Descriptor() Descriptor
	Open(context.Context, EncodeConfig) error
	EncodeInto(context.Context, *av.Frame, *EncodeResult) error
	FlushInto(context.Context, *EncodeResult) error
	HandleEvent(context.Context, *av.Event) error
	Close() error
}

Encoder turns frames into packets through caller-owned result buffers. FlushInto drains buffered output at end of stream; HandleEvent applies live controls (EventKeyframeRequired, EventBitrateChanged) — an encoder that cannot apply one must return an error, never ignore it.

type EncoderFactory

type EncoderFactory interface {
	NewEncoder(context.Context, EncodeConfig) (Encoder, error)
}

EncoderFactory opens encoders for a registered descriptor; registries hold factories so nothing allocates until a chain actually encodes.

type EncoderStage

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

EncoderStage adapts an Encoder into a pipeline.Stage: frames encode into packets (optionally restamped to the encoded output stream) and events reach the encoder before continuing downstream.

func NewEncoderStage

func NewEncoderStage(config EncoderStageConfig) (*EncoderStage, error)

NewEncoderStage wraps an opened encoder as a stage; the encoder is required.

func (*EncoderStage) Close

func (s *EncoderStage) Close() error

Close closes the wrapped encoder once.

func (*EncoderStage) DescribeNode

func (s *EncoderStage) DescribeNode() pipeline.NodeSpec

DescribeNode reports the stage's spec entry for Describe.

func (*EncoderStage) Handle

func (s *EncoderStage) Handle(ctx context.Context, msg *pipeline.Message, emitter pipeline.Emitter) error

Handle encodes one frame message into packets (events pass to the encoder first), emitting results downstream.

func (*EncoderStage) Name

func (s *EncoderStage) Name() string

Name returns the stage's node name.

func (*EncoderStage) OutputStreamID

func (s *EncoderStage) OutputStreamID() av.StreamID

OutputStreamID is the stream id the stage stamps on the packets it emits, or empty when packets keep the encoder's own ids.

type EncoderStageConfig

type EncoderStageConfig struct {
	Name string
	// Detail is optional graph-rendering context for humans.
	Detail string
	// Encoder receives frames and events and writes encoded packets into Result.
	Encoder Encoder
	// Result is caller-owned scratch. Its slice capacities define how many
	// packets and events can be emitted per input message.
	Result EncodeResult
	// OutputStreamID stamps emitted packets with the runtime-owned encoded
	// stream ID when StampOutputStream is true.
	OutputStreamID av.StreamID
	// OutputCodecEpoch stamps emitted packets with the encoded stream epoch when
	// StampOutputStream is true.
	OutputCodecEpoch av.Epoch
	// StampOutputStream overwrites packet StreamID and CodecEpoch before packets
	// leave the stage. This is useful when one decoded stream fans out into
	// several encoded output streams.
	StampOutputStream bool
}

EncoderStageConfig configures an EncoderStage: the opened encoder, the caller-owned result scratch bounding per-message output, and output stream stamping.

type Knob

type Knob struct {
	Name    string
	Type    KnobType
	Min     float64
	Max     float64
	Values  []string
	Default string
	Help    string
	// Live marks a knob the backend applies while running: a bitrate change
	// reaches it without a restart.
	Live bool
}

Knob declares one setting a backend takes: its name, type, range or choices, default, and a line of help. A backend that declares knobs has its settings checked against them when a recipe is planned and when it opens, misspellings get a suggestion, and Explain lists them.

Knobs named for the common settings receive them: bitrate (codec.Bitrate), gop (codec.KeyframeInterval), profile, level, and realtime (the low-latency mode of realtime work, unless set). rc and threads are the common names for rate control and thread count.

Settings reach a backend as codec.Setting(name, value); a name prefixed with a backend and a dot (openh264.rc) applies only when that backend serves. Anything the knobs leave out passes raw, as one codec.Setting("<backend>-params", "key=value:key=value"), checked against the backend's RawKnobs when it declares them.

func (Knob) Parse

func (k Knob) Parse(value string) (string, error)

Parse checks value against the knob and returns it in canonical form: an int as decimal digits, a bool as true or false, an enum as declared.

func (Knob) String

func (k Knob) String() string

String is the knob's one-line summary, as Explain lists it: "rc=cbr|vbr|cqp (default vbr): rate control".

type KnobType

type KnobType string

KnobType is the type of a Knob's value.

const (
	KnobBool   KnobType = "bool"
	KnobInt    KnobType = "int"
	KnobFloat  KnobType = "float"
	KnobEnum   KnobType = "enum"
	KnobString KnobType = "string"
)

The knob types. An int accepts SI suffixes (2M, 800k); a bool accepts true/false, yes/no, on/off, and 1/0; an enum one of Values, ignoring case.

type KnobValues

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

KnobValues are a backend's settings resolved against its knobs: each knob's value (set, defaulted, or empty) and the raw parameters.

func (KnobValues) Bool

func (v KnobValues) Bool(name string) bool

Bool returns a bool knob's value, false when empty.

func (KnobValues) Float

func (v KnobValues) Float(name string) float64

Float returns a float knob's value, 0 when empty.

func (KnobValues) Int

func (v KnobValues) Int(name string) int

Int returns an int knob's value, or a bool knob's as 1 or 0; 0 when empty.

func (KnobValues) Int32

func (v KnobValues) Int32(name string) int32

Int32, Uint32, and Uint16 return an int or bool knob's value parsed at that size, for C fields of that type: a knob read this way declares a range inside the type, which planning enforces with a refusal naming it, so the value fits; one that cannot reads as 0. Backends never narrow Int by hand.

func (KnobValues) IsSet

func (v KnobValues) IsSet(name string) bool

IsSet reports whether the request set the knob (not just its default).

func (KnobValues) Raw

func (v KnobValues) Raw() [][2]string

Raw returns the raw parameters in the order given, each a key and value.

func (KnobValues) String

func (v KnobValues) String(name string) string

String returns the knob's value, or "" when it is neither set nor defaulted.

func (KnobValues) Uint16

func (v KnobValues) Uint16(name string) uint16

Uint16 is Int32 for unsigned 16-bit fields.

func (KnobValues) Uint32

func (v KnobValues) Uint32(name string) uint32

Uint32 is Int32 for unsigned 32-bit fields.

func (KnobValues) With

func (v KnobValues) With(name, value string) KnobValues

With returns a copy of v with knob name set to an already-parsed value, as a live control changes it.

type Mode

type Mode string

Mode says which direction a codec implementation works in.

const (
	ModeDecode Mode = "decode"
	ModeEncode Mode = "encode"
)

The codec modes.

type Need

type Need struct {
	ID   av.CodecID
	Mode Mode
	// Backend names the backend that must serve the request.
	Backend      string
	Media        av.MediaType
	Profile      string
	PixelFormat  string
	SampleFormat string
	SampleRate   int
	BitDepth     int
	Width        int
	Height       int
	// Realtime ranks backends that declare low-latency support first among
	// otherwise equal candidates.
	Realtime bool
	// Settings are the knob settings the request makes of whichever backend
	// serves it (Settings.KnobSettings): a backend that declares knobs
	// serves only when it takes every one of them, with that value.
	Settings map[string]string
}

Need is what one request asks of the backend that serves a codec. Zero fields ask nothing.

type Option

type Option func(*Settings)

Option configures encoder/decoder settings. This package's codec constructors (Opus, VP9, …) accept them.

func Backend

func Backend(name string) Option

Backend makes one backend serve the codec, by its name (videotoolbox, openh264, goav1), instead of the runtime's preference order. A backend that is not registered, or cannot meet the request, is refused with the backends that can; selection never falls back on its own.

func BitDepth

func BitDepth(bits int) Option

BitDepth requests the coded sample bit depth (8, 10, 12); selection keeps to the backends that declare it.

func Bitrate

func Bitrate(bitsPerSecond int) Option

Bitrate sets the target encoder bitrate in bits per second.

func Channels

func Channels(channels int) Option

Channels sets the encoder output channel count (Mono/Stereo).

func ClockRate

func ClockRate(clockRate uint32) Option

ClockRate sets the RTP clock rate in Hz.

func Control

func Control[T any](fn func(T) error) Option

Control is the raw escape hatch: when the codec opens, the adapter calls fn with its concrete native encoder or decoder (or the construction config it documents), so host code applies anything the backend exposes. T is that native type, inferred from fn:

codec.Opus(codec.Control(func(e *gopus.Encoder) error { return e.SetComplexity(10) }))

A native value that is not a T fails the open, naming both types, as does an error from fn.

func FPS

func FPS(num int, den ...int) Option

FPS sets the encode frame cadence. den defaults to 1 (so FPS(30) is 30/1).

func KeyframeInterval

func KeyframeInterval(frames int) Option

KeyframeInterval sets the keyframe cadence in encoded frames.

func Level

func Level(level string) Option

Level requests a codec conformance level by its codec-specific name (H264 "3.1"); the adapter validates it at open and fails on values its backend cannot honor. Empty leaves the adapter default.

func Profile

func Profile(profile string) Option

Profile requests a codec profile by its codec-specific name (VP9 "0", H264 "baseline"); the adapter validates it at open and fails on values its backend cannot honor. Empty leaves the adapter default.

func SampleRate

func SampleRate(sampleRate int) Option

SampleRate sets the encoder output sample rate in Hz.

func Setting

func Setting(key string, value string) Option

Setting records one adapter-specific string setting. Common knobs should use the typed options above; Setting is for native/custom adapters that own their own validation vocabulary.

type ParameterReporter

type ParameterReporter interface {
	EncodedParameters() av.CodecParameters
}

ParameterReporter is an optional Encoder capability for parameters known only once the encoder is open. The runtime folds them into the encoded stream before any muxer writes its header, so the container describes the bitstream the encoder actually emits: the Opus encoder reports the identification header whose pre-skip covers its lookahead.

type Rejection

type Rejection struct {
	Descriptor Descriptor
	Reason     string
}

Rejection is one backend that cannot serve a Need, and why.

type ResiliencePolicy

type ResiliencePolicy struct {
	AcceptLoss       bool
	ConcealAudio     bool
	DropDamagedVideo bool
	RequestKeyframes bool
	MaxReorderDelay  time.Duration
}

ResiliencePolicy says how a decoder treats damaged or lossy input: whether loss is tolerated, audio concealed, damaged video dropped, keyframes requested for recovery, and how long to wait for reordered input.

type SelectError

type SelectError struct {
	Need Need
	// Rejected lists the backends registered for the codec and mode that
	// cannot serve the need, each with its reason.
	Rejected []Rejection
	// Satisfying lists the backends that would serve the need when the one it
	// names is missing or cannot.
	Satisfying []Descriptor
	// Err is ErrNotFound (no backend, or none by the requested name),
	// ErrUnavailable (only descriptors registered), or ErrUnsupportedFormat
	// (no backend fits the need).
	Err error
}

SelectError is a Need no registered backend serves. It names every backend that was considered and why each cannot serve, and, when the need names a backend, the ones that could serve it instead.

func (*SelectError) Error

func (e *SelectError) Error() string

func (*SelectError) Unwrap

func (e *SelectError) Unwrap() error

type Settings

type Settings struct {
	// Bitrate requests an encoder bitrate in bits per second. Zero lets the
	// encoder choose its default bitrate.
	Bitrate int `json:"bitrate,omitempty"`
	// Framerate requests an encoder frame cadence. Zero lets the encoder infer
	// cadence from input frames.
	Framerate av.Duration `json:"framerate,omitzero"`
	// KeyframeInterval requests a keyframe cadence in encoded frames. Zero lets
	// the encoder choose its default cadence.
	KeyframeInterval int `json:"keyframeInterval,omitempty"`
	// Profile requests an encoder profile. Empty lets the encoder choose its
	// default or preserve the selected input profile when copying compatible
	// stream metadata.
	Profile string `json:"profile,omitempty"`
	// Level requests an encoder level. Empty lets the encoder choose its default
	// or preserve the selected input level when copying compatible stream
	// metadata.
	Level string `json:"level,omitempty"`
	// Backend names the backend that must serve this codec (videotoolbox,
	// openh264, goav1). Empty selects by the runtime's preference order among
	// the backends whose capabilities fit.
	Backend string `json:"backend,omitempty"`
	// BitDepth requests the coded sample bit depth. Zero means 8.
	BitDepth int `json:"bitDepth,omitempty"`
	// Channels, SampleRate, ClockRate, ChannelLayout set the encoder output audio
	// format (zero = derive from the input stream). ChannelsSet/SampleRateSet
	// record that the value was requested explicitly, so a requested zero is
	// validated rather than treated as unset.
	Channels      int    `json:"channels,omitempty"`
	SampleRate    int    `json:"sampleRate,omitempty"`
	ClockRate     uint32 `json:"clockRate,omitempty"`
	ChannelLayout string `json:"channelLayout,omitempty"`
	ChannelsSet   bool   `json:"-"`
	SampleRateSet bool   `json:"-"`
	// Custom carries adapter-specific string settings that should not become
	// common fields. CLI and control-plane frontends can pass native knobs here
	// while external adapters keep ownership of validation and interpretation.
	Custom av.Metadata `json:"custom,omitempty"`
	// Control is the raw escape hatch: at encoder/decoder open the adapter invokes
	// it with its concrete native encoder/decoder (or construction options), so
	// callers can apply backend-specific settings directly. A non-nil error fails open.
	Control func(any) error `json:"-"`
}

Settings carries the grouped common encoder/decoder settings (tier 1) plus adapter-specific string settings and the raw Control escape hatch. Recipes populate it through codec options (Bitrate, FPS, Profile, Setting, Control, ...); adapters read it at open.

func (Settings) KnobSettings

func (s Settings) KnobSettings() map[string]string

KnobSettings are the knob settings s makes of whichever backend serves it, by knob name: the typed common settings (bitrate, gop, profile, level) and every codec.Setting not scoped to one backend.

type SimpleRegistry

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

SimpleRegistry is the per-runtime codec registry: descriptors for capability checks plus the decoder and encoder backends serving each codec. It holds many backends per codec, keyed by codec, backend name, and mode; registering the same identity again replaces it. Select picks the backend for one request. It is populated at runtime construction and read-only afterwards.

func NewRegistry

func NewRegistry() *SimpleRegistry

NewRegistry returns an empty codec registry.

func (*SimpleRegistry) CheckScopes

func (r *SimpleRegistry) CheckScopes(id av.CodecID, s Settings) error

CheckScopes refuses a setting scoped to a backend the registry holds no descriptor of for codec id (openh264.rc with no openh264), with the nearest backend name, so a misspelled scope is never silently skipped.

func (*SimpleRegistry) DecoderFactory

func (r *SimpleRegistry) DecoderFactory(id av.CodecID) (DecoderFactory, error)

DecoderFactory returns the decoder factory Select picks for a codec id with no other requirement: ErrUnavailable when only descriptors are registered, ErrNotFound when nothing is.

func (*SimpleRegistry) Descriptors

func (r *SimpleRegistry) Descriptors() []Descriptor

Descriptors returns a copy of every registered descriptor.

func (*SimpleRegistry) EncoderFactory

func (r *SimpleRegistry) EncoderFactory(id av.CodecID) (EncoderFactory, error)

EncoderFactory returns the encoder factory Select picks for a codec id with no other requirement: ErrUnavailable when only descriptors are registered, ErrNotFound when nothing is.

func (*SimpleRegistry) Find

func (r *SimpleRegistry) Find(id av.CodecID, mode Mode) ([]Descriptor, error)

Find returns the descriptors matching the codec id (empty matches all) that support mode, or ErrNotFound when none do.

func (*SimpleRegistry) Prefer

func (r *SimpleRegistry) Prefer(id av.CodecID, mode Mode, order ...string)

Prefer sets the order Select tries the backends of codec id in mode when a request names none: backend names (openh264) or kinds (hardware, lib, go), most preferred first. An empty id or mode applies to every codec or mode; the most specific order wins. Backends the order leaves out follow in the default order: no kind, hardware, lib, go, later registrations first within a kind.

func (*SimpleRegistry) RegisterDecoder

func (r *SimpleRegistry) RegisterDecoder(desc Descriptor, factory DecoderFactory)

RegisterDecoder records the descriptor (decode mode added) and adds its backend as a decoder for the codec, replacing a decoder registered under the same backend name.

func (*SimpleRegistry) RegisterDescriptor

func (r *SimpleRegistry) RegisterDescriptor(desc Descriptor)

RegisterDescriptor records a codec's capabilities without an implementation, so validation recognizes the codec.

func (*SimpleRegistry) RegisterEncoder

func (r *SimpleRegistry) RegisterEncoder(desc Descriptor, factory EncoderFactory)

RegisterEncoder records the descriptor (encode mode added) and adds its backend as an encoder for the codec, replacing an encoder registered under the same backend name.

func (*SimpleRegistry) Select

func (r *SimpleRegistry) Select(need Need) (Choice, error)

Select picks the backend that serves need: the one need names, or else the most preferred backend whose declared capabilities and knobs fit (see Prefer). It never substitutes another backend for a named one, and reads only declarations: nothing is loaded or opened.

type Spec

type Spec struct {
	ID         av.CodecID         `json:"id,omitempty"`
	Type       av.MediaType       `json:"type,omitempty"`
	Parameters av.CodecParameters `json:"parameters,omitzero"`
	Settings   Settings           `json:"settings,omitzero"`
	Copy       bool               `json:"copy,omitempty"`
	Auto       bool               `json:"auto,omitempty"`
}

Spec is a resolved codec choice: the codec id and media type, structural Parameters, and encoder Settings. Build it with the constructors (VP9, VP8, Opus, AAC, H264, HEVC, AV1, or New).

func AAC

func AAC(options ...Option) Spec

AAC builds an AAC encoder spec (defaults to 48kHz stereo).

func AV1

func AV1(options ...Option) Spec

AV1 builds an AV1 codec spec.

func H264

func H264(options ...Option) Spec

H264 builds an H.264 codec spec.

func HEVC

func HEVC(options ...Option) Spec

HEVC builds an HEVC (H.265) codec spec.

func New

func New(id av.CodecID, media av.MediaType, options ...Option) Spec

New builds a spec for an explicit codec id and media type.

func Opus

func Opus(options ...Option) Spec

Opus builds an Opus encoder spec (defaults to 48kHz stereo).

func VP8

func VP8(options ...Option) Spec

VP8 builds a VP8 encoder spec.

func VP9

func VP9(options ...Option) Spec

VP9 builds a VP9 encoder spec.

Jump to

Keyboard shortcuts

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