kolo docsbeta

kolo-video

Captura de câmera, frames I420, VP8 e VP9 com libvpx, e H.264 opcional com o codec do próprio sistema operacional. Sem cgo, sem compilador C e sem nada para instalar.

Nesta página

A kolo-video lista e abre câmeras, entrega frames I420 (com a matriz BT.601), converte outros formatos de pixel para I420, desenha frames em imagens RGBA e codifica e decodifica VP8 (RFC 6386) e VP9 em tempo real. O H.264 é opcional e vem do codec do próprio sistema operacional. Ela não envia nada pela rede e não sincroniza o áudio com o vídeo. Os pacotes Go são kolovideo, vpx e h264.

Todos os passos

De um Frame a pacotes e de volta

VP8 e VP9 funcionam em todo lugar. O H.264 usa o codec do sistema operacional, então é opcional.

  1. Um Frame é uma imagem I420: planos de 8 bits, BT.601, faixa limitada. Vem de uma câmera, de um conversor como FromNV12 ou do seu próprio código.
  2. O vpx o codifica como VP8 ou VP9 com a libvpx 1.16.0. O motor native é uma biblioteca pré-compilada carregada sem cgo; o motor portable é o mesmo código traduzido para Go. O pacote escolhe um e diz qual.
  3. O h264 o codifica como H.264 com o codec que o sistema operacional traz: VideoToolbox no macOS, Media Foundation no Windows. É opcional: Capabilities diz se está disponível, e no Linux não está.
  4. Cada codificador devolve um pacote por frame: um frame VP8 ou VP9, ou uma unidade de acesso Annex B com seu SPS e seu PPS antes de cada keyframe. Um emissor pode enviar sempre VP8 e H.264 quando puder. Sua aplicação envia os pacotes.
  5. O receptor decodifica o stream que escolheu. Pega o H.264 só se o próprio sistema consegue decodificá-lo, e o VP8 caso contrário. Cada decodificador confere um pacote antes de decodificá-lo.
  6. O decodificador devolve um Frame, ou um erro, e então espera um keyframe.

Instalação

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

Para fixar esta versão, rode go get github.com/ciranda-dev/kolo-video@v0.1.0. Ela precisa do Go 1.26 ou mais novo. Não há cgo, nem compilador C, nem libvpx, nem pkg-config, nem variável de ambiente para definir, então ela compila com CGO_ENABLED=0. O codec de VP8 e VP9 é a libvpx 1.16.0 em duas formas que carregam o mesmo código: uma biblioteca pré-compilada embutida no módulo e carregada sem cgo (velocidade total), e o mesmo código traduzido para Go (funciona em todo lugar, em tempo real até 640x480). O pacote escolhe uma em tempo de execução e diz qual. A primeira compilação do pacote vpx compila Go gerado e chega a cerca de 570 MB de memória em um Mac; as seguintes usam o cache de compilação.

Início rápido

Este programa lista as câmeras (nunca abre uma), depois codifica 30 frames gerados com VP8 e os decodifica de novo. Rode-o com go run . <dir>, em que <dir> é onde o motor native guarda a sua biblioteca; uma aplicação normalmente deixa CacheDir vazio, e assim é usado o diretório de cache do usuário.

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)
}

A linha do motor depende da plataforma (native no macOS e no Windows, portable no Linux por padrão). A última não:

Texto
30 frames encoded and decoded, 13596 bytes

O H.264 tem a mesma forma, com um passo a mais: pergunte primeiro ao sistema. Este programa codifica um frame com H.264, lê a string do codec do keyframe e o decodifica de novo. Onde o sistema não tem um codec H.264, ele imprime o motivo, e você publica só 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)
}

Em um Mac com VideoToolbox, imprimiu:

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

Em um contêiner Linux, onde não há motor, imprimiu:

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, abra uma câmera e leia frames. OpenCapture nunca pede permissão: no macOS chame antes RequestAccess. O repositório tem examples/snapshot, que salva frames da câmera como arquivos PNG (-list lista as câmeras), examples/vp8, que codifica e decodifica frames gerados e imprime o motor, o tamanho e a qualidade, e examples/h264, que faz o mesmo com H.264 e recorre ao VP8 onde o sistema não tem codec.

