opus

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 25, 2026 License: BSD-2-Clause Imports: 11 Imported by: 0

README

Pure Go Opus Codec

Go Reference Test Race Fuzz License

日本語 | English

A pure-Go implementation of the Opus audio codec (RFC 6716 / RFC 8251) with no runtime CGO dependency. The decoder passes all 12 official RFC 8251 test vectors (RMSE < 0.001) and matches the libopus 1.6.1 reference frame-by-frame. The encoder implements the full CELT quality pipeline, plus a limited low-bitrate SILK-only speech path, and produces standard Opus packets that libopus decodes correctly — see Status.

Note: the encoder is not bit-exact with libopus. The CELT path is suitable for speech and music in pure Go. The SILK path is intentionally limited to low-bitrate speech, and hybrid encoding is currently limited to high-bitrate 24/48 kHz voice packets.

Status

Area State
Decoder ✅ Passes all 12 official RFC 8251 vectors (RMSE < 0.001); matches libopus 1.6.1 reference. SILK, CELT, and hybrid (SILK+CELT) modes are reconstructed, including hybrid SILK→CELT redundancy.
Encoder ✅ Full CELT quality pipeline (Phase 1+2), limited SILK-only speech encode for low-bitrate voice, and initial hybrid speech encode for high-bitrate 24/48 kHz voice. Emits standard Opus packets that libopus 1.6.1 decodes correctly. SNR: ~48 dB (440 Hz), ~47 dB (1 kHz), ~43 dB (stereo) at 64 kbps. Not bit-exact with libopus.
CGO None at runtime. A libopus wrapper exists only for reference tests, behind the opusref build tag.
CI test, race, bench, and fuzz workflows run on amd64 and arm64.

See docs/CURRENT_IMPLEMENTATION.md for the authoritative, code-derived snapshot.

Installation

go get github.com/darui3018823/opus

Requires Go 1.24 or newer (see go.mod).

Usage

Decoding (int16)
package main

import (
	"log"

	"github.com/darui3018823/opus"
)

func main() {
	// 48 kHz, stereo.
	dec, err := opus.NewDecoder(48000, 2)
	if err != nil {
		log.Fatal(err)
	}

	// packet is one Opus packet (e.g. read from a file or the network).
	var packet []byte

	// Buffer for the decoded PCM. 120 ms at 48 kHz (the largest Opus frame)
	// is 5760 samples per channel; size generously for the frames you expect.
	pcm := make([]int16, 5760*2)

	n, err := dec.Decode(packet, pcm)
	if err != nil {
		log.Fatal(err)
	}
	// pcm[:n*2] now holds interleaved stereo samples (n samples per channel).
	_ = n
}
Decoding (float64)
// DecodeFloat returns a freshly allocated, interleaved []float64.
samples, err := dec.DecodeFloat(packet)
if err != nil {
	log.Fatal(err)
}
_ = samples
Encoding
enc, err := opus.NewEncoder(48000, 2, opus.ApplicationAudio)
if err != nil {
	log.Fatal(err)
}
enc.SetBitrate(64000)
enc.SetComplexity(10)
enc.SetVBR(true) // variable bitrate (default: CBR)

// 20 ms frame = 960 samples per channel at 48 kHz, interleaved stereo.
pcm := make([]int16, 960*2)
// ... fill pcm ...

packet, err := enc.Encode(pcm, 960)
if err != nil {
	log.Fatal(err)
}
_ = packet

// Float64 input is also supported:
//   packet, err := enc.EncodeFloat(make([]float64, 960*2), 960)
// Float32 input is supported with EncodeFloat32.

// Bandwidth is detected automatically from signal content; override if needed:
//   enc.SetBandwidth(opus.BandwidthWideband) // force wideband
//   enc.SetBandwidth(opus.BandwidthAuto)     // restore auto

// Optional content hint independent of Application:
//   enc.SetSignalType(opus.SignalVoice)

// Short CELT packets and multi-frame packets are supported:
//   packet, err := enc.Encode(pcm480, 480)   // 10 ms at 48 kHz
//   packet, err := enc.Encode(pcm1920, 1920) // 40 ms

Supported Configurations

  • Sample rates: 8 kHz, 12 kHz, 16 kHz, 24 kHz, 48 kHz. Non-48 kHz input to the encoder is resampled to 48 kHz internally; the decoder resamples its output to the requested rate.
  • Channels: mono and stereo.
  • Decoder frame sizes: all Opus durations (2.5/5/10/20/40/60 ms), selected per packet by the TOC byte.
  • Encoder frame sizes: 2.5/5/10 ms CELT packets and exact 20 ms multiples from 20 ms through 120 ms (multi-frame, RFC 6716 §3.2).
  • Encoder bandwidth: automatic (signal-content-driven FFT detection) or manual (SetBandwidth/SetMaxBandwidth). Ranges: NB/WB/SWB/FB.
  • Encoder mode selection: CELT is used for general audio, music, restricted-low-delay, and voice above the useful hybrid range. Voice boundaries account for channel count and active LBRR: SILK-only extends to 40 kbps mono or 48 kbps stereo, with extra headroom when FEC is active; 24/48 kHz voice can use hybrid at intermediate rates, then returns to CELT.
  • Application types (drive bandwidth and transient-detection behaviour):
    • opus.ApplicationVOIP — narrower bandwidth tiers, eager short-block switching
    • opus.ApplicationAudio — music/general defaults
    • opus.ApplicationRestrictedLowDelay
  • Signal hints: opus.SignalAuto, opus.SignalVoice, and opus.SignalMusic can tune encoder heuristics without changing the Opus bitstream format.

Public API

The public version constants are generated from the repository's VERSION file.

MaxFrameSize is 5760 samples per channel at 48 kHz (120 ms). MaxFrameBytes is the 1275-byte compressed-frame limit. MaxPacketSize is a conservative unpadded single-stream packet storage bound; explicit packet padding can exceed it.

Encoder
func NewEncoder(sampleRate, channels int, application Application) (*Encoder, error)
func NewEncoderWithProfile(sampleRate, channels int, application Application, profile EncoderProfile) (*Encoder, error)

func (e *Encoder) Encode(pcm []int16, frameSize int) ([]byte, error)
func (e *Encoder) Encode24(pcm []int32, frameSize int) ([]byte, error)
func (e *Encoder) EncodeFloat(pcm []float64, frameSize int) ([]byte, error)
func (e *Encoder) EncodeFloat32(pcm []float32, frameSize int) ([]byte, error)

func (e *Encoder) Bitrate() int
func (e *Encoder) EffectiveBitrate() int
func (e *Encoder) Complexity() int
func (e *Encoder) VBR() bool
func (e *Encoder) VBRConstraint() bool
func (e *Encoder) Application() Application
func (e *Encoder) SampleRate() int
func (e *Encoder) Channels() int
func (e *Encoder) Lookahead() int
func (e *Encoder) FinalRange() uint32
func (e *Encoder) InDTX() bool

func (e *Encoder) SetBitrate(bitrate int) error       // 6000–510000 bps
func (e *Encoder) SetComplexity(complexity int) error  // 0–10
func (e *Encoder) SetVBR(vbr bool)
func (e *Encoder) SetVBRConstraint(constrained bool)   // true = CVBR
func (e *Encoder) SetApplication(application Application) error
func (e *Encoder) SetSignalType(signal SignalType)
func (e *Encoder) SignalType() SignalType
func (e *Encoder) SetBandwidth(bw int) error           // Auto/NB/WB/SWB/FB
func (e *Encoder) SetMaxBandwidth(bw int) error
func (e *Encoder) MaxBandwidth() int
func (e *Encoder) Bandwidth() int
func (e *Encoder) SetDTX(dtx bool)
func (e *Encoder) DTX() bool
func (e *Encoder) SetInbandFEC(enabled bool)             // SILK-only/hybrid
func (e *Encoder) InbandFEC() bool
func (e *Encoder) SetPacketLossPerc(perc int)            // clamped to 0–100
func (e *Encoder) PacketLossPerc() int
func (e *Encoder) SetPacketPadding(n int)
func (e *Encoder) SetForceChannels(channels int) error
func (e *Encoder) ForceChannels() int
func (e *Encoder) SetLSBDepth(depth int) error
func (e *Encoder) LSBDepth() int
func (e *Encoder) SetPredictionDisabled(disabled bool)
func (e *Encoder) PredictionDisabled() bool
func (e *Encoder) SetPhaseInversionDisabled(disabled bool)
func (e *Encoder) PhaseInversionDisabled() bool
func (e *Encoder) Reset() error

