kolo docsbeta

kolo-audio

Dispositivos de áudio, captura e reprodução em PCM de 16 bits, reamostragem, mistura e Opus. Sem cgo, sem compilador C e sem nada para instalar.

Nesta página

A kolo-audio lista dispositivos de áudio, grava de um microfone e reproduz nos alto-falantes como PCM de 16 bits com sinal e intercalado. Também reamostra, converte canais, aplica ganho, mistura, mede níveis e codifica e decodifica Opus (RFC 6716), verificado com os vetores de teste da RFC 8251. Ela não sabe nada da rede nem da sincronia entre tracks. Os pacotes Go são koloaudio e opus.

Todos os passos

Do microfone aos alto-falantes

As amostras são PCM de 16 bits do começo ao fim. Só o Opus faz pacotes, e a rede entre as duas metades é sua.

  1. OpenInput abre um dispositivo de captura: CoreAudio no macOS, WASAPI no Windows e, no Linux, o protocolo PulseAudio (PulseAudio e PipeWire) ou a interface ALSA do kernel. Read devolve amostras de 16 bits intercaladas.
  2. Um Resampler converte a taxa do dispositivo para uma que o Opus aceita: 8, 12, 16, 24 ou 48 kHz. O backend também pode converter para o Config.Format que você pedir.
  3. O codificador Opus transforma cada frame de 2,5 a 60 ms, de 20 ms por padrão, em um pacote. Você define o bitrate, a correção de erros (FEC) e o DTX.
  4. Os pacotes vão para o outro lado por um transporte seu. O decodificador Opus transforma cada um em amostras; DecodeFEC reconstrói um pacote perdido a partir do seguinte e DecodeLost o disfarça.
  5. Um Resampler converte para a taxa que os alto-falantes usam, quando ela é diferente.
  6. OpenOutput abre um dispositivo de reprodução e Write enfileira as amostras. O silêncio tocado porque o buffer esvaziou é contado em Stats().Underruns.

Instalação

go get github.com/ciranda-dev/kolo-audio

Para fixar esta versão, rode go get github.com/ciranda-dev/kolo-audio@v0.1.0. Ela precisa do Go 1.26 ou mais novo. Não há cgo, nem compilador C, nem libopus, nem biblioteca de som para instalar, então ela compila com CGO_ENABLED=0. O codec Opus é a libopus 1.6.1 e o resampler é o do miniaudio, ambos traduzidos para código-fonte Go que está no repositório. A primeira compilação do pacote opus compila cerca de 2 MB de Go gerado e chega a cerca de 660 MB de memória; as seguintes usam o cache de compilação.

Início rápido

Este programa lista os dispositivos de áudio, depois codifica 20 ms de um tom de 440 Hz com Opus e o decodifica de novo. Ele não abre nenhum dispositivo. Devices nunca abre um, e uma máquina sem dispositivos de áudio imprime o motivo e segue.

main.go
package main

import (
	"errors"
	"fmt"
	"log"
	"math"

	koloaudio "github.com/ciranda-dev/kolo-audio"
	"github.com/ciranda-dev/kolo-audio/opus"
)

func main() {
	for _, kind := range []koloaudio.Kind{koloaudio.Capture, koloaudio.Playback} {
		devs, err := koloaudio.Devices(kind)
		if errors.Is(err, koloaudio.ErrNoDevice) || errors.Is(err, koloaudio.ErrUnsupported) {
			fmt.Printf("%s: %v\n", kind, err)
			continue
		}
		if err != nil {
			log.Fatal(err)
		}
		for _, d := range devs {
			fmt.Printf("%s %q default=%v\n", kind, d.Name, d.Default)
		}
	}

	enc, err := opus.NewEncoder(opus.Config{})
	if err != nil {
		log.Fatal(err)
	}
	defer enc.Close()
	dec, err := opus.NewDecoder(48000, 1)
	if err != nil {
		log.Fatal(err)
	}
	defer dec.Close()

	frame := make([]int16, enc.FrameSize())
	for i := range frame {
		frame[i] = int16(8000 * math.Sin(2*math.Pi*440*float64(i)/48000))
	}
	packet := make([]byte, opus.PacketBufferSize)
	n, err := enc.Encode(frame, packet)
	if err != nil {
		log.Fatal(err)
	}
	pcm := make([]int16, 48000*opus.MaxPacketDuration.Milliseconds()/1000)
	m, err := dec.Decode(packet[:n], pcm)
	if err != nil {
		log.Fatal(err)
	}
	peak, rms := koloaudio.Level(pcm[:m])
	fmt.Printf("20 ms in %d bytes, decoded peak %.1f dBFS, rms %.1f dBFS\n", n, peak, rms)
}

As linhas de dispositivos dependem da máquina. A última não:

Texto
20 ms in 207 bytes, decoded peak -11.3 dBFS, rms -17.0 dBFS

No macOS, peça acesso ao microfone antes de gravar. AccessStatus o lê e RequestAccess(ctx) mostra o aviso do sistema quando o usuário ainda não foi perguntado; nenhum dos dois abre um dispositivo. Este programa só imprime o estado e pede acesso, então em um Mac ele pode mostrar o aviso:

access.go
package main

import (
	"context"
	"errors"
	"fmt"
	"io/fs"
	"log"
	"time"

	koloaudio "github.com/ciranda-dev/kolo-audio"
)

func main() {
	status, err := koloaudio.AccessStatus() // never asks
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("microphone:", status)

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	switch err := koloaudio.RequestAccess(ctx); { // macOS: may show the system prompt
	case err == nil:
		fmt.Println("capture is allowed")
	case errors.Is(err, koloaudio.ErrPermission):
		fmt.Println("refused:", err, errors.Is(err, fs.ErrPermission))
	default:
		log.Fatal(err) // includes ctx.Err() when the minute ends
	}
}

Para gravar, abra um Input com OpenInput e chame Read em um laço; para reproduzir, abra um Output com OpenOutput e chame Write. O repositório tem examples/passthrough, que reproduz um dispositivo de captura em um de reprodução (use fones de ouvido), e examples/opustone, que codifica um tom, descarta um pacote e o recupera com correção de erros adiante. Os dois recebem os IDs de dispositivo como flags e nunca leem nem escrevem arquivos.

Referência da API

A referência da API é gerada a partir do código Go e está em inglês.

Pacote koloaudio · github.com/ciranda-dev/kolo-audio · v0.1.0

Package koloaudio captures and plays interleaved 16-bit PCM through the system's audio devices and provides small PCM processing helpers.

It uses no cgo and needs nothing installed. Devices exist on macOS (CoreAudio), Windows (WASAPI) and Linux (a PulseAudio protocol server, or the ALSA kernel interface), on amd64 and arm64; elsewhere they return ErrUnsupported. The Resampler and the opus subpackage work everywhere.

Experimental: the API may change before v1.0.0.

Constantes

const (
	// MinSampleRate and MaxSampleRate bound Format.SampleRate in Hz.
	MinSampleRate = 8000
	MaxSampleRate = 384000
	// MaxChannels bounds Format.Channels.
	MaxChannels = 254

	// DefaultSampleRate is used when Format.SampleRate is zero; Opus runs at 48 kHz.
	DefaultSampleRate = 48000
	// DefaultChannels is used when Format.Channels is zero (mono).
	DefaultChannels = 1
	// DefaultPeriod is the device callback period when Config.Period is zero.
	DefaultPeriod = 10 * time.Millisecond
	// DefaultBuffer is the stream buffer when Config.Buffer is zero; it holds
	// one Opus packet of the maximum duration, 120 ms.
	DefaultBuffer = 120 * time.Millisecond
	// MaxBuffer bounds Config.Buffer; it is the longest default buffer
	// among the supported sound servers.
	MaxBuffer = 2 * time.Second
	// DefaultStallTimeout is used when Config.StallTimeout is zero. It leaves
	// room for platforms that delay the first callback after resume from sleep.
	DefaultStallTimeout = 12 * time.Second
)

Format limits and defaults.

Variáveis

var (
	// ErrInvalidConfig means a Config field is out of range.
	ErrInvalidConfig = errors.New("koloaudio: invalid config")
	// ErrInvalidArgument means a buffer or value passed to a call is not valid,
	// for example a sample count that is not a whole number of frames.
	ErrInvalidArgument = errors.New("koloaudio: invalid argument")
	// ErrNoDevice means no audio backend is available or no device matches the ID.
	ErrNoDevice = errors.New("koloaudio: no such device")
	// ErrUnsupportedFormat means the sample rate or channel count is not supported.
	ErrUnsupportedFormat = errors.New("koloaudio: unsupported format")
	// ErrDeviceLost means the device stopped or stopped calling back while in use.
	ErrDeviceLost = errors.New("koloaudio: device lost")
	// ErrClosed means the stream or resampler was closed.
	ErrClosed = errors.New("koloaudio: closed")
	// ErrBackend means the audio backend failed for another reason; the
	// message holds its description.
	ErrBackend = errors.New("koloaudio: audio backend failed")
	// ErrUnsupported means the platform has no audio device backend.
	ErrUnsupported = errors.New("koloaudio: not supported on " + runtime.GOOS + "/" + runtime.GOARCH)
	// ErrPermission means the user or a policy refused microphone access, from
	// RequestAccess or OpenInput. Errors that wrap it also wrap fs.ErrPermission.
	ErrPermission = errors.New("koloaudio: microphone access not granted")
)

Funções

func ConvertChannels

func ConvertChannels(dst, src []int16, from, to int) (int, error)

ConvertChannels converts interleaved frames in src from one channel count to another into dst and returns the number of samples written. It copies when the counts match, duplicates a mono channel, and averages all channels down to mono; other conversions return ErrUnsupportedFormat. dst must hold len(src)/from*to samples and must not overlap src.

func DecodeS16LE

func DecodeS16LE(dst []int16, b []byte) ([]int16, error)

