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
- Variables
- func BackendList(descriptors []Descriptor) string
- func BitrateMetadata(bitsPerSecond int) av.Metadata
- func EventBitrate(event *av.Event) (int, bool)
- func KnobScope(key string) (string, bool)
- type BackendInfo
- type BackendKind
- type Capabilities
- type Choice
- type ControlRequest
- type ControlType
- type DecodeBounds
- type DecodeConfig
- type DecodeResult
- type DecodeStateFactory
- type Decoder
- type DecoderFactory
- type DecoderStage
- type DecoderStageConfig
- type Descriptor
- type EncodeConfig
- type EncodeResult
- type Encoder
- type EncoderFactory
- type EncoderStage
- type EncoderStageConfig
- type Knob
- type KnobType
- type KnobValues
- func (v KnobValues) Bool(name string) bool
- func (v KnobValues) Float(name string) float64
- func (v KnobValues) Int(name string) int
- func (v KnobValues) Int32(name string) int32
- func (v KnobValues) IsSet(name string) bool
- func (v KnobValues) Raw() [][2]string
- func (v KnobValues) String(name string) string
- func (v KnobValues) Uint16(name string) uint16
- func (v KnobValues) Uint32(name string) uint32
- func (v KnobValues) With(name, value string) KnobValues
- type Mode
- type Need
- type Option
- func Backend(name string) Option
- func BitDepth(bits int) Option
- func Bitrate(bitsPerSecond int) Option
- func Channels(channels int) Option
- func ClockRate(clockRate uint32) Option
- func Control[T any](fn func(T) error) Option
- func FPS(num int, den ...int) Option
- func KeyframeInterval(frames int) Option
- func Level(level string) Option
- func Profile(profile string) Option
- func SampleRate(sampleRate int) Option
- func Setting(key string, value string) Option
- type ParameterReporter
- type Registry
- func (r *Registry) CheckScopes(id av.CodecID, s Settings) error
- func (r *Registry) DecoderFactory(id av.CodecID) (DecoderFactory, error)
- func (r *Registry) Descriptors() []Descriptor
- func (r *Registry) EncoderFactory(id av.CodecID) (EncoderFactory, error)
- func (r *Registry) Find(id av.CodecID, mode Mode) ([]Descriptor, error)
- func (r *Registry) Prefer(id av.CodecID, mode Mode, order ...string)
- func (r *Registry) RegisterDecoder(desc Descriptor, factory DecoderFactory)
- func (r *Registry) RegisterDescriptor(desc Descriptor)
- func (r *Registry) RegisterEncoder(desc Descriptor, factory EncoderFactory)
- func (r *Registry) Select(need Need) (Choice, error)
- type Rejection
- type ResiliencePolicy
- type SelectError
- type Settings
- type Spec
- func AAC(options ...Option) Spec
- func AV1(options ...Option) Spec
- func H264(options ...Option) Spec
- func HEVC(options ...Option) Spec
- func New(id av.CodecID, media av.MediaType, options ...Option) Spec
- func Opus(options ...Option) Spec
- func VP8(options ...Option) Spec
- func VP9(options ...Option) Spec
Constants ¶
const ( Mono = 1 Stereo = 2 )
Audio channel-count shorthands.
Variables ¶
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") // 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.
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.
var ErrInvalidSetting = errors.New("codec: invalid setting")
ErrInvalidSetting reports a codec setting a backend does not take, or a value outside what it accepts.
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 ¶
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 ¶
EventBitrate extracts the requested bitrate in bits per second from an av.EventBitrateChanged event. It prefers the typed Event.Bitrate field and falls back to av.MetadataBitrate for callers that populated Metadata directly.
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
}
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 []av.SampleFormat
PixelFormats []av.PixelFormat
// 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.
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 ¶
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.
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 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 av.PixelFormat
SampleFormat av.SampleFormat
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 ¶
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 ¶
BitDepth requests the coded sample bit depth (8, 10, 12); selection keeps to the backends that declare it.
func Control ¶
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 KeyframeInterval ¶
KeyframeInterval sets the keyframe cadence in encoded frames.
func Level ¶
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 ¶
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 ¶
SampleRate sets the encoder output sample rate in Hz.
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 Registry ¶ added in v0.3.0
type Registry struct {
// contains filtered or unexported fields
}
Registry 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 (*Registry) CheckScopes ¶ added in v0.3.0
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 (*Registry) DecoderFactory ¶ added in v0.3.0
func (r *Registry) 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 (*Registry) Descriptors ¶ added in v0.3.0
func (r *Registry) Descriptors() []Descriptor
Descriptors returns a copy of every registered descriptor.
func (*Registry) EncoderFactory ¶ added in v0.3.0
func (r *Registry) 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 (*Registry) Find ¶ added in v0.3.0
Find returns the descriptors matching the codec id (empty matches all) that support mode, or ErrNotFound when none do.
func (*Registry) Prefer ¶ added in v0.3.0
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 (*Registry) RegisterDecoder ¶ added in v0.3.0
func (r *Registry) 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 (*Registry) RegisterDescriptor ¶ added in v0.3.0
func (r *Registry) RegisterDescriptor(desc Descriptor)
RegisterDescriptor records a codec's capabilities without an implementation, so validation recognizes the codec.
func (*Registry) RegisterEncoder ¶ added in v0.3.0
func (r *Registry) 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 (*Registry) Select ¶ added in v0.3.0
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 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 ¶
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 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).