NewEncoder preserves the historical 64 kbit/s, complexity 5, CBR defaults. Use EncoderProfileLibopus for automatic bitrate, complexity 9, and constrained VBR defaults.

Concurrency and ownership

Encoder and Decoder are stateful and are not safe for concurrent use. Create one instance per logical Opus stream and preserve packet order. All methods on the same instance, including getters, configuration methods, and Reset, must be serialized by the caller, for example with a mutex. Separate instances may be used concurrently.

Do not copy an Encoder or Decoder after first use. Encode and decode methods borrow caller-provided PCM, packet, and destination slices only until the method returns. Returned encoded packets and PCM slices are owned by the caller.

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

func (d *Decoder) Decode(data []byte, pcm []int16) (int, error)
func (d *Decoder) Decode24(data []byte, pcm []int32) (int, error)
func (d *Decoder) DecodeFloat(data []byte) ([]float64, error)
func (d *Decoder) DecodeFloat32(data []byte) ([]float32, error)
func (d *Decoder) DecodePLC(pcm []int16, frameSize int) (int, error) // CELT-only after a successful CELT decode
func (d *Decoder) DecodeFEC(data []byte, pcm []int16) (int, error)   // SILK LBRR
func (d *Decoder) Reset() error
func (d *Decoder) GetLastPacketDuration() int
func (d *Decoder) SampleRate() int
func (d *Decoder) Channels() int
func (d *Decoder) FinalRange() uint32
func (d *Decoder) Pitch() int
func (d *Decoder) SetGain(gainQ8 int) error
func (d *Decoder) Gain() int
func (d *Decoder) SetPhaseInversionDisabled(disabled bool)
func (d *Decoder) PhaseInversionDisabled() bool
Multistream and surround
func NewMultistreamEncoder(sampleRate, channels, streams, coupledStreams int, mapping []byte, application Application) (*MultistreamEncoder, error)
func NewMultistreamDecoder(sampleRate, channels, streams, coupledStreams int, mapping []byte) (*MultistreamDecoder, error)

func NewSurroundEncoder(sampleRate, channels, mappingFamily int, application Application) (*SurroundEncoder, error)
func NewSurroundDecoder(sampleRate, channels, mappingFamily int) (*SurroundDecoder, error)

Multistream packets use RFC 6716 self-delimited framing and interoperate with libopus 1.6.1. Surround supports mapping families 0, 1 (Vorbis order, up to 7.1), and 255.

Projection and Ambisonics
func NewProjectionEncoder(sampleRate, channels, mappingFamily int, application Application) (*ProjectionEncoder, error)
func NewProjectionDecoder(sampleRate, channels, streams, coupledStreams int, demixingMatrix []byte) (*ProjectionDecoder, error)
func NewAmbisonicsEncoder(sampleRate, channels, mappingFamily int, application Application) (*ProjectionEncoder, error)
func NewAmbisonicsDecoder(sampleRate, channels, mappingFamily, streams, coupledStreams int, mapping, demixingMatrix []byte) (*AmbisonicsDecoder, error)

RFC 8486 mapping families 2 and 3 are supported. Family 2 uses ACN/SN3D Ambisonics channel mapping; family 3 uses the projection mixing/demixing matrices provided by libopus 1.6.1. Both families have bidirectional libopus interoperability tests.

Packet operations
func NewRepacketizer() *Repacketizer
func (r *Repacketizer) Cat(packet []byte) error
func (r *Repacketizer) NumFrames() int
func (r *Repacketizer) Out() ([]byte, error)
func (r *Repacketizer) OutRange(begin, end int) ([]byte, error)
func PacketPad(packet []byte, newLen int) ([]byte, error)
func PacketUnpad(packet []byte) ([]byte, error)
func PacketExtensionsCount(packet []byte) (int, error)
func PacketExtensionsParse(packet []byte) ([]PacketExtension, error)
func PacketExtensionsGenerate(packet []byte, extensions []PacketExtension, paddingBytes int) ([]byte, error)

Packet extensions are transported through code-3 padding. DRED and QEXT payloads are exposed as opaque data; their neural/DSP codecs are not implemented here.

Ogg Opus containers

The github.com/darui3018823/opus/oggopus package provides CRC-checked Ogg page parsing/writing, packet continuation and lacing, OpusHead/OpusTags metadata, and complete single-logical-stream Ogg Opus readers and writers.

Architecture

github.com/darui3018823/opus/
├── opus.go / multistream.go / surround.go / projection.go
├── extensions.go / repacketizer.go         # Packet operations
├── oggopus/                                # Ogg page and Ogg Opus APIs
├── internal/
│   ├── opus_framing.go                  # TOC byte parsing/generation (RFC 6716 §3)
│   ├── dsp/                             # FFT, MDCT/IMDCT, windows, math
│   ├── entcode/                         # Range encoder/decoder
│   ├── resampler/                       # Opus-rate sample rate conversion
│   ├── celt/                            # CELT decoder parity + simplified encoder
│   ├── silk/                            # SILK decoder/encoder, tables, helpers
│   └── cgoref/                          # libopus reference wrapper (build tag: opusref)
└── docs/                                # Design and status documentation

Decoding flow: Opus packet → TOC parsed → CELT or SILK/hybrid path → range decoder + reconstruction → optional resample/channel adjust → PCM.

Encoding flow: PCM → mode selection → either SILK-only speech encode (resampling 24/48 kHz voice input to WB SILK when selected) or optional resample to 48 kHz and CELT encode (MDCT, band processing, PVQ) → range coder → TOC prepended → Opus packet.

Building & Testing

go build ./...
go vet ./...
go test ./...                 # library packages + official vectors (when present)
go test -race ./...
go test -bench=. -benchmem -run='^$' ./...

Official RFC 8251 test vectors are not committed (testdata/ is git-ignored). Tests that need them call t.Skip when they are absent. To run them locally, download and extract the vectors so they land in testdata/opus_newvectors/:

curl -fSL -o /tmp/v.tar.gz https://opus-codec.org/docs/opus_testvectors-rfc8251.tar.gz
mkdir -p testdata && tar -xzf /tmp/v.tar.gz -C testdata/
go test -run TestOfficialVectors ./...
libopus reference comparison (optional)

The TestCGORef test decodes every vector with both this codec and libopus and compares them frame-by-frame. It requires a C toolchain plus libopus and is gated behind the opusref build tag (so normal builds stay CGO-free):

go test -tags opusref -run TestCGORef .

On Windows, run CGO builds from PowerShell with a working MinGW/MSYS2 toolchain.

Fuzzing
go test -run='^$' -fuzz='^FuzzDecode$' -fuzztime=60s .
go test -run='^$' -fuzz='^FuzzOggParsers$' -fuzztime=60s ./oggopus

The fuzz suite covers single-stream decoding, packet extensions, multistream self-delimited framing, repacketization/padding, and Ogg Opus parsing. The fuzz CI workflow runs every target nightly and on demand.

Continuous Integration

Four GitHub Actions workflows, each running on a matrix of amd64 (ubuntu-latest) and arm64 (ubuntu-24.04-arm):

  • test.ymlgo vet, go test ./..., and the official RFC 8251 vectors.
  • race.ymlgo test -race ./....
  • bench.ymlgo test -bench=. -benchmem, uploading results as artifacts.
  • fuzz.yml — nightly + manual go test -fuzz per target.

Documentation

Limitations

  • SILK/hybrid encode remains voice-oriented and does not yet reproduce every libopus mode boundary or quality decision.
  • The encoder is not bit-exact with libopus, but produces standards-conformant packets that any compliant decoder (including libopus) can decode.
  • VBR/CVBR and application/signal hints shape the CELT encoder heuristics, but do not provide full libopus-equivalent mode/rate-control behavior.
  • SILK-only and hybrid encoding can emit LBRR/in-band FEC for mono and stereo via SetInbandFEC(true) and a non-zero SetPacketLossPerc.
  • DecodeFEC recovers SILK-only and hybrid packets from LBRR in the following packet. Hybrid recovery contains the redundant SILK low band. DecodePLC currently supports CELT-only streams.
  • Projection family 3 uses the predefined libopus 1.6.1 matrices; the package does not currently generate arbitrary custom encoder matrices.
  • The Ogg Opus package handles one logical stream and does not provide seeking, chained-stream orchestration, or multiplexed-stream demux.
  • Multistream/surround do not yet expose every libopus multistream CTL or the complete libopus surround energy-mask analysis.