DecodeS16LE appends the little-endian signed 16-bit samples in b to dst and returns the extended slice. An odd len(b) returns ErrInvalidArgument and dst unchanged.

func EncodeS16LE

func EncodeS16LE(dst []byte, pcm []int16) []byte

EncodeS16LE appends pcm to dst as little-endian signed 16-bit samples and returns the extended slice.

func Gain

func Gain(pcm []int16, factor float64) error

Gain multiplies every sample by factor in place, saturating at the int16 limits. factor must be finite; a negative factor also inverts the phase.

func Level

func Level(pcm []int16) (peak, rms float64)

Level returns the peak and RMS level of pcm in dBFS, where 0 dBFS is a sample magnitude of 32768. A full-scale sine has an RMS of -3.01 dBFS. Silence and an empty slice return -Inf for both.

func Mix

func Mix(dst, src []int16) int

Mix adds src into dst sample by sample, saturating at the int16 limits, and returns the number of samples mixed, min(len(dst), len(src)).

func RequestAccess

func RequestAccess(ctx context.Context) error

RequestAccess asks for microphone access on macOS when the user has not been asked yet, and returns once access is decided. It never opens a device. A refusal returns ErrPermission. The prompt waits for the person, so bound the wait with ctx; the prompt stays until answered. An app bundle needs NSMicrophoneUsageDescription in its Info.plist and, with the hardened runtime, the com.apple.security.device.audio-input entitlement; without them macOS ends the process. Linux and Windows return nil at once, elsewhere ErrUnsupported.

Tipos

type Access

type Access int

Access is the microphone access the system grants this process.

const (
	// AccessNotDetermined means the user has not been asked yet.
	AccessNotDetermined Access = iota + 1
	// AccessRestricted means a policy, such as device management, forbids access.
	AccessRestricted
	// AccessDenied means the user refused access.
	AccessDenied
	// AccessAuthorized means capture is allowed. On Linux and Windows it only
	// means that there is nothing to check.
	AccessAuthorized
)
func AccessStatus
func AccessStatus() (Access, error)

AccessStatus reports the microphone access of this process on macOS. It never asks the user and never opens a device; an unknown system status is ErrBackend. Linux and Windows have no consent step to read, so it returns AccessAuthorized, and OpenInput reports the refusals the backend returns as ErrPermission. Elsewhere it returns ErrUnsupported.

func (Access) String
func (a Access) String() string

String returns "not determined", "restricted", "denied" or "authorized".

type Config

type Config struct {
	// DeviceID selects a device from Devices. Empty means the system default
	// device; on macOS and Windows the stream follows it when it changes.
	DeviceID string
	// Format of the samples passed to Read or Write. The device converts to
	// and from its native format.
	Format Format
	// Period is the requested device callback period. Zero means DefaultPeriod.
	// The backend may round it.
	Period time.Duration
	// Buffer is the capacity of the stream buffer between the device and the
	// application. Zero means DefaultBuffer. It must be at least Period and
	// at most MaxBuffer. The buffer holds Buffer times the sample rate times
	// Channels samples of 2 bytes, allocated when the stream opens.
	Buffer time.Duration
	// StallTimeout fails the stream with ErrDeviceLost when the device makes
	// no callback for this long. Zero means DefaultStallTimeout. It must be
	// longer than Period.
	StallTimeout time.Duration
}

Config configures OpenInput and OpenOutput. Zero fields take the defaults.

type Device

type Device struct {
	// ID is opaque and stable while the system keeps the device's identifier.
	ID string
	// Name is the name the system shows for the device.
	Name string
	// Kind is Capture or Playback.
	Kind Kind
	// Default reports whether the device is the system default of its kind.
	Default bool
}

Device describes an audio device. ID and Name identify hardware on this machine (a Bluetooth ID can hold its address), so do not send them to peers.

func Devices
func Devices(kind Kind) ([]Device, error)

Devices lists the devices of the given kind. It never opens a device, asks for consent or changes process-wide state.

type Format

type Format struct {
	// SampleRate in Hz, MinSampleRate to MaxSampleRate. Zero means DefaultSampleRate.
	SampleRate int
	// Channels, 1 to MaxChannels. Zero means DefaultChannels.
	Channels int
}

Format is a PCM format: interleaved signed 16-bit samples.

type Input

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

Input captures audio from a device. Its methods are safe for concurrent use; concurrent Reads split the captured stream between them.

func OpenInput
func OpenInput(cfg Config) (*Input, error)

OpenInput opens and starts a capture device. A refusal of microphone access returns ErrPermission, which also matches ErrBackend and fs.ErrPermission. On macOS it reads AccessStatus first; call RequestAccess before it.

func (Input) Close
func (in *Input) Close() error

Close stops the device and releases it. Pending and later calls return ErrClosed. Close is idempotent and always returns nil. An Input that becomes unreachable without Close is closed by the garbage collector, which may take long; call Close.

func (Input) Format
func (in *Input) Format() Format

Format returns the format of the samples Read returns.

func (Input) Read
func (in *Input) Read(ctx context.Context, p []int16) (int, error)

