capture

package
v0.75.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 7 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 is the public microphone / system-audio capture layer of the SpeechKit framework: backend registry (RegisterBackend, Open), capture Session contract, device enumeration (ListCaptureDevices, ListOutputDevices), and the pooled PCM frame buffers (FramePool).

Backends today: one malgo (miniaudio) capture session shared by the Windows WASAPI backend (BackendWindowsWASAPIMalgo) and the macOS CoreAudio backend (BackendDarwinCoreAudioMalgo), compiled in behind the "(windows || darwin) && cgo" build tags with a small per-platform seam. System loopback (InputSourceSystemLoopback) is Windows-only until the macOS process-tap slice lands; the CoreAudio backend reports ErrUnsupportedSource for it at construction. On every other build (other platforms, or CGO_ENABLED=0) Open and NewCapturer return an error wrapping ErrBackendUnavailable. RegisterBackend is the extension point for additional platform backends.

Captured PCM uses the canonical SpeechKit format (16 kHz, 16-bit signed, mono) declared in pkg/speechkit/audio; a Session structurally satisfies pkg/speechkit's AudioRecorder (and, via SetPooledPCMHandler, its PooledPCMRecorder optimisation).

Playback (TTS/voice-agent output) is intentionally not part of this package; the reference app keeps it in app/internal/audio.

Stability: Beta — API-checked; may change with a changelog callout.

Index

Constants

View Source
const DefaultFrameCapacity = 4096

DefaultFrameCapacity is the per-buffer capacity returned by the package-level frame pool. It is sized for the worst-case malgo callback chunk we have observed in production (16 kHz mono S16 at 32 ms FrameSizeMs → 1024 bytes; doubled for a generous safety margin).

Variables

View Source
var (
	// ErrUnsupportedBackend means the requested Backend has no factory.
	ErrUnsupportedBackend = errors.New("unsupported audio backend")
	// ErrBackendUnavailable means this build has no native backend at all
	// (no cgo, or an unsupported platform).
	ErrBackendUnavailable = errors.New("audio backend unavailable in this build")
	// ErrUnsupportedSource means the backend cannot record the InputSource.
	ErrUnsupportedSource = errors.New("unsupported audio input source")
	// ErrOutputDeviceUnavailable means the loopback output device could not
	// be found or opened.
	ErrOutputDeviceUnavailable = errors.New("audio output device unavailable")
)

Sentinel errors returned by Open, ListCaptureDevices and ListOutputDevices; callers match them with errors.Is.

Functions

func Get

func Get() []byte

Get returns a recyclable buffer from the default pool.

func Put

func Put(buf []byte)

Put returns a buffer to the default pool.

func RegisterBackend

func RegisterBackend(name Backend, factory Factory) error

RegisterBackend makes factory available under name. It rejects an empty or BackendAuto name, a nil factory, and a name that is already registered, all with ErrUnsupportedBackend. Native backends register themselves at init; hosts register their own to replace or add one.

Types

type Backend

type Backend string

Backend names a registered capture implementation. Backends register themselves with RegisterBackend; Open resolves BackendAuto to the platform default.

const (
	// BackendAuto selects the platform default backend at Open time.
	BackendAuto Backend = "auto"
	// BackendWindowsWASAPIMalgo is the Windows capture backend: a malgo
	// (miniaudio) session on WASAPI, supporting microphone and loopback.
	BackendWindowsWASAPIMalgo Backend = "windows-wasapi-malgo"
	// BackendWindowsWASAPINative is reserved for a direct WASAPI backend;
	// no factory is registered for it in this build.
	BackendWindowsWASAPINative Backend = "windows-wasapi-native"
	// BackendDarwinCoreAudioMalgo is the macOS capture backend: the same
	// malgo session as BackendWindowsWASAPIMalgo, opened on CoreAudio.
	// System loopback is not available on it yet; it needs a CoreAudio
	// process tap.
	BackendDarwinCoreAudioMalgo Backend = "darwin-coreaudio-malgo"
)

Built-in backend names. Which of them a binary can actually open depends on the target and on cgo: builds without a native backend answer every Open with ErrBackendUnavailable.

type Capturer

type Capturer = Session

Capturer is kept as an alias while the app migrates to the session terminology.

func NewCapturer

func NewCapturer() (Capturer, error)

NewCapturer opens a session with the default Config.

func NewCapturerWithConfig

func NewCapturerWithConfig(cfg Config) (Capturer, error)

NewCapturerWithConfig is Open under the older capturer name.

type Config