Contributing

See CONTRIBUTING.md for guidelines on how to contribute, report bugs, and submit pull requests.

Please note that this project is released with a Contributor Code of Conduct. By participating you agree to abide by its terms.

License

BSD 2-Clause License — see LICENSE.

Acknowledgments

  • libopus — reference implementation by the Xiph.Org Foundation.
  • RFC 6716 / RFC 8251 — the Opus specification and its updates.

Support

For issues and questions, please use the GitHub issue tracker.

Documentation

Overview

Package opus provides a Pure Go implementation of the Opus audio codec. This implementation is based on the official libopus reference implementation and aims for complete compatibility without using CGO.

Index

Constants

View Source
const (
	SampleRate8kHz  = 8000
	SampleRate12kHz = 12000
	SampleRate16kHz = 16000
	SampleRate24kHz = 24000
	SampleRate48kHz = 48000
)

Sample rates supported by Opus

View Source
const (
	FrameSize2_5ms = 120  // 2.5ms at 48kHz
	FrameSize5ms   = 240  // 5ms at 48kHz
	FrameSize10ms  = 480  // 10ms at 48kHz
	FrameSize20ms  = 960  // 20ms at 48kHz (most common)
	FrameSize40ms  = 1920 // 40ms at 48kHz
	FrameSize60ms  = 2880 // 60ms at 48kHz
	FrameSize80ms  = 3840 // 80ms at 48kHz
	FrameSize100ms = 4800 // 100ms at 48kHz
	FrameSize120ms = 5760 // 120ms at 48kHz (maximum packet duration)
)

Frame sizes in samples (at 48kHz)

View Source
const (
	ApplicationVOIP               = 2048 // Voice over IP
	ApplicationAudio              = 2049 // General audio
	ApplicationRestrictedLowDelay = 2051 // Lowest latency
)

Application types

View Source
const (
	BandwidthAuto          = -1000 // automatic selection (default)
	BandwidthNarrowband    = 1101  // 4kHz
	BandwidthMediumband    = 1102  // 6kHz
	BandwidthWideband      = 1103  // 8kHz
	BandwidthSuperWideband = 1104  // 12kHz
	BandwidthFullband      = 1105  // 20kHz
)

Bandwidth types

View Source
const (
	ChannelsAuto   = -1000
	ChannelsMono   = 1
	ChannelsStereo = 2
)

Channel modes

View Source
const (
	GainQ8Min = -32768
	GainQ8Max = 32767
)

Decoder gain is expressed in Q8 dB, matching OPUS_SET_GAIN.

View Source
const (
	LSBDepthMin     = 8
	LSBDepthMax     = 24
	LSBDepthDefault = 24
)

Encoder input precision hints accepted by SetLSBDepth.

View Source
const (
	ModeSILKOnly = 1000
	ModeHybrid   = 1001
	ModeCELTOnly = 1002
)

Opus modes (internal)

View Source
const (
	BitrateAuto   = -1000
	BitrateMax    = -1
	BitrateMin    = 500    // 500 bps
	BitrateMaxVal = 512000 // 512 kbps
)

Bitrate constants

View Source
const (
	SetBitrateRequest                = 4002
	GetBitrateRequest                = 4003
	SetForceChannelsRequest          = 4022
	GetForceChannelsRequest          = 4023
	SetMaxBandwidthRequest           = 4004
	GetMaxBandwidthRequest           = 4005
	SetBandwidthRequest              = 4008
	GetBandwidthRequest              = 4009
	SetComplexityRequest             = 4010
	GetComplexityRequest             = 4011
	SetInbandFECRequest              = 4012
	GetInbandFECRequest              = 4013
	SetPacketLossPercRequest         = 4014
	GetPacketLossPercRequest         = 4015
	SetDTXRequest                    = 4016
	GetDTXRequest                    = 4017
	SetVBRRequest                    = 4006
	GetVBRRequest                    = 4007
	SetVBRConstraintRequest          = 4020
	GetVBRConstraintRequest          = 4021
	SetSignalRequest                 = 4024
	GetSignalRequest                 = 4025
	SetApplicationRequest            = 4000
	GetApplicationRequest            = 4001
	GetLookaheadRequest              = 4027
	SetExpertFrameDurationRequest    = 4040
	GetExpertFrameDurationRequest    = 4041
	SetPredictionDisabledRequest     = 4042
	GetPredictionDisabledRequest     = 4043
	SetPhaseInversionDisabledRequest = 4046
	GetPhaseInversionDisabledRequest = 4047
	ResetStateRequest                = 4028
)

Encoder/Decoder control codes (CTL)

View Source
const (
	ComplexityMin     = 0
	ComplexityMax     = 10
	ComplexityDefault = 9
)

Complexity (0-10)

View Source
const (
	PacketLossPercMin = 0
	PacketLossPercMax = 100
)

Packet loss percentage (0-100)

View Source
const (
	// MaxFrameSize is the maximum decoded packet duration in samples per
	// channel at 48 kHz (120 ms).
	MaxFrameSize = FrameSize120ms

	// MaxFrameBytes is the RFC 6716 maximum compressed payload size of one
	// Opus frame.
	MaxFrameBytes = 1275

	// MaxPacketFrames is the maximum number of frames in one Opus packet.
	MaxPacketFrames = 48

	// MaxPacketSize is a conservative storage bound for an unpadded
	// single-stream Opus packet: up to two framing bytes plus MaxFrameBytes
	// for each frame. Explicit SetPacketPadding can produce larger packets.
	MaxPacketSize = (MaxFrameBytes + 2) * MaxPacketFrames
)

Public single-stream size limits.

View Source
const (
	// ExtensionFrameAll applies an extension to every frame in a packet.
	// Generation expands it to frame-specific entries and uses the Opus repeat
	// grammar when possible.
	ExtensionFrameAll = -1

	// ExtensionIDDRED is the extension ID assigned by libopus to Deep
	// Redundancy payloads. This package transports the payload but does not
	// implement the neural DRED codec.
	ExtensionIDDRED = 126

	// ExtensionIDQEXT is the extension ID assigned by libopus to CELT quality
	// extension payloads. This package transports the payload but does not
	// implement QEXT DSP.
	ExtensionIDQEXT = 124
)
View Source
const (
	MappingFamilyMonoStereo = 0
	MappingFamilyVorbis     = 1
	MappingFamilyAmbisonics = 2
	MappingFamilyDiscrete   = 255
)

Opus channel mapping families used by Ogg Opus and the libopus surround API.

View Source
const (
	Version      = "1.2.0"
	VersionMajor = 1
	VersionMinor = 2
	VersionPatch = 0
)

Public module version generated from VERSION.

View Source
const (
	// MappingFamilyProjection identifies RFC 8486 family 3: ACN/SN3D
	// Ambisonics represented through a mixing/demixing matrix pair.
	MappingFamilyProjection = 3
)

Variables

View Source
var (
	// ErrBadArg indicates that one or more arguments are invalid
	ErrBadArg = errors.New("opus: bad argument")

	// ErrBufferTooSmall indicates that the provided buffer is too small
	ErrBufferTooSmall = errors.New("opus: buffer too small")

	// ErrInternalError indicates an internal error occurred
	ErrInternalError = errors.New("opus: internal error")

	// ErrInvalidPacket indicates the packet is invalid or corrupted
	ErrInvalidPacket = errors.New("opus: invalid packet")

	// ErrUnimplemented indicates a feature is not yet implemented
	ErrUnimplemented = errors.New("opus: unimplemented")

	// ErrInvalidState indicates the encoder/decoder is in an invalid state
	ErrInvalidState = errors.New("opus: invalid state")

	// ErrAllocFail indicates memory allocation failed
	ErrAllocFail = errors.New("opus: allocation failed")

	// ErrUnsupportedSampleRate indicates the sample rate is not supported
	ErrUnsupportedSampleRate = errors.New("opus: unsupported sample rate")

	// ErrUnsupportedChannels indicates the channel count is not supported
	ErrUnsupportedChannels = errors.New("opus: unsupported number of channels")

	// ErrUnsupportedFrameSize indicates the frame size is not supported
	ErrUnsupportedFrameSize = errors.New("opus: unsupported frame size")

	// ErrUnsupportedBandwidth indicates the bandwidth is not supported
	ErrUnsupportedBandwidth = errors.New("opus: unsupported bandwidth")
)

