cameraav

package module
v0.0.0-...-bce3f85 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 19 Imported by: ? 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.

README

cameraav

Live camera frames for goav, built with CGO_ENABLED=0 on macOS, Linux and Windows (amd64 and arm64). macOS uses AVFoundation through purego; Linux uses V4L2 ioctls and mmap; Windows uses Media Foundation COM. No FFmpeg executable or C compiler is required. OS drivers, frameworks, and camera access still apply. The macOS adapter includes two small Go-assembler C-ABI trampolines (amd64/arm64) for retain/exchange/signal callback handoff. They never enter Go or process pixels. This narrowly documented exception to the repository assembly guard avoids purego reflective callback allocations; all pixel conversion remains Go.

camera := goav.From(cameraav.New(cameraav.Config{
    Width: 1280, Height: 720, FPS: 30,
}))
output := camera.Video().Encode(codec.VP8()).To(goav.ToURI("camera.webm"))

Use cameraav.Devices(ctx) for opaque device IDs and supply one as Config.Device. An empty ID selects the first/default camera. The default mode is 640x480 at 30 fps. Dimensions and raw formats are exact. Integer frame rates allow native interval quantization smaller than one 100 ns UVC tick; the original native interval and timestamps are preserved. Distinct rates such as 29.97 fps never match a 30 fps request. Unsupported modes fail explicitly. The provider opens at Build time and begins capture when its source starts. Describe and Explain do not enumerate devices, prompt for access, or activate the camera.

Register runconfig.WithScheme("camera", cameraav.Scheme()) for URL inputs. The CLI registers it automatically:

goav cameras --json
goav describe 'uri "camera://default?width=1280&height=720&fps=30" ! video ! encode vp8 ! file camera.webm'
goav run 'uri "camera://default" ! video ! encode vp8 ! uri "whips://media.example/live"'

Select an ID with a percent-encoded device query parameter. Other parameters are width, height, fps, and queue. Unknown or repeated options fail. The queue defaults to two frames and permits 1–16; the total Go pixel storage is bounded to 128 MiB, including two working slots.

Ownership and allocation contract

The source produces planar yuv420p, copying active pixels out of native buffers before lending the frame to the pipeline. Native row padding is not exposed. Each capture owns a fixed set of frame headers and pixel buffers, allocated during OpenSource. Frame headers are borrowed during Emit; use the normal goav Ref/Retain rules to hold media longer.

A full delivery queue drops its oldest frame. If downstream references keep all preallocated slots occupied, the oldest queued frame is evicted first. If no queued frame can be reclaimed, the incoming frame is dropped. Retaining more than two frames reduces effective queue capacity. Buffers are never expanded or overwritten while retained. DropReporter exposes queue/pool sheds; OS/device-internal drops are not necessarily included. The macOS native bridge retains at most one pending sample plus the sample being copied. V4L2 has a bounded driver buffer ring. Media Foundation has one requested read in flight.

Allocation tests require zero steady-state Go allocations for raw pixel conversion and queue handoff, macOS native callback handoff, and macOS native sample-to-Go copying. The fixed Go pixel storage does not depend on sync.Pool or GC. OS allocation and driver buffering are outside that Go-heap contract. Setup, permission prompts, explicit consumer Ref calls, and errors may allocate. The capture goroutine uses fixed native argument storage; concurrent cold calls may use pools, and purego itself has internal pooling. Allocation assertions run without the race detector, whose sync.Pool behavior intentionally differs.

Valid native capture timestamps are rebased at the first delivered frame; gaps remain visible when frames drop. Linux uses monotonic arrival time when a driver marks timestamps unknown/COPY or supplies zero. Native frames older than a previously delivered arrival timestamp are dropped until capture catches up; a regression in the native monotonic clock fails explicitly. Cancellation stops native reads/callbacks; Close waits for completion before releasing native state. Windows bounds the asynchronous flush-notification wait to two seconds and retains timeout errors. A device fault or unexpected format change fails the source. Native startup/shutdown calls are subject to the operating system's own completion behavior.

Platform access and initial format support

  • macOS: permission is explicit. An app needs NSCameraUsageDescription in its Info.plist. RequestAccess(ctx) refuses an unprepared executable instead of risking the OS terminating it. The CLI packaging helper below supplies this metadata. Capture requests AVFoundation video-range NV12.
  • Linux: the user needs read/write access to the selected /dev/video* node. Device paths are validated as V4L2 character devices before opening them for capture. Native mmap storage has its own 128 MiB total cap. This backend supports single-planar streaming capture in NV12 or YUYV, progressive frames, and an integer frame rate with the interval quantization described above. Multiplanar-only, MJPEG-only, and libcamera/PipeWire-only devices are refused.
  • Windows: enable camera access for desktop applications in privacy settings. Media Foundation must be installed (including the Media Feature Pack on Windows N editions). This initial backend selects native NV12 or YUY2 modes, avoiding a hidden codec/conversion graph. Explicit interlaced or non-video-range modes are refused. When a Windows driver omits range metadata, samples retain the native YUV levels; this adapter does not invent color metadata. Unsupported modes are explicit errors.

Capture is video-only. Fractional frame-rate selection and native compressed camera formats are not yet part of this API.

For development on macOS, run from cmd/goav with the execution helper so the permission request has the required app metadata:

cd cmd/goav
CGO_ENABLED=0 GOEXPERIMENT=simd go run -exec ../../scripts/camera/go-run-macos.sh . cameras --request-access
CGO_ENABLED=0 GOEXPERIMENT=simd go run -exec ../../scripts/camera/go-run-macos.sh . run 'uri "camera://default" ! video ! encode vp8 ! file camera.webm'

Press Ctrl-C to stop and finalize the video. The helper reuses a cached, ad-hoc-signed app for the same executable and metadata; macOS may ask for permission again after a rebuild. Plain go run cannot supply this bundle metadata.

Alternatively, build the CLI with cgo disabled, then package it from the repository root on macOS:

scripts/camera/package-macos.sh /path/to/goav /new/path/GoAV.app
/new/path/GoAV.app/Contents/MacOS/goav cameras --request-access

The helper never overwrites an existing app. It creates a local ad-hoc-signed bundle; distribution signing/notarization is the application's responsibility.

Validation

Normal tests never activate a physical camera. They cover ownership after Ref, bounded retention, cleanup, URL planning, native ABI handoff, real synthetic CoreVideo/CoreMedia and Media Foundation samples (including padded native pitch), V4L2 dequeue/copy/requeue behavior, and allocation counts. The CI matrix runs the module on all three operating systems. Set GOAV_CAMERA_TEST_DEVICE explicitly for an opt-in capture smoke test; it checks frames and timestamps without saving or transmitting images. On Linux CI, a Vivid virtual device is used when present.

Documentation

Overview

Package cameraav captures camera video without cgo. It uses AVFoundation on macOS, V4L2 on Linux, and Media Foundation on Windows. Operating-system device drivers and camera permission are still required. Import this optional module to use camera inputs without adding native dependencies to goav itself.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrUnsupported   = errors.New("cameraav: unsupported platform or camera format")
	ErrPermission    = errors.New("cameraav: camera permission required")
	ErrNoDevice      = errors.New("cameraav: camera not found")
	ErrFormatChanged = errors.New("cameraav: camera changed the negotiated format")
)

Functions

func RequestAccess

func RequestAccess(ctx context.Context) error

RequestAccess requests camera permission on macOS, if needed. The application's Info.plist must contain NSCameraUsageDescription. On Linux and Windows access is managed by device permissions/privacy settings; this method cannot grant it.

func Scheme

func Scheme() provider.InputScheme

Scheme returns a provider.InputScheme that binds camera://default?width=1280&height=720&fps=30. Select a specific opaque device ID with the percent-encoded device query parameter. Binding is pure, so Describe and Explain neither enumerate nor activate cameras.

Types

type Config

type Config struct {
	Device             string
	Width, Height, FPS int
	Queue              int
	// contains filtered or unexported fields
}

Config selects exact dimensions and an integer frame rate, allowing native interval quantization smaller than 100 ns. Zero values select the default device, 640x480 at 30 frames/second, and a two-frame queue. Device is the opaque ID returned by Devices, not a display name. Unsupported modes fail explicitly. The queue drops its oldest frame when full; device callbacks never wait for the pipeline. Capture owns Queue+2 fixed slots; downstream retention of more than two frames reduces queue capacity and can cause incoming drops. Timestamps retain real capture gaps when frames are dropped.

type Device

type Device struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

Device identifies a native video capture device. IDs are platform-specific.

func Devices

func Devices(ctx context.Context) ([]Device, error)

Devices enumerates cameras without starting capture or requesting permission.

type Input

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

Input is a reusable provider.Source declaration. New performs no native I/O.

func New

func New(config Config) *Input
Example
package main

import (
	"github.com/thesyncim/goav"
	"github.com/thesyncim/goav/cameraav"
	"github.com/thesyncim/goav/codec"
)

func main() {
	camera := goav.From(cameraav.New(cameraav.Config{Width: 1280, Height: 720, FPS: 30}))
	output := camera.Video().Encode(codec.VP8()).To(goav.ToURI("camera.webm"))
	_ = output // Pass to a configured runtime's Build or Run.
}

func (*Input) Detail

func (*Input) Detail() string

func (*Input) Name

func (*Input) Name() string

func (*Input) OpenSource

func (in *Input) OpenSource(ctx context.Context) (pipeline.Source, []av.Stream, error)

func (*Input) SourceShape

func (in *Input) SourceShape() shape.Spec

Jump to

Keyboard shortcuts

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