type Config struct {
	Backend     Backend
	InputSource InputSource
	DeviceID    string
	// DeviceName is the human-readable name of the capture device. USB/UAC
	// devices can re-enumerate with a new WASAPI endpoint ID after a replug
	// or firmware update; when DeviceID no longer matches, the capturer
	// falls back to matching by this name.
	DeviceName     string
	OutputDeviceID string
	SampleRate     int
	Channels       int
	FrameSizeMs    int
	LatencyHint    string
	// CaptureThreadPriority selects the OS priority of the backend's
	// audio worker thread: "realtime" (default, TIME_CRITICAL — safe
	// because the callback only memcpys and enqueues) or "highest"
	// (malgo's own default). Ignored by backends without native thread
	// control.
	CaptureThreadPriority string
	// KeepDeviceWarm keeps the capture device initialised between
	// recordings and opens it ahead of the first one, so Start only has to
	// start a stream that already exists. Opening a WASAPI capture device
	// was measured at about 800 ms per recording (2026-09-05), which is
	// the delay between the hotkey and the first captured word. An
	// initialised device that is not started holds no stream and uses no
	// CPU. Ignored by backends that open nothing.
	KeepDeviceWarm bool
	// OnDeviceRebound, when set, is called after DeviceID was not found but
	// the device was recovered via DeviceName (USB/UAC re-enumeration). The
	// host can persist newID so the next start matches by ID again. It is
	// invoked from the backend's device-resolution path, so it must return
	// promptly and must not call back into the session.
	OnDeviceRebound func(oldID, newID, name string)
	// FramePool is the buffer pool the session leases per-frame buffers
	// from for [Session.SetPooledPCMHandler] and its internal frame
	// dispatch. nil selects [DefaultFramePool], which is shared by every
	// session in the process; hosts that run several capture sessions
	// with different frame sizes, or that want isolated pool statistics,
	// pass their own.
	FramePool *FramePool
	// Logger receives the backend's diagnostics. Nil falls back to
	// slog.Default() at log time.
	Logger *slog.Logger
}

Config selects the backend, input source, device and framing of a capture session. Zero fields take the defaults described per field; Open fills them in before handing the config to the backend.

type DeviceInfo

type DeviceInfo struct {
	ID        string `json:"deviceId"`
	Name      string `json:"label"`
	IsDefault bool   `json:"isDefault"`
}

DeviceInfo describes a capture device that can be presented to the user.

func ListCaptureDevices

func ListCaptureDevices(cfg Config) ([]DeviceInfo, error)

ListCaptureDevices returns the available microphone devices for the selected backend.

func ListOutputDevices

func ListOutputDevices(cfg Config) ([]DeviceInfo, error)

ListOutputDevices returns the available speaker devices for the selected backend.

type Event

type Event struct {
	Type    EventType
	Backend Backend
	Message string
	Err     error
	// Requested is set on an EventStopped that the session's own Stop caused.
	// Only a stop nobody asked for — unplugged device, exclusive-mode grab,
	// format change — is an interruption a host should report.
	Requested bool
}

Event is one lifecycle or health notification from a Session.

type EventType

type EventType string

EventType classifies the lifecycle and health events a Session emits on Session.Events.

const (
	// EventStarted is emitted once the device stream delivers audio.
	EventStarted EventType = "started"
	// EventStopped is emitted when the device stream ends; see
	// [Event.Requested] to tell a Stop from an interruption.
	EventStopped EventType = "stopped"
	// EventWarning carries a non-fatal backend diagnostic in Message or Err.
	EventWarning EventType = "warning"
	// EventError carries a backend failure in Err; the session may be unusable.
	EventError EventType = "error"
	// EventOverrun signals that the frame dispatcher dropped captured
	// frames because the consumer (level/VAD handlers) could not keep
	// up. The authoritative full-capture buffer is unaffected — only
	// live level/segmentation frames were lost.
	EventOverrun EventType = "overrun"
	// EventStalled signals that the capture device stopped delivering
	// frames while it claims to be running (driver stall, device
	// starvation). Emitted once per stall episode.
	EventStalled EventType = "stalled"
)

Event types. Started/Stopped bracket the device stream; Warning and Error carry a backend diagnostic; Overrun and Stalled are health signals.

type Factory

type Factory func(Config) (Session, error)

Factory constructs a Session for a normalised Config; backends register one per Backend name via RegisterBackend.

type FramePool

type FramePool struct {
	// Capacity is the cap() of fresh buffers returned by Get. Zero
	// falls back to DefaultFrameCapacity at first use.
	Capacity int
	// contains filtered or unexported fields
}

FramePool returns recyclable byte slices for short-lived PCM frame buffers. The hot path it addresses is the malgo capture callback (capture_device_malgo_cgo.go) which used to allocate a fresh slice per callback (~33×/sec per active capture, ~3300×/sec at 100 concurrent server sessions).

Contract

  • Get returns a []byte with len(buf) == 0 and cap(buf) >= pool.Capacity (DefaultFrameCapacity if unset). Callers append to it; reslicing past cap will reallocate the way the language normally would.
  • Put returns the buffer to the pool. After Put the caller MUST NOT read from or write to the slice — another goroutine may pick it up immediately.
  • Put is idempotent on the nil slice (no-op).
  • Buffers whose grown capacity exceeds 4× the configured Capacity are dropped on Put rather than retained, so pathological growth does not pin large allocations in the pool.