Referência da API

A referência da API é gerada a partir do código Go e está em inglês.

Pacote 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.

Variáveis

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")
)

Funções

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.

Pacote 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.

Variáveis

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.

Funções

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.

Pacote 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.

Variáveis

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.

Bom saber

Como um frame viaja

  1. Uma câmera, um conversor ou o seu código faz um Frame: I420, BT.601, faixa limitada.
  2. O vpx o codifica como VP8 ou VP9, e o h264 como H.264 quando o sistema tem um codec.
  3. Cada codificador devolve um pacote por frame. Sua aplicação o envia.
  4. O receptor decodifica o pacote com o decodificador correspondente, que antes o confere.
  5. O decodificador devolve um Frame, ou um erro e uma espera por keyframe.

Frames e captura

  • Um Frame tem planos Y, U e V de 8 bits, mais Timestamp e Duration. NewFrame(w, h) aloca um frame preto. Toda função que recebe um frame chama Validate e retorna ErrInvalidFrame em vez de causar um pânico.
  • FromNV12, FromYUY2, FromUYVY, FromBGRA e FromRGBA convertem uma imagem bruta com qualquer stride para um frame novo. Frame.RGBA() converte de volta, e Renderer{Scale: Fit} desenha em um *image.RGBA com barras (Fill recorta).
  • Devices() lista as câmeras sem abrir nenhuma. OpenCapture escolhe o modo suportado mais próximo do pedido e Capture.Read devolve frames. Quando o leitor é lento, no máximo Buffer frames são guardados e o mais antigo é descartado. Uma desconexão, uma falha de captura ou nenhum frame durante StallTimeout encerra a captura com ErrDeviceLost depois que os frames em buffer são lidos.
  • Os backends são AVFoundation no macOS (com purego), Media Foundation no Windows (com COM) e V4L2 no Linux (Go puro, incluindo Motion-JPEG). No macOS OpenCapture retorna ErrPermission até que o usuário conceda o acesso, e nunca o pede: RequestAccess pede. Os frames são sempre convertidos para I420 BT.601 de faixa limitada.
  • Nas demais plataformas, Devices, RequestAccess e OpenCapture retornam ErrUnsupported: a plataforma não tem backend de captura. Os frames, a conversão, o desenho e os codecs continuam funcionando.

VP8 e VP9

  • vpx.NewEncoder e vpx.NewDecoder trabalham em tempo real: uma passada, bitrate constante, sem atraso, resiliência a erros e descarte de frames. O primeiro frame e um frame a cada KeyframeInterval (2 s por padrão) são keyframes, Encode(f, true) força um e SetBitrate muda o alvo a partir do próximo frame. Encode não devolve pacote quando o controle de taxa descarta um frame.
  • O decodificador confere o cabeçalho de cada frame contra MaxPixels antes de a libvpx alocar qualquer coisa (ErrTooLarge), decodifica a partir da sua própria cópia do pacote e recusa pacotes com ErrNeedKeyframe desde o início e depois de qualquer erro, até que chegue um keyframe.
  • vpx.DecoderConfig.MaxPacketBytes recusa com ErrTooLarge um pacote que passe dele, antes de copiá-lo: 16 MiB por padrão, no máximo 256 MiB (vpx.DefaultMaxPacketBytes, o mesmo limite do h264). O decodificador mantém no máximo 1 MiB de buffer de pacotes entre chamadas.
  • Dois motores rodam a mesma libvpx 1.16.0, e vpx.Load faz a escolha uma vez por processo. O motor native é uma biblioteca pré-compilada por destino, carregada sem cgo; o motor portable é o mesmo código traduzido para Go. vpx.Capabilities() lista os maiores modos de tempo real do motor em uso: native 1920x1080 a 30 fps nas duas direções, portable 640x480 a 30 fps para codificar e 1920x1080 a 30 fps para decodificar.
  • No Linux o binário padrão é estático e usa o motor portable; compile com -tags kolovideo_native em glibc 2.28 ou mais nova para usar o native. Um app macOS assinado precisa de mais um passo para o motor native, e o Windows Smart App Control pode recusar a DLL embutida. Nos dois casos roda o motor portable e vpx.LoadError() diz o motivo.

H.264

  • h264.Capabilities() diz se o sistema consegue codificar e decodificar H.264, se o codec é de hardware, qual é o motor (VideoToolbox ou Media Foundation) e quais perfis oferece. Onde não está disponível, o erro é um *UnavailableError que coincide com h264.ErrUnavailable e nomeia a plataforma e o motivo.
  • A kolo-video não contém código H.264. O VideoToolbox no macOS e as transformações H.264 do Media Foundation nas edições desktop do Windows fazem a codificação; nada é instalado, embutido nem baixado. No Linux e em qualquer outra plataforma não há motor, e o h264 não importa o vpx nem nenhuma biblioteca nativa.
  • Os perfis são Constrained Baseline (o padrão), Main e High, até o nível 5.1, 4:2:0 progressivo de 8 bits, sem B-frames. Os tamanhos são pares e de 48 a 4096 por lado. O codificador devolve um pacote por frame, dentro da mesma chamada a Encode.
  • Um pacote é uma unidade de acesso Annex B com códigos de início de 4 bytes. Todo keyframe começa com o seu SPS e o seu PPS, então um receptor pode começar em qualquer keyframe. h264.ParseKeyframe(packet) e SPS.Codec() dão a string do codec, como avc3.42c01f. A string vem do primeiro keyframe e é apenas indicativa.
  • O par recomendado para quem envia é VP8 sempre e H.264 quando Capabilities diz que consegue codificar: duas versões de uma mesma fonte. Um receptor que não consegue decodificar H.264 pega o VP8. Nada passa de um para o outro sozinho: sua aplicação consulta Capabilities e escolhe. A kolo-media v0.1.0 não transporta H.264: o seu catálogo aceita VP8 e VP9 para vídeo.
  • O decodificador confere cada pacote em Go antes de o sistema vê-lo, então um stream fora dos perfis, níveis e ferramentas suportados é ErrUnsupportedStream, um pacote danificado é ErrCorrupt, um grande demais ErrTooLarge, e depois de qualquer erro ele retorna ErrNeedKeyframe até que chegue um keyframe.
  • SetBitrate muda o alvo a partir do próximo frame. O codificador de hardware do macOS acompanhou uma mudança de 1,9 para 0,5 Mbit/s com erro de menos de 1 por cento; o codificador por software do macOS não tinha convergido (988 kbit/s para um alvo de 500 kbit/s).

Plataformas

PlataformaVP8 e VP9H.264 (codec do SO)Backend de câmera
macOS arm64native, portable como reservaVideoToolbox, hardware no Mac que o executouAVFoundation com purego
macOS amd64igualVideoToolboxigual
Windows arm64native, portable como reservaMedia Foundation, por softwareMedia Foundation com COM
Windows amd64igualigualigual
Linux amd64, arm64portable; native com -tags kolovideo_nativenenhum: ErrUnavailableV4L2 em Go puro
Outrasportablenenhum: ErrUnavailablenenhum: ErrUnsupported