Common Opus errors

Functions

func PacketExtensionsCount added in v1.2.0

func PacketExtensionsCount(packet []byte) (int, error)

PacketExtensionsCount validates packet framing and its padding extension stream, then returns the number of extensions after repeat expansion.

func PacketExtensionsGenerate added in v1.2.0

func PacketExtensionsGenerate(packet []byte, extensions []PacketExtension, paddingBytes int) ([]byte, error)

PacketExtensionsGenerate returns a packet with the same encoded audio frames and a replacement extension stream in its code-3 padding area.

paddingBytes is the exact size of the trailing extension/padding area. Zero selects the minimal size. A positive value smaller than the encoded extension stream returns ErrBufferTooSmall. Existing packet padding and extensions are replaced.

func PacketGetBandwidth added in v1.2.0

func PacketGetBandwidth(data []byte) (int, error)

PacketGetBandwidth returns one of the Bandwidth* constants.

func PacketGetConfig added in v1.2.0

func PacketGetConfig(data []byte) (int, error)

PacketGetConfig returns the RFC 6716 TOC configuration number (0-31).

func PacketGetMode added in v1.2.0

func PacketGetMode(data []byte) (int, error)

PacketGetMode returns ModeSILKOnly, ModeHybrid, or ModeCELTOnly.

func PacketGetNumChannels added in v1.2.0

func PacketGetNumChannels(data []byte) (int, error)

PacketGetNumChannels returns the channel count encoded in the packet TOC.

func PacketGetNumFrames added in v1.2.0

func PacketGetNumFrames(data []byte) (int, error)

PacketGetNumFrames returns the number of Opus frames in the packet.

func PacketGetNumSamples added in v1.2.0

func PacketGetNumSamples(data []byte, sampleRate int) (int, error)

PacketGetNumSamples returns the packet duration in samples per channel when decoded at sampleRate.

func PacketGetSamplesPerFrame added in v1.2.0

func PacketGetSamplesPerFrame(data []byte, sampleRate int) (int, error)

PacketGetSamplesPerFrame returns the number of samples per channel in each Opus frame when decoded at sampleRate.

func PacketPad added in v1.2.0

func PacketPad(packet []byte, newLen int) ([]byte, error)

PacketPad returns packet padded to exactly newLen bytes using RFC 6716 code-3 packet padding. The encoded Opus frames are not modified.

func PacketUnpad added in v1.2.0

func PacketUnpad(packet []byte) ([]byte, error)

PacketUnpad removes RFC 6716 packet padding and returns canonical compact framing for the packet's unchanged Opus frames.

Types

type AmbisonicsDecoder added in v1.2.0

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

AmbisonicsDecoder decodes RFC 8486 family 2 or 3.

func NewAmbisonicsDecoder added in v1.2.0

func NewAmbisonicsDecoder(sampleRate, channels, mappingFamily, streams, coupledStreams int, mapping, demixingMatrix []byte) (*AmbisonicsDecoder, error)

NewAmbisonicsDecoder creates a decoder from RFC 8486 signalling fields. Family 2 uses mapping and ignores demixingMatrix. Family 3 ignores mapping and requires demixingMatrix.

func (*AmbisonicsDecoder) Decode added in v1.2.0

func (d *AmbisonicsDecoder) Decode(data []byte, pcm []int16) (int, error)

func (*AmbisonicsDecoder) Decode24 added in v1.2.0

func (d *AmbisonicsDecoder) Decode24(data []byte, pcm []int32) (int, error)

func (*AmbisonicsDecoder) DecodeFloat added in v1.2.0

func (d *AmbisonicsDecoder) DecodeFloat(data []byte) ([]float64, error)

func (*AmbisonicsDecoder) DecodeFloat32 added in v1.2.0

func (d *AmbisonicsDecoder) DecodeFloat32(data []byte) ([]float32, error)

func (*AmbisonicsDecoder) FinalRange added in v1.2.0

func (d *AmbisonicsDecoder) FinalRange() uint32

func (*AmbisonicsDecoder) MappingFamily added in v1.2.0

func (d *AmbisonicsDecoder) MappingFamily() int

func (*AmbisonicsDecoder) Reset added in v1.2.0

func (d *AmbisonicsDecoder) Reset() error

type Application

type Application = int

Application specifies the encoding mode (use constants from package)

type Decoder

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

Decoder represents the state of one Opus stream decoder.

A Decoder is stateful, must not be copied after first use, and is not safe for concurrent use. Packets for a logical stream must be supplied in decode order, and calls to Decode, DecodePLC, DecodeFEC, getters, SetGain, and Reset on the same instance must be serialized by the caller. Separate Decoder instances may be used concurrently.

Decode methods borrow packet and destination slices only for the duration of the call. Slices returned by DecodeFloat and DecodeFloat32 are owned by the caller.

func NewDecoder

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

NewDecoder creates a new Opus decoder

sampleRate must be one of: 8000, 12000, 16000, 24000, 48000 Hz channels must be 1 (mono) or 2 (stereo)

func (*Decoder) Channels added in v1.2.0

func (d *Decoder) Channels() int

Channels returns the decoder output channel count.

func (*Decoder) Decode

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

Decode decodes an Opus packet to PCM samples

data is the compressed Opus packet pcm is the output buffer for 16-bit PCM samples Returns the number of samples per channel decoded.

func (*Decoder) Decode24 added in v1.2.0

func (d *Decoder) Decode24(data []byte, pcm []int32) (int, error)

Decode24 decodes an Opus packet to interleaved signed 24-bit PCM stored in int32 values. Output is saturated to [-8388608, 8388607].

func (*Decoder) DecodeFEC

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

DecodeFEC decodes SILK in-band forward-error-correction data from the packet following a loss. The recovered duration is inferred from the packet. SILK-only and hybrid packets are supported; CELT-only packets have no LBRR.

func (*Decoder) DecodeFloat

func (d *Decoder) DecodeFloat(data []byte) ([]float64, error)

DecodeFloat decodes an Opus packet to floating-point PCM samples

data is the compressed Opus packet Returns float64 samples in range [-1.0, 1.0]

func (*Decoder) DecodeFloat32 added in v1.2.0

func (d *Decoder) DecodeFloat32(data []byte) ([]float32, error)

DecodeFloat32 decodes an Opus packet to interleaved float32 PCM samples.

func (*Decoder) DecodePLC added in v1.2.0

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

DecodePLC performs packet-loss concealment for frameSize samples per channel.

The current implementation supports CELT-only streams after at least one successful CELT decode. frameSize must be a valid Opus packet duration, an integer multiple of the active CELT frame duration, and at most 120 ms. SILK-only and hybrid PLC currently return ErrUnimplemented.

func (*Decoder) FinalRange added in v1.2.0

func (d *Decoder) FinalRange() uint32

FinalRange returns the XOR of the entropy decoder final ranges for the most recently decoded packet's constituent Opus frames.

func (*Decoder) Gain added in v1.2.0

func (d *Decoder) Gain() int

Gain returns the configured decoder output gain in Q8 dB.

func (*Decoder) GetLastPacketDuration

func (d *Decoder) GetLastPacketDuration() int

GetLastPacketDuration returns the duration of the last decoded packet in samples

func (*Decoder) PhaseInversionDisabled added in v1.2.0

func (d *Decoder) PhaseInversionDisabled() bool

PhaseInversionDisabled reports the decoder phase-inversion setting.

func (*Decoder) Pitch added in v1.2.0

func (d *Decoder) Pitch() int

Pitch returns the most recently reported decoder pitch period in samples at the decoder output rate. Zero means no pitch period is currently available.

func (*Decoder) Reset

func (d *Decoder) Reset() error

Reset resets the decoder state

func (*Decoder) SampleRate added in v1.2.0

func (d *Decoder) SampleRate() int

SampleRate returns the decoder output sample rate in Hz.

