capture

package
v0.1.0-alpha.3 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: Apache-2.0 Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package capture defines the device-independent contract between media sources (cameras, microphones, screen and tab capture, synthetic test sources) and the code that consumes them (getUserMedia/getDisplayMedia tracks, WebRTC senders, MediaRecorder). Platform code registers devices here; the engine never talks to a device API directly.

Frames are planar I420 (YUV 4:2:0 8-bit) and audio is interleaved signed 16-bit PCM, because that is what both the VP8/H.264 encoders and the Opus encoder take, and what the decoders on the receive side produce.

Index

Constants

View Source
const (
	EndStopped = "stopped" // track.stop() or the page went away
	EndDevice  = "device"  // the device vanished or failed
	EndUser    = "user"    // the user pressed Stop sharing / revoked the permission
)

End reasons of a Track.

View Source
const DefaultStartTimeout = 4 * time.Second

DefaultStartTimeout is how long getUserMedia waits for the first frame or chunk before failing the way browsers do ("Timeout starting video source").

Variables

View Source
var ErrInUse = errors.New("capture: device in use")

ErrInUse is returned when another application holds the device exclusively.

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

ErrNotFound is returned when a device id is unknown or the device has disappeared.

View Source
var ErrTimeout = errors.New("capture: timeout starting source")

ErrTimeout is returned when a device was opened but produced no data in time.

View Source
var ErrUnsupported = errors.New("capture: not supported on this platform")

ErrUnsupported is returned by a provider that does not implement a kind on this platform.

Functions

func Convert

func Convert(dst *Frame, f PixelFormat, src []byte, stride int) error

Convert converts src to I420 into dst, which must already be dst.W x dst.H. stride is the source row pitch in bytes. Every conversion uses the BT.601 limited-range matrix for RGB and the identity for YUV sources, so the result of a YUV format is bit-exact with the data the camera produced (apart from the chroma averaging that 4:2:2 to 4:2:0 needs).

func ConvertSize

func ConvertSize(f PixelFormat, w, h, stride int) int

ConvertSize reports the number of source bytes Convert needs for a w x h frame whose luma row pitch is stride bytes (for packed formats stride is the pitch of one full row; for planar formats the pitch of the Y plane).

func DecodeMJPEG

func DecodeMJPEG(dst *Frame, data []byte) error

