kolo docsbeta

kolo-video

Captura de cámara, frames I420, VP8 y VP9 con libvpx, y H.264 opcional con el códec propio del sistema operativo. Sin cgo, sin compilador de C y sin nada que instalar.

En esta página

kolo-video lista y abre cámaras, entrega frames I420 (con la matriz BT.601), convierte otros formatos de píxel a I420, dibuja frames en imágenes RGBA y codifica y decodifica VP8 (RFC 6386) y VP9 en tiempo real. H.264 es opcional y viene del códec propio del sistema operativo. No envía nada por la red y no sincroniza el audio con el video. Los paquetes de Go son kolovideo, vpx y h264.

Todos los pasos

De un Frame a paquetes y de vuelta

VP8 y VP9 funcionan en todas partes. H.264 usa el códec del sistema operativo, así que es opcional.

  1. Un Frame es una imagen I420: planos de 8 bits, BT.601, rango limitado. Viene de una cámara, de un conversor como FromNV12 o de tu propio código.
  2. vpx lo codifica como VP8 o VP9 con libvpx 1.16.0. El motor native es una biblioteca precompilada que se carga sin cgo; el motor portable es el mismo código traducido a Go. El paquete elige uno y te dice cuál.
  3. h264 lo codifica como H.264 con el códec que trae el sistema operativo: VideoToolbox en macOS, Media Foundation en Windows. Es opcional: Capabilities dice si está disponible, y en Linux no lo está.
  4. Cada codificador devuelve un paquete por frame: un frame VP8 o VP9, o una unidad de acceso Annex B con su SPS y su PPS antes de cada keyframe. Un emisor puede enviar siempre VP8 y H.264 cuando pueda. Tu aplicación envía los paquetes.
  5. El receptor decodifica el stream que eligió. Toma H.264 solo si su propio sistema puede decodificarlo, y VP8 si no. Cada decodificador revisa un paquete antes de decodificarlo.
  6. El decodificador devuelve un Frame, o un error, y entonces espera un keyframe.

Instalación

go get github.com/ciranda-dev/kolo-video

Para fijar esta versión, ejecuta go get github.com/ciranda-dev/kolo-video@v0.1.0. Necesita Go 1.26 o superior. No hay cgo, ni compilador de C, ni libvpx, ni pkg-config, ni variable de entorno que definir, así que compila con CGO_ENABLED=0. El códec de VP8 y VP9 es libvpx 1.16.0 en dos formas que llevan el mismo código: una biblioteca precompilada incluida en el módulo y cargada sin cgo (a toda velocidad), y el mismo código traducido a Go (funciona en todas partes, en tiempo real hasta 640x480). El paquete elige una en tiempo de ejecución y te dice cuál. La primera compilación del paquete vpx compila Go generado y llega a unos 570 MB de memoria en un Mac; las siguientes usan la caché de compilación.

Inicio rápido

Este programa lista las cámaras (nunca abre una), luego codifica 30 frames generados con VP8 y los decodifica de nuevo. Ejecútalo con go run . <dir>, donde <dir> es el lugar donde el motor native guarda su biblioteca; una aplicación normalmente deja CacheDir vacío, y así se usa el directorio de caché del usuario.

main.go
package main

import (
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	kolovideo "github.com/ciranda-dev/kolo-video"
	"github.com/ciranda-dev/kolo-video/vpx"
)

func main() {
	if len(os.Args) != 2 {
		log.Fatal("usage: quickstart <cache directory>")
	}
	cams, err := kolovideo.Devices()
	if err != nil && !errors.Is(err, kolovideo.ErrNoDevice) && !errors.Is(err, kolovideo.ErrUnsupported) {
		log.Fatal(err)
	}
	for _, c := range cams {
		fmt.Printf("camera %q default=%v\n", c.Name, c.Default)
	}

	rt, err := vpx.Load(vpx.LoadConfig{CacheDir: os.Args[1]})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("libvpx %s, %v engine\n", rt.Version, rt.Engine)

	enc, err := vpx.NewEncoder(vpx.Config{Codec: vpx.VP8, Width: 320, Height: 240})
	if err != nil {
		log.Fatal(err)
	}
	defer enc.Close()
	dec, err := vpx.NewDecoder(vpx.DecoderConfig{Codec: vpx.VP8})
	if err != nil {
		log.Fatal(err)
	}
	defer dec.Close()

	var bytes, frames int
	for i := range 30 {
		f, err := kolovideo.NewFrame(320, 240)
		if err != nil {
			log.Fatal(err)
		}
		for j := range f.Y {
			f.Y[j] = byte(16 + (j/320+j%320+4*i)%220)
		}
		f.Timestamp = time.Duration(i) * time.Second / 30

		pkts, err := enc.Encode(f, false)
		if err != nil {
			log.Fatal(err)
		}
		for _, p := range pkts {
			out, err := dec.Decode(p)
			if err != nil {
				log.Fatal(err)
			}
			if out != nil {
				bytes += len(p.Data)
				frames++
			}
		}
	}
	fmt.Printf("%d frames encoded and decoded, %d bytes\n", frames, bytes)
}

La línea del motor depende de la plataforma (native en macOS y Windows, portable en Linux por defecto). La última no:

Texto
30 frames encoded and decoded, 13596 bytes

H.264 tiene la misma forma, con un paso más: pregunta primero al sistema. Este programa codifica un frame con H.264, lee el string del códec del keyframe y lo decodifica de nuevo. Donde el sistema no tiene un códec H.264, imprime el motivo, y publicas solo VP8.

h264.go
package main

import (
	"errors"
	"fmt"
	"log"

	kolovideo "github.com/ciranda-dev/kolo-video"
	"github.com/ciranda-dev/kolo-video/h264"
)

func main() {
	enc, err := h264.NewEncoder(h264.Config{Width: 640, Height: 360})
	if errors.Is(err, h264.ErrUnavailable) {
		fmt.Println("H.264 is not available:", err) // publish VP8 only
		return
	}
	if err != nil {
		log.Fatal(err)
	}
	defer enc.Close()
	dec, err := h264.NewDecoder(h264.DecoderConfig{})
	if err != nil {
		log.Fatal(err)
	}
	defer dec.Close()

	frame, err := kolovideo.NewFrame(640, 360)
	if err != nil {
		log.Fatal(err)
	}
	pkts, err := enc.Encode(frame, false) // the first frame is a keyframe
	if err != nil {
		log.Fatal(err)
	}
	sps, err := h264.ParseKeyframe(pkts[0].Data)
	if err != nil {
		log.Fatal(err)
	}
	out, err := dec.Decode(pkts[0])
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s, hardware %v, %d bytes, decoded %dx%d\n", sps.Codec(), enc.Hardware(), len(pkts[0].Data), out.Width, out.Height)
}