func (*Decoder) SetGain added in v1.2.0

func (d *Decoder) SetGain(gainQ8 int) error

SetGain sets the decoder output gain in Q8 dB.

func (*Decoder) SetPhaseInversionDisabled added in v1.2.0

func (d *Decoder) SetPhaseInversionDisabled(disabled bool)

SetPhaseInversionDisabled disables intensity-stereo phase inversion while decoding CELT. This is intended for compatibility with downmixing pipelines; disabling it is not compliant with the Opus specification.

type Encoder

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

Encoder represents the state of one Opus stream encoder.

An Encoder is stateful, must not be copied after first use, and is not safe for concurrent use. Calls to Encode, configuration methods, getters, and Reset on the same instance must be serialized by the caller. Separate Encoder instances may be used concurrently.

Encode methods borrow the input PCM only for the duration of the call and return a packet owned by the caller.

func NewEncoder

func NewEncoder(sampleRate, channels int, application Application) (*Encoder, error)

NewEncoder creates a new Opus encoder

sampleRate must be one of: 8000, 12000, 16000, 24000, 48000 Hz channels must be 1 (mono) or 2 (stereo) application specifies the encoding mode

func NewEncoderWithProfile added in v1.2.0

func NewEncoderWithProfile(sampleRate, channels int, application Application, profile EncoderProfile) (*Encoder, error)

NewEncoderWithProfile creates an encoder with an explicit defaults profile. NewEncoder remains equivalent to EncoderProfileLegacy for compatibility.

func (*Encoder) Application added in v1.1.1

func (e *Encoder) Application() Application

Application returns the current application mode.

func (*Encoder) Bandwidth added in v1.1.0

func (e *Encoder) Bandwidth() int

Bandwidth reports the coded bandwidth the encoder would currently use, as a public Bandwidth* constant.

func (*Encoder) Bitrate added in v1.1.1

func (e *Encoder) Bitrate() int

Bitrate returns the configured target bitrate. It returns BitrateAuto or BitrateMax when that policy is configured.

func (*Encoder) Channels added in v1.2.0

func (e *Encoder) Channels() int

Channels returns the encoder input channel count.

func (*Encoder) Complexity added in v1.1.1

func (e *Encoder) Complexity() int

Complexity returns the current complexity setting (0–10).

func (*Encoder) DTX added in v1.1.0

func (e *Encoder) DTX() bool

DTX reports whether discontinuous transmission is enabled.

func (*Encoder) EffectiveBitrate added in v1.2.0

func (e *Encoder) EffectiveBitrate() int

EffectiveBitrate returns the numeric bitrate currently applied internally. For BitrateAuto and BitrateMax this is updated for each encoded frame size.

func (*Encoder) Encode

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

Encode encodes PCM audio samples

