Documentation
¶
Overview ¶
Package gopus implements the Opus audio codec in pure Go.
It targets RFC 6716 compatibility with pinned libopus reference behavior, uses caller-owned buffers for the main encode/decode API, and requires no cgo dependency.
Quick Start ¶
Encoding:
enc, err := gopus.NewEncoder(gopus.EncoderConfig{
SampleRate: 48000,
Channels: 2,
Application: gopus.ApplicationAudio,
})
if err != nil {
log.Fatal(err)
}
pcm := make([]float32, 960*2) // 20 ms stereo at 48 kHz
packet := make([]byte, 4000)
nPacket, err := enc.Encode(pcm, packet)
if err != nil {
log.Fatal(err)
}
packet = packet[:nPacket]
Decoding:
cfg := gopus.DefaultDecoderConfig(48000, 2)
dec, err := gopus.NewDecoder(cfg)
if err != nil {
log.Fatal(err)
}
pcmOut := make([]float32, cfg.MaxPacketSamples*cfg.Channels)
n, err := dec.Decode(packet, pcmOut)
if err != nil {
log.Fatal(err)
}
pcmOut = pcmOut[:n*cfg.Channels]
PCM And Buffers ¶
Float32 samples are normalized to [-1.0, 1.0]. Int16 helpers are available for common audio APIs. Stereo and multichannel PCM is interleaved.
Decode output needs room for up to 5760 samples per channel, the default 120 ms cap at 48 kHz. A 4000-byte encode buffer is sufficient for any Opus packet.
Packet Loss ¶
Pass nil packet data to Decode to run packet loss concealment:
if packetLost {
n, err = dec.Decode(nil, pcmOut)
} else {
n, err = dec.Decode(packet, pcmOut)
}
Controls And Extensions ¶
Standard Opus controls such as bitrate, complexity, bandwidth, FEC, DTX, gain, frame size, packet parsing, and multistream helpers are exposed on the top-level types.
Optional extension support is build dependent. Use SupportsOptionalExtension before relying on an extension surface, and treat README.md as the support matrix source of truth.
if SupportsOptionalExtension(OptionalExtensionQEXT) {
_ = enc.SetQEXT(true)
}
Multistream ¶
NewMultistreamEncoderDefault and NewMultistreamDecoderDefault support 1-8 channels with the standard Vorbis-style channel mappings used by Ogg Opus. Use the explicit multistream constructors for custom mappings.
Package Boundaries ¶
The public surface is this top-level gopus package plus four importable packages: multistream (surround / ambisonics / projection), container/ogg (Ogg Opus read/write), container/red (RFC 2198 RTP RED), and types (shared Mode / Bandwidth / Signal enumerations). The top-level package re-exports the common multistream constructors, so most applications need only gopus and, if they handle files, container/ogg.
The SILK, CELT, Hybrid, range-coder, PLC, and DNN building blocks live under internal/ and are not importable; depend on the packages above instead.
Encoder and Decoder instances are not safe for concurrent use.
Example (RoundTrip) ¶
package main
import (
"fmt"
"log"
"math"
"github.com/thesyncim/gopus"
)
func main() {
// Complete encode-decode round trip
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 1, Application: gopus.ApplicationVoIP})
if err != nil {
log.Fatal(err)
}
cfg := gopus.DefaultDecoderConfig(48000, 1)
dec, err := gopus.NewDecoder(cfg)
if err != nil {
log.Fatal(err)
}
pcmOut := make([]float32, cfg.MaxPacketSamples*cfg.Channels)
// 20ms of mono audio at 48kHz
input := make([]float32, 960)
for i := range input {
input[i] = float32(math.Sin(float64(i) * 0.02))
}
// Encode
packetBuf := make([]byte, 4000)
nPacket, err := enc.Encode(input, packetBuf)
if err != nil {
log.Fatal(err)
}
// Decode
n, err := dec.Decode(packetBuf[:nPacket], pcmOut)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Round trip ok: %t\n", nPacket > 0 && n == len(input))
}
Output: Round trip ok: true
Index ¶
- Constants
- Variables
- func ConfigFromParams(mode Mode, bandwidth Bandwidth, frameSize int) int
- func ErrorString(code int) string
- func GenerateTOC(config uint8, stereo bool, frameCode uint8) byte
- func MultistreamPacketPad(data []byte, length, newLen, numStreams int) error
- func MultistreamPacketUnpad(data []byte, length, numStreams int) (int, error)
- func PCMSoftClip(pcm []float32, channels int, softclipMem []float32)
- func PacketHasLBRR(data []byte) bool
- func PacketPad(data []byte, length, newLen int) error
- func PacketUnpad(data []byte, length int) (int, error)
- func SupportsOptionalExtension(ext OptionalExtension) bool
- func ValidConfig(config uint8) bool
- func VersionString() string
- type Application
- type Bandwidth
- type BitrateMode
- type Decoder
- func (d *Decoder) Bandwidth() Bandwidth
- func (d *Decoder) Channels() int
- func (d *Decoder) Complexity() int
- func (d *Decoder) Decode(data []byte, pcm []float32) (int, error)
- func (d *Decoder) DecodeInt16(data []byte, pcm []int16) (int, error)
- func (d *Decoder) DecodeInt24(data []byte, pcm []int32) (int, error)
- func (d *Decoder) DecodeInt24Slice(data []byte) ([]int32, error)
- func (d *Decoder) DecodeWithFEC(data []byte, pcm []float32, fec bool) (int, error)
- func (d *Decoder) FinalRange() uint32
- func (d *Decoder) Gain() int
- func (d *Decoder) IgnoreExtensions() bool
- func (d *Decoder) InDTX() bool
- func (d *Decoder) LastPacketDuration() int
- func (d *Decoder) PhaseInversionDisabled() bool
- func (d *Decoder) Pitch() int
- func (d *Decoder) Reset()
- func (d *Decoder) SampleRate() int
- func (d *Decoder) SetComplexity(complexity int) error
- func (d *Decoder) SetDNNBlob(_ []byte) error
- func (d *Decoder) SetGain(gainQ8 int) error
- func (d *Decoder) SetIgnoreExtensions(ignore bool)
- func (d *Decoder) SetPhaseInversionDisabled(disabled bool)
- type DecoderConfig
- type Encoder
- func (e *Encoder) Application() Application
- func (e *Encoder) Bandwidth() Bandwidth
- func (e *Encoder) Bitrate() int
- func (e *Encoder) BitrateMode() BitrateMode
- func (e *Encoder) Channels() int
- func (e *Encoder) Complexity() int
- func (e *Encoder) DTXEnabled() bool
- func (e *Encoder) Encode(pcm []float32, data []byte) (int, error)
- func (e *Encoder) EncodeFloat32(pcm []float32) ([]byte, error)
- func (e *Encoder) EncodeInt16(pcm []int16, data []byte) (int, error)
- func (e *Encoder) EncodeInt16Slice(pcm []int16) ([]byte, error)
- func (e *Encoder) EncodeInt24(pcm []int32, data []byte) (int, error)
- func (e *Encoder) EncodeInt24Slice(pcm []int32) ([]byte, error)
- func (e *Encoder) ExpertFrameDuration() ExpertFrameDuration
- func (e *Encoder) FECEnabled() bool
- func (e *Encoder) FinalRange() uint32
- func (e *Encoder) ForceChannels() int
- func (e *Encoder) FrameSize() int
- func (e *Encoder) InBandFEC() int
- func (e *Encoder) InDTX() bool
- func (e *Encoder) LSBDepth() int
- func (e *Encoder) Lookahead() int
- func (e *Encoder) MaxBandwidth() Bandwidth
- func (e *Encoder) Mode() EncoderMode
- func (e *Encoder) PacketLoss() int
- func (e *Encoder) PhaseInversionDisabled() bool
- func (e *Encoder) PredictionDisabled() bool
- func (e *Encoder) Reset()
- func (e *Encoder) SampleRate() int
- func (e *Encoder) SetApplication(application Application) error
- func (e *Encoder) SetBandwidth(bandwidth Bandwidth) error
- func (e *Encoder) SetBandwidthAuto() error
- func (e *Encoder) SetBitrate(bitrate int) error
- func (e *Encoder) SetBitrateMode(mode BitrateMode) error
- func (e *Encoder) SetComplexity(complexity int) error
- func (e *Encoder) SetDNNBlob(_ []byte) error
- func (e *Encoder) SetDTX(enabled bool)
- func (e *Encoder) SetExpertFrameDuration(duration ExpertFrameDuration) error
- func (e *Encoder) SetFEC(enabled bool)
- func (e *Encoder) SetForceChannels(channels int) error
- func (e *Encoder) SetFrameSize(samples int) error
- func (e *Encoder) SetInBandFEC(config int) error
- func (e *Encoder) SetLSBDepth(depth int) error
- func (e *Encoder) SetMaxBandwidth(bandwidth Bandwidth) error
- func (e *Encoder) SetMode(mode EncoderMode) error
- func (e *Encoder) SetPacketLoss(lossPercent int) error
- func (e *Encoder) SetPhaseInversionDisabled(disabled bool)
- func (e *Encoder) SetPredictionDisabled(disabled bool)
- func (e *Encoder) SetSignal(signal Signal) error
- func (e *Encoder) SetVBR(enabled bool)
- func (e *Encoder) SetVBRConstraint(constrained bool)
- func (e *Encoder) Signal() Signal
- func (e *Encoder) VADActivity() int
- func (e *Encoder) VBR() bool
- func (e *Encoder) VBRConstraint() bool
- type EncoderConfig
- type EncoderMode
- type ExpertFrameDuration
- type Mode
- type MultistreamDecoder
- func (d *MultistreamDecoder) Bandwidth() Bandwidth
- func (d *MultistreamDecoder) Channels() int
- func (d *MultistreamDecoder) Complexity() int
- func (d *MultistreamDecoder) CoupledStreams() int
- func (d *MultistreamDecoder) Decode(data []byte, pcm []float32) (int, error)
- func (d *MultistreamDecoder) DecodeInt16(data []byte, pcm []int16) (int, error)
- func (d *MultistreamDecoder) DecodeInt24(data []byte, pcm []int32) (int, error)
- func (d *MultistreamDecoder) DecodeInt24Slice(data []byte) ([]int32, error)
- func (d *MultistreamDecoder) FinalRange() uint32
- func (d *MultistreamDecoder) Gain() int
- func (d *MultistreamDecoder) GetFinalRange() uint32
- func (d *MultistreamDecoder) IgnoreExtensions() bool
- func (d *MultistreamDecoder) LastPacketDuration() int
- func (d *MultistreamDecoder) PhaseInversionDisabled() bool
- func (d *MultistreamDecoder) Reset()
- func (d *MultistreamDecoder) SampleRate() int
- func (d *MultistreamDecoder) SetComplexity(complexity int) error
- func (d *MultistreamDecoder) SetDNNBlob(_ []byte) error
- func (d *MultistreamDecoder) SetGain(gainQ8 int) error
- func (d *MultistreamDecoder) SetIgnoreExtensions(ignore bool)
- func (d *MultistreamDecoder) SetPhaseInversionDisabled(disabled bool)
- func (d *MultistreamDecoder) Streams() int
- type MultistreamEncoder
- func (e *MultistreamEncoder) Application() Application
- func (e *MultistreamEncoder) Bandwidth() Bandwidth
- func (e *MultistreamEncoder) Bitrate() int
- func (e *MultistreamEncoder) BitrateMode() BitrateMode
- func (e *MultistreamEncoder) Channels() int
- func (e *MultistreamEncoder) Complexity() int
- func (e *MultistreamEncoder) CoupledStreams() int
- func (e *MultistreamEncoder) DTXEnabled() bool
- func (e *MultistreamEncoder) Encode(pcm []float32, data []byte) (int, error)
- func (e *MultistreamEncoder) EncodeFloat32(pcm []float32) ([]byte, error)
- func (e *MultistreamEncoder) EncodeInt16(pcm []int16, data []byte) (int, error)
- func (e *MultistreamEncoder) EncodeInt16Slice(pcm []int16) ([]byte, error)
- func (e *MultistreamEncoder) EncodeInt24(pcm []int32, data []byte) (int, error)
- func (e *MultistreamEncoder) EncodeInt24Slice(pcm []int32) ([]byte, error)
- func (e *MultistreamEncoder) ExpertFrameDuration() ExpertFrameDuration
- func (e *MultistreamEncoder) FECEnabled() bool
- func (e *MultistreamEncoder) FinalRange() uint32
- func (e *MultistreamEncoder) ForceChannels() int
- func (e *MultistreamEncoder) FrameSize() int
- func (e *MultistreamEncoder) GetFinalRange() uint32
- func (e *MultistreamEncoder) InBandFEC() int
- func (e *MultistreamEncoder) LSBDepth() int
- func (e *MultistreamEncoder) Lookahead() int
- func (e *MultistreamEncoder) MaxBandwidth() Bandwidth
- func (e *MultistreamEncoder) Mode() EncoderMode
- func (e *MultistreamEncoder) PacketLoss() int
- func (e *MultistreamEncoder) PhaseInversionDisabled() bool
- func (e *MultistreamEncoder) PredictionDisabled() bool
- func (e *MultistreamEncoder) Reset()
- func (e *MultistreamEncoder) SampleRate() int
- func (e *MultistreamEncoder) SetApplication(application Application) error
- func (e *MultistreamEncoder) SetBandwidth(bw Bandwidth) error
- func (e *MultistreamEncoder) SetBandwidthAuto() error
- func (e *MultistreamEncoder) SetBitrate(bitrate int) error
- func (e *MultistreamEncoder) SetBitrateMode(mode BitrateMode) error
- func (e *MultistreamEncoder) SetComplexity(complexity int) error
- func (e *MultistreamEncoder) SetDNNBlob(_ []byte) error
- func (e *MultistreamEncoder) SetDTX(enabled bool)
- func (e *MultistreamEncoder) SetExpertFrameDuration(duration ExpertFrameDuration) error
- func (e *MultistreamEncoder) SetFEC(enabled bool)
- func (e *MultistreamEncoder) SetForceChannels(channels int) error
- func (e *MultistreamEncoder) SetFrameSize(samples int) error
- func (e *MultistreamEncoder) SetInBandFEC(config int) error
- func (e *MultistreamEncoder) SetLSBDepth(depth int) error
- func (e *MultistreamEncoder) SetMaxBandwidth(bw Bandwidth) error
- func (e *MultistreamEncoder) SetMode(mode EncoderMode) error
- func (e *MultistreamEncoder) SetPacketLoss(lossPercent int) error
- func (e *MultistreamEncoder) SetPhaseInversionDisabled(disabled bool)
- func (e *MultistreamEncoder) SetPredictionDisabled(disabled bool)
- func (e *MultistreamEncoder) SetSignal(signal Signal) error
- func (e *MultistreamEncoder) SetVBR(enabled bool)
- func (e *MultistreamEncoder) SetVBRConstraint(constrained bool)
- func (e *MultistreamEncoder) Signal() Signal
- func (e *MultistreamEncoder) Streams() int
- func (e *MultistreamEncoder) VBR() bool
- func (e *MultistreamEncoder) VBRConstraint() bool
- type OptionalExtension
- type PacketInfo
- type PacketReader
- type PacketSink
- type Reader
- type Repacketizer
- type SampleFormat
- type Signal
- type TOC
- type VAD
- type Writer
- func (w *Writer) Channels() int
- func (w *Writer) Close() error
- func (w *Writer) Flush() error
- func (w *Writer) Reset()
- func (w *Writer) SampleRate() int
- func (w *Writer) SetBitrate(bitrate int) error
- func (w *Writer) SetComplexity(complexity int) error
- func (w *Writer) SetDTX(enabled bool)
- func (w *Writer) SetFEC(enabled bool)
- func (w *Writer) Write(p []byte) (int, error)
Examples ¶
Constants ¶
const ( // SignalAuto lets the encoder detect the signal type automatically. SignalAuto = types.SignalAuto // SignalVoice hints that the input is speech, biasing toward SILK mode. SignalVoice = types.SignalVoice // SignalMusic hints that the input is music, biasing toward CELT mode. SignalMusic = types.SignalMusic )
const ( // BitrateModeVBR enables unconstrained variable bitrate mode. BitrateModeVBR = encoder.ModeVBR // BitrateModeCVBR enables constrained variable bitrate mode. BitrateModeCVBR = encoder.ModeCVBR // BitrateModeCBR enables constant bitrate mode. BitrateModeCBR = encoder.ModeCBR )
const ( // EncoderModeAuto lets the encoder choose the coding mode. EncoderModeAuto = encoder.ModeAuto // EncoderModeSILK forces SILK-only encoding where the application permits it. EncoderModeSILK = encoder.ModeSILK // EncoderModeHybrid forces hybrid SILK+CELT encoding where valid. EncoderModeHybrid = encoder.ModeHybrid // EncoderModeCELT forces CELT-only encoding. EncoderModeCELT = encoder.ModeCELT )
const ( // BitrateAuto lets the encoder pick the bitrate from the sample rate, // channel count, and application (libopus OPUS_AUTO). It is the default. BitrateAuto = encoder.BitrateAuto // BitrateMax tells the encoder to use as many bits as the output buffer // allows for each frame (libopus OPUS_BITRATE_MAX). BitrateMax = encoder.BitrateMax )
const ( // InBandFECDisabled turns in-band forward error correction off (value 0). InBandFECDisabled = encoder.InBandFECDisabled // InBandFECEnabled enables in-band FEC for all signal types (value 1). InBandFECEnabled = encoder.InBandFECEnabled // InBandFECMusicSafe enables in-band FEC only for speech-like content, // leaving music frames untouched (value 2). InBandFECMusicSafe = encoder.InBandFECMusicSafe )
In-band FEC modes for SetInBandFEC. These mirror the libopus OPUS_SET_INBAND_FEC values.
const ( // ModeSILK is the SILK-only mode, used for speech (TOC configs 0-11). ModeSILK = types.ModeSILK // ModeHybrid is the hybrid SILK+CELT mode, used for wideband speech and // music (TOC configs 12-15). ModeHybrid = types.ModeHybrid // ModeCELT is the CELT-only mode, used for music and low delay (TOC configs // 16-31). ModeCELT = types.ModeCELT )
Opus coding modes, re-exported from the types package. Each TOC configuration (0-31) maps to exactly one mode per RFC 6716 Section 3.1.
const ( // BandwidthNarrowband covers audio up to 4 kHz (8 kHz internal rate). BandwidthNarrowband = types.BandwidthNarrowband // BandwidthMediumband covers audio up to 6 kHz (12 kHz internal rate). BandwidthMediumband = types.BandwidthMediumband // BandwidthWideband covers audio up to 8 kHz (16 kHz internal rate). BandwidthWideband = types.BandwidthWideband // BandwidthSuperwideband covers audio up to 12 kHz (24 kHz internal rate). BandwidthSuperwideband = types.BandwidthSuperwideband // BandwidthFullband covers audio up to 20 kHz (48 kHz internal rate). BandwidthFullband = types.BandwidthFullband )
Opus audio bandwidths, re-exported from the types package. The bandwidth sets the upper edge of the coded spectrum; each is paired with a nominal internal sample rate.
Variables ¶
var ( // ErrInvalidSampleRate indicates a sample rate outside the Opus API set. // Valid sample rates are: 8000, 12000, 16000, 24000, 48000. ErrInvalidSampleRate = errors.New("gopus: invalid sample rate (must be 8000, 12000, 16000, 24000, or 48000)") // ErrInvalidChannels indicates an invalid channel count. // See the relevant constructor or control for the supported range. ErrInvalidChannels = errors.New("gopus: invalid channels") // ErrInvalidSampleFormat indicates an invalid streaming PCM format. ErrInvalidSampleFormat = errors.New("gopus: invalid sample format") // ErrInvalidMaxPacketSamples indicates an invalid max packet sample cap. ErrInvalidMaxPacketSamples = errors.New("gopus: invalid max packet samples (must be > 0)") // ErrInvalidMaxPacketBytes indicates an invalid max packet size cap. ErrInvalidMaxPacketBytes = errors.New("gopus: invalid max packet bytes (must be > 0)") // ErrPacketTooLarge indicates the packet exceeds configured limits. ErrPacketTooLarge = errors.New("gopus: packet exceeds configured limits") // ErrBufferTooSmall indicates the output buffer is too small for the decoded frame. // The buffer must be at least frameSize * channels samples. ErrBufferTooSmall = errors.New("gopus: output buffer too small") // ErrInvalidFrameSize indicates the input frame size doesn't match expected. // The PCM input length must be frameSize * channels. ErrInvalidFrameSize = errors.New("gopus: invalid frame size") // ErrInvalidBitrate indicates the bitrate is out of valid range. // See the relevant constructor or control for the supported range. ErrInvalidBitrate = errors.New("gopus: invalid bitrate") // ErrInvalidBitrateMode indicates an invalid bitrate mode. // Valid modes are BitrateModeVBR, BitrateModeCVBR, and BitrateModeCBR. ErrInvalidBitrateMode = errors.New("gopus: invalid bitrate mode") // ErrInvalidComplexity indicates the complexity is out of valid range. // Valid complexity values are 0 to 10. ErrInvalidComplexity = errors.New("gopus: invalid complexity (must be 0-10)") // ErrInvalidApplication indicates an invalid application hint. // Valid values include the standard application hints plus the restricted // libopus-compatible init-time hints. ErrInvalidApplication = errors.New("gopus: invalid application") // ErrInvalidPacketLoss indicates an invalid packet loss percentage. // Valid range is 0 to 100. ErrInvalidPacketLoss = errors.New("gopus: invalid packet loss percentage (must be 0-100)") // ErrInvalidFECConfig indicates an invalid in-band FEC configuration. ErrInvalidFECConfig = errors.New("gopus: invalid in-band FEC config") // ErrInvalidStreams indicates an invalid stream count for multistream encoding/decoding. // Valid stream counts are 1 to 255. ErrInvalidStreams = errors.New("gopus: invalid stream count (must be 1-255)") // ErrInvalidCoupledStreams indicates an invalid coupled streams count. // Coupled streams must be between 0 and total streams. ErrInvalidCoupledStreams = errors.New("gopus: invalid coupled streams (must be 0 to streams)") // ErrInvalidStreamIndex indicates a per-stream state lookup used an out-of-range index. ErrInvalidStreamIndex = errors.New("gopus: invalid stream index") // ErrInvalidMapping indicates an invalid channel mapping table. // The mapping table length must equal the channel count. ErrInvalidMapping = errors.New("gopus: invalid mapping table") // ErrInvalidBandwidth indicates an invalid bandwidth for the current mode. // For SILK-only mode, only NB, MB, and WB are valid (not SWB or FB). ErrInvalidBandwidth = errors.New("gopus: invalid bandwidth for mode") // ErrInvalidSignal indicates an invalid signal type hint. // Valid values are SignalAuto, SignalVoice, or SignalMusic. ErrInvalidSignal = errors.New("gopus: invalid signal type (must be SignalAuto, SignalVoice, or SignalMusic)") // ErrInvalidLSBDepth indicates an invalid LSB depth. // Valid range is 8 to 24 bits. ErrInvalidLSBDepth = errors.New("gopus: invalid LSB depth (must be 8-24)") // ErrInvalidForceChannels indicates an invalid force channels value. // Valid values are -1 (auto), 1 (mono), or 2 (stereo). ErrInvalidForceChannels = errors.New("gopus: invalid force channels (must be -1, 1, or 2)") // ErrInvalidArgument indicates one or more function arguments are invalid. ErrInvalidArgument = errors.New("gopus: invalid argument") // ErrNilPacketReader indicates a nil PacketReader was supplied to NewReader. ErrNilPacketReader = errors.New("gopus: nil packet reader") // ErrNilPacketSink indicates a nil PacketSink was supplied to NewWriter. ErrNilPacketSink = errors.New("gopus: nil packet sink") // ErrInvalidGain indicates an invalid decoder gain value. // Valid range is -32768 to 32767 (Q8 dB). ErrInvalidGain = errors.New("gopus: invalid gain (must be -32768 to 32767)") // build-time extension is not enabled in the current gopus build. ErrOptionalExtensionUnavailable = errors.New("gopus: optional extension unavailable in this build") // ErrUnimplemented indicates the requested functionality is not implemented yet. ErrUnimplemented = errors.New("gopus: feature not implemented") )
Public error types for encoding and decoding operations.
var ( // ErrPacketTooShort indicates the packet is missing bytes required to parse // its TOC, frame-count, length, or padding fields. ErrPacketTooShort = errors.New("gopus: packet too short") // ErrInvalidFrameCount indicates a code 3 packet declared a frame count // outside the valid 1-48 range (RFC 6716 Section 3.2.5). ErrInvalidFrameCount = errors.New("gopus: invalid frame count (M > 48)") // ErrInvalidPacket indicates the packet violates the RFC 6716 framing rules, // for example inconsistent frame lengths or a total duration above 120 ms. ErrInvalidPacket = errors.New("gopus: invalid packet structure") )
Errors returned by packet parsing functions.
Functions ¶
func ConfigFromParams ¶
ConfigFromParams returns the config index for given mode, bandwidth, and frame size. Returns -1 if the combination is invalid.
func ErrorString ¶
ErrorString returns a human-readable string for an Opus error code.
It mirrors opus_strerror() from celt/celt.c in libopus 1.6.1. The mapping for codes 0 through -7 is identical to libopus. Codes outside [-7, 0] return "unknown error".
Standard Opus error codes:
0 success -1 invalid argument -2 buffer too small -3 internal error -4 corrupted stream -5 request not implemented -6 invalid state -7 memory allocation failed
func GenerateTOC ¶
GenerateTOC creates a TOC byte from encoding parameters. config: Configuration index 0-31 (from configTable) stereo: True for stereo, false for mono frameCode: Frame count code 0-3
0: 1 frame 1: 2 equal-sized frames 2: 2 different-sized frames 3: arbitrary number of frames
func MultistreamPacketPad ¶
MultistreamPacketPad pads the final stream packet inside a multistream packet.
func MultistreamPacketUnpad ¶
MultistreamPacketUnpad removes padding from all streams in a multistream packet. It returns the new packet length.
func PCMSoftClip ¶
PCMSoftClip applies soft clipping to interleaved float32 PCM samples in-place.
pcm holds N*channels interleaved samples. channels is the number of audio channels. softclipMem is per-channel state of length channels; pass a zero-initialized slice for the first call and reuse it across successive calls on the same stream.
This mirrors opus_pcm_soft_clip() / opus_pcm_soft_clip_impl() from src/opus.c and celt/celt.c in libopus 1.6.1.
func PacketHasLBRR ¶
PacketHasLBRR reports whether an Opus packet carries in-band LBRR data for FEC recovery. It mirrors libopus opus_packet_has_lbrr().
func PacketPad ¶
PacketPad pads a packet in-place to newLen bytes.
data must have capacity for at least newLen bytes. length is the current packet length in data.
func PacketUnpad ¶
PacketUnpad removes packet padding in-place and returns the new packet length.
func SupportsOptionalExtension ¶
func SupportsOptionalExtension(ext OptionalExtension) bool
SupportsOptionalExtension reports whether the current build makes ext part of the supported release surface for this build. Extra controls may be compiled for parity work while still reporting false here.
Example ¶
package main
import (
"fmt"
"github.com/thesyncim/gopus"
)
func main() {
fmt.Printf("dnn_blob: %v\n", gopus.SupportsOptionalExtension(gopus.OptionalExtensionDNNBlob))
fmt.Printf("dred: %v\n", gopus.SupportsOptionalExtension(gopus.OptionalExtensionDRED))
fmt.Printf("osce_bwe: %v\n", gopus.SupportsOptionalExtension(gopus.OptionalExtensionOSCEBWE))
fmt.Printf("qext: %v\n", gopus.SupportsOptionalExtension(gopus.OptionalExtensionQEXT))
}
Output: dnn_blob: false dred: false osce_bwe: false qext: false
func ValidConfig ¶
ValidConfig returns true if the configuration index is valid.
func VersionString ¶
func VersionString() string
VersionString returns a human-readable version string for the gopus library.
The returned string identifies gopus, not libopus. It is analogous to opus_get_version_string() from celt/celt.c in libopus 1.6.1, which returns "libopus <version>". Applications that need to detect libopus at runtime should not use this function; it will not contain the substring "libopus".
Types ¶
type Application ¶
type Application int
Application hints the encoder for optimization.
const ( // ApplicationVoIP optimizes for speech transmission with low latency. // Prefers SILK mode for speech frequencies. ApplicationVoIP Application = iota // ApplicationAudio optimizes for music and high-quality audio. // Prefers CELT/Hybrid mode for full-bandwidth audio. ApplicationAudio // ApplicationLowDelay minimizes algorithmic delay. // Uses CELT mode exclusively with small frame sizes. ApplicationLowDelay // ApplicationRestrictedSilk forces SILK-only encoding. // This matches libopus OPUS_APPLICATION_RESTRICTED_SILK init-time behavior. ApplicationRestrictedSilk // ApplicationRestrictedCelt forces CELT-only encoding with low-delay semantics. // This matches libopus OPUS_APPLICATION_RESTRICTED_CELT init-time behavior. ApplicationRestrictedCelt )
type BitrateMode ¶
type BitrateMode = encoder.BitrateMode
BitrateMode controls how the encoder sizes packets.
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
Decoder decodes Opus packets into PCM audio samples.
A Decoder instance maintains internal state and is NOT safe for concurrent use. Each goroutine should create its own Decoder instance.
The decoder supports all Opus modes (SILK, Hybrid, CELT) and automatically detects the mode from the TOC byte in each packet.
func NewDecoder ¶
func NewDecoder(cfg DecoderConfig) (*Decoder, error)
NewDecoder creates a new Opus decoder.
Example ¶
package main
import (
"fmt"
"log"
"github.com/thesyncim/gopus"
)
func main() {
// Create a decoder for 48kHz stereo audio
dec, err := gopus.NewDecoder(gopus.DefaultDecoderConfig(48000, 2))
if err != nil {
log.Fatal(err)
}
fmt.Printf("Decoder: %dHz, %d channels\n", dec.SampleRate(), dec.Channels())
}
Output: Decoder: 48000Hz, 2 channels
func (*Decoder) Bandwidth ¶
Bandwidth returns the bandwidth of the last successfully decoded packet.
Returns 0 before any non-PLC packet has been decoded, matching libopus OPUS_GET_BANDWIDTH which returns st->bandwidth (zeroed by OPUS_CLEAR at init and after OPUS_RESET_STATE).
C ref: opus_decoder.c OPUS_GET_BANDWIDTH_REQUEST → "*value = st->bandwidth"
func (*Decoder) Complexity ¶
Complexity returns the current decoder complexity setting.
func (*Decoder) Decode ¶
Decode decodes an Opus packet into float32 PCM samples.
data: Opus packet data, or nil for Packet Loss Concealment (PLC). pcm: Output buffer for decoded samples. Must be large enough to hold frameSize * frameCount * channels samples, where frameSize and frameCount are determined from the packet TOC and frame code.
Returns the number of samples per channel decoded, or an error.
When data is nil, the decoder performs packet loss concealment using the last successfully decoded frame parameters. Before the first packet has been decoded, cold PLC returns zeroed audio and a nil error.
Buffer sizing: For 60ms frames at 48kHz stereo, pcm must have at least 2880 * 2 = 5760 elements. For multi-frame packets (code 1/2/3), the buffer must be large enough for all frames combined.
Multi-frame packets (RFC 6716 Section 3.2):
- Code 0: 1 frame (most common)
- Code 1: 2 equal-sized frames
- Code 2: 2 different-sized frames
- Code 3: Arbitrary number of frames (1-48)
Example ¶
package main
import (
"fmt"
"log"
"github.com/thesyncim/gopus"
)
func main() {
// Create encoder and decoder
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
cfg := gopus.DefaultDecoderConfig(48000, 2)
dec, err := gopus.NewDecoder(cfg)
if err != nil {
log.Fatal(err)
}
pcmOut := make([]float32, cfg.MaxPacketSamples*cfg.Channels)
// Encode one 20ms stereo frame.
pcm := make([]float32, 960*2)
packetBuf := make([]byte, 4000)
nPacket, err := enc.Encode(pcm, packetBuf)
if err != nil {
log.Fatal(err)
}
// Decode the packet
n, err := dec.Decode(packetBuf[:nPacket], pcmOut)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Decoded %d samples per channel\n", n)
}
Output: Decoded 960 samples per channel
Example (PacketLoss) ¶
package main
import (
"fmt"
"log"
"github.com/thesyncim/gopus"
)
func main() {
cfg := gopus.DefaultDecoderConfig(48000, 2)
dec, err := gopus.NewDecoder(cfg)
if err != nil {
log.Fatal(err)
}
pcmOut := make([]float32, cfg.MaxPacketSamples*cfg.Channels)
// First, decode a real packet to initialize state
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
pcm := make([]float32, 960*2)
packetBuf := make([]byte, 4000)
nPacket, err := enc.Encode(pcm, packetBuf)
if err != nil {
log.Fatal(err)
}
if _, err := dec.Decode(packetBuf[:nPacket], pcmOut); err != nil {
log.Fatal(err)
}
// Simulate packet loss by passing nil. Request one frame of PLC output
// (buffer sized to the last packet duration, matching libopus frame_size).
plcBuf := make([]float32, 960*cfg.Channels)
n, err := dec.Decode(nil, plcBuf)
if err != nil {
log.Fatal(err)
}
fmt.Printf("PLC generated %d samples per channel\n", n)
}
Output: PLC generated 960 samples per channel
func (*Decoder) DecodeInt16 ¶
DecodeInt16 decodes an Opus packet into int16 PCM samples.
func (*Decoder) DecodeInt24 ¶
DecodeInt24 decodes an Opus packet into 24-bit PCM samples stored in int32.
data: Opus packet data, or nil for Packet Loss Concealment (PLC). pcm: Output buffer for decoded samples. Each element carries a signed 24-bit value in the range [-8388608, 8388607] (= ±2^23), right-justified in int32 — the same convention as libopus opus_decode24().
Returns the number of samples per channel decoded, or an error.
func (*Decoder) DecodeInt24Slice ¶
DecodeInt24Slice decodes an Opus packet into 24-bit PCM samples and returns a new int32 slice. Each element carries a right-justified signed 24-bit value.
This is a convenience method that allocates the output buffer. For performance-critical code, use DecodeInt24 with a pre-allocated buffer.
func (*Decoder) DecodeWithFEC ¶
DecodeWithFEC decodes an Opus packet, optionally recovering a lost frame using FEC.
This mirrors libopus decode_fec semantics: when fec is true, the decoder uses in-band LBRR data if present and otherwise falls back to packet loss concealment instead of returning a missing-FEC error.
func (*Decoder) FinalRange ¶
FinalRange returns the final range coder state after decoding. This matches libopus OPUS_GET_FINAL_RANGE and is used for bitstream verification. Must be called after Decode() to get a meaningful value.
Per libopus, the final range is XORed with any redundancy frame's range. If the packet length was <= 1, FinalRange returns 0.
func (*Decoder) IgnoreExtensions ¶
IgnoreExtensions reports whether unknown packet extensions are ignored.
func (*Decoder) LastPacketDuration ¶
LastPacketDuration returns the duration in samples per channel at the decoder API rate.
func (*Decoder) PhaseInversionDisabled ¶
PhaseInversionDisabled reports whether CELT stereo phase inversion is disabled.
func (*Decoder) Reset ¶
func (d *Decoder) Reset()
Reset clears the decoder state for a new stream. Call this when starting to decode a new audio stream.
func (*Decoder) SampleRate ¶
SampleRate returns the sample rate in Hz.
func (*Decoder) SetComplexity ¶
SetComplexity sets decoder complexity (0-10).
func (*Decoder) SetDNNBlob ¶
SetDNNBlob reports that USE_WEIGHTS_FILE model loading is unavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable the model-loading control.
func (*Decoder) SetGain ¶
SetGain sets output gain in Q8 dB units (libopus OPUS_SET_GAIN semantics).
Valid range is [-32768, 32767], where 256 = +1 dB and -256 = -1 dB.
func (*Decoder) SetIgnoreExtensions ¶
SetIgnoreExtensions toggles whether unknown packet extensions should be ignored.
This mirrors libopus OPUS_SET_IGNORE_EXTENSIONS semantics.
func (*Decoder) SetPhaseInversionDisabled ¶
SetPhaseInversionDisabled toggles CELT stereo phase inversion during decoding.
type DecoderConfig ¶
type DecoderConfig struct {
// SampleRate must be one of: 8000, 12000, 16000, 24000, 48000.
SampleRate int
// Channels must be 1 (mono) or 2 (stereo).
Channels int
// MaxPacketSamples caps the maximum decoded samples per channel per packet.
// If zero, defaultMaxPacketSamples is used.
MaxPacketSamples int
// MaxPacketBytes caps the maximum Opus packet size in bytes.
// If zero, defaultMaxPacketBytes is used.
MaxPacketBytes int
}
DecoderConfig configures a Decoder instance.
func DefaultDecoderConfig ¶
func DefaultDecoderConfig(sampleRate, channels int) DecoderConfig
DefaultDecoderConfig returns a config with default caps for the given stream format.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder encodes PCM audio samples into Opus packets.
An Encoder instance maintains internal state and is NOT safe for concurrent use. Each goroutine should create its own Encoder instance.
The encoder supports three modes:
- SILK: optimized for speech at lower bitrates
- CELT: optimized for music and high-quality audio
- Hybrid: combines SILK and CELT for wideband speech
The mode is automatically selected based on the Application hint and bandwidth settings.
Zero-allocation design: All scratch buffers are pre-allocated at construction time. The Encode and EncodeInt16 methods perform zero heap allocations in the hot path when called with properly sized caller-provided buffers.
func NewEncoder ¶
func NewEncoder(cfg EncoderConfig) (*Encoder, error)
NewEncoder creates a new Opus encoder.
Returns an error if the config is invalid.
Example ¶
package main
import (
"fmt"
"log"
"github.com/thesyncim/gopus"
)
func main() {
// Create an encoder for 48kHz stereo audio
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
// Configure encoder settings
enc.SetBitrate(64000) // 64 kbps
enc.SetComplexity(10) // Maximum quality
fmt.Printf("Encoder: %dHz, %d channels\n", enc.SampleRate(), enc.Channels())
}
Output: Encoder: 48000Hz, 2 channels
func (*Encoder) Application ¶
func (e *Encoder) Application() Application
Application returns the current encoder application hint.
func (*Encoder) BitrateMode ¶
func (e *Encoder) BitrateMode() BitrateMode
BitrateMode returns the active encoder bitrate control mode.
func (*Encoder) Complexity ¶
Complexity returns the current complexity setting.
func (*Encoder) DTXEnabled ¶
DTXEnabled returns whether DTX is enabled.
func (*Encoder) Encode ¶
Encode encodes float32 PCM samples into an Opus packet.
pcm: Input samples (interleaved if stereo). Length must be frameSize * channels. data: Output buffer for the encoded packet. Recommended size is 4000 bytes.
Returns the number of bytes written to data, or an error. When DTX is active during silence, returns a 1-byte TOC-only packet. Returns 0 bytes only when buffering (internal lookahead not yet filled).
Buffer sizing: 4000 bytes is sufficient for any Opus packet.
Example ¶
package main
import (
"fmt"
"log"
"github.com/thesyncim/gopus"
)
func main() {
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
// Generate 20ms of stereo silence (960 samples per channel)
pcm := make([]float32, 960*2)
packetBuf := make([]byte, 4000)
// Encode the frame
n, err := enc.Encode(pcm, packetBuf)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Encoded %d PCM samples into packet: %t\n", len(pcm)/enc.Channels(), n > 0)
}
Output: Encoded 960 PCM samples into packet: true
func (*Encoder) EncodeFloat32 ¶
EncodeFloat32 encodes float32 PCM samples and returns a new byte slice.
This is a convenience method that allocates the output buffer. For performance-critical code, use Encode with a pre-allocated buffer.
pcm: Input samples (interleaved if stereo).
Returns the encoded packet or an error.
func (*Encoder) EncodeInt16 ¶
EncodeInt16 encodes int16 PCM samples into an Opus packet.
pcm: Input samples (interleaved if stereo). Length must be frameSize * channels. data: Output buffer for the encoded packet.
Returns the number of bytes written to data, or an error.
The samples are converted from int16 by dividing by 32768.
func (*Encoder) EncodeInt16Slice ¶
EncodeInt16Slice encodes int16 PCM samples and returns a new byte slice.
This is a convenience method that allocates the output buffer. For performance-critical code, use EncodeInt16 with a pre-allocated buffer.
pcm: Input samples (interleaved if stereo).
Returns the encoded packet or an error.
func (*Encoder) EncodeInt24 ¶
EncodeInt24 encodes 24-bit PCM samples stored in int32 values into an Opus packet.
pcm: Input samples (interleaved if stereo). Length must be frameSize * channels. data: Output buffer for the encoded packet.
Returns the number of bytes written to data, or an error.
The input values are interpreted with the same semantics as libopus opus_encode24(): right-justified signed 24-bit PCM carried in int32 containers with numeric range [-8388608, 8388607]. Left-shifted 24-in-32 input will be mis-scaled.
func (*Encoder) EncodeInt24Slice ¶
EncodeInt24Slice encodes 24-bit PCM samples stored in int32 values and returns a new byte slice.
This is a convenience method that allocates the output buffer. For performance-critical code, use EncodeInt24 with a pre-allocated buffer.
func (*Encoder) ExpertFrameDuration ¶
func (e *Encoder) ExpertFrameDuration() ExpertFrameDuration
ExpertFrameDuration returns the current expert frame duration policy.
func (*Encoder) FECEnabled ¶
FECEnabled returns whether FEC is enabled.
func (*Encoder) FinalRange ¶
FinalRange returns the final range coder state after encoding. This matches libopus OPUS_GET_FINAL_RANGE and is used for bitstream verification. Must be called after Encode() to get a meaningful value.
func (*Encoder) ForceChannels ¶
ForceChannels returns the forced channel count (-1 = auto).
func (*Encoder) FrameSize ¶
FrameSize returns the current frame size in samples at the API sample rate. At 96 kHz, this is 2x the 48 kHz internal frame size.
func (*Encoder) InDTX ¶
InDTX reports whether the encoder is currently in DTX mode.
This matches libopus OPUS_GET_IN_DTX semantics.
func (*Encoder) Lookahead ¶
Lookahead returns the encoder's algorithmic delay in samples.
Matches libopus OPUS_GET_LOOKAHEAD behavior:
- Base lookahead is Fs/400 (2.5ms)
- Delay compensation Fs/250 is included for VoIP/Audio
- Delay compensation is omitted for LowDelay
func (*Encoder) MaxBandwidth ¶
MaxBandwidth returns the current maximum bandwidth limit.
func (*Encoder) Mode ¶
func (e *Encoder) Mode() EncoderMode
Mode returns the current forced coding mode.
func (*Encoder) PacketLoss ¶
PacketLoss returns the configured expected packet loss percentage.
func (*Encoder) PhaseInversionDisabled ¶
PhaseInversionDisabled returns whether stereo phase inversion is disabled.
func (*Encoder) PredictionDisabled ¶
PredictionDisabled returns whether inter-frame prediction is disabled.
func (*Encoder) Reset ¶
func (e *Encoder) Reset()
Reset clears the encoder state for a new stream. Call this when starting to encode a new audio stream.
func (*Encoder) SampleRate ¶
SampleRate returns the sample rate in Hz.
func (*Encoder) SetApplication ¶
func (e *Encoder) SetApplication(application Application) error
SetApplication updates the encoder application hint.
Valid values are ApplicationVoIP, ApplicationAudio, and ApplicationLowDelay.
func (*Encoder) SetBandwidth ¶
SetBandwidth sets the target audio bandwidth.
func (*Encoder) SetBandwidthAuto ¶
SetBandwidthAuto restores automatic bandwidth selection.
func (*Encoder) SetBitrate ¶
SetBitrate sets the target bitrate in bits per second.
Positive bitrates are clamped to the libopus range. Returns ErrInvalidBitrate for non-positive non-sentinel values.
Example ¶
package main
import (
"fmt"
"log"
"github.com/thesyncim/gopus"
)
func main() {
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
// Set bitrate to 128 kbps
err = enc.SetBitrate(128000)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Bitrate set to %d bps\n", enc.Bitrate())
}
Output: Bitrate set to 128000 bps
func (*Encoder) SetBitrateMode ¶
func (e *Encoder) SetBitrateMode(mode BitrateMode) error
SetBitrateMode sets the encoder bitrate control mode.
func (*Encoder) SetComplexity ¶
SetComplexity sets the encoder's computational complexity.
complexity must be 0-10, where:
- 0-1: Minimal processing, fastest encoding
- 2-4: Basic analysis, good for real-time with limited CPU
- 5-7: Moderate analysis, balanced quality/speed
- 8-10: Thorough analysis, highest quality
Returns ErrInvalidComplexity if out of range.
Example ¶
package main
import (
"fmt"
"log"
"github.com/thesyncim/gopus"
)
func main() {
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
// Set complexity to maximum quality
err = enc.SetComplexity(10)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Complexity: %d\n", enc.Complexity())
}
Output: Complexity: 10
func (*Encoder) SetDNNBlob ¶
SetDNNBlob reports that USE_WEIGHTS_FILE model loading is unavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable the model-loading control.
func (*Encoder) SetDTX ¶
SetDTX enables or disables Discontinuous Transmission.
When enabled, the encoder reduces bitrate during silence by:
- Suppressing packets entirely during silence
- Sending periodic comfort noise frames
DTX is useful for VoIP applications to reduce bandwidth.
Example ¶
package main
import (
"fmt"
"log"
"github.com/thesyncim/gopus"
)
func main() {
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 1, Application: gopus.ApplicationVoIP})
if err != nil {
log.Fatal(err)
}
// Enable DTX for bandwidth savings during silence
enc.SetDTX(true)
fmt.Printf("DTX enabled: %v\n", enc.DTXEnabled())
}
Output: DTX enabled: true
func (*Encoder) SetExpertFrameDuration ¶
func (e *Encoder) SetExpertFrameDuration(duration ExpertFrameDuration) error
SetExpertFrameDuration sets the preferred frame duration policy.
`ExpertFrameDurationArg` keeps using the current `FrameSize()` value. Fixed durations are applied during Encode when they fit within the current frame.
func (*Encoder) SetFEC ¶
SetFEC enables or disables in-band Forward Error Correction.
When enabled, the encoder includes redundant information for loss recovery. FEC is most effective when the receiver can request retransmission of lost packets.
Example ¶
package main
import (
"fmt"
"log"
"github.com/thesyncim/gopus"
)
func main() {
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationVoIP})
if err != nil {
log.Fatal(err)
}
// Enable FEC for packet loss recovery
enc.SetFEC(true)
fmt.Printf("FEC enabled: %v\n", enc.FECEnabled())
}
Output: FEC enabled: true
func (*Encoder) SetForceChannels ¶
SetForceChannels forces the encoder to use a specific channel count.
channels must be one of:
- -1: automatic (use input channels)
- 1: force mono output
- 2: force stereo output
Note: Forcing stereo on mono input will duplicate the channel. Forcing mono on stereo input will downmix to mono.
Returns ErrInvalidForceChannels if the value is not valid.
func (*Encoder) SetFrameSize ¶
SetFrameSize sets the frame size in samples at 48kHz.
Valid sizes depend on the encoding mode:
- SILK: 480, 960, 1920, 2880, 3840, 4800, 5760 (10-120 ms)
- CELT: 120, 240, 480, 960, 1920, 2880, 3840, 4800, 5760
- Hybrid: 480, 960, 1920, 2880, 3840, 4800, 5760
Default is 960 (20ms).
func (*Encoder) SetInBandFEC ¶
SetInBandFEC sets the libopus-compatible in-band FEC configuration.
func (*Encoder) SetLSBDepth ¶
SetLSBDepth sets the bit depth of the input signal.
depth must be 8-24. This affects DTX silence detection: lower bit depths have a higher noise floor, so the encoder adjusts its silence threshold accordingly.
Default is 24 (full precision). Returns ErrInvalidLSBDepth if out of range.
func (*Encoder) SetMaxBandwidth ¶
SetMaxBandwidth sets the maximum audio bandwidth.
The encoder will not use a bandwidth higher than this limit. This is useful for limiting bandwidth without changing the sample rate.
Valid values are:
- BandwidthNarrowband (4kHz)
- BandwidthMediumband (6kHz)
- BandwidthWideband (8kHz)
- BandwidthSuperwideband (12kHz)
- BandwidthFullband (20kHz)
func (*Encoder) SetMode ¶
func (e *Encoder) SetMode(mode EncoderMode) error
SetMode sets the encoder's forced coding mode.
func (*Encoder) SetPacketLoss ¶
SetPacketLoss sets the expected packet loss percentage.
lossPercent must be in the range [0, 100].
func (*Encoder) SetPhaseInversionDisabled ¶
SetPhaseInversionDisabled disables stereo phase inversion.
Phase inversion is a technique used to improve stereo decorrelation. Some audio processing pipelines may have issues with phase-inverted audio. Disabling it (true) ensures no phase inversion is applied.
Default is false (phase inversion enabled).
func (*Encoder) SetPredictionDisabled ¶
SetPredictionDisabled disables inter-frame prediction.
When disabled (true), each frame can be decoded independently, which improves error resilience at the cost of compression efficiency. This is useful for applications with high packet loss.
Default is false (prediction enabled).
func (*Encoder) SetSignal ¶
SetSignal sets the signal type hint for mode selection.
signal must be one of:
- SignalAuto: automatically detect signal type
- SignalVoice: optimize for speech (biases toward SILK)
- SignalMusic: optimize for music (biases toward CELT)
Returns ErrInvalidSignal if the value is not valid.
func (*Encoder) SetVBR ¶
SetVBR enables or disables VBR mode.
Disabling VBR switches to CBR. Enabling VBR restores VBR while preserving the current VBR constraint state.
func (*Encoder) SetVBRConstraint ¶
SetVBRConstraint enables or disables VBR constraint.
This setting is remembered even while VBR is disabled.
func (*Encoder) VADActivity ¶
VADActivity returns the current VAD speech activity level in Q8 (0-255).
func (*Encoder) VBRConstraint ¶
VBRConstraint returns whether VBR constraint is enabled.
type EncoderConfig ¶
type EncoderConfig struct {
// SampleRate must be one of: 8000, 12000, 16000, 24000, 48000.
SampleRate int
// Channels must be 1 (mono) or 2 (stereo).
Channels int
// Application hints the encoder for optimization.
Application Application
}
EncoderConfig configures an Encoder instance.
type EncoderMode ¶
EncoderMode controls the encoder's forced coding mode.
type ExpertFrameDuration ¶
type ExpertFrameDuration int
ExpertFrameDuration mirrors libopus OPUS_SET/GET_EXPERT_FRAME_DURATION values.
It selects the duration the encoder uses for each Opus frame, overriding the duration implied by the per-call sample count. A requested duration takes effect only when it fits within the samples passed to Encode; a longer duration than the input provides is rejected with ErrInvalidFrameSize. The numeric values match the libopus OPUS_FRAMESIZE_* constants.
const ( // ExpertFrameDurationArg keeps the frame duration implied by the per-call // sample count (libopus OPUS_FRAMESIZE_ARG). This is the default. ExpertFrameDurationArg ExpertFrameDuration = 5000 // ExpertFrameDuration2_5Ms forces 2.5 ms frames (CELT-capable modes only). ExpertFrameDuration2_5Ms ExpertFrameDuration = 5001 // ExpertFrameDuration5Ms forces 5 ms frames (CELT-capable modes only). ExpertFrameDuration5Ms ExpertFrameDuration = 5002 // ExpertFrameDuration10Ms forces 10 ms frames. ExpertFrameDuration10Ms ExpertFrameDuration = 5003 // ExpertFrameDuration20Ms forces 20 ms frames. ExpertFrameDuration20Ms ExpertFrameDuration = 5004 // ExpertFrameDuration40Ms forces 40 ms frames. ExpertFrameDuration40Ms ExpertFrameDuration = 5005 // ExpertFrameDuration60Ms forces 60 ms frames. ExpertFrameDuration60Ms ExpertFrameDuration = 5006 // ExpertFrameDuration80Ms forces 80 ms frames. ExpertFrameDuration80Ms ExpertFrameDuration = 5007 // ExpertFrameDuration100Ms forces 100 ms frames. ExpertFrameDuration100Ms ExpertFrameDuration = 5008 // ExpertFrameDuration120Ms forces 120 ms frames. ExpertFrameDuration120Ms ExpertFrameDuration = 5009 )
type MultistreamDecoder ¶
type MultistreamDecoder struct {
// contains filtered or unexported fields
}
MultistreamDecoder decodes Opus multistream packets into multi-channel PCM audio.
A MultistreamDecoder instance maintains internal state and is NOT safe for concurrent use. Each goroutine should create its own MultistreamDecoder instance.
Multistream decoding is used for surround sound configurations (5.1, 7.1, etc.) where multiple coupled (stereo) and uncoupled (mono) streams are combined.
Reference: RFC 6716 Appendix B, RFC 7845 Section 5.1.1
func NewMultistreamDecoder ¶
func NewMultistreamDecoder(sampleRate, channels, streams, coupledStreams int, mapping []byte) (*MultistreamDecoder, error)
NewMultistreamDecoder creates a new multistream decoder with explicit configuration.
Parameters:
- sampleRate: output sample rate (8000, 12000, 16000, 24000, or 48000 Hz)
- channels: total output channels (1-255)
- streams: total elementary streams (N, 1-255)
- coupledStreams: number of coupled stereo streams (M, 0 to streams) with streams + coupledStreams <= 255
- mapping: channel mapping table (length must equal channels)
Returns ErrInvalidChannels when channels is outside the explicit multistream range [1, 255].
The mapping table determines how decoded audio is routed to output channels:
- Values 0 to 2*M-1: from coupled streams (even=left, odd=right of stereo pair)
- Values 2*M to N+M-1: from uncoupled (mono) streams
- Value 255: silent channel (output zeros)
func NewMultistreamDecoderDefault ¶
func NewMultistreamDecoderDefault(sampleRate, channels int) (*MultistreamDecoder, error)
NewMultistreamDecoderDefault creates a multistream decoder with default Vorbis-style mapping for standard channel configurations (1-8 channels).
This is a convenience function that calls the internal DefaultMapping() to get the appropriate streams, coupledStreams, and mapping for the given channel count. Returns ErrInvalidChannels when channels is outside the default-mapping range [1, 8]. Use NewMultistreamDecoder with an explicit mapping for layouts above 8 channels.
Supported channel counts:
- 1: mono (1 stream, 0 coupled)
- 2: stereo (1 stream, 1 coupled)
- 3: 3.0 (2 streams, 1 coupled)
- 4: quad (2 streams, 2 coupled)
- 5: 5.0 (3 streams, 2 coupled)
- 6: 5.1 surround (4 streams, 2 coupled)
- 7: 6.1 surround (4 streams, 3 coupled)
- 8: 7.1 surround (5 streams, 3 coupled)
func (*MultistreamDecoder) Bandwidth ¶
func (d *MultistreamDecoder) Bandwidth() Bandwidth
Bandwidth returns the bandwidth of the first elementary stream decoder.
func (*MultistreamDecoder) Channels ¶
func (d *MultistreamDecoder) Channels() int
Channels returns the number of audio channels.
func (*MultistreamDecoder) Complexity ¶
func (d *MultistreamDecoder) Complexity() int
Complexity returns the decoder complexity from the first elementary stream.
func (*MultistreamDecoder) CoupledStreams ¶
func (d *MultistreamDecoder) CoupledStreams() int
CoupledStreams returns the number of coupled (stereo) streams.
func (*MultistreamDecoder) Decode ¶
func (d *MultistreamDecoder) Decode(data []byte, pcm []float32) (int, error)
Decode decodes an Opus multistream packet into float32 PCM samples.
data: Opus multistream packet data, or nil for Packet Loss Concealment (PLC). pcm: Output buffer for decoded samples. Must be large enough to hold frameSize * channels samples.
Returns the number of samples per channel decoded, or an error.
When data is nil, the decoder performs packet loss concealment using the last successfully decoded frame parameters.
func (*MultistreamDecoder) DecodeInt16 ¶
func (d *MultistreamDecoder) DecodeInt16(data []byte, pcm []int16) (int, error)
DecodeInt16 decodes an Opus multistream packet into int16 PCM samples.
data: Opus multistream packet data, or nil for PLC. pcm: Output buffer for decoded samples.
Returns the number of samples per channel decoded, or an error.
func (*MultistreamDecoder) DecodeInt24 ¶
func (d *MultistreamDecoder) DecodeInt24(data []byte, pcm []int32) (int, error)
DecodeInt24 decodes an Opus multistream packet into 24-bit PCM samples stored in int32.
data: Opus multistream packet data, or nil for PLC. pcm: Output buffer for decoded samples. Each element carries a right-justified signed 24-bit value in the range [-8388608, 8388607] (= ±2^23), matching libopus opus_multistream_decode24().
Returns the number of samples per channel decoded, or an error.
func (*MultistreamDecoder) DecodeInt24Slice ¶
func (d *MultistreamDecoder) DecodeInt24Slice(data []byte) ([]int32, error)
DecodeInt24Slice decodes an Opus multistream packet into 24-bit PCM samples and returns a new int32 slice. Each element carries a right-justified signed 24-bit value.
This is a convenience method that allocates the output buffer. For performance-critical code, use DecodeInt24 with a pre-allocated buffer.
func (*MultistreamDecoder) FinalRange ¶
func (d *MultistreamDecoder) FinalRange() uint32
FinalRange returns the XOR of all elementary stream final range values.
func (*MultistreamDecoder) Gain ¶
func (d *MultistreamDecoder) Gain() int
Gain returns the output gain from the first elementary stream decoder.
func (*MultistreamDecoder) GetFinalRange ¶
func (d *MultistreamDecoder) GetFinalRange() uint32
GetFinalRange returns the XOR of all elementary stream final range values.
func (*MultistreamDecoder) IgnoreExtensions ¶
func (d *MultistreamDecoder) IgnoreExtensions() bool
IgnoreExtensions reports whether unknown packet extensions are ignored.
func (*MultistreamDecoder) LastPacketDuration ¶
func (d *MultistreamDecoder) LastPacketDuration() int
LastPacketDuration returns the last packet duration from the first stream decoder.
func (*MultistreamDecoder) PhaseInversionDisabled ¶
func (d *MultistreamDecoder) PhaseInversionDisabled() bool
PhaseInversionDisabled reports the first stream decoder's phase inversion setting.
func (*MultistreamDecoder) Reset ¶
func (d *MultistreamDecoder) Reset()
Reset clears the decoder state for a new stream. Call this when starting to decode a new audio stream.
func (*MultistreamDecoder) SampleRate ¶
func (d *MultistreamDecoder) SampleRate() int
SampleRate returns the sample rate in Hz.
func (*MultistreamDecoder) SetComplexity ¶
func (d *MultistreamDecoder) SetComplexity(complexity int) error
SetComplexity sets decoder complexity (0-10) on all elementary streams.
func (*MultistreamDecoder) SetDNNBlob ¶
func (d *MultistreamDecoder) SetDNNBlob(_ []byte) error
SetDNNBlob reports that USE_WEIGHTS_FILE model loading is unavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable the model-loading control.
func (*MultistreamDecoder) SetGain ¶
func (d *MultistreamDecoder) SetGain(gainQ8 int) error
SetGain sets output gain in Q8 dB units on all elementary stream decoders.
func (*MultistreamDecoder) SetIgnoreExtensions ¶
func (d *MultistreamDecoder) SetIgnoreExtensions(ignore bool)
SetIgnoreExtensions toggles whether unknown packet extensions should be ignored.
func (*MultistreamDecoder) SetPhaseInversionDisabled ¶
func (d *MultistreamDecoder) SetPhaseInversionDisabled(disabled bool)
SetPhaseInversionDisabled toggles CELT stereo phase inversion on all streams.
func (*MultistreamDecoder) Streams ¶
func (d *MultistreamDecoder) Streams() int
Streams returns the total number of elementary streams.
type MultistreamEncoder ¶
type MultistreamEncoder struct {
// contains filtered or unexported fields
}
MultistreamEncoder encodes multi-channel PCM audio into Opus multistream packets.
A MultistreamEncoder instance maintains internal state and is NOT safe for concurrent use. Each goroutine should create its own MultistreamEncoder instance.
Multistream encoding is used for surround sound configurations (5.1, 7.1, etc.) where multiple coupled (stereo) and uncoupled (mono) streams are combined.
Reference: RFC 6716 Appendix B, RFC 7845 Section 5.1.1
func NewMultistreamEncoder ¶
func NewMultistreamEncoder(sampleRate, channels, streams, coupledStreams int, mapping []byte, application Application) (*MultistreamEncoder, error)
NewMultistreamEncoder creates a new multistream encoder with explicit configuration.
Parameters:
- sampleRate: input sample rate (8000, 12000, 16000, 24000, or 48000 Hz)
- channels: total input channels (1-255)
- streams: total elementary streams (N, 1-255)
- coupledStreams: number of coupled stereo streams (M, 0 to streams) with streams + coupledStreams <= 255
- mapping: channel mapping table (length must equal channels)
- application: application hint for encoder optimization
Returns ErrInvalidChannels when channels is outside the explicit multistream range [1, 255].
The mapping table determines how input audio is routed to stream encoders:
- Values 0 to 2*M-1: to coupled streams (even=left, odd=right of stereo pair)
- Values 2*M to N+M-1: to uncoupled (mono) streams
- Value 255: silent channel (input ignored)
Example for 5.1 surround (6 channels, 4 streams, 2 coupled):
mapping = [0, 4, 1, 2, 3, 5] Input 0 (FL): mapping[0]=0 -> coupled stream 0, left Input 1 (C): mapping[1]=4 -> uncoupled stream 2 (2*2+0) Input 2 (FR): mapping[2]=1 -> coupled stream 0, right Input 3 (RL): mapping[3]=2 -> coupled stream 1, left Input 4 (RR): mapping[4]=3 -> coupled stream 1, right Input 5 (LFE): mapping[5]=5 -> uncoupled stream 3 (2*2+1)
func NewMultistreamEncoderDefault ¶
func NewMultistreamEncoderDefault(sampleRate, channels int, application Application) (*MultistreamEncoder, error)
NewMultistreamEncoderDefault creates a multistream encoder with default Vorbis-style mapping for standard channel configurations (1-8 channels).
This is a convenience function that calls the internal DefaultMapping() to get the appropriate streams, coupledStreams, and mapping for the given channel count. Returns ErrInvalidChannels when channels is outside the default-mapping range [1, 8]. Use NewMultistreamEncoder with an explicit mapping for layouts above 8 channels.
Supported channel counts:
- 1: mono (1 stream, 0 coupled)
- 2: stereo (1 stream, 1 coupled)
- 3: 3.0 (2 streams, 1 coupled)
- 4: quad (2 streams, 2 coupled)
- 5: 5.0 (3 streams, 2 coupled)
- 6: 5.1 surround (4 streams, 2 coupled)
- 7: 6.1 surround (4 streams, 3 coupled)
- 8: 7.1 surround (5 streams, 3 coupled)
func (*MultistreamEncoder) Application ¶
func (e *MultistreamEncoder) Application() Application
Application returns the current encoder application hint.
func (*MultistreamEncoder) Bandwidth ¶
func (e *MultistreamEncoder) Bandwidth() Bandwidth
Bandwidth returns the currently configured target bandwidth.
func (*MultistreamEncoder) Bitrate ¶
func (e *MultistreamEncoder) Bitrate() int
Bitrate returns the current total target bitrate in bits per second.
func (*MultistreamEncoder) BitrateMode ¶
func (e *MultistreamEncoder) BitrateMode() BitrateMode
BitrateMode returns the active bitrate control mode.
func (*MultistreamEncoder) Channels ¶
func (e *MultistreamEncoder) Channels() int
Channels returns the number of audio channels.
func (*MultistreamEncoder) Complexity ¶
func (e *MultistreamEncoder) Complexity() int
Complexity returns the current complexity setting.
func (*MultistreamEncoder) CoupledStreams ¶
func (e *MultistreamEncoder) CoupledStreams() int
CoupledStreams returns the number of coupled (stereo) streams.
func (*MultistreamEncoder) DTXEnabled ¶
func (e *MultistreamEncoder) DTXEnabled() bool
DTXEnabled returns whether DTX is enabled.
func (*MultistreamEncoder) Encode ¶
func (e *MultistreamEncoder) Encode(pcm []float32, data []byte) (int, error)
Encode encodes float32 PCM samples into an Opus multistream packet.
pcm: Input samples (interleaved). Length must be frameSize * channels. data: Output buffer for the encoded packet. Recommended size is 4000 bytes per stream.
Returns the number of bytes written to data, or an error. Returns 0 bytes written if DTX suppresses all frames (silence detected in all streams).
func (*MultistreamEncoder) EncodeFloat32 ¶
func (e *MultistreamEncoder) EncodeFloat32(pcm []float32) ([]byte, error)
EncodeFloat32 encodes float32 PCM samples and returns a new byte slice.
This is a convenience method that allocates the output buffer. For performance-critical code, use Encode with a pre-allocated buffer.
pcm: Input samples (interleaved).
Returns the encoded packet or an error.
func (*MultistreamEncoder) EncodeInt16 ¶
func (e *MultistreamEncoder) EncodeInt16(pcm []int16, data []byte) (int, error)
EncodeInt16 encodes int16 PCM samples into an Opus multistream packet.
pcm: Input samples (interleaved). Length must be frameSize * channels. data: Output buffer for the encoded packet.
Returns the number of bytes written to data, or an error.
func (*MultistreamEncoder) EncodeInt16Slice ¶
func (e *MultistreamEncoder) EncodeInt16Slice(pcm []int16) ([]byte, error)
EncodeInt16Slice encodes int16 PCM samples and returns a new byte slice.
This is a convenience method that allocates the output buffer. For performance-critical code, use EncodeInt16 with a pre-allocated buffer.
pcm: Input samples (interleaved).
Returns the encoded packet or an error.
func (*MultistreamEncoder) EncodeInt24 ¶
func (e *MultistreamEncoder) EncodeInt24(pcm []int32, data []byte) (int, error)
EncodeInt24 encodes 24-bit PCM samples stored in int32 values into an Opus multistream packet.
pcm: Input samples (interleaved). Length must be frameSize * channels. data: Output buffer for the encoded packet.
Returns the number of bytes written to data, or an error.
The input values are interpreted as right-justified signed 24-bit PCM carried in int32 containers with numeric range [-8388608, 8388607]. Left-shifted 24-in-32 input will be mis-scaled.
func (*MultistreamEncoder) EncodeInt24Slice ¶
func (e *MultistreamEncoder) EncodeInt24Slice(pcm []int32) ([]byte, error)
EncodeInt24Slice encodes 24-bit PCM samples stored in int32 values and returns a new byte slice.
This is a convenience method that allocates the output buffer.
func (*MultistreamEncoder) ExpertFrameDuration ¶
func (e *MultistreamEncoder) ExpertFrameDuration() ExpertFrameDuration
ExpertFrameDuration returns the current multistream expert frame duration policy.
func (*MultistreamEncoder) FECEnabled ¶
func (e *MultistreamEncoder) FECEnabled() bool
FECEnabled returns whether FEC is enabled.
func (*MultistreamEncoder) FinalRange ¶
func (e *MultistreamEncoder) FinalRange() uint32
FinalRange returns the final range coder state.
func (*MultistreamEncoder) ForceChannels ¶
func (e *MultistreamEncoder) ForceChannels() int
ForceChannels returns the forced channel count (-1 = auto).
func (*MultistreamEncoder) FrameSize ¶
func (e *MultistreamEncoder) FrameSize() int
FrameSize returns the current frame size in native-Fs samples.
func (*MultistreamEncoder) GetFinalRange ¶
func (e *MultistreamEncoder) GetFinalRange() uint32
GetFinalRange returns the final range coder state for all streams. The values from all streams are XOR combined to produce a single verification value. This matches libopus OPUS_GET_FINAL_RANGE for multistream encoders. Must be called after Encode() to get a meaningful value.
func (*MultistreamEncoder) InBandFEC ¶
func (e *MultistreamEncoder) InBandFEC() int
InBandFEC returns the current in-band FEC configuration.
func (*MultistreamEncoder) LSBDepth ¶
func (e *MultistreamEncoder) LSBDepth() int
LSBDepth returns the current LSB depth setting.
func (*MultistreamEncoder) Lookahead ¶
func (e *MultistreamEncoder) Lookahead() int
Lookahead returns the encoder's algorithmic delay in samples.
Matches libopus OPUS_GET_LOOKAHEAD behavior:
- Base lookahead is Fs/400 (2.5ms)
- Delay compensation Fs/250 is included for VoIP/Audio
- Delay compensation is omitted for LowDelay
func (*MultistreamEncoder) MaxBandwidth ¶
func (e *MultistreamEncoder) MaxBandwidth() Bandwidth
MaxBandwidth returns the maximum bandwidth limit.
func (*MultistreamEncoder) Mode ¶
func (e *MultistreamEncoder) Mode() EncoderMode
Mode returns the forced coding mode from the first stream encoder.
func (*MultistreamEncoder) PacketLoss ¶
func (e *MultistreamEncoder) PacketLoss() int
PacketLoss returns expected packet loss percentage.
func (*MultistreamEncoder) PhaseInversionDisabled ¶
func (e *MultistreamEncoder) PhaseInversionDisabled() bool
PhaseInversionDisabled reports whether stereo phase inversion is disabled.
func (*MultistreamEncoder) PredictionDisabled ¶
func (e *MultistreamEncoder) PredictionDisabled() bool
PredictionDisabled reports whether inter-frame prediction is disabled.
func (*MultistreamEncoder) Reset ¶
func (e *MultistreamEncoder) Reset()
Reset clears the encoder state for a new stream. Call this when starting to encode a new audio stream.
func (*MultistreamEncoder) SampleRate ¶
func (e *MultistreamEncoder) SampleRate() int
SampleRate returns the sample rate in Hz.
func (*MultistreamEncoder) SetApplication ¶
func (e *MultistreamEncoder) SetApplication(application Application) error
SetApplication updates the encoder application hint.
Valid values are ApplicationVoIP, ApplicationAudio, and ApplicationLowDelay.
func (*MultistreamEncoder) SetBandwidth ¶
func (e *MultistreamEncoder) SetBandwidth(bw Bandwidth) error
SetBandwidth sets the target audio bandwidth.
func (*MultistreamEncoder) SetBandwidthAuto ¶
func (e *MultistreamEncoder) SetBandwidthAuto() error
SetBandwidthAuto restores automatic bandwidth selection for all stream encoders.
func (*MultistreamEncoder) SetBitrate ¶
func (e *MultistreamEncoder) SetBitrate(bitrate int) error
SetBitrate sets the total target bitrate in bits per second.
The bitrate is distributed across streams with coupled streams getting proportionally more bits than mono streams.
Positive bitrates are clamped to 500*channels through 750000*channels.
func (*MultistreamEncoder) SetBitrateMode ¶
func (e *MultistreamEncoder) SetBitrateMode(mode BitrateMode) error
SetBitrateMode sets the multistream encoder bitrate control mode.
func (*MultistreamEncoder) SetComplexity ¶
func (e *MultistreamEncoder) SetComplexity(complexity int) error
SetComplexity sets the encoder's computational complexity for all streams.
complexity must be 0-10, where:
- 0-1: Minimal processing, fastest encoding
- 2-4: Basic analysis, good for real-time with limited CPU
- 5-7: Moderate analysis, balanced quality/speed
- 8-10: Thorough analysis, highest quality
Returns ErrInvalidComplexity if out of range.
func (*MultistreamEncoder) SetDNNBlob ¶
func (e *MultistreamEncoder) SetDNNBlob(_ []byte) error
SetDNNBlob reports that USE_WEIGHTS_FILE model loading is unavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable the model-loading control.
func (*MultistreamEncoder) SetDTX ¶
func (e *MultistreamEncoder) SetDTX(enabled bool)
SetDTX enables or disables Discontinuous Transmission for all streams.
When enabled, the encoders reduce bitrate during silence by emitting 1-byte TOC-only packets. The decoder handles CNG (Comfort Noise Generation).
func (*MultistreamEncoder) SetExpertFrameDuration ¶
func (e *MultistreamEncoder) SetExpertFrameDuration(duration ExpertFrameDuration) error
SetExpertFrameDuration sets the preferred frame duration policy for multistream encoding.
func (*MultistreamEncoder) SetFEC ¶
func (e *MultistreamEncoder) SetFEC(enabled bool)
SetFEC enables or disables in-band Forward Error Correction for all streams.
When enabled, the encoders include redundant information for loss recovery.
func (*MultistreamEncoder) SetForceChannels ¶
func (e *MultistreamEncoder) SetForceChannels(channels int) error
SetForceChannels forces channel count on all stream encoders.
channels must be -1 (auto), 1 (mono), or 2 (stereo).
func (*MultistreamEncoder) SetFrameSize ¶
func (e *MultistreamEncoder) SetFrameSize(samples int) error
SetFrameSize sets the frame size in native-Fs samples.
Valid sizes are the per-rate Opus frame sizes: (Fs/400)<<n (2.5/5/10 ms) and n*Fs/50 (20/40/60/80/100/120 ms). At 48 kHz these are 120, 240, 480, 960, 1920, 2880, 3840, 4800, and 5760.
func (*MultistreamEncoder) SetInBandFEC ¶
func (e *MultistreamEncoder) SetInBandFEC(config int) error
SetInBandFEC sets the libopus-compatible in-band FEC configuration.
func (*MultistreamEncoder) SetLSBDepth ¶
func (e *MultistreamEncoder) SetLSBDepth(depth int) error
SetLSBDepth sets the input signal's LSB depth for all stream encoders. Valid range is 8-24 bits. This affects DTX sensitivity. Returns an error if the depth is out of range.
func (*MultistreamEncoder) SetMaxBandwidth ¶
func (e *MultistreamEncoder) SetMaxBandwidth(bw Bandwidth) error
SetMaxBandwidth sets the maximum bandwidth limit for all stream encoders. The actual bandwidth will be clamped to this limit.
func (*MultistreamEncoder) SetMode ¶
func (e *MultistreamEncoder) SetMode(mode EncoderMode) error
SetMode sets the forced coding mode for all stream encoders.
func (*MultistreamEncoder) SetPacketLoss ¶
func (e *MultistreamEncoder) SetPacketLoss(lossPercent int) error
SetPacketLoss sets expected packet loss percentage for all stream encoders.
lossPercent must be in the range [0, 100].
func (*MultistreamEncoder) SetPhaseInversionDisabled ¶
func (e *MultistreamEncoder) SetPhaseInversionDisabled(disabled bool)
SetPhaseInversionDisabled toggles stereo phase inversion on all stream encoders.
func (*MultistreamEncoder) SetPredictionDisabled ¶
func (e *MultistreamEncoder) SetPredictionDisabled(disabled bool)
SetPredictionDisabled toggles inter-frame prediction on all stream encoders.
func (*MultistreamEncoder) SetSignal ¶
func (e *MultistreamEncoder) SetSignal(signal Signal) error
SetSignal sets the signal type hint for all stream encoders. Use SignalVoice for speech content, SignalMusic for music content, or SignalAuto (default) for automatic detection.
func (*MultistreamEncoder) SetVBR ¶
func (e *MultistreamEncoder) SetVBR(enabled bool)
SetVBR enables or disables VBR mode.
Disabling VBR switches to CBR. Enabling VBR restores VBR while preserving the current VBR constraint state.
func (*MultistreamEncoder) SetVBRConstraint ¶
func (e *MultistreamEncoder) SetVBRConstraint(constrained bool)
SetVBRConstraint enables or disables constrained VBR mode. This setting is remembered even while VBR is disabled.
func (*MultistreamEncoder) Signal ¶
func (e *MultistreamEncoder) Signal() Signal
Signal returns the current signal type hint. Returns SignalAuto, SignalVoice, or SignalMusic.
func (*MultistreamEncoder) Streams ¶
func (e *MultistreamEncoder) Streams() int
Streams returns the total number of elementary streams.
func (*MultistreamEncoder) VBR ¶
func (e *MultistreamEncoder) VBR() bool
VBR reports whether VBR mode is enabled.
func (*MultistreamEncoder) VBRConstraint ¶
func (e *MultistreamEncoder) VBRConstraint() bool
VBRConstraint reports whether constrained VBR mode is enabled.
type OptionalExtension ¶
type OptionalExtension string
OptionalExtension identifies a recognized libopus build-time extension surface.
const ( // OptionalExtensionDRED identifies DRED controls and standalone DRED packet // helpers, which are supported only when built with -tags gopus_dred. OptionalExtensionDRED OptionalExtension = "dred" // OptionalExtensionDNNBlob identifies supported weights-file model blob loading. OptionalExtensionDNNBlob OptionalExtension = "dnn_blob" // OptionalExtensionQEXT identifies the optional extended-precision theta path, // which is supported only when built with -tags gopus_qext. OptionalExtensionQEXT OptionalExtension = "qext" // OptionalExtensionOSCEBWE identifies decoder-side OSCE BWE controls, which // remain parity-only extra controls rather than supported release surface. OptionalExtensionOSCEBWE OptionalExtension = "osce_bwe" )
type PacketInfo ¶
type PacketInfo struct {
TOC TOC // Parsed TOC byte
FrameCount int // Number of frames (1-48 for code 3)
FrameSizes []int // Size in bytes of each frame
Padding int // Padding bytes (code 3 only)
TotalSize int // Total packet size
}
PacketInfo contains parsed information about an Opus packet.
func ParsePacket ¶
func ParsePacket(data []byte) (PacketInfo, error)
ParsePacket parses an Opus packet and returns information about its structure. It determines the frame boundaries based on the TOC byte's frame code (0-3).
type PacketReader ¶
type PacketReader interface {
// ReadPacketInto fills dst with the next Opus packet.
//
// granulePos is the source packet position in decoded-sample units when the
// container provides one (for example Ogg Opus granule positions). Sources
// that do not track positions should return 0.
//
// Returns io.EOF when stream ends. Return n=0, err=nil to trigger PLC.
ReadPacketInto(dst []byte) (n int, granulePos uint64, err error)
}
PacketReader provides Opus packets for streaming decode. Implementations should return io.EOF when no more packets are available.
type PacketSink ¶
type PacketSink interface {
// WritePacket writes an encoded Opus packet.
// Returns number of bytes written and any error.
//
// If the sink also implements io.Closer, Writer.Close forwards to it after
// flushing any buffered audio.
WritePacket(packet []byte) (int, error)
}
PacketSink receives encoded Opus packets from streaming encode.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader decodes an Opus stream, implementing io.Reader. Output is PCM samples in the configured format.
The Reader handles frame boundaries internally, buffering decoded PCM samples and serving byte-oriented reads.
Example:
reader, err := gopus.NewReader(gopus.DefaultDecoderConfig(48000, 2), source, gopus.FormatFloat32LE) io.Copy(audioOutput, reader)
func NewReader ¶
func NewReader(cfg DecoderConfig, source PacketReader, format SampleFormat) (*Reader, error)
NewReader creates a streaming decoder.
Parameters:
- cfg: decoder configuration
- source: provides Opus packets for decoding
- format: output sample format (FormatFloat32LE or FormatInt16LE)
func (*Reader) LastGranulePos ¶
LastGranulePos returns the most recent packet position reported by the source.
For Ogg Opus this is the granule position from the underlying page header. Sources that do not track positions may leave this at 0.
func (*Reader) Read ¶
Read implements io.Reader, reading decoded PCM bytes.
The Reader handles frame boundaries internally, fetching and decoding packets as needed to fill the buffer.
func (*Reader) Reset ¶
func (r *Reader) Reset()
Reset clears buffers and decoder state for a new stream.
func (*Reader) SampleRate ¶
SampleRate returns the sample rate in Hz.
type Repacketizer ¶
type Repacketizer struct {
// contains filtered or unexported fields
}
Repacketizer accumulates Opus packet frames and emits new packets assembled from any contiguous frame range.
It mirrors libopus repacketizer behavior:
- all added packets must share TOC bits 7..2,
- total stored duration must not exceed 120ms.
func NewRepacketizer ¶
func NewRepacketizer() *Repacketizer
NewRepacketizer creates a new repacketizer state.
func (*Repacketizer) Cat ¶
func (r *Repacketizer) Cat(packet []byte) error
Cat adds one Opus packet to the repacketizer state.
func (*Repacketizer) NumFrames ¶
func (r *Repacketizer) NumFrames() int
NumFrames returns the number of frames currently accumulated.
func (*Repacketizer) Out ¶
func (r *Repacketizer) Out(data []byte) (int, error)
Out assembles all accumulated frames into one Opus packet.
type SampleFormat ¶
type SampleFormat int
SampleFormat specifies the PCM sample format for streaming.
const ( // FormatFloat32LE is 32-bit float, little-endian (4 bytes per sample). FormatFloat32LE SampleFormat = iota // FormatInt16LE is 16-bit signed integer, little-endian (2 bytes per sample). FormatInt16LE )
func (SampleFormat) BytesPerSample ¶
func (f SampleFormat) BytesPerSample() int
BytesPerSample returns the number of bytes per sample for the format.
type Signal ¶
Signal represents a hint about the input signal type. This helps the encoder optimize for speech or music content.
type TOC ¶
type TOC struct {
Config uint8 // Configuration 0-31
Mode Mode // Derived from config
Bandwidth Bandwidth // Derived from config
FrameSize int // Frame size in samples at 48kHz
Stereo bool // True if stereo
FrameCode uint8 // Code 0-3
}
TOC represents the parsed Table of Contents byte from an Opus packet.
type VAD ¶ added in v0.1.2
type VAD struct {
// contains filtered or unexported fields
}
VAD analyzes 10 or 20 ms mono PCM frames with Opus's SILK voice detector. It keeps a noise estimate across frames and is not safe for concurrent use.
func (*VAD) AnalyzeInt16 ¶ added in v0.1.2
AnalyzeInt16 returns SILK speech activity in Q8 (0-255). The caller chooses the activity threshold and handles turn timing. PCM must be mono at the sample rate passed to NewVAD, with exactly 10 or 20 ms per frame.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer encodes PCM samples to an Opus stream, implementing io.WriteCloser. Input is PCM samples in the configured format.
The Writer buffers input samples until a complete frame is accumulated, then encodes and sends the packet to the sink.
Example:
writer, err := gopus.NewWriter(48000, 2, sink, gopus.FormatFloat32LE, gopus.ApplicationAudio) io.Copy(writer, audioInput) writer.Close() // flush remaining buffered samples
func NewWriter ¶
func NewWriter(sampleRate, channels int, sink PacketSink, format SampleFormat, application Application) (*Writer, error)
NewWriter creates a streaming encoder.
Parameters:
- sampleRate: input sample rate (8000, 12000, 16000, 24000, or 48000)
- channels: number of audio channels (1 or 2)
- sink: receives encoded Opus packets
- format: input sample format (FormatFloat32LE or FormatInt16LE)
- application: encoder application hint
func (*Writer) Close ¶
Close flushes buffered samples and closes the underlying sink when supported.
If the sink implements io.Closer, Close forwards to it after a successful flush. Close is idempotent.
func (*Writer) Flush ¶
Flush encodes any buffered samples. If samples don't fill a complete frame, they are zero-padded. Call Flush before closing the stream to ensure all audio is encoded.
func (*Writer) Reset ¶
func (w *Writer) Reset()
Reset clears buffers and encoder state for a new stream. It also clears the closed flag so the writer can be reused with a reusable sink.
func (*Writer) SampleRate ¶
SampleRate returns the sample rate in Hz.
func (*Writer) SetBitrate ¶
SetBitrate sets the target bitrate in bits per second. Valid range is 6000 to 510000 (6 kbps to 510 kbps).
func (*Writer) SetComplexity ¶
SetComplexity sets the encoder's computational complexity (0-10).
Source Files
¶
- application_common.go
- controls_common.go
- decoder.go
- decoder_96k_default.go
- decoder_controls.go
- decoder_decode.go
- decoder_dred_fields_default.go
- decoder_dred_helpers_default.go
- decoder_fec.go
- decoder_fixedpoint_celt_default.go
- decoder_fixedpoint_fields_default.go
- decoder_misc.go
- decoder_opus_frame.go
- decoder_osce_bwe_apply_default.go
- decoder_osce_bwe_state_default.go
- decoder_osce_fields_default.go
- decoder_osce_lace_apply_default.go
- decoder_osce_lace_state_default.go
- decoder_plc_helpers.go
- decoder_qext_hook_default.go
- decoder_qext_payloads_default.go
- dnn_blob_controls_default.go
- doc.go
- dred_payload_byteexact_tier_strict.go
- encode_common.go
- encoder.go
- encoder_96k_default.go
- encoder_application.go
- encoder_controls.go
- encoder_encode.go
- errors.go
- multistream.go
- multistream_application.go
- multistream_decode.go
- multistream_decode_fixedpoint_default.go
- multistream_decoder_controls.go
- multistream_encode.go
- multistream_encoder_controls.go
- optional_extensions.go
- packet.go
- packet_extension_helpers.go
- packet_extensions.go
- packet_multistream_helpers.go
- packet_parse.go
- packet_repacketizer.go
- pcm.go
- pcm_convert_default.go
- sample_rate_default.go
- softclip.go
- stream.go
- vad.go
- version.go
Directories
¶
| Path | Synopsis |
|---|---|
|
container
|
|
|
ogg
Package ogg implements Ogg Opus container reading and writing.
|
Package ogg implements Ogg Opus container reading and writing. |
|
red
Package red implements RFC 2198 RTP Payload for Redundant Audio Data.
|
Package red implements RFC 2198 RTP Payload for Redundant Audio Data. |
|
examples
|
|
|
bench-decode
command
Package main benchmarks Opus decode throughput for gopus vs libopus.
|
Package main benchmarks Opus decode throughput for gopus vs libopus. |
|
bench-encode
command
Package main benchmarks Opus encode throughput for gopus vs libopus.
|
Package main benchmarks Opus encode throughput for gopus vs libopus. |
|
decode-play
command
Package main demonstrates decoding an Ogg Opus file to WAV with optional playback.
|
Package main demonstrates decoding an Ogg Opus file to WAV with optional playback. |
|
encode-play
command
Package main demonstrates encoding audio with gopus and playing the result.
|
Package main demonstrates encoding audio with gopus and playing the result. |
|
ffmpeg-interop
command
Package main demonstrates gopus interoperability with ffmpeg.
|
Package main demonstrates gopus interoperability with ffmpeg. |
|
low-delay
command
Package main demonstrates low-delay, CELT-only encoding.
|
Package main demonstrates low-delay, CELT-only encoding. |
|
mix-arrivals
command
Package main demonstrates WebRTC-style speech mixing with real open-source clips.
|
Package main demonstrates WebRTC-style speech mixing with real open-source clips. |
|
ogg-file
command
Package main demonstrates Ogg Opus file creation and reading.
|
Package main demonstrates Ogg Opus file creation and reading. |
|
packet-loss
command
Package main demonstrates the two ways gopus recovers from a lost packet on a real (lossy) network: packet loss concealment and in-band forward error correction.
|
Package main demonstrates the two ways gopus recovers from a lost packet on a real (lossy) network: packet loss concealment and in-band forward error correction. |
|
repacketizer
command
Package main demonstrates the Opus repacketizer and packet-inspection helpers.
|
Package main demonstrates the Opus repacketizer and packet-inspection helpers. |
|
roundtrip
command
Package main demonstrates gopus encode-decode roundtrip with quality metrics.
|
Package main demonstrates gopus encode-decode roundtrip with quality metrics. |
|
roundtrip-min
command
Package main is the smallest useful gopus program: it encodes one frame of PCM to an Opus packet and decodes it straight back, using the caller-owned buffer Encode/Decode API.
|
Package main is the smallest useful gopus program: it encodes one frame of PCM to an Opus packet and decodes it straight back, using the caller-owned buffer Encode/Decode API. |
|
sample-rates
command
Package main demonstrates sample-rate handling and the int16 PCM API.
|
Package main demonstrates sample-rate handling and the int16 PCM API. |
|
surround
command
Package main demonstrates multistream (surround) encoding and decoding.
|
Package main demonstrates multistream (surround) encoding and decoding. |
|
internal
|
|
|
arena
Package arena provides a generic single-type bump allocator used to back many logical scratch buffers with one contiguous allocation.
|
Package arena provides a generic single-type bump allocator used to back many logical scratch buffers with one contiguous allocation. |
|
benchutil
Package benchutil locates the pinned libopus reference binaries (opus_demo, opus_compare) and writes the raw-PCM and bitstream input files the parity and benchmark tooling feeds to them.
|
Package benchutil locates the pinned libopus reference binaries (opus_demo, opus_compare) and writes the raw-PCM and bitstream input files the parity and benchmark tooling feeds to them. |
|
celt
Package celt implements the CELT decoder per RFC 6716 Section 4.3.
|
Package celt implements the CELT decoder per RFC 6716 Section 4.3. |
|
cpufeat
Package cpufeat detects optional CPU instruction-set extensions at process start and exposes them through the AMD64 and ARM64 variables so the codec can gate its SIMD code paths at runtime.
|
Package cpufeat detects optional CPU instruction-set extensions at process start and exposes them through the AMD64 and ARM64 variables so the codec can gate its SIMD code paths at runtime. |
|
dnnblob
Package dnnblob parses and validates the libopus USE_WEIGHTS_FILE neural weights blob and exposes typed views over its records.
|
Package dnnblob parses and validates the libopus USE_WEIGHTS_FILE neural weights blob and exposes typed views over its records. |
|
dnnmath
Package dnnmath provides the activation, exponent and input-quantization kernels libopus' neural-network code (DRED, OSCE) relies on.
|
Package dnnmath provides the activation, exponent and input-quantization kernels libopus' neural-network code (DRED, OSCE) relies on. |
|
dred
Package dred implements libopus Deep Redundancy (DRED): the in-band extension that carries a heavily compressed RDOVAE representation of recent speech so a decoder can recover audio lost to packet loss.
|
Package dred implements libopus Deep Redundancy (DRED): the in-band extension that carries a heavily compressed RDOVAE representation of recent speech so a decoder can recover audio lost to packet loss. |
|
dred/rdovae
Package rdovae implements the libopus RDOVAE (rate-distortion-optimized variational auto-encoder) used by Deep Redundancy (DRED).
|
Package rdovae implements the libopus RDOVAE (rate-distortion-optimized variational auto-encoder) used by Deep Redundancy (DRED). |
|
encoder
Package encoder implements the unified Opus encoder defined by RFC 6716.
|
Package encoder implements the unified Opus encoder defined by RFC 6716. |
|
fixedpoint
Package fixedpoint is the gopus FIXED_POINT CELT codec: a pure-integer port of libopus' CELT encoder and decoder for the static 48000/960 mode.
|
Package fixedpoint is the gopus FIXED_POINT CELT codec: a pure-integer port of libopus' CELT encoder and decoder for the static 48000/960 mode. |
|
hybrid
Package hybrid implements the Hybrid decoder for Opus.
|
Package hybrid implements the Hybrid decoder for Opus. |
|
lpcnetplc
Package lpcnetplc implements the libopus LPCNet packet-loss concealment and DRED recovery decoder.
|
Package lpcnetplc implements the libopus LPCNet packet-loss concealment and DRED recovery decoder. |
|
opusmath
Package opusmath holds the gopus floating-point math kernels shared by the CELT, SILK and Opus glue layers.
|
Package opusmath holds the gopus floating-point math kernels shared by the CELT, SILK and Opus glue layers. |
|
osce/bwe
Package bwe implements the libopus OSCE blind-bandwidth-extension network (BBWENet), which extends 16 kHz decoded speech up to 48 kHz.
|
Package bwe implements the libopus OSCE blind-bandwidth-extension network (BBWENet), which extends 16 kHz decoded speech up to 48 kHz. |
|
osce/lace
Package lace implements the libopus OSCE LACE and NoLACE neural postfilters that enhance decoded SILK speech.
|
Package lace implements the libopus OSCE LACE and NoLACE neural postfilters that enhance decoded SILK speech. |
|
plc
Package plc implements Opus-level Packet Loss Concealment (PLC): the machinery that synthesizes plausible audio for frames whose packets were lost, dropped, or arrived too late.
|
Package plc implements Opus-level Packet Loss Concealment (PLC): the machinery that synthesizes plausible audio for frames whose packets were lost, dropped, or arrived too late. |
|
qualitycompare
Package qualitycompare is the single, canonical quality comparator for gopus-vs-libopus parity tests.
|
Package qualitycompare is the single, canonical quality comparator for gopus-vs-libopus parity tests. |
|
rangecoding
Package rangecoding implements the Opus range coder: the entropy encoder/decoder defined in RFC 6716 Section 4.1 and ported, bit for bit, from libopus celt/entenc.c (encoder) and celt/entdec.c (decoder), with constants from celt/mfrngcod.h and celt/entcode.h.
|
Package rangecoding implements the Opus range coder: the entropy encoder/decoder defined in RFC 6716 Section 4.1 and ported, bit for bit, from libopus celt/entenc.c (encoder) and celt/entdec.c (decoder), with constants from celt/mfrngcod.h and celt/entcode.h. |
|
silk
Package silk implements the SILK speech layer of Opus (RFC 6716 Section 4.2), the low-level codec used by gopus for the SILK and Hybrid Opus modes.
|
Package silk implements the SILK speech layer of Opus (RFC 6716 Section 4.2), the low-level codec used by gopus for the SILK and Hybrid Opus modes. |
|
util
Package util provides small, dependency-free helpers shared across the gopus codec packages.
|
Package util provides small, dependency-free helpers shared across the gopus codec packages. |
|
Package multistream implements the Opus multistream engine: encoding and decoding of packets that carry several elementary Opus streams (each a normal SILK / CELT / Hybrid stream) which are decoded independently and routed to output channels via a channel-mapping table.
|
Package multistream implements the Opus multistream engine: encoding and decoding of packets that carry several elementary Opus streams (each a normal SILK / CELT / Hybrid stream) which are decoded independently and routed to output channels via a channel-mapping table. |
|
Package testvectors provides utilities for parsing and validating against official RFC 8251 Opus test vectors.
|
Package testvectors provides utilities for parsing and validating against official RFC 8251 Opus test vectors. |
|
tools
|
|
|
benchguard
command
|
|
|
encoderbenchcmp
command
|
|
|
qualityreport
command
|
|
|
safety_soak
command
|
|
|
testvectorbenchcmp
command
|
|
|
typeparityrewrite
command
|
|
|
Package types defines small, dependency-free enumerations shared across the gopus packages.
|
Package types defines small, dependency-free enumerations shared across the gopus packages. |