Concurrency

FramePool wraps sync.Pool — safe for concurrent Get / Put from many goroutines. The pool may discard entries at any GC cycle; callers MUST treat Get as may-allocate-fresh.

Observability

HitRatio() returns a coarse hit/miss ratio over the pool's lifetime. It is intended for occasional sanity checks and metric exports; the underlying counters use atomic adds so HitRatio is safe to call concurrently with Get and Put.

var DefaultFramePool FramePool

DefaultFramePool is the process-wide pool a session uses when Config.FramePool is nil. Hosts that need isolation (several capture sessions with different frame sizes, per-session statistics, tests) construct their own FramePool and pass it in the session Config.

func (*FramePool) Get

func (p *FramePool) Get() []byte

Get returns a recyclable buffer with len 0 and capacity at least p.Capacity (or DefaultFrameCapacity when unset).

func (*FramePool) HitRatio

func (p *FramePool) HitRatio() float64

HitRatio returns the fraction of Get calls served from the cache (1.0 = always hit, 0.0 = always allocated fresh). Returns 0 when no operations have happened yet. The return is a snapshot — the counters may advance immediately after the call.

Concretely: HitRatio = (gets - misses) / gets, where misses is incremented inside sync.Pool.New (i.e. every fresh allocation counts as a miss).

func (*FramePool) Put

func (p *FramePool) Put(buf []byte)

Put returns the buffer to the pool. nil buffers are silently dropped. Buffers whose capacity exceeds 4× the configured Capacity are dropped to prevent unbounded growth from pinning the pool.

func (*FramePool) Stats

func (p *FramePool) Stats() Stats

Stats returns the lifetime counters. Hits can be derived as stats.Gets - stats.Misses.

type InputSource

type InputSource string

InputSource selects what a session records. The zero value means InputSourceMicrophone.

const (
	// InputSourceMicrophone records the selected (or default) capture device.
	InputSourceMicrophone InputSource = "microphone"
	// InputSourceSystemLoopback records what the selected output device
	// plays (WASAPI loopback); unavailable on macOS in this build.
	InputSourceSystemLoopback InputSource = "system_loopback"
	// InputSourceMicAndSystem is the mixed source Meeting Mode asks for;
	// no backend serves it yet, so Open returns ErrUnsupportedSource.
	InputSourceMicAndSystem InputSource = "mic_and_system"
)

Input sources. A backend that cannot serve a source rejects Open with ErrUnsupportedSource instead of silently recording something else.

type PooledPCMHandler

type PooledPCMHandler = func(buf []byte, release func())

PooledPCMHandler receives one captured PCM frame with explicit buffer-ownership semantics. The release closure MUST be invoked exactly once when the handler is done with buf — either before returning, or asynchronously once any retained reference is released. The buffer MUST NOT be read or written after release.

See FramePool for the underlying lifecycle. The optimisation only matters for sustained capture (~33 callbacks/sec per session); short-lived recording paths can stay on the legacy SetPCMHandler API without ceremony.

Declared as a type alias (not a defined type) so implementations of Session structurally satisfy interfaces declared outside this package (e.g. pkg/speechkit's PooledPCMRecorder) without importing this package.

type Session

type Session interface {
	Start() error
	Stop() ([]byte, error)
	IsRunning() bool
	Events() <-chan Event
	SetLevelHandler(func(float64))
	SetPCMHandler(func([]byte))
	// SetPooledPCMHandler installs the pool-aware variant of the PCM
	// callback. When set (non-nil), the capture backend leases the
	// per-frame buffer from the session's [FramePool] ([Config.FramePool],
	// [DefaultFramePool] when unset) instead of allocating fresh, and
	// invokes the handler with a release closure. The handler MUST call release exactly once
	// before returning OR before retaining any reference to the
	// slice. Forgetting to release leaks one pool slot per frame but
	// does not corrupt data.
	//
	// When both SetPCMHandler and SetPooledPCMHandler are set, the
	// pool-aware variant wins — the legacy handler is not invoked
	// for that frame, so callers that adopt the pooled API should
	// also unset the legacy one to avoid surprise.
	//
	// Backends not yet wired to honour the pool MAY no-op this
	// setter; the legacy SetPCMHandler path remains the canonical
	// contract for all existing callers.
	SetPooledPCMHandler(PooledPCMHandler)
	Close() error
}

Session records microphone PCM and exposes both level and live-audio callbacks.

func Open

func Open(cfg Config) (Session, error)

Open normalises cfg (defaults for backend, source, 16 kHz mono, 32 ms frames, realtime thread priority) and constructs a session from the registered backend. It returns ErrBackendUnavailable when the build has no default backend, ErrUnsupportedBackend for an unknown name, and wraps any other backend failure.

type Stats

type Stats struct {
	Gets   uint64
	Misses uint64
}

Stats are the raw lifetime counters. Useful for OTel meter callbacks that prefer integer reports over a derived ratio.

Jump to

Keyboard shortcuts

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