Documentation
¶
Overview ¶
Package gopus implements Opus audio encoding and decoding in pure Go. It supports the SILK, CELT, and Hybrid modes defined by RFC 6716 and RFC 8251 without requiring cgo or an external codec library.
Streams and samples ¶
Encoder and Decoder process mono or stereo streams. Use MultistreamEncoder and MultistreamDecoder for multichannel layouts. Codec instances retain stream history and are not safe for concurrent use. Each independent stream needs its own instance. Reset clears stream history; each Reset method documents which controls it preserves.
PCM is interleaved: each successive group of samples contains one sample per channel. Float32 methods use normalized full scale; integer input methods use signed 16-bit samples or right-justified 24-bit samples in int32 values. Decoder.DecodeInt24 writes int32 values at 24-bit PCM scale without clipping to the signed 24-bit range. Frame sizes and decoded sample counts are measured per channel at the configured sample rate. Encoders return packet byte counts.
Buffers and packet loss ¶
Encode and Decode methods write into caller-provided buffers. Reusing codec instances and adequately sized buffers avoids steady-state allocations in the covered hot paths; constructors and initial warmup can allocate. A decode buffer sized to DecoderConfig.MaxPacketSamples times Channels holds the largest packet allowed by that configuration. Only the returned sample count times Channels elements contain decoded output.
An empty packet passed to Decoder.Decode requests packet-loss concealment. The output buffer length selects the requested duration, except that a full configured-size buffer uses the last decoded packet's duration when available. To recover a missing packet from the next packet's in-band FEC, call Decoder.DecodeWithFEC with fec set to true, then call Decode with the same packet to decode its primary audio. The decoder conceals the loss if FEC is unavailable. Native 96 kHz FEC requests always use concealment and ignore the supplied packet.
Reader and Writer adapt packet sources and sinks to little-endian PCM byte streams. They require packet-aware transport interfaces; they do not frame a byte stream of concatenated Opus packets. ParsePacket inspects packet framing, and Repacketizer combines or separates compatible frames without re-encoding.
Build configuration ¶
Go 1.27 or later is required. Ordinary builds use scalar Go kernels. GOEXPERIMENT=simd enables Go SIMD kernels where implemented, with runtime CPU checks and scalar fallbacks. The nosimd and purego build tags force scalar kernels even when the experiment is enabled.
Optional extensions require their matching build tags: gopus_qext for QEXT and native 96 kHz, gopus_dred for DRED, gopus_osce for OSCE and deep PLC, and gopus_custom_modes for Opus Custom. The gopus_fixed_point tag selects the integer codec pipeline. SupportsOptionalExtension reports the supported API surface of the current build; compiled extra controls may still report false. DRED controls and standalone recovery APIs also compile with gopus_osce, while the supported DRED probe requires gopus_dred.
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, 1500)
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 SpeechDetector
- 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 asks the encoder to choose a bitrate from the stream format and // application (libopus OPUS_AUTO). 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 accepted by SetInBandFEC.
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. // Rates are 8000, 12000, 16000, 24000, or 48000 Hz; builds with gopus_qext // also accept 96000 Hz. 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 a negative max packet sample cap or // one whose decoder scratch length cannot fit in int-sized storage. ErrInvalidMaxPacketSamples = errors.New("gopus: invalid max packet samples (must be nonnegative and fit decoder scratch)") // 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 an encode packet budget or decode PCM buffer is // too small for the operation. Decode buffers must hold frameSize * channels // samples; encode buffers must hold the resulting packet. 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") // ErrInternalError indicates malformed packet extensions prevent a packet // operation from collecting extension data. Repacketizer.OutRange and // PacketPad return it for this extension-processing failure. ErrInternalError = errors.New("gopus: internal error") // 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 that the requested functionality is unsupported. ErrUnimplemented = errors.New("gopus: feature not implemented") )
Errors returned by the public encoding, decoding, and streaming APIs.
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 TOC configuration index for mode, bandwidth, and frameSize. frameSize is measured in samples at 48 kHz. It returns -1 when the combination does not appear in the Opus configuration table.
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 packs a configuration, channel flag, and frame-count code into a TOC byte. config contributes its low five bits, and frameCode contributes its low two bits:
0: 1 frame 1: 2 equal-sized frames 2: 2 different-sized frames 3: frame count is encoded in the packet
The function masks these fields; it does not validate their values.
func MultistreamPacketPad ¶
MultistreamPacketPad pads the final stream packet in a multistream packet in place. length is the current packet length in bytes, newLen is the target length in bytes, and numStreams is the number of constituent Opus streams. The input slice must contain length bytes and have capacity for newLen bytes. If its original length is shorter, reslice the caller's slice to newLen after success.
func MultistreamPacketUnpad ¶
MultistreamPacketUnpad removes padding from every stream in a multistream packet in place and returns the new packet length in bytes. length is the number of input bytes and numStreams is the number of constituent Opus streams; all but the final stream packet must use self-delimited framing. data must contain length bytes. The function does not extend data, so len(data) must also be large enough for the rebuilt output.
func PCMSoftClip ¶
PCMSoftClip soft-clips interleaved float32 PCM in place. Samples should be normalized to roughly [-1, 1]. channels is the channel count, and softclipMem must hold at least one state value per channel. Pass zeroed state on the first call and reuse it for successive blocks from the same stream. The function processes complete interleaved frames; an incomplete trailing frame is ignored. Invalid channel counts or a short state slice leave pcm unchanged.
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 the first SILK or Hybrid frame in data carries the LBRR flag for in-band FEC. It returns false for CELT and when the first frame cannot be extracted. This is a payload probe, not full packet framing validation; use ParsePacket to validate the complete packet.
func PacketPad ¶
PacketPad pads a packet in place to exactly newLen bytes. length is the current packet length in bytes. data must contain length bytes and have capacity for newLen bytes. If len(data) is shorter, reslice the caller's slice to newLen after success. It returns ErrInternalError when packet extension data cannot be collected.
func PacketUnpad ¶
PacketUnpad removes packet padding in place and returns the new packet length in bytes. length is the current packet length; data must contain that many bytes. Use data[:n] with the returned length n to access the unpadded packet.
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 gopus's compiled-in identification string.
Types ¶
type Application ¶
type Application int
Application selects the encoder's operating profile. The standard profiles tune encoding for speech, general audio, or low delay; the restricted profiles force SILK-only or CELT-only encoding and can be selected only at construction.
const ( // ApplicationVoIP tunes the encoder for interactive speech. ApplicationVoIP Application = iota // ApplicationAudio tunes the encoder for general audio. ApplicationAudio // ApplicationLowDelay minimizes algorithmic delay. 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 selects variable, constrained-variable, or constant bitrate.
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
Decoder decodes Opus packets into PCM samples. It retains stream state and is not safe for concurrent use; use one Decoder per stream. Construct it with NewDecoder; the zero value is not ready for use.
func NewDecoder ¶
func NewDecoder(cfg DecoderConfig) (*Decoder, error)
NewDecoder returns a Decoder configured by cfg. It returns an error if the sample rate, channel count, or packet limits are invalid.
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 data into interleaved float32 PCM in pcm. The buffer length is measured in samples across all channels; the returned sample count is per channel, and the first n*Channels elements contain the output.
An empty data slice performs packet-loss concealment. Its requested duration comes from len(pcm)/Channels and must be a positive multiple of 2.5 ms. If pcm has exactly DecoderConfig.MaxPacketSamples*Channels elements and a packet has already been decoded or concealed, Decode uses the most recent output duration as the concealment request. Before the first decode, a valid full-buffer request returns zeroed PCM.
Deliberately sized PLC requests larger than MaxPacketSamples are honored; MaxPacketSamples and MaxPacketBytes limit coded packets. Decode returns an error for malformed packets, packet-limit violations, invalid PLC durations, or a short output buffer.
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, 1500)
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, 1500)
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 data into interleaved signed 16-bit PCM in pcm. The returned sample count is per channel; pcm must hold n*Channels elements, and the first n*Channels elements contain the output. An empty data slice performs packet-loss concealment, with the requested duration derived from pcm's per-channel length.
func (*Decoder) DecodeInt24 ¶
DecodeInt24 decodes data into interleaved 24-bit-scale PCM stored in pcm. Each int32 holds a right-justified signed value; the nominal 24-bit range is [-8388608, 8388607]. The libopus RES2INT24 conversion does not soft-clip or clamp to that range: a +1.0 sample maps to 8388608, and output gain can also produce values outside the nominal 24-bit interval. The returned sample count is per channel; pcm must hold n*Channels elements. An empty data slice performs packet-loss concealment.
func (*Decoder) DecodeInt24Slice ¶
DecodeInt24Slice decodes data into a newly allocated, caller-owned interleaved PCM slice. Each int32 holds a right-justified signed 24-bit-scale value using the same unsaturated conversion as DecodeInt24. The slice contains n*Channels elements for n samples per channel. For empty data, it requests the most recent output duration, or MaxPacketSamples when LastPacketDuration is zero.
func (*Decoder) DecodeWithFEC ¶
DecodeWithFEC decodes data into interleaved float32 PCM and returns samples per channel. When fec is false, it behaves like Decode. When fec is true, data is the packet received after a loss and len(pcm)/Channels requests the missing duration; the request must be a positive multiple of 2.5 ms. The decoder recovers in-band FEC when usable LBRR is present and otherwise performs packet-loss concealment. Empty data also performs concealment. This call does not decode the supplied packet's primary frame: call Decode with the same packet afterward.
Example ¶
package main
import (
"fmt"
"log"
"math"
"github.com/thesyncim/gopus"
)
func main() {
const frameSize = 960 // 20 ms at 48 kHz, per channel
enc, err := gopus.NewEncoder(gopus.EncoderConfig{
SampleRate: 48000,
Channels: 1,
Application: gopus.ApplicationVoIP,
})
if err != nil {
log.Fatal(err)
}
enc.SetFEC(true)
if err := enc.SetPacketLoss(20); err != nil {
log.Fatal(err)
}
cfg := gopus.DefaultDecoderConfig(48000, 1)
dec, err := gopus.NewDecoder(cfg)
if err != nil {
log.Fatal(err)
}
input := make([]float32, frameSize)
packet := make([]byte, cfg.MaxPacketBytes)
output := make([]float32, cfg.MaxPacketSamples*cfg.Channels)
// Deliver the first packet, lose the second, and receive the third.
for frame := range 3 {
for i := range input {
input[i] = float32(0.5 * math.Sin(2*math.Pi*440*float64(frame*frameSize+i)/48000))
}
n, err := enc.Encode(input, packet)
if err != nil {
log.Fatal(err)
}
if frame == 0 {
if _, err := dec.Decode(packet[:n], output); err != nil {
log.Fatal(err)
}
}
if frame != 2 {
continue
}
// Request the missing duration first. The decoder uses PLC if the
// following packet does not carry FEC for this loss.
recovered, err := dec.DecodeWithFEC(packet[:n], output[:frameSize], true)
if err != nil {
log.Fatal(err)
}
// Consume the recovered output before reusing its storage below.
fmt.Printf("recovered %d samples\n", recovered)
decoded, err := dec.Decode(packet[:n], output)
if err != nil {
log.Fatal(err)
}
fmt.Printf("decoded %d samples\n", decoded)
}
}
Output: recovered 960 samples decoded 960 samples
func (*Decoder) FinalRange ¶
FinalRange reports the decoder's captured range state, matching libopus OPUS_GET_FINAL_RANGE. It is useful for bitstream verification.
The main decode range is XORed with any redundancy-frame range. The result is zero when the decoded frame is empty or has at most one payload byte, including an empty or one-byte final frame in a multi-frame packet.
func (*Decoder) IgnoreExtensions ¶
IgnoreExtensions reports whether supported packet-extension payloads are ignored during decoding.
func (*Decoder) InDTX ¶
InDTX reports the libopus DTX indication from the recorded decode-data length. It is true for a recorded length of one or two bytes. Normal decoding records the packet length; FEC recovery records the recovered first-frame payload length. It is false before decoding and after packet-loss concealment.
func (*Decoder) LastPacketDuration ¶
LastPacketDuration returns the most recent decoded or concealed duration in samples per channel at the decoder API rate. It is zero before the first decode and after Reset.
func (*Decoder) PhaseInversionDisabled ¶
PhaseInversionDisabled reports whether CELT stereo phase inversion is disabled.
func (*Decoder) Pitch ¶
Pitch returns the decoded pitch period in 48 kHz-equivalent samples, matching libopus OPUS_GET_PITCH. CELT reports its postfilter period; SILK reports a lag only for voiced audio. It returns zero when neither decoder has a usable pitch.
func (*Decoder) Reset ¶
func (d *Decoder) Reset()
Reset clears codec, packet, PLC, FEC, soft-clip, and optional recovery history and resets last-packet metadata. It preserves the decoder configuration and controls, including the sample rate, channels, packet limits, output gain, complexity, phase-inversion setting, extension policy, and loaded model blobs. Call it when starting a new audio stream on the same Decoder.
func (*Decoder) SampleRate ¶
SampleRate returns the sample rate in Hz.
func (*Decoder) SetComplexity ¶
SetComplexity sets decoder complexity (0-10).
func (*Decoder) SetDNNBlob ¶
SetDNNBlob returns ErrOptionalExtensionUnavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable model loading.
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 controls whether packet-extension payloads supported by enabled optional features are used during decoding. Enabling it also clears any cached DRED payload. 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 8000, 12000, 16000, 24000, or 48000 Hz.
// Builds with gopus_qext also accept 96000 Hz.
SampleRate int
// Channels must be 1 (mono) or 2 (stereo).
Channels int
// MaxPacketSamples caps the maximum decoded samples per channel per packet.
// Zero selects 5,760 samples, or 120 ms at 48 kHz. The limit must fit
// the decoder work buffers; [NewDecoder] rejects overflowing sizes.
MaxPacketSamples int
// MaxPacketBytes caps the maximum Opus packet size in bytes.
// Zero selects 1,500 bytes.
MaxPacketBytes int
}
DecoderConfig sets the sample rate, channel count, and packet limits for a Decoder.
func DefaultDecoderConfig ¶
func DefaultDecoderConfig(sampleRate, channels int) DecoderConfig
DefaultDecoderConfig returns a DecoderConfig with default packet limits for the given stream format. It allows up to 5,760 decoded samples per channel and 1,500 packet bytes; set MaxPacketSamples or MaxPacketBytes to raise a limit.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder encodes one interleaved PCM stream into Opus packets. Construct it with NewEncoder; the zero value is not ready for use. Encoder retains codec state across calls and is not safe for concurrent use, so use one Encoder per stream. Encode, EncodeInt16, and EncodeInt24 write packets into caller-provided buffers; the Slice methods return owned packet slices.
func NewEncoder ¶
func NewEncoder(cfg EncoderConfig) (*Encoder, error)
NewEncoder returns an initialized Encoder for cfg. Its configured frame size starts at 20 ms and its target bitrate starts at 64,000 bits per second. A zero-valued Application selects ApplicationVoIP. It returns ErrInvalidSampleRate, ErrInvalidChannels, or ErrInvalidApplication when cfg contains an unsupported value.
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)
}
if err := enc.SetBitrate(64000); err != nil { // bits per second
log.Fatal(err)
}
if err := enc.SetComplexity(10); err != nil {
log.Fatal(err)
}
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 configured encoder application profile.
func (*Encoder) Bandwidth ¶
Bandwidth returns the bandwidth currently selected by the encoder. It can differ from the explicit request made by SetBandwidth until a frame is encoded.
func (*Encoder) Bitrate ¶
Bitrate returns the configured target bitrate, including BitrateAuto and BitrateMax when either sentinel mode is selected.
func (*Encoder) BitrateMode ¶
func (e *Encoder) BitrateMode() BitrateMode
BitrateMode returns the active encoder bitrate control mode.
func (*Encoder) Channels ¶
Channels returns the configured input channel count: 1 for mono or 2 for stereo. SetForceChannels can request fewer coded output channels.
func (*Encoder) Complexity ¶
Complexity returns the current complexity setting.
func (*Encoder) DTXEnabled ¶
DTXEnabled reports whether the DTX setting is enabled; InDTX reports whether the encoder is currently in its DTX state.
func (*Encoder) Encode ¶
Encode encodes one interleaved float32 PCM frame. pcm must contain exactly FrameSize()*Channels() samples. A fixed ExpertFrameDuration can select a shorter prefix, but pcm must still contain the configured frame. len(data) is both the packet byte budget and destination; Encode copies the packet there and returns the number of bytes written. It returns ErrInvalidFrameSize for invalid frame geometry and ErrBufferTooSmall when the output budget cannot hold the packet. During DTX, silence can produce a one-byte TOC-only 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, 1500)
// 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 one interleaved float32 PCM frame and returns a newly allocated packet slice that remains valid across later Encode calls. pcm must contain exactly FrameSize()*Channels() samples.
func (*Encoder) EncodeInt16 ¶
EncodeInt16 encodes one interleaved signed 16-bit PCM frame. pcm must contain exactly FrameSize()*Channels() samples. Each input sample is scaled by 1/32768. len(data) is both the packet byte budget and destination. It returns the number of bytes written, ErrInvalidFrameSize for an incorrect input length or selected frame, or ErrBufferTooSmall when the packet cannot fit.
func (*Encoder) EncodeInt16Slice ¶
EncodeInt16Slice encodes one interleaved signed 16-bit PCM frame and returns a newly allocated packet slice that remains valid across later Encode calls. pcm must contain exactly FrameSize()*Channels() samples; input is scaled by 1/32768.
func (*Encoder) EncodeInt24 ¶
EncodeInt24 encodes one interleaved signed 24-bit PCM frame. Each int32 in pcm must be right-justified in [-8388608, 8388607], and pcm must contain exactly FrameSize()*Channels() samples. len(data) is both the packet byte budget and destination. It returns the number of bytes written, ErrInvalidFrameSize for invalid input geometry, or ErrBufferTooSmall when the packet cannot fit.
func (*Encoder) EncodeInt24Slice ¶
EncodeInt24Slice encodes one interleaved signed 24-bit PCM frame and returns a newly allocated packet slice that remains valid across later Encode calls. Each int32 sample must be right-justified in [-8388608, 8388607], and pcm must contain exactly FrameSize()*Channels() samples.
func (*Encoder) ExpertFrameDuration ¶
func (e *Encoder) ExpertFrameDuration() ExpertFrameDuration
ExpertFrameDuration returns the current expert frame duration policy.
func (*Encoder) FECEnabled ¶
FECEnabled reports whether an in-band FEC policy is enabled. It does not indicate whether a particular packet contains redundancy.
func (*Encoder) FinalRange ¶
FinalRange returns the range coder state from the most recent encode, matching libopus OPUS_GET_FINAL_RANGE. Reset sets it to zero.
func (*Encoder) ForceChannels ¶
ForceChannels returns the configured output-channel request: -1 follows the input channel count, while 1 or 2 forces that coded channel count.
func (*Encoder) FrameSize ¶
FrameSize returns the configured input frame size in samples per channel at the API rate. A fixed ExpertFrameDuration can make an Encode call code a shorter prefix. At 96 kHz, FrameSize is twice the 48 kHz-equivalent 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 delay in samples per channel at the API sample rate, matching libopus OPUS_GET_LOOKAHEAD. The base delay is 2.5 ms; VoIP, Audio, and RestrictedSilk add 4 ms of compensation. LowDelay and RestrictedCelt omit that compensation.
func (*Encoder) MaxBandwidth ¶
MaxBandwidth returns the current maximum bandwidth limit.
func (*Encoder) Mode ¶
func (e *Encoder) Mode() EncoderMode
Mode returns the configured coding mode. EncoderModeAuto means the encoder selects a mode for each frame.
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 codec and analysis history, resets the final range, and restarts first-frame processing for a new stream. It retains the sample rate, channel count, configured frame size, application, and ordinary controls. The selected bandwidth is reinitialized; an explicit bandwidth request remains configured. In builds with DRED controls, Reset sets DREDDuration to zero, disabling DRED emission.
func (*Encoder) SampleRate ¶
SampleRate returns the configured input sample rate in Hz.
func (*Encoder) SetApplication ¶
func (e *Encoder) SetApplication(application Application) error
SetApplication changes the encoder application profile. Valid values are ApplicationVoIP, ApplicationAudio, and ApplicationLowDelay; restricted profiles can only be selected with NewEncoder. A different profile can be selected only before the encoder commits its first frame. Reapplying the current standard profile remains valid after encoding starts. SetApplication returns ErrInvalidApplication for an unsupported profile or a late change.
func (*Encoder) SetBandwidth ¶
SetBandwidth requests a target audio bandwidth. The selected bandwidth can differ until a frame is encoded. It returns ErrInvalidBandwidth for an unsupported value.
func (*Encoder) SetBandwidthAuto ¶
SetBandwidthAuto restores automatic bandwidth selection.
func (*Encoder) SetBitrate ¶
SetBitrate sets the target bitrate in bits per second. Positive values are clamped to the range supported by libopus for this stream. BitrateAuto and BitrateMax select the corresponding libopus sentinel modes. It returns ErrInvalidBitrate for other non-positive 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 selects variable (VBR), constrained-variable (CVBR), or constant (CBR) packet sizing. It returns ErrInvalidBitrateMode for an unsupported mode.
func (*Encoder) SetComplexity ¶
SetComplexity sets encoder analysis and coding effort from 0 through 10. Higher values spend more CPU on analysis and search, but do not guarantee a better result for every input. It returns ErrInvalidComplexity outside this 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 returns ErrOptionalExtensionUnavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable model loading.
func (*Encoder) SetDTX ¶
SetDTX enables or disables discontinuous transmission during silence. During DTX, Encode can return no packet or a short one- or two-byte packet. DTXEnabled reports the configured setting; InDTX reports encoder activity.
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 selects the frame duration used by Encode. The ExpertFrameDurationArg setting uses FrameSize(); a fixed duration selects that duration from the configured input frame. Encode still requires the full configured frame and uses the selected prefix. A duration longer than the configured frame fails with ErrInvalidFrameSize. Unsupported values return ErrInvalidArgument.
func (*Encoder) SetFEC ¶
SetFEC enables or disables in-band Forward Error Correction. When the encoder produces redundancy, it carries SILK data for a preceding frame in a later SILK or Hybrid packet. SetPacketLoss supplies the expected loss percentage used by the encoder.
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 selects the coded channel count: -1 follows the configured input count, 1 forces mono, and 2 forces stereo. The requested count cannot exceed the configured input count; forcing mono from stereo downmixes the input. It returns ErrInvalidForceChannels for an unsupported or unavailable count.
func (*Encoder) SetFrameSize ¶
SetFrameSize sets the input frame size in samples per channel at the API rate. At 96 kHz the wrapper stores a 48 kHz-equivalent count while the core receives the native-rate size. It returns ErrInvalidFrameSize for a duration that Opus does not support or that violates the restricted-SILK minimum.
func (*Encoder) SetInBandFEC ¶
SetInBandFEC selects the in-band FEC policy: InBandFECDisabled, InBandFECEnabled, or InBandFECMusicSafe. The last policy lets the encoder omit redundancy for music-classified frames. It returns ErrInvalidFECConfig for any other value.
func (*Encoder) SetLSBDepth ¶
SetLSBDepth sets the nominal input precision in bits, from 8 through 24. The value informs digital-silence detection and CELT noise-floor decisions; it does not rescale PCM samples. The default is 24. It returns ErrInvalidLSBDepth outside this range.
func (*Encoder) SetMaxBandwidth ¶
SetMaxBandwidth caps the bandwidth selected for encoded audio without changing the input sample rate. It returns ErrInvalidBandwidth for an unsupported bandwidth.
func (*Encoder) SetMode ¶
func (e *Encoder) SetMode(mode EncoderMode) error
SetMode selects automatic mode choice or forces SILK, Hybrid, or CELT coding where the application and frame duration permit it. EncoderModeAuto restores automatic selection. It returns ErrInvalidArgument for an unsupported mode.
func (*Encoder) SetPacketLoss ¶
SetPacketLoss sets the expected packet loss percentage from 0 through 100. The estimate informs redundancy decisions when in-band FEC is enabled. It returns ErrInvalidPacketLoss outside this range.
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. This reduces dependence on preceding frames and can improve resilience to packet loss at the cost of compression efficiency. The default is false.
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 latest available Opus-level activity estimate in Q8 (0-255), not a percentage or the standalone SILK VAD result. It reads the most recent encoder decision without analyzing new PCM. It returns 0 before the first decision, after Reset, or when no Opus activity decision is available.
func (*Encoder) VBRConstraint ¶
VBRConstraint returns whether VBR constraint is enabled.
type EncoderConfig ¶
type EncoderConfig struct {
// SampleRate must be 8000, 12000, 16000, 24000, or 48000 Hz.
// Builds with gopus_qext also accept 96000 Hz.
SampleRate int
// Channels must be 1 (mono) or 2 (stereo).
Channels int
// Application selects the operating profile. Its zero value, ApplicationVoIP,
// is used when the field is omitted. Restricted profiles force one coding mode
// and can be selected only when NewEncoder creates the encoder.
Application Application
}
EncoderConfig describes the input format and application profile for an Encoder.
type EncoderMode ¶
EncoderMode selects automatic coding-mode selection or forces a 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 interleaved PCM. It retains stream state and is not safe for concurrent use; use one decoder per stream.
func NewMultistreamDecoder ¶
func NewMultistreamDecoder(sampleRate, channels, streams, coupledStreams int, mapping []byte) (*MultistreamDecoder, error)
NewMultistreamDecoder returns a decoder for an explicit channel mapping. sampleRate is in hertz and must be 8, 12, 16, 24, or 48 kHz; 96 kHz is available in builds tagged gopus_qext. channels is the number of output channels (1–255), streams is the number of elementary streams (1–255), and coupledStreams is the number of initial stereo streams (0–streams). The sum streams+coupledStreams must not exceed 255.
mapping must contain one entry per output channel. Values 0 through 2*coupledStreams-1 select left or right channels of coupled streams (even is left, odd is right); subsequent values select mono streams. Repeated values duplicate a decoded channel, and 255 produces silence. The constructor copies mapping.
The constructor returns an error for an unsupported rate, invalid count, or invalid mapping.
func NewMultistreamDecoderDefault ¶
func NewMultistreamDecoderDefault(sampleRate, channels int) (*MultistreamDecoder, error)
NewMultistreamDecoderDefault returns a decoder with the Vorbis mapping for 1–8 output channels. Use NewMultistreamDecoder for other layouts. It returns an error for an unsupported sample rate or channel count.
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 a packet into interleaved float32 PCM, or performs packet loss concealment (PLC) when data is nil or empty. It returns the number of samples per channel written. For a packet, pcm must have room for that packet's duration; a larger buffer is allowed, and its unused tail is left unchanged.
For PLC, the per-channel request size is inferred from len(pcm)/Channels(), not from the previous packet. The buffer length must contain whole interleaved frames; requests above 120 ms are capped to 120 ms. A buffer too small for a packet or a PLC frame returns ErrBufferTooSmall. A malformed PLC frame length returns ErrInvalidFrameSize.
func (*MultistreamDecoder) DecodeInt16 ¶
func (d *MultistreamDecoder) DecodeInt16(data []byte, pcm []int16) (int, error)
DecodeInt16 decodes a packet into interleaved signed 16-bit PCM, or performs PLC when data is nil or empty. It returns the number of samples per channel written. For a packet, pcm must have room for its duration; for PLC, the per-channel request size is inferred from the whole interleaved frames in pcm and is capped at 120 ms. A short buffer returns ErrBufferTooSmall.
func (*MultistreamDecoder) DecodeInt24 ¶
func (d *MultistreamDecoder) DecodeInt24(data []byte, pcm []int32) (int, error)
DecodeInt24 decodes a packet into interleaved signed 24-bit PCM stored in int32 values, or performs PLC when data is nil or empty. Values use the right-justified 24-bit PCM scale; output gain can exceed that range. The method returns the number of samples per channel written. For a packet, pcm must have room for its duration; for PLC, the per-channel request size is inferred from the whole interleaved frames in pcm and is capped at 120 ms. A short buffer returns ErrBufferTooSmall.
func (*MultistreamDecoder) DecodeInt24Slice ¶
func (d *MultistreamDecoder) DecodeInt24Slice(data []byte) ([]int32, error)
DecodeInt24Slice decodes a packet into interleaved signed 24-bit PCM stored in a newly allocated int32 slice. Values are right-justified. For nil or empty data it requests 60 ms of PLC. Use DecodeInt24 with a reusable buffer to avoid the output allocation.
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()
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 returns ErrOptionalExtensionUnavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable model loading.
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 interleaved multichannel PCM into Opus multistream packets. It retains stream state and is not safe for concurrent use; use one encoder per stream.
func NewMultistreamEncoder ¶
func NewMultistreamEncoder(sampleRate, channels, streams, coupledStreams int, mapping []byte, application Application) (*MultistreamEncoder, error)
NewMultistreamEncoder returns an encoder for an explicit channel mapping. sampleRate is in hertz and must be 8, 12, 16, 24, or 48 kHz; 96 kHz is available in builds tagged gopus_qext. channels is the number of input channels (1–255), streams is the number of elementary streams (1–255), and coupledStreams is the number of initial stereo streams (0–streams). The sum streams+coupledStreams must not exceed 255.
mapping must contain one entry per input channel. Values 0 through 2*coupledStreams-1 select left or right channels of coupled streams (even is left, odd is right); subsequent values select mono streams. The value 255 omits an input channel. Every stream must receive input, and both channels of every coupled stream must be mapped. The constructor copies mapping.
The constructor returns an error for an unsupported rate, invalid count, mapping or layout, or invalid application.
func NewMultistreamEncoderDefault ¶
func NewMultistreamEncoderDefault(sampleRate, channels int, application Application) (*MultistreamEncoder, error)
NewMultistreamEncoderDefault returns an encoder with the Vorbis mapping for 1–8 input channels. Use NewMultistreamEncoder for other layouts. It returns an error for an unsupported sample rate, channel count, or application.
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 configured total target, including BitrateAuto or BitrateMax when selected. Libopus OPUS_GET_BITRATE instead sums the effective targets of its child encoders.
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)
func (*MultistreamEncoder) EncodeFloat32 ¶
func (e *MultistreamEncoder) EncodeFloat32(pcm []float32) ([]byte, error)
EncodeFloat32 encodes interleaved float32 PCM and returns a newly allocated packet slice. The input must contain exactly FrameSize()*Channels() samples; ExpertFrameDuration may select a shorter coded frame from that input. For allocation-free steady-state encoding, use Encode with a reusable packet buffer.
func (*MultistreamEncoder) EncodeInt16 ¶
func (e *MultistreamEncoder) EncodeInt16(pcm []int16, data []byte) (int, error)
EncodeInt16 encodes interleaved signed 16-bit PCM. pcm must contain exactly FrameSize()*Channels() samples; ExpertFrameDuration may select a shorter coded frame from that input. data is the packet buffer, and its length is the total byte budget shared by all elementary streams. It returns the number of bytes written or an error; a buffer that is too small returns ErrBufferTooSmall. Samples are scaled by 1/32768 and coded with a 16-bit LSB depth, matching opus_multistream_encode().
func (*MultistreamEncoder) EncodeInt16Slice ¶
func (e *MultistreamEncoder) EncodeInt16Slice(pcm []int16) ([]byte, error)
EncodeInt16Slice encodes interleaved signed 16-bit PCM and returns a newly allocated packet slice. The input must contain exactly FrameSize()*Channels() samples; ExpertFrameDuration may select a shorter coded frame. For allocation-free steady-state encoding, use EncodeInt16 with a reusable packet buffer.
func (*MultistreamEncoder) EncodeInt24 ¶
func (e *MultistreamEncoder) EncodeInt24(pcm []int32, data []byte) (int, error)
EncodeInt24 encodes interleaved signed 24-bit PCM carried in int32 values. pcm must contain exactly FrameSize()*Channels() values; ExpertFrameDuration may select a shorter coded frame from that input. data is the packet buffer, and its length is the total byte budget shared by all elementary streams. It returns the number of bytes written or an error; a buffer that is too small returns ErrBufferTooSmall.
Each input value must be right-justified in the range [-8388608, 8388607]. Left-shifted 24-in-32 PCM is mis-scaled. Values are converted to float32 by dividing by 8388608 and coded at a 24-bit LSB depth.
func (*MultistreamEncoder) EncodeInt24Slice ¶
func (e *MultistreamEncoder) EncodeInt24Slice(pcm []int32) ([]byte, error)
EncodeInt24Slice encodes interleaved right-justified signed 24-bit PCM stored in int32 values and returns a newly allocated packet slice. The input must contain exactly FrameSize()*Channels() values; ExpertFrameDuration may select a shorter coded frame. For allocation-free steady-state encoding, use EncodeInt24 with a reusable packet 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 configured input frame size in samples per channel at the encoder's native sample rate. ExpertFrameDuration can select a shorter coded frame from each input frame.
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 codec and analysis history for a new stream. It preserves the encoder's sample rate, channel layout, frame size, and expert frame-duration policy.
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 changes the encoder application hint before any stream has committed a frame. Reapplying the current hint remains valid afterward. An encode that returns a low-space packet without committing a child frame leaves the application mutable.
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 returns ErrOptionalExtensionUnavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable model loading.
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 the channel count on stream encoders in order.
channels must be -1 (auto), 1 (mono), or 2 (stereo). A mixed layout returns ErrInvalidForceChannels when its first mono stream rejects 2; earlier coupled streams retain the stereo setting, matching libopus.
func (*MultistreamEncoder) SetFrameSize ¶
func (e *MultistreamEncoder) SetFrameSize(samples int) error
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 CELT QEXT encoder extension, // 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 in the packet.
FrameSizes []int // Frame payload sizes in bytes, excluding headers and padding.
Padding int // Trailing padding bytes; nonzero only for code 3 packets.
TotalSize int // Complete packet size in bytes, including headers and padding.
}
PacketInfo describes an Opus packet's TOC and frame layout.
func ParsePacket ¶
func ParsePacket(data []byte) (PacketInfo, error)
ParsePacket parses a complete Opus packet and returns its frame layout. FrameSizes contains payload lengths in packet order; packet headers and trailing padding are reported separately. It returns an error for truncated, malformed, overlong, or over-duration packets.
type PacketReader ¶
type PacketReader interface {
// ReadPacketInto writes the next packet into dst and returns its byte length.
// The caller may reuse dst after this call returns.
//
// granulePos is the source position in decoded samples at 48 kHz when the
// container provides one, as with an Ogg Opus granule position. Return 0
// when positions are unavailable.
//
// Return io.EOF when the stream ends. A final complete packet may be
// returned with n > 0 and io.EOF; Reader drains its PCM before returning EOF.
// Return n=0, err=nil to request packet loss concealment for one frame.
ReadPacketInto(dst []byte) (n int, granulePos uint64, err error)
}
PacketReader provides Opus packets for streaming decode. ReadPacketInto writes the next packet into dst and returns its byte length; callers may reuse dst after the call. Return io.EOF when the stream ends.
type PacketSink ¶
type PacketSink interface {
// WritePacket writes one encoded Opus packet and returns the number of bytes
// accepted. Writer does not retry; a short count returns io.ErrShortWrite,
// except that an error returned with zero bytes is preserved. The packet buffer
// is reused after this method returns, so copy packet if retaining it.
//
// If the sink also implements io.Closer, Writer.Close calls it at most once
// after attempting a flush, or after an earlier sink write error.
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 packets from a PacketReader and exposes PCM as an io.Reader. Read returns little-endian samples in the configured format. A Reader is not safe for concurrent use.
func NewReader ¶
func NewReader(cfg DecoderConfig, source PacketReader, format SampleFormat) (*Reader, error)
NewReader creates a Reader that decodes packets from source into format. It returns ErrNilPacketReader for a nil source, ErrInvalidSampleFormat for an unsupported format, or the decoder configuration error.
func (*Reader) LastGranulePos ¶
LastGranulePos returns the most recent packet position reported by the source.
For Ogg Opus this is the computed granule position of that packet. Sources that do not track positions may leave this at 0.
func (*Reader) Read ¶
Read implements io.Reader and returns decoded PCM bytes in the format passed to NewReader. Each call decodes at most one packet, so a short read at a packet boundary is normal. It returns io.EOF after the source ends and buffered PCM has been consumed. An empty destination does not advance the source or buffered PCM; it returns io.EOF only when EOF is already known and no PCM remains.
func (*Reader) Reset ¶
func (r *Reader) Reset()
Reset clears buffered PCM and decoder state. It does not reset or replace the PacketReader, so subsequent reads continue from that source's current position.
func (*Reader) SampleRate ¶
SampleRate returns the sample rate in Hz.
type Repacketizer ¶
type Repacketizer struct {
// contains filtered or unexported fields
}
Repacketizer copies frames from Opus packets and assembles packets from contiguous frame ranges. Added packets must have the same TOC configuration and channel flag (bits 7 through 2); their frame-count codes may differ. The accumulator accepts at most 48 frames and 120 ms of audio. Repacketizer is not safe for concurrent use.
func NewRepacketizer ¶
func NewRepacketizer() *Repacketizer
NewRepacketizer creates an empty repacketizer.
func (*Repacketizer) Cat ¶
func (r *Repacketizer) Cat(packet []byte) error
Cat parses packet and copies its encoded frame data into the accumulator. The caller may reuse packet after Cat returns. It returns an error for an invalid packet, incompatible TOC configuration or channel flag, or an accumulator that would exceed its frame-count or duration limits.
func (*Repacketizer) NumFrames ¶
func (r *Repacketizer) NumFrames() int
NumFrames returns the number of accumulated audio frames, not the number of packets passed to Cat.
func (*Repacketizer) Out ¶
func (r *Repacketizer) Out(data []byte) (int, error)
Out assembles all accumulated frames into one Opus packet. data must have enough length for the output packet; the returned count is the number of bytes written.
func (*Repacketizer) OutRange ¶
func (r *Repacketizer) OutRange(begin, end int, data []byte) (int, error)
OutRange assembles the accumulated frame range [begin, end) into one Opus packet. end is exclusive. data must have enough length for the output; the returned count is the number of bytes written. It returns ErrInvalidArgument for an empty or out-of-range range, ErrInternalError for malformed packet extensions, and ErrBufferTooSmall when data is short.
func (*Repacketizer) Reset ¶
func (r *Repacketizer) Reset()
Reset discards all accumulated frames so the repacketizer can be reused.
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 SpeechDetector ¶ added in v0.2.0
type SpeechDetector struct {
// contains filtered or unexported fields
}
SpeechDetector scores how likely mono PCM is speech with the neural analysis that Opus runs inside its encoder (libopus activity_probability). Unlike VAD, which follows level against a noise estimate, the network scores spectral and temporal structure over several windows, so steady noise, hum, and isolated clicks score low even when loud. It does not separate speech from every other foreground sound: a cough or other people talking can score high. It keeps a recurrent network state and is not safe for concurrent use.
func NewSpeechDetector ¶ added in v0.2.0
func NewSpeechDetector(sampleRate int) (*SpeechDetector, error)
NewSpeechDetector creates a detector for 16, 24, or 48 kHz mono PCM, the rates of the Opus analysis. It returns an error for other sample rates.
func (*SpeechDetector) AnalyzeFloat32 ¶ added in v0.2.0
func (d *SpeechDetector) AnalyzeFloat32(pcm []float32) (float32, error)
AnalyzeFloat32 is AnalyzeInt16 for float32 PCM where 1.0 is full scale, the scale Encoder.Encode uses. Samples beyond twice full scale are clamped.
func (*SpeechDetector) AnalyzeInt16 ¶ added in v0.2.0
func (d *SpeechDetector) AnalyzeInt16(pcm []int16) (float32, error)
AnalyzeInt16 analyzes one mono frame of signed 16-bit PCM and returns the speech probability in [0, 1], not a speech/no-speech boolean. The caller chooses the threshold and handles turn timing. PCM must use the rate passed to NewSpeechDetector and contain exactly 10 or 20 ms of samples; each successful call advances the detector state.
The network works on 20 ms windows and completes one for every 20 ms of input. The newest window ends 10 ms before the newest sample, and the network's recurrent output smooths over earlier windows. A 10 ms frame completes a window on every second call and repeats the previous result in between. The result is 0 until the first window completes and while the newest window is exactly zero, where the encoder repeats its previous estimate. The first ten windows (about 200 ms) after construction or Reset are a warm-up in which the estimate is less reliable.
Example ¶
package main
import (
"fmt"
"log"
"github.com/thesyncim/gopus"
)
func main() {
det, err := gopus.NewSpeechDetector(16000)
if err != nil {
log.Fatal(err)
}
// One 20 ms frame of 16 kHz mono PCM. Real audio replaces the zeros.
frame := make([]int16, 320)
probability, err := det.AnalyzeInt16(frame)
if err != nil {
log.Fatal(err)
}
// Compare against a threshold of your choosing; exact digital silence scores 0.
fmt.Printf("speech probability %.2f\n", probability)
}
Output: speech probability 0.00
func (*SpeechDetector) Reset ¶ added in v0.2.0
func (d *SpeechDetector) Reset()
Reset clears the analysis and network state for a new audio stream.
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 mono PCM at 8, 12, or 16 kHz with Opus's SILK voice detector. It keeps an adaptive noise estimate across frames and is not safe for concurrent use.
func NewVAD ¶ added in v0.1.2
NewVAD creates a detector for 8, 12, or 16 kHz mono PCM. It returns an error for other sample rates.
func (*VAD) AnalyzeInt16 ¶ added in v0.1.2
AnalyzeInt16 analyzes one mono frame of signed 16-bit PCM and returns SILK speech activity in Q8 (0-255), not a speech/no-speech boolean. The caller chooses the activity threshold and handles turn timing. PCM must use the rate passed to NewVAD and contain exactly 10 or 20 ms of samples; each successful call advances the detector state.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer encodes PCM bytes from io.Writer calls into Opus packets for a PacketSink. It buffers incomplete frames and is not safe for concurrent use.
func NewWriter ¶
func NewWriter(sampleRate, channels int, sink PacketSink, format SampleFormat, application Application) (*Writer, error)
NewWriter creates a Writer that encodes interleaved PCM at sampleRate with channels and sends packets to sink. format selects little-endian float32 or signed int16 input, and application selects the encoder's intended use. The writer uses a 20 ms frame duration by default. It returns an error for a nil sink, unsupported format, or invalid encoder configuration.
func (*Writer) Close ¶
Close attempts to flush buffered samples and closes the underlying sink when supported, including when flushing fails. If both flushing and closing fail, the returned error matches both. Repeated calls return nil and do not retry the sink close.
func (*Writer) Flush ¶
Flush encodes buffered PCM. A partial final frame is zero-padded to the configured frame size. With no buffered PCM, Flush has no effect.
func (*Writer) Reset ¶
func (w *Writer) Reset()
Reset clears buffered PCM and encoder state and clears the closed flag. It retains the PacketSink without resetting or reopening it, so the sink must be reusable if the Writer is reused.
func (*Writer) SampleRate ¶
SampleRate returns the sample rate in Hz.
func (*Writer) SetBitrate ¶
SetBitrate sets the target bitrate in bits per second. Positive values are clamped to the encoder's supported range. BitrateAuto and BitrateMax select automatic and output-buffer-limited bitrates; other nonpositive values return ErrInvalidBitrate.
func (*Writer) SetComplexity ¶
SetComplexity sets the encoder's computational complexity (0-10).
func (*Writer) Write ¶
Write implements io.Writer for interleaved little-endian PCM in the format passed to NewWriter. It buffers incomplete frames and encodes each complete frame. On success it consumes all of p. On error, the returned count covers only input bytes in frames handled before the error; packets sent before an error are not rolled back. A sink error closes the Writer.
Source Files
¶
- application_common.go
- controls_common.go
- decoder.go
- decoder_controls.go
- decoder_decode.go
- decoder_dred_default.go
- decoder_fec.go
- decoder_fixed_qext_default.go
- decoder_fixedpoint_default.go
- decoder_misc.go
- decoder_opus_frame.go
- decoder_osce_bwe_apply_default.go
- decoder_osce_fields_default.go
- decoder_plc_helpers.go
- decoder_qext_default.go
- dnn_blob_controls_default.go
- doc.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_encode.go
- optional_extensions.go
- packet.go
- packet_extensions.go
- packet_repacketizer.go
- pcm.go
- pcm_convert_default.go
- sample_rate_default.go
- smooth_fade_simd_default.go
- softclip.go
- speech_detector.go
- stream.go
- vad.go
- version.go
Directories
¶
| Path | Synopsis |
|---|---|
|
container
|
|
|
ogg
Package ogg reads and writes Ogg Opus streams.
|
Package ogg reads and writes Ogg Opus streams. |
|
red
Package red implements RFC 2198 redundancy for RTP payloads.
|
Package red implements RFC 2198 redundancy for RTP payloads. |
|
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. |
|
internal/cleanup
Package cleanup reports errors from deferred example cleanup operations.
|
Package cleanup reports errors from deferred example cleanup operations. |
|
internal/wav
Package wav writes interleaved float32 PCM to classic RIFF/WAVE files.
|
Package wav writes interleaved float32 PCM to classic RIFF/WAVE files. |
|
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 exposes architecture feature flags.
|
Package cpufeat exposes architecture feature flags. |
|
dnnblob
Package dnnblob parses the USE_WEIGHTS_FILE format read by libopus `dnn/parse_lpcnet_weights.c`.
|
Package dnnblob parses the USE_WEIGHTS_FILE format read by libopus `dnn/parse_lpcnet_weights.c`. |
|
dnnmath
Package dnnmath provides float32 activation, exponent, quantization, and small-vector kernels used by the optional DRED, OSCE, and LPCNet networks.
|
Package dnnmath provides float32 activation, exponent, quantization, and small-vector kernels used by the optional DRED, OSCE, and LPCNet networks. |
|
dred
Package dred implements the experimental Opus Deep Redundancy (DRED) extension.
|
Package dred implements the experimental Opus Deep Redundancy (DRED) extension. |
|
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 stateful Opus encoder described by RFC 6716.
|
Package encoder implements the stateful Opus encoder described by RFC 6716. |
|
fixedpoint
Package fixedpoint contains integer CELT math helpers and the FIXED_POINT CELT encoder and decoder.
|
Package fixedpoint contains integer CELT math helpers and the FIXED_POINT CELT encoder and decoder. |
|
hybrid
Package hybrid implements the Opus Hybrid-mode decoder.
|
Package hybrid implements the Opus Hybrid-mode decoder. |
|
lpcnetplc
Package lpcnetplc implements the LPCNet feature prediction, pitch analysis, and FARGAN synthesis used by libopus's neural packet-loss concealment and DRED recovery paths.
|
Package lpcnetplc implements the LPCNet feature prediction, pitch analysis, and FARGAN synthesis used by libopus's neural packet-loss concealment and DRED recovery paths. |
|
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 the codec-specific concealment used after a lost Opus frame.
|
Package plc implements the codec-specific concealment used after a lost Opus frame. |
|
qualitycompare
Package qualitycompare provides the shared quality comparator for gopus and libopus parity tests.
|
Package qualitycompare provides the shared quality comparator for gopus and libopus parity tests. |
|
rangecoding
Package rangecoding implements the Opus range coder in RFC 6716 Section 4.1.
|
Package rangecoding implements the Opus range coder in RFC 6716 Section 4.1. |
|
silk
Package silk implements the SILK speech layer in RFC 6716 Section 4.2.
|
Package silk implements the SILK speech layer in RFC 6716 Section 4.2. |
|
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 encodes and decodes Opus packets with multiple elementary streams, as used for surround sound and ambisonics.
|
Package multistream encodes and decodes Opus packets with multiple elementary streams, as used for surround sound and ambisonics. |
|
scripts
|
|
|
benchmarks
Package benchmarks holds source templates that the native A/B workflow installs into the CELT package for architecture-specific measurements.
|
Package benchmarks holds source templates that the native A/B workflow installs into the CELT package for architecture-specific measurements. |
|
Package testvectors parses opus_demo bitstreams and supports quality checks against the RFC 8251 Opus test vectors.
|
Package testvectors parses opus_demo bitstreams and supports quality checks against the RFC 8251 Opus test vectors. |
|
tools
|
|
|
benchguard
command
|
|
|
encoderbenchcmp
command
|
|
|
qualityreport
command
|
|
|
safety_soak
command
|
|
|
testvectorbenchcmp
command
|
|
|
typeparityrewrite
command
|
|
|
Package types defines the Mode, Bandwidth, and Signal values shared by gopus packages.
|
Package types defines the Mode, Bandwidth, and Signal values shared by gopus packages. |