pcm contains interleaved 16-bit PCM samples (left, right, left, right, ...) frameSize is the number of samples per channel (at the encoder's sample rate) Returns compressed Opus packet

func (*Encoder) Encode24 added in v1.2.0

func (e *Encoder) Encode24(pcm []int32, frameSize int) ([]byte, error)

Encode24 encodes interleaved signed 24-bit PCM stored in int32 values. The nominal input range is [-8388608, 8388607].

func (*Encoder) EncodeFloat

func (e *Encoder) EncodeFloat(pcm []float64, frameSize int) ([]byte, error)

EncodeFloat encodes floating-point PCM samples

pcm contains interleaved float64 samples in range [-1.0, 1.0] frameSize is the number of samples per channel (at the encoder's sample rate)

func (*Encoder) EncodeFloat32 added in v1.2.0

func (e *Encoder) EncodeFloat32(pcm []float32, frameSize int) ([]byte, error)

EncodeFloat32 encodes interleaved float32 PCM samples in range [-1.0, 1.0]. frameSize is the number of samples per channel at the encoder sample rate.

func (*Encoder) FinalRange added in v1.2.0

func (e *Encoder) FinalRange() uint32

FinalRange returns the XOR of the entropy coder final ranges for the most recently encoded packet's constituent Opus frames.

func (*Encoder) ForceChannels added in v1.2.0

func (e *Encoder) ForceChannels() int

ForceChannels returns the configured forced stream channel count.

func (*Encoder) InDTX added in v1.2.0

func (e *Encoder) InDTX() bool

InDTX reports whether the most recently encoded packet used the encoder's DTX silence path.

func (*Encoder) InbandFEC added in v1.2.0

func (e *Encoder) InbandFEC() bool

InbandFEC reports whether inband FEC is enabled.

func (*Encoder) LSBDepth added in v1.2.0

func (e *Encoder) LSBDepth() int

LSBDepth returns the configured input precision hint.

func (*Encoder) Lookahead added in v1.2.0

func (e *Encoder) Lookahead() int

Lookahead returns the codec lookahead in samples at the encoder input rate.

func (*Encoder) MaxBandwidth added in v1.2.0

func (e *Encoder) MaxBandwidth() int

MaxBandwidth returns the configured automatic bandwidth cap.

func (*Encoder) PacketLossPerc added in v1.2.0

func (e *Encoder) PacketLossPerc() int

PacketLossPerc reports the configured expected packet-loss percentage.

func (*Encoder) PhaseInversionDisabled added in v1.2.0

func (e *Encoder) PhaseInversionDisabled() bool

PhaseInversionDisabled reports the encoder phase-inversion setting.

func (*Encoder) PredictionDisabled added in v1.2.0

func (e *Encoder) PredictionDisabled() bool

PredictionDisabled reports whether predictive mode routing is disabled.

func (*Encoder) Reset

func (e *Encoder) Reset() error

Reset resets the encoder state

func (*Encoder) SampleRate added in v1.2.0

func (e *Encoder) SampleRate() int

SampleRate returns the encoder input sample rate in Hz.

func (*Encoder) SetApplication

func (e *Encoder) SetApplication(application Application) error

SetApplication changes the application mode. This re-derives the CELT content hint (voice for VOIP, music otherwise), which influences bandwidth selection and transient sensitivity; it does not affect already-emitted packets. Invalid application values return ErrBadArg and leave the encoder unchanged.

func (*Encoder) SetBandwidth added in v1.1.0

func (e *Encoder) SetBandwidth(bw int) error

SetBandwidth forces a specific coded bandwidth, overriding the automatic selection (it is still clamped to the input sample rate's Nyquist limit). Pass BandwidthAuto to return to automatic selection (the default). bw must be BandwidthAuto or one of the public Bandwidth* constants. CELT has no medium-band mode, so BandwidthMediumband is rounded up to BandwidthWideband.

func (*Encoder) SetBitrate

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

SetBitrate sets the target bitrate in bits per second

func (*Encoder) SetComplexity

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

SetComplexity sets the computational complexity (0-10) Higher values use more CPU but may provide better quality

func (*Encoder) SetDTX added in v1.1.0

func (e *Encoder) SetDTX(enabled bool)

SetDTX enables or disables discontinuous transmission. When enabled, frames the encoder detects as silent are emitted as minimal packets (a few bytes) instead of being padded to the target size. This reduces bitrate during silence. The decoder reconstructs such frames as digital silence. DTX is off by default. The reduction is effective in any rate mode; in CBR it overrides the fixed-size padding for silent CELT frames, while SILK digital-silence frames are kept compact even without DTX.

func (*Encoder) SetForceChannels added in v1.2.0

func (e *Encoder) SetForceChannels(channels int) error

SetForceChannels controls the channel count written to the Opus stream. ChannelsAuto uses the constructor channel count. A stereo encoder may be forced to mono; forcing stereo from a mono input is invalid.

func (*Encoder) SetInbandFEC added in v1.2.0

func (e *Encoder) SetInbandFEC(enabled bool)

SetInbandFEC enables or disables SILK inband forward error correction (LBRR). When enabled together with a non-zero packet-loss percentage, SILK-only packets carry a low-bitrate redundant copy of the previous packet's frame(s), which a decoder can recover via its decode_fec path after a lost packet. FEC applies to SILK-only and hybrid speech paths; it is off by default and has no effect on CELT-only packets.

func (*Encoder) SetLSBDepth added in v1.2.0

func (e *Encoder) SetLSBDepth(depth int) error

SetLSBDepth sets the input precision hint in bits per sample.

func (*Encoder) SetMaxBandwidth added in v1.1.0

func (e *Encoder) SetMaxBandwidth(bw int) error

SetMaxBandwidth caps the automatically selected coded bandwidth. bw must be one of the public Bandwidth* constants (Narrowband..Fullband). The encoder never exceeds this cap, nor the input sample rate's Nyquist limit. The default is BandwidthFullband (no extra cap). Has no effect when an explicit bandwidth is forced via SetBandwidth.

func (*Encoder) SetPacketLossPerc added in v1.2.0

func (e *Encoder) SetPacketLossPerc(perc int)

SetPacketLossPerc sets the expected packet-loss percentage (0..100) used to tune the FEC redundancy (higher loss → smaller, more frequent LBRR frames). With FEC enabled, a value of 0 disables LBRR emission.

func (*Encoder) SetPacketPadding added in v1.1.0

func (e *Encoder) SetPacketPadding(n int)

SetPacketPadding sets the number of code-3 padding-data bytes appended to each emitted packet (RFC 6716 §3.2.5). When n > 0, every packet is encoded as a code-3 packet with the padding flag set and n zero bytes appended at the end; the padding does not affect the decoded audio (the decoder strips it). This is useful for keeping a constant on-the-wire packet size or for obscuring the true payload length. n <= 0 disables padding (the default), restoring the compact code-0/1/2/3 selection.

func (*Encoder) SetPhaseInversionDisabled added in v1.2.0

func (e *Encoder) SetPhaseInversionDisabled(disabled bool)

SetPhaseInversionDisabled disables CELT intensity-stereo phase inversion.

func (*Encoder) SetPredictionDisabled added in v1.2.0

func (e *Encoder) SetPredictionDisabled(disabled bool)

SetPredictionDisabled disables predictive SILK/hybrid mode routing. CELT remains available for all supported frame durations.

func (*Encoder) SetSignalType added in v1.1.1

func (e *Encoder) SetSignalType(s SignalType)

SetSignalType overrides the content hint used by encoder heuristics. SignalAuto (the default) re-derives the hint from the current Application setting (VOIP → voice, otherwise music). Calling this with SignalVoice or SignalMusic pins the hint regardless of the Application value; a subsequent SetApplication call will overwrite it again.

func (*Encoder) SetVBR

func (e *Encoder) SetVBR(vbr bool)

SetVBR enables or disables variable bitrate mode. When enabled, this sets constrained VBR (CVBR), which is the libopus default: the encoder produces variable-size packets but keeps the average bitrate close to the target. Use SetVBRConstraint(false) for unconstrained VBR.

func (*Encoder) SetVBRConstraint added in v1.1.0

func (e *Encoder) SetVBRConstraint(constrained bool)

SetVBRConstraint controls the VBR constraint. When true (default), CVBR is used; when false, unconstrained VBR is used. Has no effect if VBR is disabled.

func (*Encoder) SignalType added in v1.1.1

func (e *Encoder) SignalType() SignalType

SignalType reports the current content hint.

func (*Encoder) VBR added in v1.1.1

func (e *Encoder) VBR() bool

VBR reports whether variable bitrate is enabled.

func (*Encoder) VBRConstraint added in v1.2.0

func (e *Encoder) VBRConstraint() bool

VBRConstraint reports whether constrained VBR is enabled.

type EncoderProfile added in v1.2.0

type EncoderProfile int

EncoderProfile selects constructor defaults without changing the encoded Opus format or the available controls.

const (
	// EncoderProfileLegacy preserves NewEncoder's historical defaults:
	// 64 kbit/s, complexity 5, and CBR.
	EncoderProfileLegacy EncoderProfile = iota
	// EncoderProfileLibopus uses libopus-style defaults: automatic bitrate,
	// complexity 9, and constrained VBR.
	EncoderProfileLibopus
)

type MappingMatrix added in v1.2.0

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

MappingMatrix is an RFC 8486 Q15 matrix stored in column-major order. Gain is expressed in signed Q8 dB (S7.8), as in libopus.

func NewMappingMatrix added in v1.2.0

func NewMappingMatrix(rows, cols, gain int, data []int16) (*MappingMatrix, error)

NewMappingMatrix validates and copies a Q15, column-major matrix.

func NewMappingMatrixFromBytes added in v1.2.0

func NewMappingMatrixFromBytes(rows, cols, gain int, data []byte) (*MappingMatrix, error)

NewMappingMatrixFromBytes decodes little-endian Q15 coefficients in the format stored by RFC 8486 and returned by libopus' projection encoder.

func (*MappingMatrix) At added in v1.2.0

func (m *MappingMatrix) At(row, col int) (int16, error)

At returns the coefficient at row, col.

func (*MappingMatrix) Bytes added in v1.2.0

func (m *MappingMatrix) Bytes() []byte

Bytes returns the RFC 8486 little-endian matrix representation.

func (*MappingMatrix) Coefficients added in v1.2.0

func (m *MappingMatrix) Coefficients() []int16

Coefficients returns a copy of the column-major Q15 coefficients.

func (*MappingMatrix) Cols added in v1.2.0

func (m *MappingMatrix) Cols() int

func (*MappingMatrix) Gain added in v1.2.0

func (m *MappingMatrix) Gain() int

func (*MappingMatrix) Rows added in v1.2.0

func (m *MappingMatrix) Rows() int

type MultistreamDecoder added in v1.2.0

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

MultistreamDecoder decodes RFC 7845 multistream packets.

func NewMultistreamDecoder added in v1.2.0

func NewMultistreamDecoder(sampleRate, channels, streams, coupledStreams int, mapping []byte) (*MultistreamDecoder, error)

NewMultistreamDecoder creates a multistream decoder.

func (*MultistreamDecoder) Channels added in v1.2.0

func (d *MultistreamDecoder) Channels() int

func (*MultistreamDecoder) CoupledStreams added in v1.2.0

func (d *MultistreamDecoder) CoupledStreams() int

func (*MultistreamDecoder) Decode added in v1.2.0

func (d *MultistreamDecoder) Decode(data []byte, pcm []int16) (int, error)

Decode decodes a multistream packet to interleaved int16 PCM.

func (*MultistreamDecoder) Decode24 added in v1.2.0

func (d *MultistreamDecoder) Decode24(data []byte, pcm []int32) (int, error)

Decode24 decodes a multistream packet to signed 24-bit PCM in int32 values.

func (*MultistreamDecoder) DecodeFloat added in v1.2.0

func (d *MultistreamDecoder) DecodeFloat(data []byte) ([]float64, error)

DecodeFloat decodes a multistream packet to interleaved float64 PCM.

func (*MultistreamDecoder) DecodeFloat32 added in v1.2.0

func (d *MultistreamDecoder) DecodeFloat32(data []byte) ([]float32, error)

DecodeFloat32 decodes a multistream packet to interleaved float32 PCM.

func (*MultistreamDecoder) FinalRange added in v1.2.0

func (d *MultistreamDecoder) FinalRange() uint32

FinalRange returns the XOR of all elementary stream final ranges.

func (*MultistreamDecoder) Mapping added in v1.2.0

func (d *MultistreamDecoder) Mapping() []byte

func (*MultistreamDecoder) Reset added in v1.2.0

func (d *MultistreamDecoder) Reset() error

Reset resets every elementary decoder.

func (*MultistreamDecoder) SampleRate added in v1.2.0

func (d *MultistreamDecoder) SampleRate() int

func (*MultistreamDecoder) StreamDecoder added in v1.2.0

func (d *MultistreamDecoder) StreamDecoder(stream int) (*Decoder, error)

StreamDecoder returns the elementary decoder for stream.

func (*MultistreamDecoder) Streams added in v1.2.0

func (d *MultistreamDecoder) Streams() int

type MultistreamEncoder added in v1.2.0

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

MultistreamEncoder encodes several elementary Opus streams into one RFC 7845 multistream packet. Coupled streams precede mono streams.

func NewMultistreamEncoder added in v1.2.0

func NewMultistreamEncoder(sampleRate, channels, streams, coupledStreams int, mapping []byte, application Application) (*MultistreamEncoder, error)

NewMultistreamEncoder creates a multistream encoder. mapping maps each input channel to a coded channel index, or 255 to omit that channel.

func (*MultistreamEncoder) Bitrate added in v1.2.0

func (e *MultistreamEncoder) Bitrate() int

Bitrate returns the configured aggregate bitrate policy.

func (*MultistreamEncoder) Channels added in v1.2.0

func (e *MultistreamEncoder) Channels() int

Channels returns the number of interleaved input channels.

func (*MultistreamEncoder) CoupledStreams added in v1.2.0

func (e *MultistreamEncoder) CoupledStreams() int

CoupledStreams returns the number of stereo elementary streams.

func (*MultistreamEncoder) Encode added in v1.2.0

func (e *MultistreamEncoder) Encode(pcm []int16, frameSize int) ([]byte, error)

Encode encodes interleaved int16 PCM.

func (*MultistreamEncoder) Encode24 added in v1.2.0

func (e *MultistreamEncoder) Encode24(pcm []int32, frameSize int) ([]byte, error)

Encode24 encodes interleaved signed 24-bit PCM stored in int32 values.

func (*MultistreamEncoder) EncodeFloat added in v1.2.0

func (e *MultistreamEncoder) EncodeFloat(pcm []float64, frameSize int) ([]byte, error)

EncodeFloat encodes interleaved float64 PCM.

func (*MultistreamEncoder) EncodeFloat32 added in v1.2.0

func (e *MultistreamEncoder) EncodeFloat32(pcm []float32, frameSize int) ([]byte, error)

EncodeFloat32 encodes interleaved float32 PCM.

func (*MultistreamEncoder) FinalRange added in v1.2.0

func (e *MultistreamEncoder) FinalRange() uint32

FinalRange returns the XOR of all elementary stream final ranges.

func (*MultistreamEncoder) Mapping added in v1.2.0

func (e *MultistreamEncoder) Mapping() []byte

Mapping returns a copy of the channel mapping.

func (*MultistreamEncoder) Reset added in v1.2.0

func (e *MultistreamEncoder) Reset() error

Reset resets every elementary encoder while retaining configuration.

func (*MultistreamEncoder) SampleRate added in v1.2.0

func (e *MultistreamEncoder) SampleRate() int

SampleRate returns the encoder input sample rate.

func (*MultistreamEncoder) SetBitrate added in v1.2.0

func (e *MultistreamEncoder) SetBitrate(bitrate int) error

SetBitrate sets the aggregate bitrate and distributes it by coded channel count. BitrateAuto and BitrateMax are applied to every elementary encoder.

func (*MultistreamEncoder) SetComplexity added in v1.2.0

func (e *MultistreamEncoder) SetComplexity(complexity int) error

SetComplexity applies a complexity setting to every elementary stream.

func (*MultistreamEncoder) SetVBR added in v1.2.0

func (e *MultistreamEncoder) SetVBR(enabled bool)

SetVBR applies the VBR setting to every elementary stream.

func (*MultistreamEncoder) SetVBRConstraint added in v1.2.0

func (e *MultistreamEncoder) SetVBRConstraint(enabled bool)

SetVBRConstraint applies constrained VBR to every elementary stream.

func (*MultistreamEncoder) StreamEncoder added in v1.2.0

func (e *MultistreamEncoder) StreamEncoder(stream int) (*Encoder, error)

StreamEncoder returns the elementary encoder for stream.

func (*MultistreamEncoder) Streams added in v1.2.0

func (e *MultistreamEncoder) Streams() int

Streams returns the number of elementary Opus streams.

type PacketExtension added in v1.2.0

type PacketExtension struct {
	ID    int
	Frame int
	Data  []byte
}

PacketExtension is an opaque Opus packet extension associated with one zero-based frame. Data is copied on both input and output.

func PacketExtensionsParse added in v1.2.0

func PacketExtensionsParse(packet []byte) ([]PacketExtension, error)

PacketExtensionsParse returns packet extensions in bitstream order. Repeat indicators are expanded into frame-specific entries.

type ProjectionDecoder added in v1.2.0

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

ProjectionDecoder decodes a multistream packet and applies an RFC 8486 family-3 demixing matrix.

func NewProjectionDecoder added in v1.2.0

func NewProjectionDecoder(sampleRate, channels, streams, coupledStreams int, demixingMatrix []byte) (*ProjectionDecoder, error)

NewProjectionDecoder creates a family-3 decoder from the little-endian Q15 matrix stored in signalling metadata. The matrix must have channels rows and streams+coupledStreams columns.

func (*ProjectionDecoder) Channels added in v1.2.0

func (d *ProjectionDecoder) Channels() int

func (*ProjectionDecoder) CoupledStreams added in v1.2.0

func (d *ProjectionDecoder) CoupledStreams() int

func (*ProjectionDecoder) Decode added in v1.2.0

func (d *ProjectionDecoder) Decode(data []byte, pcm []int16) (int, error)

func (*ProjectionDecoder) Decode24 added in v1.2.0

func (d *ProjectionDecoder) Decode24(data []byte, pcm []int32) (int, error)

func (*ProjectionDecoder) DecodeFloat added in v1.2.0

func (d *ProjectionDecoder) DecodeFloat(data []byte) ([]float64, error)

func (*ProjectionDecoder) DecodeFloat32 added in v1.2.0

func (d *ProjectionDecoder) DecodeFloat32(data []byte) ([]float32, error)

func (*ProjectionDecoder) FinalRange added in v1.2.0

func (d *ProjectionDecoder) FinalRange() uint32

func (*ProjectionDecoder) Reset added in v1.2.0

func (d *ProjectionDecoder) Reset() error

func (*ProjectionDecoder) SampleRate added in v1.2.0

func (d *ProjectionDecoder) SampleRate() int

func (*ProjectionDecoder) StreamDecoder added in v1.2.0

func (d *ProjectionDecoder) StreamDecoder(stream int) (*Decoder, error)

func (*ProjectionDecoder) Streams added in v1.2.0

func (d *ProjectionDecoder) Streams() int

type ProjectionEncoder added in v1.2.0

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

ProjectionEncoder encodes RFC 8486 mapping family 2 or 3 Ambisonics. The packet payload is an ordinary Opus multistream packet; family, stream counts, mapping, demixing matrix, and matrix gain belong in container or signalling metadata.

func NewAmbisonicsEncoder added in v1.2.0

func NewAmbisonicsEncoder(sampleRate, channels, mappingFamily int, application Application) (*ProjectionEncoder, error)

NewAmbisonicsEncoder is an alias for NewProjectionEncoder.

func NewProjectionEncoder added in v1.2.0

func NewProjectionEncoder(sampleRate, channels, mappingFamily int, application Application) (*ProjectionEncoder, error)

NewProjectionEncoder creates an Ambisonics encoder for RFC 8486 mapping family 2 or 3. Family 2 supports orders 0 through 14; family 3 uses the first- through fifth-order matrices provided by libopus 1.6.1.

func (*ProjectionEncoder) Bitrate added in v1.2.0

func (e *ProjectionEncoder) Bitrate() int

func (*ProjectionEncoder) Channels added in v1.2.0

func (e *ProjectionEncoder) Channels() int

func (*ProjectionEncoder) CoupledStreams added in v1.2.0

func (e *ProjectionEncoder) CoupledStreams() int

func (*ProjectionEncoder) DemixingMatrix added in v1.2.0

func (e *ProjectionEncoder) DemixingMatrix() *MappingMatrix

DemixingMatrix returns a copy of the family-3 demixing matrix. Family 2 has no demixing matrix and returns nil.

func (*ProjectionEncoder) DemixingMatrixBytes added in v1.2.0

func (e *ProjectionEncoder) DemixingMatrixBytes() []byte

DemixingMatrixBytes returns the RFC 8486 little-endian matrix payload.

func (*ProjectionEncoder) DemixingMatrixGain added in v1.2.0

func (e *ProjectionEncoder) DemixingMatrixGain() int

DemixingMatrixGain returns the family-3 matrix gain in signed Q8 dB.

func (*ProjectionEncoder) Encode added in v1.2.0

func (e *ProjectionEncoder) Encode(pcm []int16, frameSize int) ([]byte, error)

func (*ProjectionEncoder) Encode24 added in v1.2.0

func (e *ProjectionEncoder) Encode24(pcm []int32, frameSize int) ([]byte, error)

func (*ProjectionEncoder) EncodeFloat added in v1.2.0

func (e *ProjectionEncoder) EncodeFloat(pcm []float64, frameSize int) ([]byte, error)

func (*ProjectionEncoder) EncodeFloat32 added in v1.2.0

func (e *ProjectionEncoder) EncodeFloat32(pcm []float32, frameSize int) ([]byte, error)

func (*ProjectionEncoder) FinalRange added in v1.2.0

func (e *ProjectionEncoder) FinalRange() uint32

func (*ProjectionEncoder) Mapping added in v1.2.0

func (e *ProjectionEncoder) Mapping() []byte

Mapping returns the RFC 8486 family-2 channel mapping. Family 3 uses a demixing matrix instead of a channel mapping table and returns nil.

func (*ProjectionEncoder) MappingFamily added in v1.2.0

func (e *ProjectionEncoder) MappingFamily() int

func (*ProjectionEncoder) Reset added in v1.2.0

func (e *ProjectionEncoder) Reset() error

func (*ProjectionEncoder) SampleRate added in v1.2.0

func (e *ProjectionEncoder) SampleRate() int

func (*ProjectionEncoder) SetBitrate added in v1.2.0

func (e *ProjectionEncoder) SetBitrate(bitrate int) error

SetBitrate sets the aggregate bitrate. Ambisonics divides numeric rates equally between elementary streams, matching libopus' family-2 policy.

func (*ProjectionEncoder) SetComplexity added in v1.2.0

func (e *ProjectionEncoder) SetComplexity(complexity int) error

func (*ProjectionEncoder) SetVBR added in v1.2.0

func (e *ProjectionEncoder) SetVBR(enabled bool)

func (*ProjectionEncoder) SetVBRConstraint added in v1.2.0

func (e *ProjectionEncoder) SetVBRConstraint(enabled bool)

func (*ProjectionEncoder) StreamEncoder added in v1.2.0

func (e *ProjectionEncoder) StreamEncoder(stream int) (*Encoder, error)

func (*ProjectionEncoder) Streams added in v1.2.0

func (e *ProjectionEncoder) Streams() int

type Repacketizer added in v1.2.0

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

Repacketizer combines Opus frames with matching TOC configurations without decoding and re-encoding their audio.

func NewRepacketizer added in v1.2.0

func NewRepacketizer() *Repacketizer

NewRepacketizer creates an empty single-stream Opus repacketizer.

func (*Repacketizer) Cat added in v1.2.0

func (r *Repacketizer) Cat(packet []byte) error

Cat appends every frame from packet. All packets must have the same TOC configuration and channel count, and the accumulated duration must not exceed the Opus 120 ms packet limit.

func (*Repacketizer) NumFrames added in v1.2.0

func (r *Repacketizer) NumFrames() int

NumFrames returns the number of accumulated Opus frames.

func (*Repacketizer) Out added in v1.2.0

func (r *Repacketizer) Out() ([]byte, error)

Out returns one packet containing every accumulated frame.

func (*Repacketizer) OutRange added in v1.2.0

func (r *Repacketizer) OutRange(begin, end int) ([]byte, error)

OutRange returns one packet containing frames [begin,end).

func (*Repacketizer) Reset added in v1.2.0

func (r *Repacketizer) Reset()

Reset removes all frames accumulated by the repacketizer.

type SignalType added in v1.1.1

type SignalType = celt.SignalType

SignalType is a content hint that lets the encoder tune heuristics for the dominant signal type without changing the bitstream format.

const (
	// SignalAuto lets the encoder derive a hint from the Application setting
	// (VOIP → voice, Audio/RestrictedLowDelay → music). This is the default.
	SignalAuto SignalType = celt.SignalUnknown
	// SignalVoice marks speech-leaning content. The encoder uses narrower
	// bandwidth tiers (matching ApplicationVOIP) and switches to short blocks
	// more eagerly on plosive onsets.
	SignalVoice SignalType = celt.SignalVoice
	// SignalMusic marks music or general audio content, applying wider
	// bandwidth tiers and standard transient sensitivity.
	SignalMusic SignalType = celt.SignalMusic
)

type SurroundDecoder added in v1.2.0

type SurroundDecoder struct {
	*MultistreamDecoder
	// contains filtered or unexported fields
}

SurroundDecoder is a MultistreamDecoder initialized from a standard channel mapping family.

func NewSurroundDecoder added in v1.2.0

func NewSurroundDecoder(sampleRate, channels, mappingFamily int) (*SurroundDecoder, error)

NewSurroundDecoder creates a decoder for mapping family 0, 1, or 255.

func (*SurroundDecoder) LFEStream added in v1.2.0

func (d *SurroundDecoder) LFEStream() int

func (*SurroundDecoder) MappingFamily added in v1.2.0

func (d *SurroundDecoder) MappingFamily() int

type SurroundEncoder added in v1.2.0

type SurroundEncoder struct {
	*MultistreamEncoder
	// contains filtered or unexported fields
}

SurroundEncoder adds libopus-style channel layouts and rate allocation to a MultistreamEncoder.

func NewSurroundEncoder added in v1.2.0

func NewSurroundEncoder(sampleRate, channels, mappingFamily int, application Application) (*SurroundEncoder, error)

NewSurroundEncoder creates an encoder for mapping family 0, 1, or 255. Mapping family 1 uses the standard Vorbis channel order for 1 through 8 channels. Mapping family 255 creates one uncoupled stream per channel.

func (*SurroundEncoder) Bitrate added in v1.2.0

func (e *SurroundEncoder) Bitrate() int

Bitrate returns the configured aggregate surround bitrate policy.

func (*SurroundEncoder) Encode added in v1.2.0

func (e *SurroundEncoder) Encode(pcm []int16, frameSize int) ([]byte, error)

func (*SurroundEncoder) Encode24 added in v1.2.0

func (e *SurroundEncoder) Encode24(pcm []int32, frameSize int) ([]byte, error)

func (*SurroundEncoder) EncodeFloat added in v1.2.0

func (e *SurroundEncoder) EncodeFloat(pcm []float64, frameSize int) ([]byte, error)

func (*SurroundEncoder) EncodeFloat32 added in v1.2.0

func (e *SurroundEncoder) EncodeFloat32(pcm []float32, frameSize int) ([]byte, error)

func (*SurroundEncoder) LFEStream added in v1.2.0

func (e *SurroundEncoder) LFEStream() int

LFEStream returns the LFE elementary stream index, or -1 when absent.

func (*SurroundEncoder) MappingFamily added in v1.2.0

func (e *SurroundEncoder) MappingFamily() int

MappingFamily returns the configured channel mapping family.

func (*SurroundEncoder) SetBitrate added in v1.2.0

func (e *SurroundEncoder) SetBitrate(bitrate int) error

SetBitrate sets the aggregate surround bitrate. It is distributed immediately before each encode because libopus' allocation depends on frame duration.

Directories

Path Synopsis
toccheck command
celt
Package celt implements the CELT (Constrained Energy Lapped Transform) codec.
Package celt implements the CELT (Constrained Energy Lapped Transform) codec.
cgoref
Package cgoref is the libopus CGO reference wrapper.
Package cgoref is the libopus CGO reference wrapper.
cmd/genversion command
dsp
Package dsp provides digital signal processing utilities for the Opus codec.
Package dsp provides digital signal processing utilities for the Opus codec.
entcode
Package entcode provides entropy coding (range coding) for Opus, bit-exact with the range coder in libopus 1.3.1 (celt/entcode.c, celt/entenc.c, celt/entdec.c).
Package entcode provides entropy coding (range coding) for Opus, bit-exact with the range coder in libopus 1.3.1 (celt/entcode.c, celt/entenc.c, celt/entdec.c).
extensions
Package extensions implements the Opus packet-extension grammar carried in RFC 6716 code-3 padding.
Package extensions implements the Opus packet-extension grammar carried in RFC 6716 code-3 padding.
resampler
Package resampler provides high-quality sample rate conversion for Opus.
Package resampler provides high-quality sample rate conversion for Opus.
silk
Package silk implements the SILK speech codec for Opus.
Package silk implements the SILK speech codec for Opus.
testing
Package testing provides verification and comparison tools for Opus library development.
Package testing provides verification and comparison tools for Opus library development.
Package oggopus implements Ogg page framing and the Ogg Opus mapping.
Package oggopus implements Ogg page framing and the Ogg Opus mapping.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL