kolo docsbeta

kolo-audio

Dispositivos de audio, captura y reproducción en PCM de 16 bits, remuestreo, mezcla y Opus. Sin cgo, sin compilador de C y sin nada que instalar.

En esta página

kolo-audio lista dispositivos de audio, graba desde un micrófono y reproduce en los altavoces como PCM de 16 bits con signo e intercalado. También remuestrea, convierte canales, aplica ganancia, mezcla, mide niveles y codifica y decodifica Opus (RFC 6716), comprobado con los vectores de prueba de la RFC 8251. No sabe nada de la red ni de la sincronía entre tracks. Los paquetes de Go son koloaudio y opus.

Todos los pasos

Del micrófono a los altavoces

Las muestras son PCM de 16 bits de principio a fin. Solo Opus hace paquetes, y la red entre las dos mitades es tuya.

  1. OpenInput abre un dispositivo de captura: CoreAudio en macOS, WASAPI en Windows y, en Linux, el protocolo PulseAudio (PulseAudio y PipeWire) o la interfaz ALSA del kernel. Read devuelve muestras de 16 bits intercaladas.
  2. Un Resampler convierte la frecuencia del dispositivo a una que Opus acepta: 8, 12, 16, 24 o 48 kHz. El backend también puede convertir al Config.Format que pidas.
  3. El codificador Opus convierte cada frame de 2,5 a 60 ms, de 20 ms por defecto, en un paquete. Tú eliges la tasa de bits, la corrección de errores (FEC) y DTX.
  4. Los paquetes van al otro lado por un transporte tuyo. El decodificador Opus convierte cada uno en muestras; DecodeFEC reconstruye un paquete perdido con el siguiente y DecodeLost lo disimula.
  5. Un Resampler convierte a la frecuencia que usan los altavoces, cuando es distinta.
  6. OpenOutput abre un dispositivo de reproducción y Write encola las muestras. El silencio que suena porque el búfer se vació se cuenta en Stats().Underruns.

Instalación

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

Para fijar esta versión, ejecuta go get github.com/ciranda-dev/kolo-audio@v0.1.0. Necesita Go 1.26 o superior. No hay cgo, ni compilador de C, ni libopus, ni biblioteca de sonido que instalar, así que compila con CGO_ENABLED=0. El códec Opus es libopus 1.6.1 y el resampler es el de miniaudio, ambos traducidos a código fuente de Go que está en el repositorio. La primera compilación del paquete opus compila unos 2 MB de Go generado y llega a unos 660 MB de memoria; las siguientes usan la caché de compilación.

Inicio rápido

Este programa lista los dispositivos de audio, luego codifica 20 ms de un tono de 440 Hz con Opus y lo decodifica de nuevo. No abre ningún dispositivo. Devices nunca abre uno, y una máquina sin dispositivos de audio imprime el motivo y sigue.

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)
}

Las líneas de dispositivos dependen de la máquina. La última no:

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

En macOS, pide acceso al micrófono antes de grabar. AccessStatus lo lee y RequestAccess(ctx) muestra el aviso del sistema si al usuario aún no se le preguntó; ninguno abre un dispositivo. Este programa solo imprime el estado y pide acceso, así que en un Mac puede mostrar el 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 grabar, abre un Input con OpenInput y llama a Read en un bucle; para reproducir, abre un Output con OpenOutput y llama a Write. El repositorio tiene examples/passthrough, que reproduce un dispositivo de captura en uno de reproducción (usa audífonos), y examples/opustone, que codifica un tono, descarta un paquete y lo recupera con corrección de errores hacia adelante. Ambos reciben los ID de dispositivo como flags y nunca leen ni escriben archivos.

Referencia de la API

La referencia de la API se genera a partir del código Go y está en inglés.

Paquete 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.

Variables

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")
)

Funciones

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.

Paquete 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
)

Variables

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.

Conviene saber

Cómo viaja el audio

  1. OpenInput abre un dispositivo de captura y Read devuelve muestras de 16 bits intercaladas.
  2. Un Resampler convierte la frecuencia del dispositivo a una que Opus acepta.
  3. El opus.Encoder convierte cada frame en un paquete.
  4. Tu aplicación envía los paquetes. kolo-audio no envía nada.
  5. El opus.Decoder convierte cada paquete en muestras, o DecodeFEC y DecodeLost cubren uno perdido.
  6. Write encola las muestras en un Output.