En un Mac con VideoToolbox imprimió:

Texto
avc3.42c01e, hardware true, 739 bytes, decoded 640x360

En un contenedor Linux, donde no hay motor, imprimió:

Texto
H.264 is not available: kolovideo/h264: no H.264 engine on linux/arm64 in this release; V4L2 stateful H.264 devices: none

Para capturar, abre una cámara y lee frames. OpenCapture nunca pide permiso: en macOS llama antes a RequestAccess. El repositorio tiene examples/snapshot, que guarda frames de la cámara como archivos PNG (-list lista las cámaras), examples/vp8, que codifica y decodifica frames generados e imprime el motor, el tamaño y la calidad, y examples/h264, que hace lo mismo con H.264 y recurre a VP8 donde el sistema no tiene códec.

Referencia de la API

La referencia de la API se genera a partir del código Go y está en inglés.

Paquete kolovideo · github.com/ciranda-dev/kolo-video · v0.1.0

Package kolovideo captures camera video and converts, scales and renders raw I420 frames for Kolo. Subpackage vpx encodes and decodes VP8 and VP9; subpackage h264 encodes and decodes H.264 with the operating system's codec where there is one. Nothing needs to be installed and no package uses cgo.

Experimental: the API may change before v1.0.0.

Constantes

const (
	// DefaultWidth, DefaultHeight and DefaultFrameRate are the common
	// browser capture default, 640x480 at 30 fps. vpx.DefaultFrameRate and
	// h264.DefaultFrameRate are the encoders' rate for frames without a
	// Duration, the same value.
	DefaultWidth     = 640
	DefaultHeight    = 480
	DefaultFrameRate = 30
	// MinFrameRate and MaxFrameRate bound a wanted frame rate: one frame per
	// hour, so that a frame duration in 90 kHz ticks fits the 32-bit duration of
	// libvpx, and 1000 frames per second, the finest rate a 90 kHz clock gives
	// 90 ticks to.
	MinFrameRate = 1.0 / 3600
	MaxFrameRate = 1000
	// DefaultBuffer frames are held for a slow reader: one late read is
	// absorbed without adding latency.
	DefaultBuffer = 2
	// DefaultStallTimeout is the wait for a frame before the device counts
	// as lost, the timeout of the V4L2 reference capture loop.
	DefaultStallTimeout = 2 * time.Second
	// DefaultMaxPixels bounds the capture size: 8,912,896 pixels, the VP9
	// level 5 picture size (4096x2176), which holds 4K UHD. vpx.DefaultMaxPixels
	// bounds decoded VP8 and VP9 frames with the same value; h264.DefaultMaxPixels
	// bounds the coded size of H.264 pictures and is a different value.
	DefaultMaxPixels = 8912896
)

Capture defaults.

Variables

var (
	// ErrInvalidConfig means a configuration field is out of range.
	ErrInvalidConfig = errors.New("kolovideo: invalid config")
	// ErrInvalidFrame means a frame or raw image has inconsistent sizes.
	ErrInvalidFrame = errors.New("kolovideo: invalid frame")
	// ErrNoDevice means no camera matches the request.
	ErrNoDevice = errors.New("kolovideo: no such device")
	// ErrUnsupportedFormat means the device or stream offers no format this
	// package can convert.
	ErrUnsupportedFormat = errors.New("kolovideo: unsupported format")
	// ErrPermission means the system has not granted camera access.
	ErrPermission = errors.New("kolovideo: camera access not granted")
	// ErrDeviceLost means the camera was disconnected, failed, or sent no
	// frame within the stall timeout.
	ErrDeviceLost = errors.New("kolovideo: device lost")
	// ErrClosed means the capture, encoder or decoder was closed.
	ErrClosed = errors.New("kolovideo: closed")
	// ErrUnsupported means this platform has no backend for the feature:
	// camera capture on a system other than macOS, Linux, and Windows on
	// amd64 or arm64, or a system whose camera framework is missing.
	ErrUnsupported = errors.New("kolovideo: not supported on this platform")
)

Funciones

func RequestAccess

func RequestAccess(ctx context.Context) error

RequestAccess asks the user for camera access where the system requires it (macOS) and returns ErrPermission if it is refused. It may show a system prompt. On Linux and Windows it returns nil at once; where capture is not supported it returns ErrUnsupported.

Tipos

type Capture

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

Capture is an open camera. Its methods are safe for concurrent use.

func OpenCapture
func OpenCapture(cfg CaptureConfig) (*Capture, error)

OpenCapture opens a camera and starts capturing.

func (Capture) Close
func (c *Capture) Close() error

Close stops the camera. Blocked and later Read calls return ErrClosed. A zero Capture, which holds no camera, can be closed and read too. Close is idempotent; only the first call can return an error.

func (Capture) Device
func (c *Capture) Device() Device

Device returns the camera in use.

func (Capture) Mode
func (c *Capture) Mode() Mode

Mode returns the mode in use.

func (Capture) Read
func (c *Capture) Read(ctx context.Context) (*Frame, error)

Read returns the oldest buffered frame, waiting for one if needed. After the camera is lost, buffered frames are returned first, then an error wrapping ErrDeviceLost or ErrPermission. After Close it returns ErrClosed.

func (Capture) Stats
func (c *Capture) Stats() Stats

Stats returns the frame counters.

type CaptureConfig

type CaptureConfig struct {
	// DeviceID is a Device.ID; empty means the default camera.
	DeviceID string
	// Width and Height are the wanted size, DefaultWidth by DefaultHeight
	// if both are zero. The nearest supported mode is used.
	Width, Height int
	// FrameRate is the wanted rate, DefaultFrameRate if zero. It is capped
	// at the chosen mode's highest rate.
	FrameRate float64
	// Buffer is the number of frames held while the reader is slow; when
	// it is full the oldest frame is dropped. Default DefaultBuffer.
	Buffer int
	// StallTimeout is how long Read waits for a frame before it returns
	// ErrDeviceLost. Default DefaultStallTimeout; negative disables it.
	StallTimeout time.Duration
	// MaxPixels is the largest mode accepted, so a faulty camera cannot
	// make every frame a huge allocation. Default DefaultMaxPixels.
	MaxPixels int
}

CaptureConfig selects a camera and mode. Zero fields take defaults.

type Device

type Device struct {
	// ID identifies the camera to OpenCapture. It is stable while the
	// camera stays connected.
	ID   string
	Name string
	// Default marks the system's preferred camera.
	Default bool
	// Modes lists supported modes when the platform reports them without
	// starting the camera; it is empty on Windows. A Linux node held exclusively
	// by another program is listed with no modes.
	Modes []Mode
}

Device is a camera.

func Devices
func Devices() ([]Device, error)

Devices lists the cameras connected now.

type Frame

type Frame struct {
	Width, Height int
	Y, U, V       []byte
	// YStride and UVStride are the bytes between the starts of two rows.
	YStride, UVStride int
	// Timestamp is the capture time on the system monotonic clock.
	Timestamp time.Duration
	// Duration is the nominal display time of the frame.
	Duration time.Duration
}

Frame is a raw I420 picture: planar YUV 4:2:0, 8 bits per sample, BT.601 limited range. The U and V planes are (Width+1)/2 by (Height+1)/2.

func FromBGRA
func FromBGRA(width, height int, src []byte, stride int) (*Frame, error)

FromBGRA converts 32-bit B, G, R, A pixels to a new I420 frame. Alpha is ignored.

func FromNV12
func FromNV12(width, height int, y []byte, yStride int, uv []byte, uvStride int) (*Frame, error)

FromNV12 converts an NV12 picture (a Y plane and an interleaved UV plane) to a new I420 frame.

func FromRGBA
func FromRGBA(width, height int, src []byte, stride int) (*Frame, error)

FromRGBA converts 32-bit R, G, B, A pixels, such as image.RGBA.Pix, to a new I420 frame. Alpha is ignored.

func FromUYVY
func FromUYVY(width, height int, src []byte, stride int) (*Frame, error)

FromUYVY converts a packed 4:2:2 picture in U Y0 V Y1 order to a new I420 frame. The width must be even.

func FromYUY2
func FromYUY2(width, height int, src []byte, stride int) (*Frame, error)

FromYUY2 converts a packed 4:2:2 picture in Y0 U Y1 V order (also called YUYV) to a new I420 frame. The width must be even.

func NewFrame
func NewFrame(width, height int) (*Frame, error)

NewFrame allocates a black frame with tightly packed planes.

func (Frame) RGBA
func (f *Frame) RGBA() (*image.RGBA, error)

RGBA converts the frame to a new image of the same size.

func (Frame) Validate
func (f *Frame) Validate() error

Validate reports whether the sizes, strides and plane lengths agree.

func (Frame) YCbCr
func (f *Frame) YCbCr() *image.YCbCr

YCbCr returns an image that shares the frame's planes, or nil if the frame is invalid. The image/color package treats the samples as full range, so use RGBA or Renderer for exact colors.

type Mode

type Mode struct {
	Width, Height int
	// FrameRate is the highest rate in Device.Modes, 0 if unknown. In
	// Capture.Mode it is the rate the camera was set to, or the requested
	// rate if the camera does not report one.
	FrameRate float64
	// Format is the camera's native format; captured frames are always
	// I420.
	Format PixelFormat
}

Mode is one capture size and frame rate a camera supports.

type PixelFormat

type PixelFormat int

PixelFormat is a camera's native pixel layout.

const (
	FormatUnknown PixelFormat = iota
	FormatI420
	FormatNV12
	FormatYUY2
	FormatUYVY
	FormatBGRA
	FormatMJPEG
)

Pixel formats a camera may deliver.

func (PixelFormat) String
func (p PixelFormat) String() string

String returns the format name.

type Renderer

type Renderer struct {
	Scale ScaleMode
	// contains filtered or unexported fields
}

Renderer draws frames into RGBA images of any size. It keeps a scratch image between calls, so reuse one Renderer per video stream. A Renderer is not safe for concurrent use.

func (Renderer) Render
func (r *Renderer) Render(dst *image.RGBA, f *Frame) error

Render draws f into dst.Bounds(), keeping the frame's aspect ratio. Scaling uses approximate bilinear interpolation.

type ScaleMode

type ScaleMode int

ScaleMode says how Renderer maps a frame onto a destination of another shape.

const (
	// Fit shows the whole frame and fills the bars left over with black.
	Fit ScaleMode = iota
	// Fill covers the whole destination and crops the frame's overflow.
	Fill
)

type Stats

type Stats struct {
	// Frames is the number of frames received from the camera.
	Frames uint64
	// Dropped is the number of frames discarded because Buffer was full.
	Dropped uint64
	// Invalid is the number of camera frames that could not be converted.
	Invalid uint64
}

Stats counts frames since OpenCapture.

Paquete vpx

github.com/ciranda-dev/kolo-video/vpx

Package vpx encodes and decodes VP8 and VP9 video with libvpx 1.16.0, set up for real-time use. It needs no installed library, compiler or cgo.

Two engines run the same libvpx. The native engine is a prebuilt shared library embedded in the package and loaded without cgo; it is the default on macOS and Windows, and on Linux only with the build tag kolovideo_native, so that binaries stay static and start on any distribution. The portable engine is the same code translated to Go; it works everywhere, runs single-threaded and encodes in real time up to 640x480. When the native engine cannot load, the portable engine is used and LoadError says why. Streams from the two engines are byte-identical only when the encoder runs one thread.

Experimental: the API may change before v1.0.0.

Constantes

const (
	// DefaultFrameRate is the rate assumed for frames without a Duration:
	// kolovideo.DefaultFrameRate.
	DefaultFrameRate = kolovideo.DefaultFrameRate
	// DefaultBitsPerPixel sets the default bitrate: 0.07 bits per pixel per
	// frame, about 4.4 Mbit/s for 1080p at 30 fps.
	DefaultBitsPerPixel = 0.07
	// DefaultKeyframeInterval starts a new group of pictures every 2 s.
	DefaultKeyframeInterval = 2 * time.Second
)

Encoder defaults.

const DefaultMaxPacketBytes = 16 << 20

DefaultMaxPacketBytes bounds a packet: 16 MiB, the default MaxBytes of the kolo-media playout. A VP8 or VP9 frame at DefaultMaxPixels is far smaller.

const DefaultMaxPixels = kolovideo.DefaultMaxPixels

DefaultMaxPixels bounds decoded frames: 8,912,896 pixels, the VP9 level 5 picture size (4096x2176), as kolovideo.DefaultMaxPixels for capture.

Variables

var (
	// ErrCorrupt means a packet is truncated or not a valid frame.
	ErrCorrupt = errors.New("kolovideo/vpx: corrupt packet")
	// ErrTooLarge means a packet is larger than MaxPacketBytes or declares a
	// frame larger than MaxPixels.
	ErrTooLarge = errors.New("kolovideo/vpx: packet or frame too large")
	// ErrNeedKeyframe means the decoder drops packets until a keyframe,
	// at the start and after a decoding error.
	ErrNeedKeyframe = errors.New("kolovideo/vpx: waiting for a keyframe")
	// ErrCodec means libvpx failed for a reason other than bad input.
	ErrCodec = errors.New("kolovideo/vpx: codec error")
)
var (
	// ErrNativeUnsupported means this platform or build has no native library:
	// Linux without the kolovideo_native tag, or another platform.
	ErrNativeUnsupported = native.ErrUnsupported
	// ErrNativeIntegrity means the embedded library does not match its checksum.
	ErrNativeIntegrity = native.ErrIntegrity
	// ErrNativeABI means the library does not offer the interface this package
	// expects.
	ErrNativeABI = native.ErrABI
	// ErrNativeSignature means the code signature of a library file on macOS
	// is not valid.
	ErrNativeSignature = native.ErrSignature
	// ErrNativeCache means the cache directory or file cannot be used: another
	// user owns it or a directory above it can be changed by others. That
	// includes a group-writable directory such as a home with mode 0775 and a
	// private group: use mode 0755 or set LoadConfig.CacheDir.
	ErrNativeCache = native.ErrCache
)

The reasons the native engine can fail to load. LoadError, Runtime.NativeErr and the error of Load with EngineNative match them with errors.Is; the error text names the platform, each way that was tried and the operating system's message.

var ErrUnavailable = errors.New("kolovideo/vpx: libvpx unavailable")

ErrUnavailable means the requested libvpx engine cannot run.

Funciones

func LoadError
func LoadError() error

LoadError returns why the native engine is not in use, nil if it is. On Linux builds without the kolovideo_native tag it says so.

func Notices
func Notices() string

Notices returns the licence and patent grant texts of the code in this package: libvpx, the C runtime parts of the portable engine and the native libraries, and the translator's helpers. An application that ships binaries must include them.

func WriteLibrary
func WriteLibrary(dir string) (string, error)

WriteLibrary writes the embedded native library into dir and returns its path, for an application that signs the library and ships it, then names it in LoadConfig.Library (on macOS also as Contents/Frameworks/libkolovpx.dylib, which is loaded without configuration). It errors when no library is embedded.

Tipos

type Codec
type Codec int

Codec is a video codec.

const (
	VP8 Codec = iota + 1
	VP9
)

Supported codecs.

func (Codec) String
func (c Codec) String() string

String returns the codec name.

type Config
type Config struct {
	Codec Codec
	// Width and Height of every frame: 1 to 16383 for VP8, 1 to 65536 for
	// VP9.
	Width, Height int
	// FrameRate is the nominal rate, DefaultFrameRate if zero; otherwise
	// kolovideo.MinFrameRate to kolovideo.MaxFrameRate.
	FrameRate float64
	// Bitrate is the target in bits per second, DefaultBitsPerPixel times
	// pixels times FrameRate if zero.
	Bitrate int
	// KeyframeInterval is the time between keyframes, measured on frame
	// timestamps; DefaultKeyframeInterval if zero, negative for keyframes
	// only on request.
	KeyframeInterval time.Duration
}

Config sets up an Encoder. Zero fields take defaults.

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

Decoder decodes packets into I420 frames. Its methods are safe for concurrent use.

func NewDecoder
func NewDecoder(cfg DecoderConfig) (*Decoder, error)

NewDecoder creates a decoder. Call Close to free it.

func (Decoder) Close
func (d *Decoder) Close() error

Close frees the decoder. It is idempotent.

func (Decoder) Decode
func (d *Decoder) Decode(p Packet) (*kolovideo.Frame, error)

Decode decodes one packet. It returns a nil frame and nil error when the packet holds no frame to show. Frames may change size at keyframes. After any error, packets are refused with ErrNeedKeyframe until the next keyframe.

type DecoderConfig
type DecoderConfig struct {
	Codec Codec
	// MaxPixels is the largest frame accepted, checked in each frame
	// header before decoding; DefaultMaxPixels if zero.
	MaxPixels int
	// MaxPacketBytes bounds a packet, checked before it is copied;
	// DefaultMaxPacketBytes if zero, at most 256 MiB.
	MaxPacketBytes int
}

DecoderConfig sets up a Decoder.

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

Encoder encodes I420 frames. Its methods are safe for concurrent use.

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

NewEncoder creates an encoder. Call Close to free it.

func (Encoder) Close
func (e *Encoder) Close() error

Close frees the encoder. It is idempotent.

func (Encoder) Config
func (e *Encoder) Config() Config

Config returns the configuration with defaults filled in.

func (Encoder) Encode
func (e *Encoder) Encode(f *kolovideo.Frame, forceKeyframe bool) ([]Packet, error)

Encode compresses one frame of the configured size. It returns no packet when rate control drops the frame. A keyframe is made when forceKeyframe is set, for the first frame, and every KeyframeInterval.

func (Encoder) SetBitrate
func (e *Encoder) SetBitrate(bps int) error

SetBitrate changes the target bitrate in bits per second, effective from the next frame.

type EngineKind
type EngineKind int

EngineKind names a libvpx engine.

const (
	EngineAuto EngineKind = iota
	EngineNative
	EnginePortable
)

Engines. The native engine is the prebuilt library, the portable engine is the same libvpx translated to Go.

func Engine
func Engine() EngineKind

Engine returns the engine in use, loading the default one if needed. It returns EngineAuto if no engine can run.

func (EngineKind) String
func (k EngineKind) String() string

String returns the engine name.

type Limits
type Limits struct {
	Engine EngineKind
	Encode RealTime
	Decode RealTime
}

Limits are the largest modes the engine in use handled in real time.

func Capabilities
func Capabilities() Limits

Capabilities returns reference limits, not a run-time probe: the largest encode and decode modes measured as real time for the engine in use, so a caller can cap resolution. Real time means a mean time per frame below the 33.3 ms period for a camera-like stream, on an Apple M5: the native engine reaches 1920x1080 at 30 fps for encode and decode, VP8 and VP9; the portable engine encodes up to 640x480 at 30 fps and decodes up to 1920x1080. A slower CPU reaches less. It returns the zero Limits if no engine can run.

type LoadConfig
type LoadConfig struct {
	// Engine is EngineAuto if zero: native, with the portable engine as the
	// fallback when the native library cannot load.
	Engine EngineKind
	// CacheDir is the root of the native library cache, os.UserCacheDir()/kolo-video
	// if empty.
	CacheDir string
	// Library is the path of a libkolovpx the application ships and signs
	// itself, loaded instead of the embedded one. It is not checked against a
	// hash. An altered library that still carries a valid signature can be
	// killed by the operating system when it is loaded, which cannot be caught.
	Library string
}

LoadConfig selects and sets up the engine. Library and CacheDir apply to the native engine only.

type Packet
type Packet struct {
	Data     []byte
	Keyframe bool
	// Timestamp and Duration come from the frame and pass through the
	// decoder unchanged.
	Timestamp time.Duration
	Duration  time.Duration
}

Packet is one encoded frame.

type RealTime
type RealTime struct {
	Width, Height int
	FrameRate     float64
}

RealTime is a picture size and frame rate.

type Runtime
type Runtime struct {
	Engine  EngineKind
	Version string // libvpx version, such as "v1.16.0"
	// NativeErr is why the native engine is not in use, nil if it is. Check it
	// after Load with EngineAuto: ErrNativeIntegrity and ErrNativeSignature are
	// not reported any other way.
	NativeErr error
}

Runtime describes the engine in use.

func Load
func Load(cfg LoadConfig) (Runtime, error)

Load selects the libvpx engine. It is optional: NewEncoder, NewDecoder, Engine, LoadError and Capabilities load the default configuration when nothing is loaded (on macOS and Windows that extracts and loads the native library), so call Load first to choose another one. Once an engine is active, Load with another configuration returns kolovideo.ErrInvalidConfig and the first engine stays. With Engine set to EngineNative, a native load failure returns ErrUnavailable wrapping the cause and nothing is loaded.

With EngineAuto a failed native load is not an error: the portable engine runs and Load returns nil. Read Runtime.NativeErr (or LoadError) to learn why. ErrNativeIntegrity and ErrNativeSignature there mean that the embedded bytes or a bundle library did not verify, which is corruption or tampering, not the plain absence of a native library (ErrNativeUnsupported); log them.

Paquete h264

github.com/ciranda-dev/kolo-video/h264

Package h264 encodes and decodes H.264 video with the codec of the operating system: VideoToolbox on macOS, the Media Foundation H.264 transforms on Windows desktop editions. It contains no H.264 encoder or decoder and needs no installed library, compiler or cgo. Where the system has no usable codec, Capabilities and the constructors report why with an *UnavailableError.

Packets are Annex B access units with 4-byte start codes, one picture each, holding only slices, SPS and PPS; every keyframe starts with its SPS and PPS. Encoders produce Constrained Baseline, Main or High within level 5.1, without B-frames, one packet per frame. Decoders check every packet in Go before the system sees it and refuse streams outside those profiles and levels.

Experimental: the API may change before v1.0.0.

Constantes

const (
	// DefaultFrameRate is the rate assumed for frames without a Duration:
	// kolovideo.DefaultFrameRate.
	DefaultFrameRate = kolovideo.DefaultFrameRate
	// DefaultBitsPerPixel sets the default bitrate: about 4.4 Mbit/s for
	// 1080p at 30 fps.
	DefaultBitsPerPixel = 0.07
	// DefaultKeyframeInterval starts a new group of pictures every 2 s.
	DefaultKeyframeInterval = 2 * time.Second
	// DefaultMaxPixels bounds the coded size of decoded pictures: 36864
	// macroblocks, the level 5.1 MaxFS.
	DefaultMaxPixels = 9437184
	// DefaultMaxPacketBytes bounds a packet, as kolo-media's playout MaxBytes.
	DefaultMaxPacketBytes = 16 << 20
	// MaxBitrate is the level 5.1 MaxBR in bits per second, in the Baseline
	// and Main unit.
	MaxBitrate = 240000000
)

Defaults and bounds. The level limits are those of level 5.1 (ITU-T H.264 Table A-1), the highest level every engine documents.

Variables

var (
	// ErrUnavailable means this system has no H.264 codec kolo-video can use;
	// the error returned is an *UnavailableError that wraps it.
	ErrUnavailable = errors.New("kolovideo/h264: no H.264 codec on this system")
	// ErrCorrupt means a packet is not valid H.264 or the system decoder
	// reported bad data.
	ErrCorrupt = errors.New("kolovideo/h264: corrupt packet")
	// ErrTooLarge means a packet, its NAL unit count or its picture exceeds a
	// bound.
	ErrTooLarge = errors.New("kolovideo/h264: packet or picture too large")
	// ErrNeedKeyframe means the decoder drops packets until an IDR with its
	// SPS and PPS.
	ErrNeedKeyframe = errors.New("kolovideo/h264: waiting for a keyframe")
	// ErrUnsupportedStream means the stream uses a profile, level or tool this
	// package refuses.
	ErrUnsupportedStream = errors.New("kolovideo/h264: unsupported stream")
	// ErrProfile means the system encoder cannot produce the requested
	// profile.
	ErrProfile = errors.New("kolovideo/h264: profile not available from the system encoder")
	// ErrCodec means the system codec failed for a reason other than bad
	// input.
	ErrCodec = errors.New("kolovideo/h264: system codec error")
)

Tipos

type Config
type Config struct {
	// Width and Height are even, 48 to 4096, at most 36864 macroblocks, and
	// macroblocks times FrameRate at most 983040 (level 5.1).
	Width, Height int
	// FrameRate is kolovideo.MinFrameRate to MaxFrameRate, DefaultFrameRate
	// if zero.
	FrameRate float64
	// Bitrate is the target in bits per second, 1 to MaxBitrate;
	// DefaultBitsPerPixel times pixels times FrameRate if zero.
	Bitrate int
	// KeyframeInterval is the time between keyframes on frame timestamps,
	// DefaultKeyframeInterval if zero, negative for keyframes on request only.
	KeyframeInterval time.Duration
	// Profile is ConstrainedBaseline if zero.
	Profile Profile
}

Config sets up an Encoder. Zero fields take defaults.

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

Decoder decodes H.264 packets with the system codec. Its methods are safe for concurrent use. Every packet is checked in Go before the system sees it, and pictures come out in decoding order.

func NewDecoder
func NewDecoder(cfg DecoderConfig) (*Decoder, error)

NewDecoder creates a decoder. Call Close to free it.

func (Decoder) Close
func (d *Decoder) Close() error

Close frees the decoder. It is idempotent. It waits for a Decode in progress.

func (Decoder) Decode
func (d *Decoder) Decode(p Packet) (*kolovideo.Frame, error)

Decode returns the picture in p, or nil and nil when p holds no picture. After any error, packets are refused with ErrNeedKeyframe until an IDR with its SPS and PPS.

func (Decoder) Hardware
func (d *Decoder) Hardware() bool

Hardware reports whether the system decodes this stream in hardware.

func (Decoder) SPS
func (d *Decoder) SPS() (s SPS, ok bool)

SPS returns the active sequence parameter set, ok false before the first keyframe.

type DecoderConfig
type DecoderConfig struct {
	// MaxPixels bounds the coded picture size, macroblocks times 256 before
	// cropping, which is what the system decoder allocates: 1920x1080 is
	// coded as 1920x1088. DefaultMaxPixels if zero, at most DefaultMaxPixels.
	MaxPixels int
	// MaxPacketBytes bounds a packet, DefaultMaxPacketBytes if zero, at most
	// 256 MiB so that bit offsets fit in 32 bits.
	MaxPacketBytes int
}

DecoderConfig sets up a Decoder. Zero fields take defaults.

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

Encoder encodes I420 frames with the system codec. Its methods are safe for concurrent use.

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

NewEncoder creates an encoder. On Windows it also checks the profile; call Close to free it.

func (Encoder) Close
func (e *Encoder) Close() error

Close frees the encoder. It is idempotent.

func (Encoder) Config
func (e *Encoder) Config() Config

Config returns the configuration with defaults filled in.

func (Encoder) Encode
func (e *Encoder) Encode(f *kolovideo.Frame, forceKeyframe bool) ([]Packet, error)

Encode returns the access unit for f, or none when the system encoder dropped the frame. A keyframe is made for the first frame, every KeyframeInterval and when forceKeyframe is set.

func (Encoder) Hardware
func (e *Encoder) Hardware() bool

Hardware reports whether the system encodes this stream in hardware.

func (Encoder) SetBitrate
func (e *Encoder) SetBitrate(bps int) error

SetBitrate changes the target bitrate from the next frame.

type Limits
type Limits struct{ Encode, Decode Support }

Limits is the encode and decode support of this system.

func Capabilities
func Capabilities() Limits

Capabilities probes the system codec once per process and returns the result.

type Packet
type Packet struct {
	Data []byte
	// Keyframe is set by the encoder; Decode ignores it and reads the NAL types.
	Keyframe bool
	// Timestamp and Duration pass through unchanged.
	Timestamp time.Duration
	Duration  time.Duration
}

Packet is one access unit: Annex B, 4-byte start codes, NAL types 1, 5, 7 and 8 only, one picture. A keyframe starts with an SPS and a PPS, then an IDR picture.

type Profile
type Profile int

Profile is an H.264 profile.

const (
	ConstrainedBaseline Profile = iota + 1 // profile_idc 66 with constraint_set1
	Main                                   // profile_idc 77
	High                                   // profile_idc 100
)

Profiles.

func (Profile) String
func (p Profile) String() string

String returns the profile name.

type SPS
type SPS struct {
	ID                             uint32
	ProfileIDC, Constraints, Level uint8
	// Width and Height are the picture size after cropping.
	Width, Height int
	MaxRefFrames  uint32
	FullRange     bool
	// Matrix is matrix_coefficients, 2 (unspecified) without a colour
	// description.
	Matrix uint8
}

SPS holds the sequence parameter set fields this package checks.

func ParseKeyframe
func ParseKeyframe(packet []byte) (SPS, error)

ParseKeyframe returns the first SPS of an Annex B keyframe packet, checked as Decoder checks it with the default bounds. It never panics.

func (SPS) Codec
func (s SPS) Codec() string

Codec returns the codec string, such as "avc3.42c01f" (RFC 6381 3.3).

func (SPS) Profile
func (s SPS) Profile() (p Profile, ok bool)

Profile classifies the SPS by RFC 6184 Table 5; ok is false for other profiles.

type Support
type Support struct {
	Available bool
	// Hardware reports that the system has a hardware codec for this direction.
	Hardware bool
	// Engine is "VideoToolbox" or "Media Foundation".
	Engine string
	// Profiles lists what the engine produces (encode) or accepts (decode). On
	// Windows the encode list is probed at run time; on macOS it comes from
	// the API and each encoder confirms its profile at the first keyframe.
	Profiles []Profile
	// MaxWidth and MaxHeight are the limits the system vendor documents, 0
	// when it documents none. No system documents or reports a frame-rate
	// limit, so none is reported.
	MaxWidth, MaxHeight int
	// Err says why Available is false.
	Err error
}

Support describes one direction of the system codec.

type UnavailableError
type UnavailableError struct {
	GOOS, GOARCH string
	// Engine is "VideoToolbox", "Media Foundation", or "" when none is built in.
	Engine string
	// Reason is the system's message, or why no engine exists for this platform.
	Reason string
	// Code is the OSStatus or HRESULT, 0 if none.
	Code int64
	// Devices lists, on Linux, the V4L2 stateful H.264 devices found and not used.
	Devices []string
}

UnavailableError says why H.264 is absent.

func (UnavailableError) Error
func (e *UnavailableError) Error() string

Error returns the reason with the platform and code.

func (UnavailableError) Unwrap
func (e *UnavailableError) Unwrap() error

Unwrap returns ErrUnavailable.

Conviene saber

Cómo viaja un frame

  1. Una cámara, un conversor o tu código hace un Frame: I420, BT.601, rango limitado.
  2. vpx lo codifica como VP8 o VP9, y h264 como H.264 cuando el sistema tiene un códec.
  3. Cada codificador devuelve un paquete por frame. Tu aplicación lo envía.
  4. El receptor decodifica el paquete con el decodificador que corresponde, que antes lo revisa.
  5. El decodificador devuelve un Frame, o un error y una espera de keyframe.

Frames y captura

  • Un Frame tiene planos Y, U y V de 8 bits, más Timestamp y Duration. NewFrame(w, h) reserva un frame negro. Toda función que recibe un frame llama a Validate y devuelve ErrInvalidFrame en vez de provocar un pánico.
  • FromNV12, FromYUY2, FromUYVY, FromBGRA y FromRGBA convierten una imagen en bruto con cualquier stride a un frame nuevo. Frame.RGBA() convierte de vuelta, y Renderer{Scale: Fit} dibuja en un *image.RGBA con barras (Fill recorta).
  • Devices() lista las cámaras sin abrir ninguna. OpenCapture elige el modo admitido más cercano a la petición y Capture.Read devuelve frames. Cuando el lector es lento se guardan como máximo Buffer frames y se descarta el más antiguo. Una desconexión, un fallo de captura o no recibir frames durante StallTimeout termina la captura con ErrDeviceLost después de leer los frames en búfer.
  • Los backends son AVFoundation en macOS (con purego), Media Foundation en Windows (con COM) y V4L2 en Linux (Go puro, con Motion-JPEG incluido). En macOS OpenCapture devuelve ErrPermission hasta que el usuario concede el acceso, y nunca lo pide: RequestAccess lo pide. Los frames siempre se convierten a I420 BT.601 de rango limitado.
  • En las demás plataformas, Devices, RequestAccess y OpenCapture devuelven ErrUnsupported: la plataforma no tiene backend de captura. Los frames, la conversión, el dibujo y los códecs siguen funcionando.

VP8 y VP9

  • vpx.NewEncoder y vpx.NewDecoder trabajan en tiempo real: una pasada, tasa de bits constante, sin retardo, resistencia a errores y descarte de frames. El primer frame y un frame por cada KeyframeInterval (2 s por defecto) son keyframes, Encode(f, true) fuerza uno y SetBitrate cambia el objetivo desde el siguiente frame. Encode no devuelve ningún paquete cuando el control de tasa descarta un frame.
  • El decodificador comprueba la cabecera de cada frame contra MaxPixels antes de que libvpx reserve memoria (ErrTooLarge), decodifica desde su propia copia del paquete y rechaza paquetes con ErrNeedKeyframe desde el inicio y después de cualquier error, hasta que llega un keyframe.
  • vpx.DecoderConfig.MaxPacketBytes rechaza con ErrTooLarge un paquete que lo supere, antes de copiarlo: 16 MiB por defecto, como mucho 256 MiB (vpx.DefaultMaxPacketBytes, el mismo límite que en h264). El decodificador conserva como mucho 1 MiB de búfer de paquetes entre llamadas.
  • Dos motores ejecutan la misma libvpx 1.16.0, y vpx.Load hace la elección una vez por proceso. El motor native es una biblioteca precompilada por destino, cargada sin cgo; el motor portable es el mismo código traducido a Go. vpx.Capabilities() lista los modos de tiempo real más grandes del motor en uso: native 1920x1080 a 30 fps en las dos direcciones, portable 640x480 a 30 fps para codificar y 1920x1080 a 30 fps para decodificar.
  • En Linux el binario por defecto es estático y usa el motor portable; compila con -tags kolovideo_native en glibc 2.28 o superior para usar el native. Una app macOS firmada necesita un paso más para el motor native, y Windows Smart App Control puede rechazar la DLL incluida. En ambos casos corre el motor portable y vpx.LoadError() dice por qué.

H.264

  • h264.Capabilities() dice si el sistema puede codificar y decodificar H.264, si el códec es de hardware, qué motor es (VideoToolbox o Media Foundation) y qué perfiles ofrece. Donde no está disponible, el error es un *UnavailableError que coincide con h264.ErrUnavailable y nombra la plataforma y el motivo.
  • kolo-video no contiene código H.264. VideoToolbox en macOS y las transformaciones H.264 de Media Foundation en las ediciones de escritorio de Windows hacen la codificación; no se instala, incluye ni descarga nada. En Linux y en cualquier otra plataforma no hay motor, y h264 no importa vpx ni ninguna biblioteca nativa.
  • Los perfiles son Constrained Baseline (el predeterminado), Main y High, hasta el nivel 5.1, 4:2:0 progresivo de 8 bits, sin B-frames. Los tamaños son pares y de 48 a 4096 por lado. El codificador devuelve un paquete por frame, dentro de la misma llamada a Encode.
  • Un paquete es una unidad de acceso Annex B con códigos de inicio de 4 bytes. Cada keyframe empieza con su SPS y su PPS, así que un receptor puede empezar en cualquier keyframe. h264.ParseKeyframe(packet) y SPS.Codec() dan el string del códec, como avc3.42c01f. El string sale del primer keyframe y es orientativo.
  • El par recomendado para quien envía es VP8 siempre y H.264 cuando Capabilities dice que puede codificar: dos versiones de una misma fuente. Un receptor que no puede decodificar H.264 toma VP8. Nada pasa de uno a otro por sí solo: tu aplicación consulta Capabilities y elige. kolo-media v0.1.0 no transporta H.264: su catálogo acepta VP8 y VP9 para video.
  • El decodificador revisa cada paquete en Go antes de que lo vea el sistema, así que un stream fuera de los perfiles, niveles y herramientas admitidos es ErrUnsupportedStream, un paquete dañado es ErrCorrupt, uno demasiado grande ErrTooLarge, y después de cualquier error devuelve ErrNeedKeyframe hasta que llega un keyframe.
  • SetBitrate cambia el objetivo desde el siguiente frame. El codificador de hardware de macOS siguió un cambio de 1,9 a 0,5 Mbit/s con un error de menos del 1 por ciento; el codificador por software de macOS no había convergido (988 kbit/s para un objetivo de 500 kbit/s).

Plataformas

PlataformaVP8 y VP9H.264 (códec del SO)Backend de cámara
macOS arm64native, portable como respaldoVideoToolbox, hardware en el Mac que lo ejecutóAVFoundation con purego
macOS amd64igualVideoToolboxigual
Windows arm64native, portable como respaldoMedia Foundation, por softwareMedia Foundation con COM
Windows amd64igualigualigual
Linux amd64, arm64portable; native con -tags kolovideo_nativeninguno: ErrUnavailableV4L2 en Go puro
Otrasportableninguno: ErrUnavailableninguno: ErrUnsupported

Qué se ejecutó con H.264:

  • macOS arm64, un Apple M5: las pruebas de ida y vuelta a 640x480, 1280x720 y 1920x1080 en Constrained Baseline, Main y High decodificaron todos los frames con un PSNR de luma de al menos 42,69 dB, con el codificador y el decodificador de hardware. También se probaron la ruta por software (con el hardware desactivado) y la entrada dañada, y el binario se ejecutó firmado ad hoc con el hardened runtime. Bajo Rosetta, amd64 pasó las mismas pruebas. No se usó ningún Mac Intel.
  • Windows 11 ARM64 en una VM: las mismas pruebas con un PSNR de luma de al menos 42,86 dB, una imagen por cada paquete desde el primero, solo con transformaciones por software. La emulación x64 de la VM pasó las pruebas funcionales. No se ejecutó Windows amd64 nativo.
  • Los codificadores de macOS y de Windows produjeron streams que decodificó el decodificador del otro sistema.
  • Linux, en contenedores Debian y Alpine: el mensaje de ausencia, un binario estático y los analizadores. En ninguna máquina de prueba existe un dispositivo de códec V4L2 con estado, así que la detección nunca se ejecutó contra un controlador real.
  • Sin validar: codificar y decodificar en Linux (no se ofrece), VA-API, las transformaciones de hardware de Windows, las ediciones N y Windows Server, una app firmada con Developer ID y notarizada, una cámara real alimentando el codificador H.264, y navegadores y teléfonos.

Un stream de cámara se ejecutó solo en la cámara integrada de un Mac. La captura en Linux y en Windows nunca se ejecutó con una cámara real.

Límites

Un valor fuera de rango devuelve ErrInvalidConfig o ErrInvalidFrame. Las tablas completas están en Límites.

  • Frames: de 1 a 65536 por lado. CaptureConfig.MaxPixels y DecoderConfig.MaxPixels acotan las imágenes: 8.912.896 píxeles para VP8 y VP9 y 9.437.184 para H.264.
  • Los frames VP8 van de 1 a 16383 por lado, y el frame VP9 más grande es de 65536.
  • Codificador H.264: tamaños pares de 48 a 4096, como máximo 36864 macrobloques, y macrobloques por tasa de frames como máximo 983040. Eso es 1920x1080 hasta 120 fps y 3840x2160 hasta 30 fps. Tasa de bits de 1 a 240.000.000 bit/s.
  • Decodificador H.264: perfiles 66, 77 y 100, niveles de 1 a 5.1, como máximo 16 MiB por paquete por defecto, y una imagen por paquete.
  • El motor portable usa como máximo 1 GiB de memoria por instancia.

Seguridad

  • La cabecera de cada frame se comprueba en Go contra MaxPixels antes de que libvpx reserve memoria, y el decodificador trabaja sobre su propia copia del paquete.
  • En H.264, solo los tipos de unidad NAL 1, 5, 7 y 8 llegan al sistema. Un conjunto de parámetros solo se acepta en un paquete de keyframe, y el nivel, el tamaño de la imagen y los frames de referencia se comprueban contra la Tabla A-1 de la especificación H.264.
  • En Windows, los slices dañados que pasan las comprobaciones los disimula el sistema y los devuelve como imágenes, así que Decode no los informa, y un fallo dentro del decodificador termina la aplicación. Un cuelgue dentro del códec del sistema bloquea Decode y Close.
  • Las bibliotecas nativas incluidas se comprueban contra su SHA-256 antes de cada carga, y el directorio de caché y todos los directorios por encima de él se comprueban en cuanto a propietario y permisos. Una app macOS firmada puede rechazar la biblioteca, y corre el motor portable.
  • La biblioteca no hace ninguna conexión de red, no lanza ningún proceso y no usa cgo.

Estado

  • Hecho: frames y conversiones, captura de cámara en macOS, Windows y Linux, VP8 y VP9 en dos motores, y H.264 con VideoToolbox y Media Foundation, con objetivos de fuzzing y pruebas.
  • Probado: H.264 se ejecutó en un Mac y en una VM de Windows, como dice la lista de plataformas. Un stream de cámara se ejecutó solo en un Mac.
  • No hecho: H.264 en Linux, y kolo-media todavía no transporta H.264.
  • Experimental. La API puede cambiar antes de la v1.0.0.

Errores

ErrorMensaje
ErrClosedkolovideo: closed
ErrDeviceLostkolovideo: device lost
ErrInvalidConfigkolovideo: invalid config
ErrInvalidFramekolovideo: invalid frame
ErrNoDevicekolovideo: no such device
ErrPermissionkolovideo: camera access not granted
ErrUnsupportedkolovideo: not supported on this platform
ErrUnsupportedFormatkolovideo: unsupported format
vpx.ErrCodeckolovideo/vpx: codec error
vpx.ErrCorruptkolovideo/vpx: corrupt packet
vpx.ErrNativeABInative libvpx ABI mismatch
vpx.ErrNativeCachenative libvpx cache is unusable
vpx.ErrNativeIntegrityembedded native libvpx does not match its checksum
vpx.ErrNativeSignaturenative libvpx code signature is not valid
vpx.ErrNativeUnsupportedno native libvpx
vpx.ErrNeedKeyframekolovideo/vpx: waiting for a keyframe
vpx.ErrTooLargekolovideo/vpx: packet or frame too large
vpx.ErrUnavailablekolovideo/vpx: libvpx unavailable
h264.ErrCodeckolovideo/h264: system codec error
h264.ErrCorruptkolovideo/h264: corrupt packet
h264.ErrNeedKeyframekolovideo/h264: waiting for a keyframe
h264.ErrProfilekolovideo/h264: profile not available from the system encoder
h264.ErrTooLargekolovideo/h264: packet or picture too large
h264.ErrUnavailablekolovideo/h264: no H.264 codec on this system
h264.ErrUnsupportedStreamkolovideo/h264: unsupported stream

Todos los errores empiezan con kolovideo:, o con kolovideo/vpx: o kolovideo/h264: en los paquetes de códec, y envuelven un centinela, así que errors.Is funciona. ErrUnsupported significa que esta plataforma no tiene backend de captura, y el error nombra GOOS y GOARCH. h264.ErrUnavailable llega como un *UnavailableError que dice por qué el sistema no tiene códec.

Referencias