Read blocks until at least one frame is captured, then copies up to len(p) samples and returns the count. len(p) must be a positive multiple of the channel count. It returns ctx.Err(), ErrClosed or ErrDeviceLost.

func (Input) Stats
func (in *Input) Stats() Stats

Stats returns the stream counters.

type Kind

type Kind int

Kind selects capture (input) or playback (output) devices.

const (
	// Capture devices record audio.
	Capture Kind = iota + 1
	// Playback devices play audio.
	Playback
)
func (Kind) String
func (k Kind) String() string

String returns "capture" or "playback".

type Output

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

Output plays audio on a device. Its methods are safe for concurrent use; concurrent Writes may interleave their samples.

func OpenOutput
func OpenOutput(cfg Config) (*Output, error)

OpenOutput opens and starts a playback device. It plays silence until the first Write.

func (Output) Close
func (out *Output) Close() error

Close stops the device and releases it, discarding queued audio. Pending and later calls return ErrClosed. Close is idempotent and always returns nil. An Output that becomes unreachable without Close is closed by the garbage collector, which may take long; call Close.

func (Output) Format
func (out *Output) Format() Format

Format returns the format Write expects.

func (Output) Stats
func (out *Output) Stats() Stats

Stats returns the stream counters.

func (Output) Write
func (out *Output) Write(ctx context.Context, p []int16) (int, error)

Write queues p for playback, blocking while the buffer is full, and returns the number of samples queued. len(p) must be a positive multiple of the channel count. On ctx.Err(), ErrClosed or ErrDeviceLost the count tells how much was queued.

type Resampler

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

Resampler converts interleaved PCM from one sample rate to another with linear interpolation and a 4th-order low-pass filter. It keeps state between calls, so a stream can be fed in chunks of any size. Its methods are safe for concurrent use. A call that fails inside the resampler returns ErrBackend, and the next call starts again from a cleared filter state.

func NewResampler
func NewResampler(channels, inRate, outRate int) (*Resampler, error)

NewResampler returns a Resampler for the given channel count and rates in Hz.

func (Resampler) Close
func (r *Resampler) Close() error

Close releases the Resampler. Later calls return ErrClosed. Close is idempotent and always returns nil.

func (Resampler) Flush
func (r *Resampler) Flush(dst []int16) (int, error)

Flush writes the output still held back by the filter delay, as if the input were followed by silence, then resets the Resampler. A dst of (Latency()+1)*channels samples always suffices; Flush returns the samples written.

func (Resampler) Latency
func (r *Resampler) Latency() int

Latency returns the delay the filter adds, in output frames.

func (Resampler) OutputLen
func (r *Resampler) OutputLen(n int) int

OutputLen returns the number of samples Process writes when it consumes n input samples, given the current state. It saturates at math.MaxInt.

func (Resampler) Process
func (r *Resampler) Process(dst, src []int16) (written, consumed int, err error)

Process resamples src into dst and returns the number of samples written and consumed. It stops when dst is full or src is used up; pass the unconsumed rest of src again with the next call. dst must hold at least one frame.

func (Resampler) Reset
func (r *Resampler) Reset()

Reset clears the filter state, dropping any held-back output.

type Stats

type Stats struct {
	// Frames moved through the device callback.
	Frames uint64
	// Overruns counts captured frames dropped, oldest first, because the
	// application did not read fast enough. Always zero on an Output.
	Overruns uint64
	// Underruns counts frames of silence played because the buffer was empty
	// after the first Write. Always zero on an Input.
	Underruns uint64
	// Buffered is the number of frames waiting in the stream buffer.
	Buffered int
}

Stats counts what happened on a stream since it was opened. Counts are in frames.

Pacote opus

github.com/ciranda-dev/kolo-audio/opus

Package opus encodes and decodes Opus (RFC 6716) with libopus 1.6.1 translated to Go. It needs no cgo and no installed library. Samples are interleaved signed 16-bit PCM.

Constantes

const (
	// PacketBufferSize is an output buffer size for Encode that holds any
	// packet, as libopus recommends.
	PacketBufferSize = 4000
	// MaxPacketDuration is the longest audio one packet can carry. Size
	// Decode buffers for it to accept any packet.
	MaxPacketDuration = 120 * time.Millisecond
)

Variáveis

var (
	// ErrInvalidConfig means a Config field or constructor argument is out of range.
	ErrInvalidConfig = errors.New("koloaudio: opus: invalid config")
	// ErrInvalidArgument means a buffer or value passed to a call is not valid.
	ErrInvalidArgument = errors.New("koloaudio: opus: invalid argument")
	// ErrFrameSize means the PCM length is not an allowed frame duration.
	ErrFrameSize = errors.New("koloaudio: opus: invalid frame size")
	// ErrBufferTooSmall means the output buffer cannot hold the result.
	ErrBufferTooSmall = errors.New("koloaudio: opus: buffer too small")
	// ErrInvalidPacket means the packet is empty or corrupt.
	ErrInvalidPacket = errors.New("koloaudio: opus: invalid packet")
	// ErrInternal means libopus detected an internal error or the codec
	// faulted. After a fault the next call continues on a new codec
	// instance with the same settings and fresh codec state.
	ErrInternal = errors.New("koloaudio: opus: internal error")
	// ErrUnimplemented means libopus does not implement the request.
	ErrUnimplemented = errors.New("koloaudio: opus: not implemented")
	// ErrInvalidState means the libopus state is invalid.
	ErrInvalidState = errors.New("koloaudio: opus: invalid state")
	// ErrAllocFail means libopus could not allocate memory.
	ErrAllocFail = errors.New("koloaudio: opus: allocation failed")
	// ErrClosed means the encoder or decoder was closed.
	ErrClosed = errors.New("koloaudio: opus: closed")
)

Tipos

type Application
type Application int

Application tunes the encoder for a kind of signal.

const (
	// VoIP favors speech intelligibility. It is the default.
	VoIP Application = iota
	// Audio favors faithfulness to the input, for music and mixed content.
	Audio
	// LowDelay disables the speech modes to save a few milliseconds of delay.
	LowDelay
)
type Config
type Config struct {
	// SampleRate is 8000, 12000, 16000, 24000 or 48000 Hz. Zero means 48000.
	SampleRate int
	// Channels is 1 or 2. Zero means 1.
	Channels int
	// Application defaults to VoIP.
	Application Application
	// Bitrate in bits per second, 500 to 512000. Zero lets libopus choose
	// from the sample rate and channel count.
	Bitrate int
	// Complexity from 1 to 10 trades CPU for quality. Zero keeps the libopus
	// default, 9. SetComplexity also accepts 0.
	Complexity int
	// FEC adds in-band forward error correction when PacketLossPercent > 0.
	FEC bool
	// PacketLossPercent is the expected loss, 0 to 100.
	PacketLossPercent int
	// DTX sends almost nothing during silence.
	DTX bool
	// CBR makes every packet of a frame duration the same size, so sizes do
	// not reveal speech. Turn DTX off with it: DTX still sends 1 or 2 byte
	// packets in silence. The default is variable bitrate.
	CBR bool
	// FrameDuration is 2.5, 5, 10, 20, 40 or 60 ms. Zero means 20 ms.
	FrameDuration time.Duration
}

Config configures an Encoder. Zero fields take the defaults.

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

Decoder decodes Opus packets to PCM. Its methods are safe for concurrent use. Close releases its codec but is not required to avoid a leak.

func NewDecoder
func NewDecoder(sampleRate, channels int) (*Decoder, error)

NewDecoder returns a Decoder that outputs sampleRate Hz (8000, 12000, 16000, 24000 or 48000) with 1 or 2 channels, whatever the packets hold.

func (Decoder) Close
func (d *Decoder) Close() error

Close releases the Decoder. Later calls return ErrClosed. Close is idempotent and always returns nil.

func (Decoder) Decode
func (d *Decoder) Decode(packet []byte, pcm []int16) (int, error)

Decode decodes packet into pcm and returns the number of samples written, all channels together. pcm must hold the packet's duration; MaxPacketDuration always suffices. A corrupt packet, or one longer than an Opus packet can be without padding (1275 bytes per frame, 48 frames), returns ErrInvalidPacket. A codec fault returns ErrInternal.

func (Decoder) DecodeFEC
func (d *Decoder) DecodeFEC(packet []byte, pcm []int16) (int, error)

DecodeFEC reconstructs a lost packet from the forward error correction data in the packet that followed it, and fills all of pcm, whose duration must be that of the lost packet: a multiple of 2.5 ms up to MaxPacketDuration. Without FEC data it conceals the loss like DecodeLost. Decode packet itself afterwards.

func (Decoder) DecodeLost
func (d *Decoder) DecodeLost(pcm []int16) (int, error)

DecodeLost conceals a lost packet by filling all of pcm, whose duration must be that of the lost packet: a multiple of 2.5 ms up to MaxPacketDuration. Call it once per lost packet.

func (Decoder) DecodedLen
func (d *Decoder) DecodedLen(packet []byte) (int, error)

DecodedLen returns the number of samples, all channels together, that Decode writes for packet. It reads only the packet header, so Decode can still reject the packet.

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

Encoder encodes PCM frames to Opus packets. Its methods are safe for concurrent use. Close releases its codec but is not required to avoid a leak.

func NewEncoder
func NewEncoder(cfg Config) (*Encoder, error)

NewEncoder returns an Encoder for cfg.

func (Encoder) Close
func (e *Encoder) Close() error

Close releases the Encoder. Later calls return ErrClosed. Close is idempotent and always returns nil.

func (Encoder) Encode
func (e *Encoder) Encode(pcm []int16, out []byte) (int, error)

Encode encodes one frame of exactly FrameSize samples into out and returns the packet length. PacketBufferSize bytes always suffice; a shorter out is not an error, libopus limits the packet to len(out) bytes at the cost of quality. With DTX, a packet of 2 bytes or less carries silence and need not be sent. A codec fault returns ErrInternal.

