Documentation
¶
Overview ¶
Package kit is how a codec in a shared library or OS framework becomes a goav backend, from any module, with no cgo: a Codec declares the backend (its identity, capabilities, knobs, libraries, license, and releases) and a session per mode; Register adds it to a runtime.
type symbols struct {
compress func(dst *byte, dstLen *uint64, src *byte, srcLen uint64, level int32) int32 `sym:"compress2"`
}
sym := &symbols{}
option := kit.Register(kit.Codec{
ID: "zlib", Media: av.MediaVideo, Backend: "zlib", Kind: codec.KindLib,
Knobs: []codec.Knob{{Name: "level", Type: codec.KnobInt, Min: 0, Max: 9, Default: "6"}},
Libraries: []kit.Library{{Name: "libz", System: []string{"/usr/lib/libz.1.dylib"}, Fix: "install zlib", Symbols: sym}},
License: kit.License{Class: kit.LicensePermissive},
NewVideoEncoder: newEncoder, // Encode(*kit.Picture, emit), Flush, Close
NewVideoDecoder: newDecoder, // Decode(*kit.Packet, emit), Flush, Close
})
The kit binds the symbols when the runtime is built, each library file once per process, and owns everything between goav and the sessions: I420 and NV12 pictures, Annex B and AVCC framing, parameter sets, timestamps and reordering, pooled payloads, knob checking, live controls, damaged units (a session returns Damaged and decoding goes on), and Close. A backend takes only the settings it declares; read them with the sized accessors (Int32, Uint32, Uint16) for C fields. Params exposes a C parameter struct as raw parameters, Picture.Owner lends decoded memory without a copy, and libcodec/codectest.Run is the conformance suite. github.com/thesyncim/goav/libcodec/proof/extbackend is a complete backend.
Video decoder transitions have distinct semantics. EOS/FlushInto drains valid delayed pictures in presentation order. Discontinuity, including a discontinuous packet, discards pending pictures, timing and backend reference state and resumes from a keyframe. CodecChanged also discards old output before the event is forwarded, adopts the new stream identity, epoch, timebase, geometry and parameter sets, and opens a fresh session. No pre-change picture can appear after the new configuration event.
Audio decoder transitions use the same drain/discard boundary: EOS drains delayed samples, while discontinuities discard them by opening a fresh session. CodecChanged adopts stream identity, epoch, rate, channels, layout and extradata. Backend packets use the sample clock even when input packets use another timebase. Unsupported codec switches or backend configuration refusals return an error before committing the replacement configuration.
Index ¶
- Constants
- Variables
- func BindVTable(vtable uintptr, table any) error
- func Damaged(backend, call string, status int64) error
- func Fail(backend, op, call string, status int64) error
- func Probe(options ...runconfig.Option) error
- func Register(codecs ...Codec) runconfig.Option
- type AudioConfig
- type AudioDecoder
- type AudioEncoder
- type Bitstream
- type Codec
- type Configured
- type Error
- type Handles
- type Library
- type License
- type LicenseClass
- type Packet
- type Params
- type Picture
- type Release
- type ReleaseFile
- type Samples
- type Updater
- type VideoConfig
- type VideoDecoder
- type VideoEncoder
- type Window
Constants ¶
const EventSetting av.EventType = "codec_setting"
EventSetting is the event that changes encoder knobs while running: each Metadata entry is a knob and its new value, applied as Updater says. Send it with control.Deliver; bitrate also arrives as av.EventBitrateChanged and keyframe requests as av.EventKeyframeRequired.
const NV12 av.PixelFormat = "nv12"
NV12 is semi-planar 4:2:0: a luma plane, then one plane of interleaved Cb and Cr. Hardware codecs prefer it; goav frames are planar, so the kit converts NV12 to and from I420.
Variables ¶
var ErrDamaged = errors.New("libcodec: damaged unit")
ErrDamaged marks a unit the library could not decode. A decoder session returns it (through Damaged) and stays usable: the kit drops the unit, asks upstream for a keyframe, and goes on decoding.
ErrUnavailable reports a backend that cannot run here: its library or framework did not load, a symbol is missing, the version is outside its window, the platform has none, or the backend is turned off. errors.Is also matches codec.ErrUnavailable.
Functions ¶
func BindVTable ¶
BindVTable binds the func fields of table, in order, to the consecutive function pointers of a C++ or COM virtual table at vtable: field i calls slot i. Pass the receiver as the first argument.
func Damaged ¶
Damaged is the error a decoder session returns for a unit its library rejected as damaged: call is the library call, status its code.
func Fail ¶
Fail is an Error for a call the backend made into its library: op is open, encode, decode, or control, and status the library's own code.
func Probe ¶
Probe reports each kit backend the options register that cannot run here, with its fix: Probe(libcodec.OpenH264()) is nil only when libopenh264 loads, binds, and has a version in the backend's window.
func Register ¶
Register returns the runtime option that adds each backend to the runtime's codec registry, alongside every other backend of its codec. It binds the libraries then: a backend that cannot run here registers descriptor-only, so selection passes it over for one that can, and naming it explicitly is refused with the reason and the fix.
Types ¶
type AudioConfig ¶
type AudioConfig struct {
SampleRate int
Channels int
Realtime bool
Knobs codec.KnobValues
ExtraData []byte
}
AudioConfig is what an audio session opens with: the PCM layout, the settings already checked against the backend's declaration, and for a decoder the stream's codec configuration (an AudioSpecificConfig).
type AudioDecoder ¶
type AudioDecoder interface {
Decode(packet *Packet, emit func(*Samples) error) error
Flush(emit func(*Samples) error) error
Close() error
}
AudioDecoder is a backend's audio decoder session: Decode takes one packet and reports PCM through emit, stamped with the packet's PTS.
type AudioEncoder ¶
type AudioEncoder interface {
Encode(samples *Samples, emit func(*Packet) error) error
Flush(emit func(*Packet) error) error
Close() error
}
AudioEncoder is a backend's audio encoder session. Encode takes samples and reports packets through emit, now or later; a packet's PTS is the sample time of its first decoded sample, so codec priming shows before zero. Flush drains the rest. Configured reports the codec configuration.
type Bitstream ¶
type Bitstream int
Bitstream is how a video backend frames its payloads. Raw passes them through untouched: AV1 and VP9 OBUs and frames, or anything not split into NAL units. For H.264 and HEVC, which goav carries as Annex B, AnnexB keeps start codes and AVCC converts to length prefixes, moving the parameter sets between the stream and the codec configuration record.
type Codec ¶
type Codec struct {
// ID, Media, and Backend identify the backend: h264/openh264. Kind ranks
// it for selection (codec.KindHardware or codec.KindLib). Explain names
// the Go module and package it lives in, read from the constructors.
ID av.CodecID
Media av.MediaType
Backend string
Kind codec.BackendKind
// Platforms lists the GOOS values the backend runs on; empty is all.
// Profiles, Capabilities, and Realtime declare what it can do: selection
// keeps to backends whose declarations fit a request.
// Capabilities.PixelFormats defaults to i420 and yuv420p for video, and
// SampleFormats to s16 for audio.
Platforms []string
Profiles []string
Capabilities codec.Capabilities
Realtime bool
// Knobs are the encoder's settings and DecoderKnobs the decoder's (see
// codec.Knob and its common knobs); a backend takes no setting it does
// not declare. RawKnobs check the encoder's raw parameters (see Params);
// nil leaves them to the library, which checks them at open.
Knobs []codec.Knob
DecoderKnobs []codec.Knob
RawKnobs []codec.Knob
// Bitstream says how a video backend frames its payloads, and Pixels the
// pixel format its encoder reads (default i420; nv12 is converted).
Bitstream Bitstream
Pixels av.PixelFormat
// Reorder says the decoder returns pictures in decode order; the kit
// holds them and hands them on in presentation order.
Reorder bool
// Libraries are bound when Register runs (at goav.New, never in init),
// each file once per process. Version then reports the bound library's
// version, which must fall in ABI, the window of releases whose layouts
// the backend mirrors. A backend that cannot run registers
// descriptor-only, with a status that says why (not-installed, disabled,
// outside-window) and the error with the fix; selection passes it over.
Libraries []Library
ABI Window
Version func() (string, error)
// License is the library's license, with the notice and terms it asks a
// program to carry; Releases are its published builds, for installers
// and lockfiles.
License License
Releases []Release
// The session constructors; a nil one leaves that mode unregistered.
NewVideoEncoder func(VideoConfig) (VideoEncoder, error)
NewVideoDecoder func(VideoConfig) (VideoDecoder, error)
NewAudioEncoder func(AudioConfig) (AudioEncoder, error)
NewAudioDecoder func(AudioConfig) (AudioDecoder, error)
// contains filtered or unexported fields
}
Codec declares one library backend of one codec: its identity, what it can do, the settings it takes, the libraries it binds, its license, and its sessions. It is a plain value: reading it loads nothing. Register turns it into encoder and decoder factories; the kit owns everything between goav and the sessions: frame and packet conversion, timestamps, reference-counted buffers, settings, live controls, and Close.
type Configured ¶
type Configured interface {
Config() []byte
}
Configured is an optional encoder capability: the codec configuration known at open (an AudioSpecificConfig, an avcC or hvcC record, Annex B parameter sets, an av1C), which the stream reports as its extradata before any muxer writes a header.
type Error ¶
Error is a libcodec backend failure with the exact fix: what failed (Op: load, symbol, version, platform, disabled, open, encode, decode, control), on which library, symbol, or setting (Name), and what to do about it.
type Handles ¶
type Handles[T any] struct { // contains filtered or unexported fields }
Handles maps Go values to integer handles a C library can carry as an opaque refcon and hand back in callbacks, so no Go pointer ever crosses into C. purego callbacks are a fixed process-wide budget that is never freed: create one per C signature and route each call through a handle. Methods are safe for concurrent use, including from C threads.
type Library ¶
Library is one shared library or OS framework a backend binds: the name errors give it, where it lives, the fix to show when it cannot load, and Symbols, a pointer to the struct its entry points bind into. Path pins the file (absolute: libcodec.Library sets it); otherwise the kit takes the first of System, the absolute paths a system install puts it at, that exists. Nothing searches the working directory. The struct's fields carry a sym tag naming the symbol:
type symbols struct {
create func(**uintptr) int32 `sym:"WelsCreateSVCEncoder"`
version func(*version) `sym:"WelsGetCodecVersionEx,optional"`
keyCB uintptr `sym:"kCFTypeDictionaryKeyCallBacks"`
realtime uintptr `sym:"kVTCompressionPropertyKey_RealTime,value"`
}
A func field is bound to the function; a uintptr field receives the symbol's address, or with ",value" the pointer stored there (a CFStringRef constant). A missing ",optional" symbol leaves the field zero.
func (Library) Bind ¶
Bind loads the library from Path and resolves its symbols. A library that does not load, or a missing symbol, is an *Error carrying the fix.
type License ¶
type License struct {
Class LicenseClass
Notice string
Terms string
}
License is how a backend's library is licensed: its Class, the Notice its terms ask a program to show wherever it credits its codecs (Explain prints it), and the Terms a program must reproduce with itself.
type LicenseClass ¶
type LicenseClass string
LicenseClass sorts licenses by what they ask of the program that loads the library.
const ( // LicensePermissive is BSD, MIT, Apache: keep the notices. LicensePermissive LicenseClass = "permissive" // LicenseCopyleft is GPL and LGPL: the terms reach the program. LicenseCopyleft LicenseClass = "copyleft" // LicenseSystem is a library the OS ships: the program carries none. LicenseSystem LicenseClass = "system" )
The license classes.
type Packet ¶
Packet is one encoded unit lent to or by a backend for the length of one call: never keep Data. PTS, DTS, and Duration are in the stream's time base (samples for audio). A video encoder of an AVCC bitstream sets Config to its codec configuration record (avcC, hvcC) whenever it is new; the kit writes the parameter sets in-band ahead of every keyframe.
type Params ¶
type Params[T any] struct { // contains filtered or unexported fields }
Params exposes the fields of a C parameter struct T as raw parameters, by the C names their c struct tags give, so a backend reaches every knob its library has without mapping them by hand. Scalar fields (bools, integers, floats) are parameters; a struct field tagged c:",inline" adds its own fields, and an array of structs tagged c:",first" adds the fields of its first element. Knobs is the raw schema for Codec.RawKnobs, typed and ranged by each field's Go type; Apply writes validated values.
type Picture ¶
type Picture struct {
Width, Height int
Format av.PixelFormat
Planes [3][]byte
Strides [3]int
Owner av.BufferOwner
PTS int64
Duration int64
Keyframe bool
}
Picture is one picture lent to or by a backend. Format is a goav pixel format name (i420, i422, i444, yuv420p10le) or nv12. The planes are valid for the length of the call, unless Owner is set: a decoder that lends its own memory (a CVPixelBuffer, a dav1d picture) sets Owner, holding one reference, and the kit publishes the planes without a copy, retaining Owner once per plane; the decoder drops its own reference after emit returns. PTS and Duration are in the stream's time base; Keyframe asks an encoder for a keyframe.
type Release ¶
type Release struct {
Version string
Files []ReleaseFile
}
Release is one published build of a backend's library: its version and, per platform, where it is fetched from and the SHA-256 it must have. A backend lists in Codec.Releases the releases inside its ABI window that it can bind; installers and lockfiles read them from the declaration, so a backend from any module installs like the ones goav ships.
type ReleaseFile ¶
ReleaseFile is a release's library for one platform (GOOS/GOARCH, such as linux/amd64): the URL to fetch, the SHA-256 of what it serves, and the library's file name once unpacked (a .bz2 or .gz URL is unpacked).
type Samples ¶
Samples is interleaved signed 16-bit PCM lent to or by a backend for one call: never keep PCM. PTS counts samples per channel at SampleRate.
type Updater ¶
type Updater interface {
Update(knob string, values codec.KnobValues) error
}
Updater is an optional encoder capability for knobs declared Live: Update applies the new value of knob (in values) while running. Without it, or for a knob that is not Live, the kit restarts the session with the new value on a keyframe.
type VideoConfig ¶
type VideoConfig struct {
Width, Height int
TimeBase av.TimeBase
// FrameDuration is the nominal frame duration in TimeBase units, 0 when
// unknown.
FrameDuration int64
BitDepth int
Realtime bool
Knobs codec.KnobValues
ParameterSets [][]byte
// ExtraData is a raw-bitstream decoder's codec configuration, as the
// stream carries it (an av1C, say).
ExtraData []byte
}
VideoConfig is what a video session opens with. Knobs are its settings, already checked against the backend's declaration. A decoder of an AVCC bitstream gets the stream's ParameterSets (VPS, SPS, PPS NAL units without start codes); the kit opens it once they are known and again when they change.
type VideoDecoder ¶
type VideoDecoder interface {
Decode(unit *Packet, emit func(*Picture) error) error
Flush(emit func(*Picture) error) error
Close() error
}
VideoDecoder is a backend's decoder session. Decode takes one access unit and reports decoded pictures through emit in presentation order, now or on a later call, each with the PTS of the access unit it came from; Flush drains the rest.
type VideoEncoder ¶
type VideoEncoder interface {
Encode(picture *Picture, emit func(*Packet) error) error
Flush(emit func(*Packet) error) error
Close() error
}
VideoEncoder is a backend's encoder session. Encode takes one picture and reports finished packets through emit, now or on a later call, in decode order, each with the PTS of the picture it carries; Flush drains the rest. The kit calls a session from one goroutine at a time.