duplexaudio

package
v0.6.20 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT 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.

Documentation

Rendered for darwin/amd64

Overview

Package duplexaudio provides lock-free full-duplex float32 audio streaming, instant barge-in flush-to-silence, hardware VoiceProcessingIO AEC/AGC integration, and x/workgroup real-time thread pinning on macOS without cgo.

The package is built around three pieces:

  • RingBuffer: a lock-free, zero-allocation single-producer/single-consumer float32 ring buffer with an atomic RingBuffer.Flush watermark for sub-microsecond barge-in cancellation.
  • Engine: a full-duplex audio engine supporting 16 kHz, 24 kHz, and 48 kHz float32 streams with Engine.WritePlayback, Engine.ReadCapture, and Engine.BargeIn. It supports live macOS AudioUnit hardware (kAudioUnitSubType_VoiceProcessingIO or HAL output) as well as a deterministic loopback mode pinned via workgroup.RunPinned for headless tests and benchmarks.
  • Probe: a non-blocking host capability probe that inspects CoreAudio devices, microphone TCC authorization status, VoiceProcessingIO and AVAudioIONode availability, CATapDescription system audio tap support, and os_workgroup availability without triggering macOS permission prompts.

Zero values of RingBuffer and Engine are not usable; construct them with NewRingBuffer and NewEngine.

Basic usage:

eng, err := duplexaudio.NewEngine(duplexaudio.Config{
	SampleRate:      24000,
	Channels:        1,
	VoiceProcessing: true,
	Workgroup:       true,
	Mode:            duplexaudio.ModeLoopback,
	LoopbackEcho:    true,
})
if err != nil {
	log.Fatal(err)
}
defer eng.Close()

if err := eng.Start(ctx); err != nil {
	log.Fatal(err)
}
eng.WritePlayback(samples)
latency := eng.BargeIn()
Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/duplexaudio"
)

func main() {
	eng, err := duplexaudio.NewEngine(duplexaudio.Config{
		SampleRate:   24000,
		Channels:     1,
		FrameSize:    128,
		Mode:         duplexaudio.ModeLoopback,
		LoopbackEcho: true,
	})
	if err != nil {
		panic(err)
	}
	defer eng.Close()

	// Write a 4-sample playback burst and render one slice.
	eng.WritePlayback([]float32{0.25, 0.5, -0.25, -0.5})
	out := make([]float32, 4)
	eng.RenderSlice(out, nil)

	capBuf := make([]float32, 4)
	n := eng.ReadCapture(capBuf)
	fmt.Printf("captured=%d first=%.2f\n", n, capBuf[0])

	// Queue more audio, then trigger instant barge-in flush.
	eng.WritePlayback([]float32{1.0, 1.0, 1.0, 1.0})
	_ = eng.BargeIn()
	eng.RenderSlice(out, nil)
	fmt.Printf("after barge-in: %.1f %.1f\n", out[0], out[1])
}
Output:
captured=4 first=0.25
after barge-in: 0.0 0.0

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidConfig is returned when Config contains unsupported parameters.
	ErrInvalidConfig = errors.New("duplexaudio: invalid config")
	// ErrClosed is returned when an operation is attempted on a closed Engine.
	ErrClosed = errors.New("duplexaudio: engine closed")
	// ErrAlreadyStarted is returned when Start is called on a running Engine.
	ErrAlreadyStarted = errors.New("duplexaudio: engine already started")
	// ErrPermissionDenied is returned in ModeLive when microphone TCC
	// authorization is not granted.
	ErrPermissionDenied = errors.New("duplexaudio: microphone permission not authorized")
	// ErrNoDevice is returned in ModeLive when no audio device is available.
	ErrNoDevice = errors.New("duplexaudio: no audio device available")
)

Functions

func EnableAVAudioVoiceProcessing

func EnableAVAudioVoiceProcessing(node avfaudio.AVAudioIONode, enabled bool) error

EnableAVAudioVoiceProcessing enables or disables hardware voice processing (AEC/AGC) on an AVAudioIONode via AVAudioIONode.SetVoiceProcessingEnabledError.

func ProbeSystemTap

func ProbeSystemTap() (available bool, tapUUID string, activeTaps int)

ProbeSystemTap probes CoreAudio CATapDescription support (macOS 14.2+) and queries the current number of active system audio taps without creating a live tap or triggering a Screen & System Audio Recording TCC prompt.

Types

type Config

type Config struct {
	// SampleRate in Hz. Supported values are 16000, 24000, and 48000.
	// Defaults to 24000.
	SampleRate int
	// Channels per frame (1 for mono, 2 for stereo). Defaults to 1.
	Channels int
	// FrameSize is the number of frames processed per render slice.
	// Defaults to 256 (~10.67 ms at 24 kHz).
	FrameSize int
	// RingCapacity is the sample capacity of each lock-free ring buffer.
	// Defaults to 8 * FrameSize * Channels.
	RingCapacity int
	// VoiceProcessing enables hardware AEC/AGC via
	// kAudioUnitSubType_VoiceProcessingIO in live mode.
	VoiceProcessing bool
	// AGC enables automatic gain control when VoiceProcessing is true.
	AGC bool
	// Workgroup pins the loopback/audio worker thread to a macOS os_workgroup
	// at UserInteractive QoS using x/workgroup.
	Workgroup bool
	// Mode selects ModeAuto, ModeLoopback, or ModeLive.
	Mode Mode
	// LoopbackEcho copies rendered playback slices into the capture ring in
	// ModeLoopback so callers can verify full-duplex round-trip audio and
	// barge-in silence end-to-end.
	LoopbackEcho bool
}

Config configures a full-duplex Engine.

type DeviceInfo

type DeviceInfo struct {
	ID              uint32
	Name            string
	SampleRate      float64
	InputChannels   int
	OutputChannels  int
	IsDefaultInput  bool
	IsDefaultOutput bool
}

DeviceInfo describes a CoreAudio hardware or virtual audio device.

type Engine

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

Engine manages lock-free full-duplex float32 playback and capture streams with instant barge-in flush-to-silence.

The zero value is not usable; create one with NewEngine.

func NewEngine

func NewEngine(cfg Config) (*Engine, error)

NewEngine creates a full-duplex audio Engine with the given configuration.

func (*Engine) BargeIn

func (e *Engine) BargeIn() time.Duration

BargeIn immediately flushes all queued playback audio to silence.

When the engine is running, BargeIn waits (up to 50 ms) for the active render loop or AudioUnit callback to observe the flush and emit a silent slice, returning the measured flush-to-silence latency. When the engine is stopped, BargeIn returns the immediate flush latency.

func (*Engine) CaptureRing

func (e *Engine) CaptureRing() *RingBuffer

CaptureRing returns the underlying lock-free capture ring buffer.

func (*Engine) Close

func (e *Engine) Close() error

Close stops audio processing and marks the engine as closed. Close is idempotent.

func (*Engine) Mode

func (e *Engine) Mode() Mode

Mode returns the active operating mode (after Engine.Start) or the configured mode before Start.

func (*Engine) PlaybackRing

func (e *Engine) PlaybackRing() *RingBuffer

PlaybackRing returns the underlying lock-free playback ring buffer.

func (*Engine) ReadCapture

func (e *Engine) ReadCapture(dst []float32) int

ReadCapture drains captured float32 samples into dst and returns the number of samples read. Remaining elements of dst are zero-filled.

func (*Engine) RenderSlice

func (e *Engine) RenderSlice(playbackOut, captureIn []float32)

RenderSlice executes one synchronous full-duplex audio slice: it drains playback samples into playbackOut (zero-filling on underrun or barge-in), acknowledges any pending Engine.BargeIn, and writes captureIn (or playbackOut when Config.LoopbackEcho is enabled and captureIn is nil) into the capture ring buffer.

RenderSlice is safe to call directly in deterministic offline tests without calling Engine.Start.

func (*Engine) Start

func (e *Engine) Start(ctx context.Context) error

Start begins audio processing. In ModeAuto, Start probes the host and chooses live hardware only when audio devices exist and microphone permission is already authorized; otherwise it starts in ModeLoopback.

func (*Engine) Stats

func (e *Engine) Stats() EngineStats

Stats returns a snapshot of the engine's counters and barge-in latencies.

func (*Engine) Stop

func (e *Engine) Stop() error

Stop halts audio processing without closing the engine. Stop is idempotent.

func (*Engine) WritePlayback

func (e *Engine) WritePlayback(samples []float32) int

WritePlayback enqueues float32 playback samples into the lock-free playback ring buffer and returns the number of samples written.

type EngineStats

type EngineStats struct {
	Mode                  Mode
	SampleRate            int
	Channels              int
	FrameSize             int
	VoiceProcessingActive bool
	WorkgroupActive       bool
	RenderCallbacks       uint64
	PlaybackUnderruns     uint64
	PlaybackOverruns      uint64
	CaptureUnderruns      uint64
	CaptureOverruns       uint64
	BargeInCount          uint64
	LastBargeInLatency    time.Duration
	MaxBargeInLatency     time.Duration
}

EngineStats is a point-in-time snapshot of Engine counters and latency.

type HostCapabilities

type HostCapabilities struct {
	Devices                         []DeviceInfo
	DefaultInputID                  uint32
	DefaultOutputID                 uint32
	HasInputDevice                  bool
	HasOutputDevice                 bool
	MicPermission                   PermissionStatus
	VoiceProcessingIOAvailable      bool
	AVAudioVoiceProcessingAvailable bool
	SystemTapAvailable              bool
	ActiveSystemTaps                int
	DeviceWorkgroupAvailable        bool
	WorkgroupAvailable              bool
	MaxParallelThreads              int
}

HostCapabilities summarizes the audio hardware, permissions, and macOS subsystem features available on the current host.

func Probe

func Probe() HostCapabilities

Probe inspects host CoreAudio devices, microphone TCC status, VoiceProcessingIO availability, CATapDescription support, and x/workgroup support. Probe is strictly read-only and never blocks on TCC prompts.

Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/duplexaudio"
)