func (Encoder) FrameSize
func (e *Encoder) FrameSize() int

FrameSize returns the number of samples, all channels together, that Encode takes per call.

func (Encoder) SetBitrate
func (e *Encoder) SetBitrate(bps int) error

SetBitrate sets the target bitrate, 500 to 512000 bits per second, or 0 to let libopus choose.

func (Encoder) SetCBR
func (e *Encoder) SetCBR(on bool) error

SetCBR turns constant bitrate on or off. With it on, every packet of a frame duration has the same size, as long as out in Encode holds that size, and DTX still shortens packets in silence. Off is variable bitrate.

func (Encoder) SetComplexity
func (e *Encoder) SetComplexity(c int) error

SetComplexity sets the complexity, 0 to 10.

func (Encoder) SetDTX
func (e *Encoder) SetDTX(on bool) error

SetDTX turns discontinuous transmission on or off.

func (Encoder) SetFEC
func (e *Encoder) SetFEC(on bool) error

SetFEC turns in-band forward error correction on or off.

func (Encoder) SetPacketLossPercent
func (e *Encoder) SetPacketLossPercent(p int) error

SetPacketLossPercent sets the expected packet loss, 0 to 100.

Bom saber

Como o áudio viaja

  1. OpenInput abre um dispositivo de captura e Read devolve amostras de 16 bits intercaladas.
  2. Um Resampler converte a taxa do dispositivo para uma que o Opus aceita.
  3. O opus.Encoder transforma cada frame em um pacote.
  4. Sua aplicação envia os pacotes. A kolo-audio não envia nada.
  5. O opus.Decoder transforma cada pacote em amostras, ou DecodeFEC e DecodeLost cobrem um perdido.
  6. Write enfileira as amostras em um Output.

Dispositivos

  • Devices(kind) lista os dispositivos de Capture ou Playback e nunca abre um. Um Device tem um ID opaco, um Name, o seu Kind e Default, que é verdadeiro para o padrão do sistema do seu tipo.
  • Os backends são CoreAudio no macOS (com purego), WASAPI no Windows (com COM) e, no Linux, primeiro o protocolo PulseAudio (PulseAudio e PipeWire respondem no mesmo socket) e a interface ALSA do kernel só quando nenhum servidor de som responde. Todos são Go puro e não usam cgo.
  • Config.DeviceID escolhe um dispositivo. Vazio significa o padrão do sistema, e no macOS e no Windows o stream acompanha o padrão quando ele muda. Um ID explícito fixa o stream. Um ID que Devices não listou retorna ErrNoDevice.
  • Os dispositivos ALSA são PCMs de hardware: não há dmix nem plug para compartilhar, e um dispositivo é exclusivo enquanto está aberto. Um usuário de Linux precisa de acesso a /dev/snd; se for negado, o erro envolve fs.ErrPermission.
  • No macOS, a captura precisa do consentimento do usuário. Uma ferramenta de linha de comando herda a permissão do seu terminal. Um app bundle precisa de NSMicrophoneUsageDescription no seu Info.plist; com o hardened runtime ele também precisa do entitlement com.apple.security.device.audio-input, e no App Sandbox da capacidade Audio Input. A documentação da Apple diz que sem a chave ou o entitlement o macOS encerra o app quando ele pede acesso ou usa o microfone, então nesse caso RequestAccess não pode retornar um erro. Isso vem da documentação da Apple e não foi testado aqui: nenhum app bundle foi assinado nem notarizado. Listar dispositivos não pede.
  • AccessStatus retorna um Access (AccessNotDetermined, AccessRestricted, AccessDenied ou AccessAuthorized) sem perguntar. RequestAccess(ctx) mostra o aviso do sistema se o usuário ainda não foi perguntado e retorna quando o acesso é decidido: nil, ou um erro que envolve ErrPermission e fs.ErrPermission. O aviso espera a pessoa e não há timeout embutido, então limite a espera com ctx: quando ele termina, RequestAccess retorna ctx.Err() e o aviso fica até ser respondido. Nenhum dos dois abre um dispositivo. Sem consentimento, OpenInput retorna um erro que envolve ErrPermission, ErrBackend e fs.ErrPermission.
  • No Linux e no Windows não há etapa de consentimento para ler nem pedir: AccessStatus retorna AccessAuthorized e RequestAccess retorna nil. Uma recusa ali (a configuração de privacidade do microfone do Windows, as permissões de /dev/snd) aparece quando OpenInput falha com um erro que envolve ErrPermission e fs.ErrPermission. Onde não há suporte a dispositivos, os dois retornam ErrUnsupported.
  • Devices, OpenInput e OpenOutput não recebem contexto, e nenhum bloqueia sem limite: um servidor PulseAudio que não responde custa no máximo 30 s por etapa. Chame-os de uma goroutine se quem chama não puder esperar.

