opus

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 10 Imported by: 0

README




Pion Opus

Pure Go implementation of the Opus Codec

Opus join us on Discord Follow us on Bluesky
GitHub Workflow Status Go Reference Coverage Status Go Report Card


This package provides a Pure Go implementation of the Opus Codec

Why Opus?

  • open and royalty-free - No license fees or restrictions. Use it as you wish!
  • versatile - Wide bitrate support. Can be used in constrained networks and high quality stereo.
  • ubiquitous - Used in video streaming, gaming, storing music and video conferencing.

Why a Go implementation?

  • empower interesting use cases - This project also exports the internals of the Encoder and Decoder. Allowing for things like analysis of a Opus bitstream without decoding the entire thing.
  • learning - This project was written to be read by others. It includes excerpts and links to RFC 6716
  • safety - Go provides memory safety. Avoids a class of bugs that are devastating in sensitive environments.
  • maintainability - Go was designed to build simple, reliable, and efficient software.
  • inspire - Go is a power language, but lacking in media libraries. We hope this project inspires the next generation to build more media libraries for Go.

You can read more here

RFCs

Implemented

Running

See our examples for demonstrations of how to use this package.

Roadmap

The library is used as a part of our WebRTC implementation. Please refer to that roadmap to track our major milestones.

See also Issue 9

Community

Pion has an active community on the Discord.

Follow the Pion Bluesky or Pion Twitter for project updates and important WebRTC news.

We are always looking to support your projects. Please reach out if you have something to build! If you need commercial support or don't want to use public methods you can contact us at team@pion.ly

Contributing

Check out the contributing wiki to join the group of amazing people making this project possible

License

MIT License - see LICENSE for full text

Documentation

Overview

Package opus provides a Opus Audio Codec RFC 6716 implementation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Application

type Application int

Application selects the encoder's tuning profile, mirroring libopus's OPUS_APPLICATION_* control values (opus_defines.h) and their numeric IDs. RFC 6716 does not define per-application behavior as part of the bitstream; it only describes the underlying control parameters — bitrate mode, frame duration, DTX — that each profile is meant to bias (see RFC 6716 Section 2.1, "Control Parameters"). Selecting an Application here only records the chosen profile, retrievable via Application(); it does not change VBR, frame duration, or DTX on its own — pass WithVBR, WithConstrainedVBR, etc. explicitly.

const (
	// ApplicationAudio tunes the encoder for music and general audio. This
	// is the default application.
	ApplicationAudio Application = 2049

	// ApplicationVoIP tunes the encoder for voice over a lossy,
	// latency-sensitive network. In libopus this profile defaults to VBR
	// (RFC 6716 Section 2.1.8) and DTX (RFC 6716 Section 2.1.9); this
	// encoder does not wire those defaults automatically.
	ApplicationVoIP Application = 2048

	// ApplicationRestrictedLowDelay tunes the encoder for the lowest
	// possible algorithmic delay by skipping mode-switching analysis
	// between the SILK and CELT layers. Frame duration and look-ahead
	// trade-offs are described in RFC 6716 Section 2.1.4; this encoder
	// does not vary either by application.
	ApplicationRestrictedLowDelay Application = 2051
)

type Bandwidth

type Bandwidth byte

The Bandwidth the Opus codec scales from 6 kbit/s narrowband mono speech to 510 kbit/s fullband stereo music, with algorithmic delays ranging from 5 ms to 65.2 ms. At any given time, either the LP layer, the MDCT layer, or both, may be active. It can seamlessly switch between all of its various operating modes, giving it a great deal of flexibility to adapt to varying content and network conditions without renegotiating the current session. The codec allows input and output of various audio bandwidths, defined as follows:

+----------------------+-----------------+-------------------------+
| Abbreviation         | Audio Bandwidth | Sample Rate (Effective) |
+----------------------+-----------------+-------------------------+
| NB (narrowband)      |           4 kHz |                   8 kHz |
|                      |                 |                         |
| MB (medium-band)     |           6 kHz |                  12 kHz |
|                      |                 |                         |
| WB (wideband)        |           8 kHz |                  16 kHz |
|                      |                 |                         |
| SWB (super-wideband) |          12 kHz |                  24 kHz |
|                      |                 |                         |
| FB (fullband)        |      20 kHz (*) |                  48 kHz |
+----------------------+-----------------+-------------------------+

https://datatracker.ietf.org/doc/html/rfc6716#section-2