func main() {
	caps := duplexaudio.Probe()
	fmt.Printf("voice_processing_io=%v workgroup=%v\n",
		caps.VoiceProcessingIOAvailable, caps.WorkgroupAvailable)
}
Output:
voice_processing_io=true workgroup=true

type Mode

type Mode int

Mode selects how Engine drives audio I/O.

const (
	// ModeAuto probes the host and uses ModeLive if audio devices and
	// microphone authorization are available; otherwise it falls back to
	// ModeLoopback without triggering TCC prompts.
	ModeAuto Mode = iota
	// ModeLoopback runs a deterministic in-process full-duplex render loop
	// (optionally pinned with x/workgroup) without touching hardware or TCC.
	ModeLoopback
	// ModeLive opens a macOS AudioUnit (VoiceProcessingIO or HALOutput).
	// It refuses to start if Probe reports missing devices or unauthorized mic.
	ModeLive
)

func (Mode) String

func (m Mode) String() string

String returns a human-readable name for m.

type PermissionStatus

type PermissionStatus int

PermissionStatus reports the macOS TCC microphone authorization state without triggering an interactive permission prompt.

const (
	PermissionNotDetermined PermissionStatus = iota
	PermissionRestricted
	PermissionDenied
	PermissionAuthorized
)

func (PermissionStatus) String

func (s PermissionStatus) String() string

String returns a human-readable name for s.

type RingBuffer

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

RingBuffer is a lock-free single-producer, single-consumer ring buffer of float32 audio samples.

One producer goroutine calls RingBuffer.Write while one consumer (typically a Core Audio render callback or real-time worker) calls RingBuffer.Read. Any goroutine may call RingBuffer.Flush to discard queued samples for instant barge-in silence; the consumer observes the flush watermark on its next RingBuffer.Read without racing against concurrent writes.

RingBuffer.Write, RingBuffer.Read, and RingBuffer.Flush perform zero heap allocations. The zero value is not usable; create one with NewRingBuffer.

Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/duplexaudio"
)

func main() {
	rb := duplexaudio.NewRingBuffer(8)
	rb.Write([]float32{0.1, 0.2, 0.3, 0.4})
	fmt.Println("available:", rb.Available())

	dropped := rb.Flush()
	fmt.Println("dropped:", dropped, "available:", rb.Available())

	dst := make([]float32, 2)
	n := rb.Read(dst)
	fmt.Printf("read=%d silence=%.1f,%.1f\n", n, dst[0], dst[1])
}
Output:
available: 4
dropped: 4 available: 0
read=0 silence=0.0,0.0

func NewRingBuffer

func NewRingBuffer(capacity int) *RingBuffer

NewRingBuffer allocates a lock-free float32 ring buffer with at least capacity samples. Capacity is rounded up to a power of two (minimum 2). If capacity <= 0, a default capacity of 1024 samples is used.

func (*RingBuffer) Available

func (r *RingBuffer) Available() int

Available returns the number of unread, unflushed samples currently queued.

func (*RingBuffer) Capacity

func (r *RingBuffer) Capacity() int

Capacity returns the usable sample capacity of the ring buffer.

func (*RingBuffer) Flush

func (r *RingBuffer) Flush() int

Flush immediately discards all queued samples by advancing the atomic flush watermark to the current write cursor. RingBuffer.Available drops to 0 immediately and the next RingBuffer.Read emits silence.

Flush returns the number of queued samples discarded, performs zero allocations, and is safe to call concurrently with RingBuffer.Write and RingBuffer.Read.

func (*RingBuffer) Flushes

func (r *RingBuffer) Flushes() uint64

Flushes returns the number of RingBuffer.Flush calls that discarded at least one queued sample.

func (*RingBuffer) Free

func (r *RingBuffer) Free() int

Free returns the number of sample slots that can be written immediately without overwriting unread data.

func (*RingBuffer) Overruns

func (r *RingBuffer) Overruns() uint64

Overruns returns the number of RingBuffer.Write calls that dropped samples because the ring buffer was full.

func (*RingBuffer) Read

func (r *RingBuffer) Read(dst []float32) int

Read drains up to len(dst) samples into dst and returns the number of non-silent samples read. If fewer than len(dst) samples are available, the remaining elements of dst are zero-filled (silence).

If a RingBuffer.Flush occurred, Read advances past all flushed samples and outputs silence for any shortfall without counting the flush itself as an underrun. Normal short reads increment RingBuffer.Underruns.

Read performs zero allocations and is safe for real-time audio callbacks.

func (*RingBuffer) Underruns

func (r *RingBuffer) Underruns() uint64

Underruns returns the number of RingBuffer.Read calls that encountered fewer samples than requested (excluding intentional RingBuffer.Flush silences).

func (*RingBuffer) Write

func (r *RingBuffer) Write(src []float32) int

Write copies as many samples from src as fit into the ring buffer and returns the number of samples written. If len(src) exceeds available free space, the excess samples are dropped and RingBuffer.Overruns is incremented.

Write performs zero allocations and is safe to call concurrently with one RingBuffer.Read caller and any RingBuffer.Flush caller.

Jump to

Keyboard shortcuts

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