Streams

  • Config.Format é o formato que o seu Read ou Write vê: 48000 Hz e 1 canal por padrão, de 8000 a 384000 Hz e de 1 a 254 canais. O backend converte entre ele e o formato do dispositivo; um pedido que ele não consegue atender retorna ErrUnsupportedFormat.
  • Read bloqueia até que pelo menos um frame seja capturado. Se a aplicação lê devagar demais, os frames mais antigos são descartados e contados em Stats().Overruns; a thread de áudio nunca espera pela aplicação. Write enfileira todas as suas amostras e bloqueia enquanto o buffer está cheio. O dispositivo toca silêncio até o primeiro Write, e o silêncio tocado depois porque o buffer esvaziou é contado em Stats().Underruns.
  • Close para e libera o dispositivo. É idempotente, e as chamadas bloqueadas e as posteriores retornam ErrClosed. Sempre o chame: um stream que não é fechado mantém o dispositivo funcionando até que o coletor de lixo o ache inalcançável.
  • Um stream perdido faz todos os Read e Write seguintes falharem com ErrDeviceLost, e a captura em buffer é descartada. Abra um novo stream para continuar. Passar para um novo dispositivo padrão não é um erro.
  • Input e Output são seguros para uso concorrente.

Reamostragem e utilitários de PCM

  • NewResampler(channels, inRate, outRate) converte taxas com interpolação linear e um filtro passa-baixa de quarta ordem, em blocos de qualquer tamanho. É o resampler do miniaudio, traduzido para Go, e a sua saída é idêntica bit a bit à do original. Process devolve as amostras escritas e consumidas, Latency é o atraso do filtro e Flush escreve a cauda retida.
  • ConvertChannels copia, duplica mono ou tira a média para mono. Gain escala no lugar com saturação, Mix soma com saturação e Level devolve o pico e o RMS em dBFS. EncodeS16LE e DecodeS16LE convertem de e para bytes little-endian.

Opus

  • opus.NewEncoder(opus.Config{...}) recebe a taxa de amostragem (8000, 12000, 16000, 24000 ou 48000, 48000 por padrão), 1 ou 2 canais, uma aplicação (VoIP, Audio ou LowDelay), um bitrate de 500 a 512000 bit/s, uma complexidade de 1 a 10, a correção de erros adiante (FEC) com PacketLossPercent, DTX, bitrate constante (CBR) e uma duração de frame de 2,5, 5, 10, 20, 40 ou 60 ms (20 ms por padrão). SetBitrate e os outros setters mudam ajustes entre frames.
  • Encode(pcm, out) recebe exatamente FrameSize() amostras e devolve o tamanho do pacote. Um out de PacketBufferSize (4000 bytes) sempre comporta um pacote.
  • NewDecoder(sampleRate, channels) e Decode(packet, pcm): dimensione pcm para MaxPacketDuration, 120 ms, para aceitar qualquer pacote. DecodeFEC(next, pcm) reconstrói um pacote perdido a partir do seguinte, e DecodeLost(pcm) o disfarça. Nos dois, pcm deve cobrir exatamente a duração perdida.
  • Os pacotes Opus seguem a RFC 6716 e podem ser transportados como cargas úteis da RFC 7587.
  • Bitrate constante. Com bitrate variável, o tamanho do pacote acompanha o sinal, então quem vê só os tamanhos dos pacotes, por exemplo de áudio criptografado, consegue distinguir fala de silêncio (RFC 6562). Com opus.Config.CBR (ou Encoder.SetCBR(true)) todos os pacotes de uma duração de frame têm o mesmo comprimento, (bitrate * duração do frame + 4) / 8 bytes (pelo menos 1), para tom, silêncio, ruído e fala igualmente, a 16, 32 e 64 kbit/s, mono e estéreo. O padrão continua sendo bitrate variável, e os pacotes com CBR desligado não mudam. Mantenha o DTX desligado com ela: o DTX ainda troca o silêncio por pacotes de 1 ou 2 bytes, e isso mostra quando alguém fica quieto. Passe a Encode um out de pelo menos esse tamanho; um menor corta o pacote. O bitrate variável restrito, o padrão da libopus, não é constante e é o que o CBR desliga.

Plataformas

PlataformaBackend de dispositivosO que foi executado
macOS arm64CoreAudio com puregoTestes, enumeração real de dispositivos, registro de listeners e um build com hardened runtime em um Mac. Um stream de reprodução com silêncio e um stream de captura abertos nos dispositivos embutidos do Mac.
macOS amd64igualBinário de testes sob o Rosetta. Sem um Mac Intel nativo.
Windows arm64WASAPI com COMTestes e enumeração real de endpoints em uma VM de Windows 11 com dispositivos de som virtuais. Nenhum stream aberto.
Windows amd64igualOs mesmos testes sob a emulação x64 da VM.
Linux, servidor de somprotocolo PulseAudioReproduzir, gravar e remover um dispositivo contra servidores reais no Docker, só com um sink nulo.
Linux, sem servidorinterface ALSA do kernelEnumeração, negociação e reprodução para gravação com a placa de loopback snd-aloop em um kernel real. Sem uma placa de som real.
QualquerDispositivo nuloOs testes usam um dispositivo virtual com temporizador em todas as plataformas.