O que foi executado com H.264:

  • macOS arm64, um Apple M5: os testes de ida e volta a 640x480, 1280x720 e 1920x1080 em Constrained Baseline, Main e High decodificaram todos os frames com PSNR de luma de pelo menos 42,69 dB, com o codificador e o decodificador de hardware. Também foram testados o caminho por software (com o hardware desligado) e a entrada danificada, e o binário rodou assinado ad hoc com o hardened runtime. Sob o Rosetta, o amd64 passou nos mesmos testes. Nenhum Mac Intel foi usado.
  • Windows 11 ARM64 em uma VM: os mesmos testes com PSNR de luma de pelo menos 42,86 dB, uma imagem para cada pacote desde o primeiro, só com transformações por software. A emulação x64 da VM passou nos testes funcionais. O Windows amd64 nativo não foi executado.
  • Os codificadores do macOS e do Windows produziram streams que o decodificador do outro sistema decodificou.
  • Linux, em contêineres Debian e Alpine: a mensagem de ausência, um binário estático e os analisadores. Nenhuma máquina de teste tem um dispositivo de codec V4L2 com estado, então a detecção nunca rodou contra um driver real.
  • Não validado: codificar e decodificar no Linux (não é oferecido), VA-API, as transformações de hardware do Windows, as edições N e o Windows Server, um app assinado com Developer ID e notarizado, uma câmera real alimentando o codificador H.264, e navegadores e celulares.

Um stream de câmera rodou só na câmera embutida de um Mac. A captura no Linux e no Windows nunca rodou com uma câmera real.

Limites

Um valor fora do intervalo retorna ErrInvalidConfig ou ErrInvalidFrame. As tabelas completas estão em Limites.

  • Frames: de 1 a 65536 por lado. CaptureConfig.MaxPixels e DecoderConfig.MaxPixels limitam as imagens: 8.912.896 pixels para VP8 e VP9 e 9.437.184 para H.264.
  • Os frames VP8 vão de 1 a 16383 por lado, e o maior frame VP9 é de 65536.
  • Codificador H.264: tamanhos pares de 48 a 4096, no máximo 36864 macroblocos, e macroblocos vezes a taxa de frames no máximo 983040. Isso é 1920x1080 até 120 fps e 3840x2160 até 30 fps. Bitrate de 1 a 240.000.000 bit/s.
  • Decodificador H.264: perfis 66, 77 e 100, níveis de 1 a 5.1, no máximo 16 MiB por pacote por padrão, e uma imagem por pacote.
  • O motor portable usa no máximo 1 GiB de memória por instância.

Segurança

  • O cabeçalho de cada frame é conferido em Go contra MaxPixels antes de a libvpx alocar qualquer coisa, e o decodificador trabalha sobre a sua própria cópia do pacote.
  • No H.264, só os tipos de unidade NAL 1, 5, 7 e 8 chegam ao sistema. Um conjunto de parâmetros só é aceito em um pacote de keyframe, e o nível, o tamanho da imagem e os frames de referência são conferidos contra a Tabela A-1 da especificação H.264.
  • No Windows, os slices danificados que passam pelas verificações são disfarçados pelo sistema e devolvidos como imagens, então Decode não os informa, e uma falha dentro do decodificador encerra a aplicação. Um travamento dentro do codec do sistema bloqueia Decode e Close.
  • As bibliotecas nativas embutidas são conferidas contra o seu SHA-256 antes de cada carga, e o diretório de cache e todos os diretórios acima dele são conferidos quanto a dono e permissões. Um app macOS assinado pode recusar a biblioteca, e roda o motor portable.
  • A biblioteca não faz nenhuma conexão de rede, não inicia nenhum processo e não usa cgo.

Estado

  • Feito: frames e conversões, captura de câmera no macOS, no Windows e no Linux, VP8 e VP9 em dois motores, e H.264 com VideoToolbox e Media Foundation, com alvos de fuzzing e testes.
  • Testado: o H.264 rodou em um Mac e em uma VM de Windows, como diz a lista de plataformas. Um stream de câmera rodou só em um Mac.
  • Não feito: H.264 no Linux, e a kolo-media ainda não transporta H.264.
  • Experimental. A API pode mudar antes da v1.0.0.

Erros

ErroMensagem
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

Todo erro começa com kolovideo:, ou com kolovideo/vpx: ou kolovideo/h264: nos pacotes de codec, e envolve um sentinela, então errors.Is funciona. ErrUnsupported significa que esta plataforma não tem backend de captura, e o erro nomeia GOOS e GOARCH. h264.ErrUnavailable chega como um *UnavailableError que diz por que o sistema não tem codec.

Referências