const (
	BandwidthAuto          Bandwidth = 0 // let the encoder select based on bitrate
	BandwidthNarrowband    Bandwidth = 1
	BandwidthMediumband    Bandwidth = 2
	BandwidthWideband      Bandwidth = 3
	BandwidthSuperwideband Bandwidth = 4
	BandwidthFullband      Bandwidth = 5
)

Bandwidth constants. Numbered explicitly, not with iota, because BandwidthAuto's 0 value doesn't belong to the Narrowband..Fullband sequence it's leading.

func (Bandwidth) SampleRate

func (b Bandwidth) SampleRate() int

SampleRate returns the effective SampleRate for a given bandwidth.

func (Bandwidth) String

func (b Bandwidth) String() string

type Configuration

type Configuration byte

Configuration numbers in each range (e.g., 0...3 for NB SILK- only) correspond to the various choices of frame size, in the same order. For example, configuration 0 has a 10 ms frame size and configuration 3 has a 60 ms frame size.

+-----------------------+-----------+-----------+-------------------+
| Configuration         | Mode      | Bandwidth | Frame Sizes       |
| Number(s)             |           |           |                   |
+-----------------------+-----------+-----------+-------------------+
| 0...3                 | SILK-only | NB        | 10, 20, 40, 60 ms |
|                       |           |           |                   |
| 4...7                 | SILK-only | MB        | 10, 20, 40, 60 ms |
|                       |           |           |                   |
| 8...11                | SILK-only | WB        | 10, 20, 40, 60 ms |
|                       |           |           |                   |
| 12...13               | Hybrid    | SWB       | 10, 20 ms         |
|                       |           |           |                   |
| 14...15               | Hybrid    | FB        | 10, 20 ms         |
|                       |           |           |                   |
| 16...19               | CELT-only | NB        | 2.5, 5, 10, 20 ms |
|                       |           |           |                   |
| 20...23               | CELT-only | WB        | 2.5, 5, 10, 20 ms |
|                       |           |           |                   |
| 24...27               | CELT-only | SWB       | 2.5, 5, 10, 20 ms |
|                       |           |           |                   |
| 28...31               | CELT-only | FB        | 2.5, 5, 10, 20 ms |
+-----------------------+-----------+-----------+-------------------+

https://datatracker.ietf.org/doc/html/rfc6716#section-3.1

type Decoder

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

Decoder decodes the Opus bitstream into PCM.

func NewDecoder

func NewDecoder() Decoder

NewDecoder creates a new Opus Decoder.

func NewDecoderWithOutput

func NewDecoderWithOutput(sampleRate, channels int) (Decoder, error)

NewDecoderWithOutput creates a new Opus Decoder with the requested output sample rate and channel count.

func (*Decoder) Decode

func (d *Decoder) Decode(in, out []byte) (bandwidth Bandwidth, isStereo bool, err error)

Decode decodes the Opus bitstream into S16LE PCM.

func (*Decoder) DecodeFloat32

func (d *Decoder) DecodeFloat32(in []byte, out []float32) (bandwidth Bandwidth, isStereo bool, err error)

DecodeFloat32 decodes the Opus bitstream into F32LE PCM.

func (*Decoder) DecodePLC

func (d *Decoder) DecodePLC(out []int16) error

DecodePLC recovers one missing 20 ms packet into signed 16-bit PCM.

func (*Decoder) DecodeToFloat32

func (d *Decoder) DecodeToFloat32(in []byte, out []float32) (int, error)

DecodeToFloat32 decodes Opus data into float32 PCM and returns the sample count per channel.

func (*Decoder) DecodeToInt16

func (d *Decoder) DecodeToInt16(in []byte, out []int16) (int, error)

DecodeToInt16 decodes Opus data into signed 16-bit PCM and returns the sample count per channel.

func (*Decoder) Init

func (d *Decoder) Init(sampleRate, channels int) error

Init initializes a pre-allocated Opus decoder.

type Encoder

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

Encoder encodes PCM into Opus packets.

func NewEncoder

func NewEncoder(opts ...EncoderOption) (*Encoder, error)

NewEncoder creates a new Opus encoder with the supplied options.

Defaults: 48 kHz, mono, 24 kbit/s, complexity 5. Pass options to override any of these. The current implementation supports 48 kHz, 1 or 2 channels, 20 ms CELT-only packets, plus SILK-only encoding via EncodeSILK. Transient detection is a follow-up.

func (*Encoder) Application

func (e *Encoder) Application() Application

Application returns the current encoder application mode.

func (*Encoder) Bandwidth

func (e *Encoder) Bandwidth() Bandwidth

Bandwidth returns the configured bandwidth (BandwidthAuto by default).

func (*Encoder) Complexity

func (e *Encoder) Complexity() int

func (*Encoder) ConstrainedVBR

func (e *Encoder) ConstrainedVBR() bool

ConstrainedVBR returns whether constrained VBR is enabled.

func (*Encoder) Encode

func (e *Encoder) Encode(in []byte, out []byte) (int, error)

Encode encodes S16LE PCM into a single Opus packet.

The input must contain exactly one 20 ms mono 48 kHz frame.

func (*Encoder) EncodeFloat32

func (e *Encoder) EncodeFloat32(in []float32, out []byte) (int, error)

EncodeFloat32 encodes float PCM into a single Opus packet.

The input must contain one 20 ms 48 kHz frame.

func (*Encoder) EncodeSILK

func (e *Encoder) EncodeSILK(pcm []int16, bandwidth Bandwidth, out []byte) (int, error)

EncodeSILK encodes one 20, 40, or 60 ms mono SILK frame into a SILK-only Opus packet. pcm must hold exactly one frame of mono s16 samples at the bandwidth's internal rate: 160/320/480 (Narrowband/8 kHz), 240/480/720 (Mediumband/12 kHz), or 320/640/960 (Wideband/16 kHz) samples for 20/40/60 ms. Durations longer than 20 ms are coded as multiple 20 ms SILK coding units in a single SILK header, per RFC 6716 Section 4.2.1. This is a separate entry point from Encode/EncodeFloat32 — bitrate-based auto-selection always picks CELT bandwidths (Wideband and up); SILK is for callers who specifically want a SILK-only voice packet (VoIP/narrowband use cases), not an automatic CELT/SILK/hybrid switch. Superwideband and Fullband aren't SILK bandwidths and are rejected. Applies a fixed DC-removal high-pass before encoding (libopus's dc_reject applied to the shared PCM path); the pitch-adaptive VoIP cutoff (hp_cutoff) is not implemented. Covers voiced/LTP prediction, noise shaping and NLSF interpolation (see internal/silk); the delayed-decision NSQ, stereo, hybrid mode, and the bitrate-control loop are not yet implemented.

func (*Encoder) LossRate

func (e *Encoder) LossRate() int

LossRate returns the expected packet loss rate (0-100 percent).

func (*Encoder) MaxBandwidth

func (e *Encoder) MaxBandwidth() Bandwidth

MaxBandwidth returns the maximum bandwidth the auto-select algorithm may choose.

func (*Encoder) SetApplication

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

SetApplication updates the encoder application mode.

func (*Encoder) SetBandwidth

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

SetBandwidth sets the encoder bandwidth, overriding auto-selection.

func (*Encoder) SetBitrate

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

SetBitrate updates the target bitrate in bits per second.

func (*Encoder) SetComplexity

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

SetComplexity updates the encoder complexity on the standard Opus 0..10 scale.

func (*Encoder) SetConstrainedVBR

func (e *Encoder) SetConstrainedVBR(cvbr bool)

SetConstrainedVBR enables or disables constrained VBR (RFC 6716 Section 2.1.8).

func (*Encoder) SetLossRate

func (e *Encoder) SetLossRate(rate int) error

SetLossRate sets the expected packet loss rate (0-100 percent), the control parameter behind the packet loss resilience trade-off described in RFC 6716 Section 2.1.6.

func (*Encoder) SetMaxBandwidth

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

SetMaxBandwidth sets the maximum bandwidth the auto-select algorithm may choose. Only affects encoding when bandwidth is set to BandwidthAuto (the default).

func (*Encoder) SetVBR

func (e *Encoder) SetVBR(vbr bool)

SetVBR enables or disables variable bitrate encoding (RFC 6716 Section 2.1.8).

func (*Encoder) VBR

func (e *Encoder) VBR() bool

VBR returns whether variable bitrate encoding is enabled.

type EncoderOption

type EncoderOption func(*Encoder) error

EncoderOption configures an Encoder during construction.

Options are applied in the order they are passed to NewEncoder. Each option returns an error if the requested value is unsupported by the current encoder slice, so callers can detect unsupported configurations at construction time rather than at first encode.

func WithApplication

func WithApplication(app Application) EncoderOption

WithApplication sets the encoder application mode.

func WithBandwidth

func WithBandwidth(bw Bandwidth) EncoderOption

WithBandwidth sets the encoder bandwidth explicitly (Narrowband through Fullband; Mediumband is SILK-only and not supported here). Use WithMaxBandwidth instead to cap auto-selection rather than fixing it.

func WithBitrate

func WithBitrate(bps int) EncoderOption

WithBitrate sets the target bitrate in bits per second. Valid range is 6000 to 510000.

func WithChannels

func WithChannels(channels int) EncoderOption

WithChannels sets the channel count (1 for mono, 2 for stereo).

func WithComplexity

func WithComplexity(complexity int) EncoderOption

WithComplexity sets the encoder complexity on the standard Opus 0..10 scale. Higher values enable more analysis (pitch detection, spreading, dynalloc) for better quality at the cost of CPU.

func WithConstrainedVBR

func WithConstrainedVBR(cvbr bool) EncoderOption

WithConstrainedVBR enables or disables constrained VBR. When enabled, the encoder simulates a "bit reservoir" to bound short-term bitrate variation instead of producing plain VBR — recommended for low-latency links over a constrained connection (RFC 6716 Section 2.1.8).

func WithMaxBandwidth

func WithMaxBandwidth(bw Bandwidth) EncoderOption

WithMaxBandwidth sets the maximum bandwidth the auto-select algorithm may choose. Has no effect when an explicit bandwidth is set via WithBandwidth.

func WithSampleRate

func WithSampleRate(rate int) EncoderOption

WithSampleRate sets the input sample rate in Hz. The current encoder only supports 48 kHz (the CELT internal rate).

func WithVBR

func WithVBR(vbr bool) EncoderOption

WithVBR enables or disables variable bitrate encoding. VBR is the more efficient mode and is the Opus default; CBR is reserved for transports that require a fixed frame size or for highly sensitive streams (RFC 6716 Section 2.1.8).

type OpusDecoder

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

OpusDecoder wraps Decoder with a qrtc-compatible method surface.

func CreateOpusDecoder

func CreateOpusDecoder(config *OpusDecoderConfig) (*OpusDecoder, error)

CreateOpusDecoder creates a pure-Go Opus decoder through the compatibility API.

func (*OpusDecoder) Close

func (d *OpusDecoder) Close() error

Close releases decoder resources. It is a no-op for the pure-Go decoder.

func (*OpusDecoder) Decode

func (d *OpusDecoder) Decode(in, out []byte) (int, error)

Decode decodes an Opus packet into S16LE PCM.

type OpusDecoderConfig

type OpusDecoderConfig struct {
	SampleRate  int
	MaxChannels int
}

OpusDecoderConfig configures the compatibility decoder API used by github.com/qrtc/opus-go callers.

type OpusEncoder

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

OpusEncoder wraps Encoder with a qrtc-compatible method surface.

func CreateOpusEncoder

func CreateOpusEncoder(config *OpusEncoderConfig) (*OpusEncoder, error)

CreateOpusEncoder creates a pure-Go Opus encoder through the compatibility API.

In addition to the upstream 48 kHz/20 ms CELT API, it supports the xiaozhi wire format of 8/12/16/24/48 kHz PCM, one or two channels, and 60 ms packets. That path resamples each 20 ms segment to 48 kHz and packs three CBR CELT frames into a single Opus Code 3 packet.

func (*OpusEncoder) Close

func (e *OpusEncoder) Close() error

Close releases encoder resources. It is a no-op for the pure-Go encoder.

func (*OpusEncoder) Encode

func (e *OpusEncoder) Encode(in, out []byte) (int, error)

Encode encodes S16LE PCM into an Opus packet.

type OpusEncoderConfig

type OpusEncoderConfig struct {
	SampleRate    int
	MaxChannels   int
	Application   Application
	FrameDuration time.Duration
	Bitrate       int
}

OpusEncoderConfig configures the compatibility encoder API used by github.com/qrtc/opus-go callers.

Directories

Path Synopsis
examples
decode command
Package main is an example of an Opus decoder that save the output PCM to disk
Package main is an example of an Opus decoder that save the output PCM to disk
internal
bitdepth
Package bitdepth provides utilities to convert between different audio bitdepths
Package bitdepth provides utilities to convert between different audio bitdepths
celt
Package celt implements the MDCT layer of the Opus decoder.
Package celt implements the MDCT layer of the Opus decoder.
rangecoding
Package rangecoding provides a Range coder for the Opus bitstream
Package rangecoding provides a Range coder for the Opus bitstream
resample/silk
Package silkresample ports the RFC 6716 SILK resampler.
Package silkresample ports the RFC 6716 SILK resampler.
silk
Package silk provides a Silk coder
Package silk provides a Silk coder
slicetools
Package slicetools provides shared helpers for reusing scratch slices.
Package slicetools provides shared helpers for reusing scratch slices.
pkg
oggreader
Package oggreader implements the Ogg media container reader
Package oggreader implements the Ogg media container reader

Jump to

Keyboard shortcuts

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