Dispositivos

  • Devices(kind) lista los dispositivos de Capture o Playback y nunca abre uno. Un Device tiene un ID opaco, un Name, su Kind y Default, que es verdadero para el predeterminado del sistema de su tipo.
  • Los backends son CoreAudio en macOS (con purego), WASAPI en Windows (con COM) y, en Linux, primero el protocolo PulseAudio (PulseAudio y PipeWire responden en el mismo socket) y la interfaz ALSA del kernel solo cuando ningún servidor de sonido responde. Todos son Go puro y no usan cgo.
  • Config.DeviceID elige un dispositivo. Vacío significa el predeterminado del sistema, y en macOS y Windows el stream sigue al predeterminado cuando cambia. Un ID explícito fija el stream. Un ID que Devices no listó devuelve ErrNoDevice.
  • Los dispositivos ALSA son PCM de hardware: no hay dmix ni plug para compartir, y un dispositivo es exclusivo mientras está abierto. Un usuario de Linux necesita acceso a /dev/snd; si se le niega, el error envuelve fs.ErrPermission.
  • En macOS, la captura necesita el consentimiento del usuario. Una herramienta de línea de comandos hereda el permiso de su terminal. Un app bundle necesita NSMicrophoneUsageDescription en su Info.plist; con el hardened runtime también necesita el entitlement com.apple.security.device.audio-input, y en el App Sandbox la capacidad Audio Input. La documentación de Apple dice que sin la clave o el entitlement macOS termina la app cuando pide acceso o usa el micrófono, así que entonces RequestAccess no puede devolver un error. Esto viene de la documentación de Apple y no se probó aquí: no se firmó ni notarizó ningún app bundle. Listar dispositivos no lo pide.
  • AccessStatus devuelve un Access (AccessNotDetermined, AccessRestricted, AccessDenied o AccessAuthorized) sin preguntar. RequestAccess(ctx) muestra el aviso del sistema si al usuario aún no se le preguntó y vuelve cuando el acceso queda decidido: nil, o un error que envuelve ErrPermission y fs.ErrPermission. El aviso espera a la persona y no hay un timeout incorporado, así que acota la espera con ctx: cuando termina, RequestAccess devuelve ctx.Err() y el aviso queda hasta que se responda. Ninguno abre un dispositivo. Sin consentimiento, OpenInput devuelve un error que envuelve ErrPermission, ErrBackend y fs.ErrPermission.
  • En Linux y Windows no hay un paso de consentimiento que leer ni pedir: AccessStatus devuelve AccessAuthorized y RequestAccess devuelve nil. Una negativa allí (la configuración de privacidad del micrófono de Windows, los permisos de /dev/snd) aparece cuando OpenInput falla con un error que envuelve ErrPermission y fs.ErrPermission. Donde no hay soporte de dispositivos, ambos devuelven ErrUnsupported.
  • Devices, OpenInput y OpenOutput no reciben contexto, y ninguno bloquea sin límite: un servidor PulseAudio que no responde cuesta como máximo 30 s por paso. Llámalos desde una goroutine si quien llama no debe esperar.

Streams

  • Config.Format es el formato que ven tu Read o tu Write: 48000 Hz y 1 canal por defecto, de 8000 a 384000 Hz y de 1 a 254 canales. El backend convierte entre él y el formato del dispositivo; una petición que no puede cumplir devuelve ErrUnsupportedFormat.
  • Read bloquea hasta que se captura al menos un frame. Si la aplicación lee demasiado despacio, se descartan los frames más antiguos y se cuentan en Stats().Overruns; el hilo de audio nunca espera a la aplicación. Write encola todas sus muestras y bloquea mientras el búfer está lleno. El dispositivo reproduce silencio hasta el primer Write, y el silencio posterior por un búfer vacío se cuenta en Stats().Underruns.
  • Close detiene y libera el dispositivo. Es idempotente, y las llamadas bloqueadas y las posteriores devuelven ErrClosed. Llámalo siempre: un stream sin cerrar mantiene su dispositivo en marcha hasta que el recolector de basura lo encuentra inalcanzable.
  • Un stream perdido hace fallar todos los Read y Write posteriores con ErrDeviceLost, y la captura en búfer se descarta. Abre un stream nuevo para seguir. Cambiar a un nuevo dispositivo predeterminado no es un error.
  • Input y Output son seguros para uso concurrente.