Em hardware de som real, streams só foram abertos em um Mac (arm64): reprodução de silêncio e captura nos dispositivos embutidos, a 16000 Hz mono, 44100 Hz estéreo e 48000 Hz mono, também com -race. Windows e Linux não abriram nenhum stream em hardware de som real. Os testes que abrem dispositivos reais só rodam com KOLO_AUDIO_HW_TEST=1. As demais plataformas compilam, e Devices, OpenInput e OpenOutput retornam ErrUnsupported; o resampler, os utilitários de PCM e o Opus funcionam. O decodificador do Opus passa nos 12 vetores da RFC 8251, mono e estéreo, no macOS arm64 e no Windows (arm64 nativamente, amd64 sob emulação). CGO_ENABLED=0 sempre funciona e gera binários estáticos no Linux.

Limites

Um valor fora do intervalo retorna ErrInvalidConfig, ErrInvalidArgument ou ErrUnsupportedFormat. As tabelas completas estão em Limites.

  • Config.Period de 10 ms, Config.Buffer de 120 ms (até 2 s) e Config.StallTimeout de 12 s por padrão.
  • Nada cresce além de Buffer. O módulo da libopus é ligado com no máximo 1 MiB de memória e o resampler com 512 KiB, então um stream hostil não consegue fazer um codec crescer sem limite.
  • Um pacote Opus com mais de 61296 bytes é ErrInvalidPacket antes de chegar ao codec, e DecodeFEC e DecodeLost são limitados a 120 ms.
  • O número de streams e de instâncias de codec é da aplicação, e cada instância custa a sua própria memória, cerca de 0,8 a 0,9 MB por um par codificador e decodificador.

Segurança

  • O leitor do PulseAudio confere cada tamanho contra o que sobra no buffer, nunca aloca a partir de um tamanho, aceita frames de no máximo 16 MiB e aplica um timeout a cada requisição. Um endereço IPv6 de qualquer forma é recusado.
  • O cookie de autenticação é lido só de $PULSE_COOKIE, $XDG_CONFIG_HOME/pulse/cookie ou ~/.pulse-cookie, é enviado só ao servidor e nunca é registrado em log nem colocado em um erro.
  • A kolo-audio não carrega nenhuma biblioteca própria, não extrai nada para o disco e chama dlopen só para frameworks do sistema, então uma aplicação assinada com o hardened runtime não precisa de nenhum entitlement extra por causa dela. No macOS, importar o pacote carrega a libobjc na partida (o pacote de Objective-C do purego); ele não abre nenhum dispositivo e não pergunta nada.
  • Os analisadores têm alvos de fuzzing, e decodificar pacotes malformados nunca escreve além do buffer de quem chama.

Estado

  • Feito: listagem de dispositivos, captura e reprodução no macOS, no Windows e no Linux, reamostragem e utilitários de PCM, e codificação e decodificação Opus, com alvos de fuzzing e testes.
  • Testado: em hardware de som real, só em um Mac (arm64), reprodução de silêncio e captura nos dispositivos embutidos, como diz a tabela de plataformas. Windows e Linux não abriram nenhum stream em hardware de som real. AccessStatus leu o estado real em um Mac (autorizado). RequestAccess só foi executado contra um simulado, nunca em um sistema real, porque pode mostrar o aviso, e nenhuma recusa real foi observada.
  • Experimental. A API pode mudar antes da v1.0.0.

Erros

ErroMensagem
ErrBackendkoloaudio: audio backend failed
ErrClosedkoloaudio: closed
ErrDeviceLostkoloaudio: device lost
ErrInvalidArgumentkoloaudio: invalid argument
ErrInvalidConfigkoloaudio: invalid config
ErrNoDevicekoloaudio: no such device
ErrPermissionkoloaudio: microphone access not granted
ErrUnsupported
ErrUnsupportedFormatkoloaudio: unsupported format
opus.ErrAllocFailkoloaudio: opus: allocation failed
opus.ErrBufferTooSmallkoloaudio: opus: buffer too small
opus.ErrClosedkoloaudio: opus: closed
opus.ErrFrameSizekoloaudio: opus: invalid frame size
opus.ErrInternalkoloaudio: opus: internal error
opus.ErrInvalidArgumentkoloaudio: opus: invalid argument
opus.ErrInvalidConfigkoloaudio: opus: invalid config
opus.ErrInvalidPacketkoloaudio: opus: invalid packet
opus.ErrInvalidStatekoloaudio: opus: invalid state
opus.ErrUnimplementedkoloaudio: opus: not implemented

Todo erro começa com koloaudio: (os do pacote opus continuam com opus:) e envolve um sentinela, então errors.Is funciona. Um microfone recusado, vindo de RequestAccess ou OpenInput, envolve ErrPermission e fs.ErrPermission; vindo de OpenInput ele também envolve ErrBackend. Os erros de OpenOutput não envolvem ErrPermission. ErrUnsupported significa que este GOOS e GOARCH não tem um backend de dispositivos.

Referências