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
- Variables
- func Convert(dst *Frame, f PixelFormat, src []byte, stride int) error
- func ConvertSize(f PixelFormat, w, h, stride int) int
- func DecodeMJPEG(dst *Frame, data []byte) error
- func FromRGBA(dst *Frame, src *image.RGBA)
- func LiveTracks() int
- func RGBToU(r, g, b int) uint8
- func RGBToV(r, g, b int) uint8
- func RGBToY(r, g, b int) uint8
- func Register(p Provider)
- func Scale(dst, src *Frame)
- func Unregister(name string)
- func YUVToRGB(y, u, v uint8) (r, g, b uint8)
- type AudioCaps
- type AudioChunk
- type AudioConstraints
- type AudioLease
- type AudioMode
- type AudioSource
- type CapsProvider
- type DeviceInfo
- type Frame
- type Kind
- type Mode
- type Moder
- type PixelFormat
- type Provider
- type Sub
- type Track
- func (t *Track) AudioMode() AudioMode
- func (t *Track) Clone() *Track
- func (t *Track) Enabled() bool
- func (t *Track) End(reason string, err error)
- func (t *Track) EndInfo() (reason string, err error)
- func (t *Track) Ended() <-chan struct{}
- func (t *Track) Reopen(c VideoConstraints) error
- func (t *Track) SetEnabled(on bool)
- func (t *Track) SubscribeAudio() (<-chan *AudioChunk, func())
- func (t *Track) SubscribeVideo() (<-chan *Frame, func())
- func (t *Track) VideoMode() VideoMode
- type VideoCaps
- type VideoConstraints
- type VideoLease
- type VideoMode
- type VideoSource
Constants ¶
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.
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 ¶
var ErrInUse = errors.New("capture: device in use")
ErrInUse is returned when another application holds the device exclusively.
var ErrNotFound = errors.New("capture: device not found")
ErrNotFound is returned when a device id is unknown or the device has disappeared.
var ErrTimeout = errors.New("capture: timeout starting source")
ErrTimeout is returned when a device was opened but produced no data in time.
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 ¶
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 ¶
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 Register ¶
func Register(p Provider)
Register adds a provider (call from init()). Registering the same name twice replaces it.
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 ¶
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 ¶
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 ¶
FromImage converts any image.Image (slow path, used by tests and one-off captures).
func NewFrame ¶
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.
type Mode ¶
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.
type Moder ¶
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.
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 ¶
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) Reopen ¶
func (t *Track) Reopen(c VideoConstraints) error
Reopen changes the video mode of the shared source (applyConstraints).
func (*Track) SetEnabled ¶
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 ¶
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.
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 ¶
VideoCapsOf returns the capabilities of the camera or screen source with this id.
type VideoConstraints ¶
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) 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 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). |