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.
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.
- 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.
- 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.
- 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.
- 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.
- Un Resampler convierte a la frecuencia que usan los altavoces, cuando es distinta.
- 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-audioPara 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.
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:
20 ms in 207 bytes, decoded peak -11.3 dBFS, rms -17.0 dBFSEn 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:
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.
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) []byteEncodeS16LE appends pcm to dst as little-endian signed 16-bit samples and returns the extended slice.
func Gain
func Gain(pcm []int16, factor float64) errorGain 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) intMix 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) errorRequestAccess 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 intAccess 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() stringString 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() errorClose 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() FormatFormat 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() StatsStats returns the stream counters.
type Kind
type Kind intKind 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() stringString 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() errorClose 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() FormatFormat returns the format Write expects.
func (Output) Stats
func (out *Output) Stats() StatsStats 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() errorClose 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() intLatency returns the delay the filter adds, in output frames.
func (Resampler) OutputLen
func (r *Resampler) OutputLen(n int) intOutputLen 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
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 intApplication 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() errorClose 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() errorClose 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() intFrameSize returns the number of samples, all channels together, that Encode takes per call.
func (Encoder) SetBitrate
func (e *Encoder) SetBitrate(bps int) errorSetBitrate 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) errorSetCBR 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) errorSetComplexity sets the complexity, 0 to 10.
func (Encoder) SetDTX
func (e *Encoder) SetDTX(on bool) errorSetDTX turns discontinuous transmission on or off.
func (Encoder) SetFEC
func (e *Encoder) SetFEC(on bool) errorSetFEC turns in-band forward error correction on or off.
func (Encoder) SetPacketLossPercent
func (e *Encoder) SetPacketLossPercent(p int) errorSetPacketLossPercent sets the expected packet loss, 0 to 100.
Conviene saber
Cómo viaja el audio
OpenInputabre un dispositivo de captura yReaddevuelve muestras de 16 bits intercaladas.- Un
Resamplerconvierte la frecuencia del dispositivo a una que Opus acepta. - El
opus.Encoderconvierte cada frame en un paquete. - Tu aplicación envía los paquetes. kolo-audio no envía nada.
- El
opus.Decoderconvierte cada paquete en muestras, oDecodeFECyDecodeLostcubren uno perdido. Writeencola las muestras en unOutput.
Dispositivos
Devices(kind)lista los dispositivos deCaptureoPlaybacky nunca abre uno. UnDevicetiene unIDopaco, unName, suKindyDefault, 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.DeviceIDelige 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 queDevicesno listó devuelveErrNoDevice.- Los dispositivos ALSA son PCM de hardware: no hay
dmixniplugpara compartir, y un dispositivo es exclusivo mientras está abierto. Un usuario de Linux necesita acceso a/dev/snd; si se le niega, el error envuelvefs.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
NSMicrophoneUsageDescriptionen suInfo.plist; con el hardened runtime también necesita el entitlementcom.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 entoncesRequestAccessno 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. AccessStatusdevuelve unAccess(AccessNotDetermined,AccessRestricted,AccessDeniedoAccessAuthorized) 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 envuelveErrPermissionyfs.ErrPermission. El aviso espera a la persona y no hay un timeout incorporado, así que acota la espera conctx: cuando termina,RequestAccessdevuelvectx.Err()y el aviso queda hasta que se responda. Ninguno abre un dispositivo. Sin consentimiento,OpenInputdevuelve un error que envuelveErrPermission,ErrBackendyfs.ErrPermission.- En Linux y Windows no hay un paso de consentimiento que leer ni pedir:
AccessStatusdevuelveAccessAuthorizedyRequestAccessdevuelve nil. Una negativa allí (la configuración de privacidad del micrófono de Windows, los permisos de/dev/snd) aparece cuandoOpenInputfalla con un error que envuelveErrPermissionyfs.ErrPermission. Donde no hay soporte de dispositivos, ambos devuelvenErrUnsupported. Devices,OpenInputyOpenOutputno 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.Formates el formato que ven tuReado tuWrite: 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 devuelveErrUnsupportedFormat.Readbloquea 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 enStats().Overruns; el hilo de audio nunca espera a la aplicación.Writeencola todas sus muestras y bloquea mientras el búfer está lleno. El dispositivo reproduce silencio hasta el primerWrite, y el silencio posterior por un búfer vacío se cuenta enStats().Underruns.Closedetiene y libera el dispositivo. Es idempotente, y las llamadas bloqueadas y las posteriores devuelvenErrClosed. 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
ReadyWriteposteriores conErrDeviceLost, y la captura en búfer se descarta. Abre un stream nuevo para seguir. Cambiar a un nuevo dispositivo predeterminado no es un error. InputyOutputson 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.Processdevuelve las muestras escritas y consumidas,Latencyes el retardo del filtro yFlushescribe la cola retenida.ConvertChannelscopia, duplica mono o promedia a mono.Gainescala en el lugar con saturación,Mixsuma con saturación yLeveldevuelve el pico y el RMS en dBFS.EncodeS16LEyDecodeS16LEconvierten 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,AudiooLowDelay), una tasa de bits de 500 a 512000 bit/s, una complejidad de 1 a 10, la corrección de errores hacia adelante (FEC) conPacketLossPercent,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).SetBitratey los demás setters cambian ajustes entre frames.Encode(pcm, out)recibe exactamenteFrameSize()muestras y devuelve la longitud del paquete. UnoutdePacketBufferSize(4000 bytes) siempre contiene un paquete.NewDecoder(sampleRate, channels)yDecode(packet, pcm): dimensionapcmparaMaxPacketDuration, 120 ms, para aceptar cualquier paquete.DecodeFEC(next, pcm)reconstruye un paquete perdido a partir del siguiente, yDecodeLost(pcm)lo disimula. En ambos,pcmdebe 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(oEncoder.SetCBR(true)) todos los paquetes de una duración de frame tienen la misma longitud,(bitrate * duración del frame + 4) / 8bytes (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 conCBRapagado no cambian. ManténDTXapagado con ella: DTX sigue sustituyendo el silencio por paquetes de 1 o 2 bytes, y eso delata cuándo alguien calla. Pasa aEncodeunoutde 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 queCBRapaga.
Plataformas
| Plataforma | Backend de dispositivos | Qué se ejecutó |
|---|---|---|
| macOS arm64 | CoreAudio con purego | Pruebas, 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 amd64 | igual | Binario de pruebas bajo Rosetta. Sin un Mac Intel nativo. |
| Windows arm64 | WASAPI con COM | Pruebas y enumeración real de endpoints en una VM de Windows 11 con dispositivos de sonido virtuales. Ningún stream abierto. |
| Windows amd64 | igual | Las mismas pruebas bajo la emulación x64 de la VM. |
| Linux, servidor de sonido | protocolo PulseAudio | Reproducir, grabar y retirar un dispositivo contra servidores reales en Docker, solo con un sink nulo. |
| Linux, sin servidor | interfaz ALSA del kernel | Enumeració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. |
| Cualquiera | Dispositivo nulo | Las 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.Periodde 10 ms,Config.Bufferde 120 ms (hasta 2 s) yConfig.StallTimeoutde 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
ErrInvalidPacketantes de llegar al códec, yDecodeFECyDecodeLostestá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/cookieo~/.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
dlopensolo 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 cargalibobjcal 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.
AccessStatusleyó el estado real en un Mac (autorizado).RequestAccesssolo 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
| Error | Mensaje |
|---|---|
ErrBackend | koloaudio: audio backend failed |
ErrClosed | koloaudio: closed |
ErrDeviceLost | koloaudio: device lost |
ErrInvalidArgument | koloaudio: invalid argument |
ErrInvalidConfig | koloaudio: invalid config |
ErrNoDevice | koloaudio: no such device |
ErrPermission | koloaudio: microphone access not granted |
ErrUnsupported | |
ErrUnsupportedFormat | koloaudio: unsupported format |
opus.ErrAllocFail | koloaudio: opus: allocation failed |
opus.ErrBufferTooSmall | koloaudio: opus: buffer too small |
opus.ErrClosed | koloaudio: opus: closed |
opus.ErrFrameSize | koloaudio: opus: invalid frame size |
opus.ErrInternal | koloaudio: opus: internal error |
opus.ErrInvalidArgument | koloaudio: opus: invalid argument |
opus.ErrInvalidConfig | koloaudio: opus: invalid config |
opus.ErrInvalidPacket | koloaudio: opus: invalid packet |
opus.ErrInvalidState | koloaudio: opus: invalid state |
opus.ErrUnimplemented | koloaudio: 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
- RFC 6716, Definition of the Opus Audio Codec (Proposed Standard, septiembre de 2012, actualizada por la RFC 8251).
- Toma: los límites de paquete (secciones 3.2.1 y 3.2.5), las frecuencias de muestreo y los canales.
- No implementa: nada.
- RFC 8251, Updates to the Opus Audio Codec (Proposed Standard, octubre de 2017).
- Toma: los vectores de prueba de conformidad.
- No implementa: nada.
- RFC 7587, RTP Payload Format for the Opus Speech and Audio Codec (Proposed Standard, junio de 2015).
- Toma: el reloj RTP de 48 kHz; los paquetes Opus se pueden llevar como su payload.
- No implementa: el empaquetado RTP.
- RFC 6562, Guidelines for the Use of Variable Bit Rate Audio with Secure RTP (Proposed Standard, marzo de 2012).
- Toma: bitrate constante contra las filtraciones por tamaño.
- No implementa: nada.