DecodeMJPEG decodes one Motion-JPEG frame into dst (which must already have the JPEG's dimensions).

Two Motion-JPEG quirks are handled: many UVC cameras omit the Huffman tables (the format is "abbreviated JPEG" and every decoder is expected to use the Annex K tables), which image/jpeg rejects, so the standard tables are inserted when the frame has no DHT segment; and JPEG is full-range (JFIF) while I420 here is limited-range, so samples are rescaled. Decoding uses image/jpeg, which is pure Go and returns planar YCbCr without an RGB step.

func FromRGBA

func FromRGBA(dst *Frame, src *image.RGBA)

FromRGBA converts src into dst (which must be src's size), averaging each 2x2 block for chroma. Alpha is ignored.

func LiveTracks

func LiveTracks() int

LiveTracks counts tracks that have not ended (tests, the leak checks).

func RGBToU

func RGBToU(r, g, b int) uint8

func RGBToV

func RGBToV(r, g, b int) uint8

func RGBToY

func RGBToY(r, g, b int) uint8

RGBToY, RGBToU and RGBToV are the BT.601 limited-range forward transform.

func Register

func Register(p Provider)

Register adds a provider (call from init()). Registering the same name twice replaces it.

func Scale

func Scale(dst, src *Frame)

Scale writes src into dst (any sizes) with an area-average filter when shrinking and a nearest-neighbour pick when growing. The screen sources use it to honour max width/height constraints.

func Unregister

func Unregister(name string)

Unregister removes a provider by name (tests).

func YUVToRGB

func YUVToRGB(y, u, v uint8) (r, g, b uint8)

YUVToRGB converts one BT.601 limited-range sample (the range webcams and the VP8/H.264 encoders assume).

Types

type AudioCaps

type AudioCaps struct {
	Rates                      []int // sample rates the source delivers (usually just its native rate)
	MinChannels, MaxChannels   int
	DefaultRate, DefaultChanns int
}

AudioCaps describes a microphone.

func AudioCapsOf

func AudioCapsOf(id string) AudioCaps

AudioCapsOf returns the capabilities of the microphone with this id.

func DefaultAudioCaps

func DefaultAudioCaps() AudioCaps

DefaultAudioCaps is the capability of a microphone that did not say.

type AudioChunk

type AudioChunk struct {
	Rate     int
	Channels int
	PCM      []int16
	PTS      time.Duration
}

AudioChunk is a block of interleaved 16-bit PCM.

type AudioConstraints

type AudioConstraints struct {
	Rate, Channels                               int
	EchoCancellation, NoiseSuppression, AutoGain bool
}

AudioConstraints: Rate 0 means the source's preferred rate; consumers resample.

type AudioLease

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

AudioLease is VideoLease for microphones.

func AcquireAudio

func AcquireAudio(id string, c AudioConstraints, timeout time.Duration) (*AudioLease, error)

AcquireAudio starts the microphone with this id or joins the running stream.

func AcquireAudioFrom

func AcquireAudioFrom(key string, open func() (AudioSource, error), c AudioConstraints, timeout time.Duration) (*AudioLease, error)

AcquireAudioFrom is AcquireAudio for an unregistered source.

func (*AudioLease) Ended

func (l *AudioLease) Ended() <-chan struct{}

func (*AudioLease) Err

func (l *AudioLease) Err() error

func (*AudioLease) Mode

func (l *AudioLease) Mode() AudioMode

func (*AudioLease) Release

func (l *AudioLease) Release()

func (*AudioLease) Subscribe

func (l *AudioLease) Subscribe() *Sub[AudioChunk]

type AudioMode

type AudioMode struct {
	Rate, Channels int
}

AudioMode is the format a running microphone really delivers.

type AudioSource

type AudioSource interface {
	Info() DeviceInfo
	Start(c AudioConstraints) (<-chan *AudioChunk, error)
	Stop() error
	Err() error
}

AudioSource produces PCM chunks until Stop.

func OpenAudio

func OpenAudio(id string) (AudioSource, error)

OpenAudio opens the microphone with this id.

type CapsProvider

type CapsProvider interface {
	VideoCaps(id string) (VideoCaps, bool)
	AudioCaps(id string) (AudioCaps, bool)
}

CapsProvider is implemented by providers that know the capabilities of their devices. Providers that do not are treated as able to deliver anything within DefaultVideoCaps / DefaultAudioCaps.

type DeviceInfo

type DeviceInfo struct {
	ID      string // stable per machine, opaque to pages (the engine hashes it per origin before exposing it)
	GroupID string
	Label   string
	Kind    Kind
	// Facing is "user", "environment" or "" (unknown); only meaningful for cameras.
	Facing string
}

DeviceInfo describes one capture device.

func Devices

func Devices(kind Kind) []DeviceInfo

Devices lists every registered device of a kind, ordered by provider name then device order.

type Frame

type Frame struct {
	W, H              int
	Y, U, V           []byte
	YStride, UVStride int
	PTS               time.Duration // capture time since the source started
}

Frame is one I420 video frame. Y has YStride*H bytes, U and V have UVStride*((H+1)/2) bytes each.

func FromImage

func FromImage(img image.Image) *Frame

FromImage converts any image.Image (slow path, used by tests and one-off captures).

func NewBlack

func NewBlack(w, h int) *Frame

NewBlack returns a black frame of the given size.

func NewFrame

func NewFrame(w, h int) *Frame

NewFrame allocates a zeroed w x h I420 frame (stride == width, chroma stride == (w+1)/2). Odd sizes are allowed; chroma planes are rounded up.

func (*Frame) Black

func (f *Frame) Black()

Black fills the frame with limited-range black (Y=16, U=V=128).

func (*Frame) Clone

func (f *Frame) Clone() *Frame

Clone returns a deep copy.

func (*Frame) ToRGBA

func (f *Frame) ToRGBA() *image.RGBA

ToRGBA converts the frame to an opaque RGBA image (previews, PNG output, tests).

type Kind

type Kind string

Kind is the MediaDeviceInfo kind of a device.

const (
	VideoInput  Kind = "videoinput"
	AudioInput  Kind = "audioinput"
	AudioOutput Kind = "audiooutput"
	// Screen is not a MediaDeviceInfo kind: it is the source behind getDisplayMedia (a tab, a window or a monitor).
	Screen Kind = "screen"
)

type Mode

type Mode struct {
	W, H           int
	FPSMin, FPSMax float64
}

Mode is one resolution a camera can deliver and the frame-rate range it can deliver it at. It deliberately knows nothing about the pixel format: the provider picks the format when the source starts.

func ClosestMode

func ClosestMode(modes []Mode, w, h int, fps float64) (Mode, bool)

ClosestMode picks the mode nearest to a requested size, preferring (in order) a mode that can reach the requested frame rate and, among equals, the larger frame rate. A zero request component means "don't care".

type Moder

type Moder interface {
	Mode() (w, h int, fps float64)
}

Moder is implemented by sources that know the mode they negotiated with the device. Without it the first frame decides the size and the requested rate is reported.

type PixelFormat

type PixelFormat string

PixelFormat names a raw camera layout that Convert understands. Names follow the V4L2 / Media Foundation usage (YUYV == YUY2, YU12 == I420).

const (
	PixYUYV  PixelFormat = "YUYV" // packed 4:2:2, Y0 U Y1 V
	PixUYVY  PixelFormat = "UYVY" // packed 4:2:2, U Y0 V Y1
	PixNV12  PixelFormat = "NV12" // Y plane, then interleaved U V at half resolution
	PixNV21  PixelFormat = "NV21" // like NV12 with V first
	PixI420  PixelFormat = "I420" // planar Y, U, V (V4L2 YU12)
	PixYV12  PixelFormat = "YV12" // planar Y, V, U
	PixRGB24 PixelFormat = "RGB24"
	PixBGR24 PixelFormat = "BGR24"
	PixGrey  PixelFormat = "GREY"
)

type Provider

type Provider interface {
	Name() string
	Devices() []DeviceInfo
	OpenVideo(id string) (VideoSource, error)
	OpenAudio(id string) (AudioSource, error)
}

Provider enumerates and opens devices for one platform or one synthetic backend.

type Sub

type Sub[T any] struct {
	C chan *T
	// contains filtered or unexported fields
}

A Sub is one consumer of a shared source. Items are delivered in order; a consumer that falls behind loses its oldest items (a live source never waits for a reader). C is closed when the source ends or the sub is cancelled.

func (*Sub[T]) Cancel

func (s *Sub[T]) Cancel()

Cancel detaches the subscription (idempotent).

type Track

type Track struct {
	ID     string
	Kind   Kind // VideoInput, AudioInput, or Screen (a video track made from a display source)
	Device DeviceInfo
	// Surface is "browser" or "window" for display tracks.
	Surface string
	Origin  string
	// contains filtered or unexported fields
}

Track is one MediaStreamTrack's worth of live media: a lease on a source plus the enabled flag. The JS side holds its id; the WebRTC and recorder pipelines look it up with LookupTrack and Subscribe.

func LookupTrack

func LookupTrack(id string) *Track

LookupTrack finds a live track by the id the page sees as MediaStreamTrack.id.

func NewAudioTrack

func NewAudioTrack(l *AudioLease, dev DeviceInfo, origin string, onEnd func(*Track)) *Track

NewAudioTrack wraps an audio lease.

func NewVideoTrack

func NewVideoTrack(l *VideoLease, dev DeviceInfo, origin string, onEnd func(*Track)) *Track

NewVideoTrack wraps a lease. onEnd (optional) runs once, after the track ended for any reason.

func (*Track) AudioMode

func (t *Track) AudioMode() AudioMode

func (*Track) Clone

func (t *Track) Clone() *Track

Clone makes another track on the same source.

func (*Track) Enabled

func (t *Track) Enabled() bool

func (*Track) End

func (t *Track) End(reason string, err error)

End stops the track (idempotent); only the first reason counts.

func (*Track) EndInfo

func (t *Track) EndInfo() (reason string, err error)

EndInfo is why the track ended ("" while live).

func (*Track) Ended

func (t *Track) Ended() <-chan struct{}

Ended is closed once the track ended.

func (*Track) Reopen

func (t *Track) Reopen(c VideoConstraints) error

Reopen changes the video mode of the shared source (applyConstraints).

func (*Track) SetEnabled

func (t *Track) SetEnabled(on bool)

SetEnabled implements MediaStreamTrack.enabled: a disabled video track delivers black frames, a disabled audio track silence, at the normal rate.

func (*Track) SubscribeAudio

func (t *Track) SubscribeAudio() (<-chan *AudioChunk, func())

SubscribeAudio is SubscribeVideo for microphones.

func (*Track) SubscribeVideo

func (t *Track) SubscribeVideo() (<-chan *Frame, func())

SubscribeVideo returns a stream of this track's frames. It honours Enabled by substituting black frames. cancel detaches the consumer. The channel closes when the track ends.

func (*Track) VideoMode

func (t *Track) VideoMode() VideoMode

VideoMode and AudioMode are the real mode of the underlying source.

type VideoCaps

type VideoCaps struct {
	Modes []Mode
}

VideoCaps is what the JS constraint solver and getCapabilities() work from.

func DefaultVideoCaps

func DefaultVideoCaps() VideoCaps

DefaultVideoCaps is the capability of a source that did not say: the usual webcam ladder at 1..60 fps.

func VideoCapsOf

func VideoCapsOf(id string) VideoCaps

VideoCapsOf returns the capabilities of the camera or screen source with this id.

func (VideoCaps) Bounds

func (c VideoCaps) Bounds() (minW, maxW, minH, maxH int, minF, maxF float64)

Bounds returns the extreme width, height and frame rate over all modes (zeroes when empty).

type VideoConstraints

type VideoConstraints struct {
	Width, Height int
	FrameRate     float64
}

VideoConstraints is the already-resolved request (the JS constraint solver picks concrete numbers; a source returns the closest mode it supports and reports it in the first frame's W/H).

type VideoLease

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

VideoLease is one holder of a running (possibly shared) video source.

func AcquireVideo

func AcquireVideo(id string, c VideoConstraints, timeout time.Duration) (*VideoLease, error)

AcquireVideo starts the camera with this id, or joins the stream another consumer already runs. The device is stopped when the last lease is released. If the device is already running in another mode the existing mode is kept (a camera can only run one); use Reopen to change it.

func AcquireVideoFrom

func AcquireVideoFrom(key string, open func() (VideoSource, error), c VideoConstraints, timeout time.Duration) (*VideoLease, error)

AcquireVideoFrom is AcquireVideo for a source that is not in the global registry (the app's screen sources). Leases with the same key share one source.

func (*VideoLease) Ended

func (l *VideoLease) Ended() <-chan struct{}

Ended is closed when the device stops for good (unplugged, taken by another application, last release).

func (*VideoLease) Err

func (l *VideoLease) Err() error

Err is why the device stopped (nil for a clean stop). Valid after Ended is closed.

func (*VideoLease) Mode

func (l *VideoLease) Mode() VideoMode

Mode is the negotiated mode.

func (*VideoLease) Release

func (l *VideoLease) Release()

Release gives the lease back (idempotent).

func (*VideoLease) Reopen

func (l *VideoLease) Reopen(c VideoConstraints) error

Reopen restarts the device with new constraints; every lease and subscription keeps working.

func (*VideoLease) Subscribe

func (l *VideoLease) Subscribe() *Sub[Frame]

Subscribe returns a new frame stream. Frames are shared and must be treated as read-only.

type VideoMode

type VideoMode struct {
	W, H int
	FPS  float64
}

VideoMode is the mode a running camera or screen source really delivers.

type VideoSource

type VideoSource interface {
	Info() DeviceInfo
	// Start begins capture and returns the frame channel, which is closed after Stop or on a device error.
	Start(c VideoConstraints) (<-chan *Frame, error)
	Stop() error
	// Err reports why the channel closed (nil after a clean Stop).
	Err() error
}

VideoSource produces frames until Stop. Start may be called once per source instance; Open a new instance for another consumer.

func OpenVideo

func OpenVideo(id string) (VideoSource, error)

OpenVideo opens the camera or screen source with this id.

Directories

Path Synopsis
Package avf is the macOS capture backend (AVFoundation cameras and microphones through purego's Objective-C runtime).
Package avf is the macOS capture backend (AVFoundation cameras and microphones through purego's Objective-C runtime).
cmd
capdemo command
Command capdemo lists the capture devices of this machine and records from one of them, so the hardware paths can be checked without a browser:
Command capdemo lists the capture devices of this machine and records from one of them, so the hardware paths can be checked without a browser:
Package constraints solves MediaStreamConstraints against what the capture providers can really do.
Package constraints solves MediaStreamConstraints against what the capture providers can really do.
Package platform registers the capture providers of the current operating system.
Package platform registers the capture providers of the current operating system.
Package policy decides whether a document or frame may use camera, microphone and display capture under Permissions-Policy (the response header) and the iframe allow attribute.
Package policy decides whether a document or frame may use camera, microphone and display capture under Permissions-Policy (the response header) and the iframe allow attribute.
Package pulse is a small pure-Go client for the PulseAudio native protocol over a unix socket.
Package pulse is a small pure-Go client for the PulseAudio native protocol over a unix socket.
Package screen turns "something that can hand over its current pixels" into a capture.VideoSource: the whole browser window or one tab for getDisplayMedia.
Package screen turns "something that can hand over its current pixels" into a capture.VideoSource: the whole browser window or one tab for getDisplayMedia.
Package synthetic provides deterministic fake devices for tests, CI and demos: a test-pattern camera, a tone or noise microphone and a placeholder speaker.
Package synthetic provides deterministic fake devices for tests, CI and demos: a test-pattern camera, a tone or noise microphone and a placeholder speaker.
Package v4l2 is a pure-Go (no cgo, no libv4l) Video4Linux2 capture provider: it enumerates /dev/video*, lists formats, sizes and frame intervals with the VIDIOC_ENUM_* ioctls, and streams with memory-mapped buffers.
Package v4l2 is a pure-Go (no cgo, no libv4l) Video4Linux2 capture provider: it enumerates /dev/video*, lists formats, sizes and frame intervals with the VIDIOC_ENUM_* ioctls, and streams with memory-mapped buffers.
Package wincap is the Windows capture backend (Media Foundation cameras, WASAPI microphones).
Package wincap is the Windows capture backend (Media Foundation cameras, WASAPI microphones).

Jump to

Keyboard shortcuts

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