Remuestreo y utilidades de PCM

  • NewResampler(channels, inRate, outRate) convierte frecuencias con interpolación lineal y un filtro pasa bajos de cuarto orden, en trozos de cualquier tamaño. Es el resampler de miniaudio, traducido a Go, y su salida es idéntica bit a bit a la del original. Process devuelve las muestras escritas y consumidas, Latency es el retardo del filtro y Flush escribe la cola retenida.
  • ConvertChannels copia, duplica mono o promedia a mono. Gain escala en el lugar con saturación, Mix suma con saturación y Level devuelve el pico y el RMS en dBFS. EncodeS16LE y DecodeS16LE convierten desde y hacia bytes little-endian.

Opus

  • opus.NewEncoder(opus.Config{...}) recibe la frecuencia de muestreo (8000, 12000, 16000, 24000 o 48000, 48000 por defecto), 1 o 2 canales, una aplicación (VoIP, Audio o LowDelay), una tasa de bits de 500 a 512000 bit/s, una complejidad de 1 a 10, la corrección de errores hacia adelante (FEC) con PacketLossPercent, DTX, tasa de bits constante (CBR) y una duración de frame de 2,5, 5, 10, 20, 40 o 60 ms (20 ms por defecto). SetBitrate y los demás setters cambian ajustes entre frames.
  • Encode(pcm, out) recibe exactamente FrameSize() muestras y devuelve la longitud del paquete. Un out de PacketBufferSize (4000 bytes) siempre contiene un paquete.
  • NewDecoder(sampleRate, channels) y Decode(packet, pcm): dimensiona pcm para MaxPacketDuration, 120 ms, para aceptar cualquier paquete. DecodeFEC(next, pcm) reconstruye un paquete perdido a partir del siguiente, y DecodeLost(pcm) lo disimula. En ambos, pcm debe cubrir exactamente la duración perdida.
  • Los paquetes Opus siguen la RFC 6716 y pueden transportarse como cargas útiles de la RFC 7587.
  • Tasa de bits constante. Con tasa variable, el tamaño del paquete sigue a la señal, así que quien solo ve los tamaños de los paquetes, por ejemplo de audio cifrado, puede distinguir el habla del silencio (RFC 6562). Con opus.Config.CBR (o Encoder.SetCBR(true)) todos los paquetes de una duración de frame tienen la misma longitud, (bitrate * duración del frame + 4) / 8 bytes (al menos 1), para tono, silencio, ruido y habla por igual, a 16, 32 y 64 kbit/s, mono y estéreo. Por defecto sigue la tasa variable, y los paquetes con CBR apagado no cambian. Mantén DTX apagado con ella: DTX sigue sustituyendo el silencio por paquetes de 1 o 2 bytes, y eso delata cuándo alguien calla. Pasa a Encode un out de al menos ese tamaño; uno más corto recorta el paquete. La tasa variable restringida, la de libopus por defecto, no es constante y es lo que CBR apaga.

Plataformas

PlataformaBackend de dispositivosQué se ejecutó
macOS arm64CoreAudio con puregoPruebas, enumeración real de dispositivos, registro de listeners y una compilación con hardened runtime en un Mac. Se abrieron un stream de reproducción con silencio y un stream de captura en los dispositivos integrados del Mac.
macOS amd64igualBinario de pruebas bajo Rosetta. Sin un Mac Intel nativo.
Windows arm64WASAPI con COMPruebas y enumeración real de endpoints en una VM de Windows 11 con dispositivos de sonido virtuales. Ningún stream abierto.
Windows amd64igualLas mismas pruebas bajo la emulación x64 de la VM.
Linux, servidor de sonidoprotocolo PulseAudioReproducir, grabar y retirar un dispositivo contra servidores reales en Docker, solo con un sink nulo.
Linux, sin servidorinterfaz ALSA del kernelEnumeración, negociación y reproducción hacia grabación con la tarjeta de bucle snd-aloop en un kernel real. Sin una tarjeta de sonido real.
CualquieraDispositivo nuloLas pruebas usan un dispositivo virtual con temporizador en todas las plataformas.

En hardware de sonido real solo se abrieron streams en un Mac (arm64): reproducción de silencio y captura en los dispositivos integrados, a 16000 Hz mono, 44100 Hz estéreo y 48000 Hz mono, también con -race. Windows y Linux no abrieron ningún stream en hardware de sonido real. Las pruebas que abren dispositivos reales solo se ejecutan con KOLO_AUDIO_HW_TEST=1. Las demás plataformas compilan, y Devices, OpenInput y OpenOutput devuelven ErrUnsupported; el resampler, las utilidades de PCM y Opus funcionan. El decodificador de Opus pasa los 12 vectores de la RFC 8251, mono y estéreo, en macOS arm64 y en Windows (arm64 de forma nativa, amd64 bajo emulación). CGO_ENABLED=0 siempre funciona y da binarios estáticos en Linux.

Límites

Un valor fuera de rango devuelve ErrInvalidConfig, ErrInvalidArgument o ErrUnsupportedFormat. Las tablas completas están en Límites.

  • Config.Period de 10 ms, Config.Buffer de 120 ms (hasta 2 s) y Config.StallTimeout de 12 s por defecto.
  • Nada crece más allá de Buffer. El módulo de libopus se enlaza con como máximo 1 MiB de memoria y el resampler con 512 KiB, así que un stream hostil no puede hacer crecer un códec sin límite.
  • Un paquete Opus de más de 61296 bytes es ErrInvalidPacket antes de llegar al códec, y DecodeFEC y DecodeLost están limitados a 120 ms.
  • El número de streams y de instancias de códec lo decide la aplicación, y cada instancia cuesta su propia memoria, de 0,8 a 0,9 MB aproximadamente por un par codificador y decodificador.

Seguridad

  • El lector de PulseAudio comprueba cada longitud contra lo que queda en el búfer, nunca reserva memoria a partir de una longitud, acepta frames de como máximo 16 MiB y aplica un tiempo límite a cada petición. Se rechaza una dirección IPv6 de cualquier forma.
  • La cookie de autenticación se lee solo de $PULSE_COOKIE, $XDG_CONFIG_HOME/pulse/cookie o ~/.pulse-cookie, se envía solo al servidor y nunca se registra ni se pone en un error.
  • kolo-audio no carga ninguna biblioteca propia, no extrae nada al disco y llama a dlopen solo para frameworks del sistema, así que una aplicación firmada con el hardened runtime no necesita ningún entitlement extra por ella. En macOS, importar el paquete carga libobjc al arrancar (el paquete de Objective-C de purego); no abre ningún dispositivo y no pregunta nada.
  • Los analizadores tienen objetivos de fuzzing, y decodificar paquetes mal formados nunca escribe más allá del búfer de quien llama.

Estado

  • Hecho: listado de dispositivos, captura y reproducción en macOS, Windows y Linux, remuestreo y utilidades de PCM, y codificación y decodificación Opus, con objetivos de fuzzing y pruebas.
  • Probado: en hardware de sonido real, solo en un Mac (arm64), reproducción de silencio y captura en los dispositivos integrados, como dice la tabla de plataformas. Windows y Linux no abrieron ningún stream en hardware de sonido real. AccessStatus leyó el estado real en un Mac (autorizado). RequestAccess solo se ejecutó contra un simulado, nunca en un sistema real, porque puede mostrar el aviso, y no se observó ninguna negativa real.
  • Experimental. La API puede cambiar antes de la v1.0.0.

Errores

ErrorMensaje
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

Todos los errores empiezan con koloaudio: (los del paquete opus siguen con opus:) y envuelven un centinela, así que errors.Is funciona. Un micrófono rechazado, desde RequestAccess u OpenInput, envuelve ErrPermission y fs.ErrPermission; desde OpenInput también envuelve ErrBackend. Los errores de OpenOutput no envuelven ErrPermission. ErrUnsupported significa que este GOOS y GOARCH no tiene un backend de dispositivos.

Referencias