gopus

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2026 License: BSD-3-Clause Imports: 16 Imported by: 14 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gopus

Pure-Go Opus codec — RFC 6716 / RFC 8251, bit-exact and quality parity with pinned libopus 1.6.1, a drop-in for the C library with no cgo.

Encoder, decoder, multistream, projection/ambisonics, Ogg, and RTP RED — all in plain Go, with caller-owned, zero-allocation encode and decode hot paths. Codec math and bitstream decisions are matched to the pinned reference and proven by a live C oracle (see Parity & testing).

Install

go get github.com/thesyncim/gopus

Requires Go 1.25 or newer.

Quick start

The hot-path API takes caller-owned buffers and returns the number of bytes / samples written, so the encode and decode loops allocate nothing:

func (e *Encoder) Encode(pcm []float32, data []byte) (int, error)
func (d *Decoder) Decode(data []byte, pcm []float32) (int, error)

Encode one 20 ms stereo frame at 48 kHz, then decode it back:

package main

import (
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	const (
		sampleRate = 48000
		channels   = 2
		frameSize  = 960 // 20 ms at 48 kHz
	)

	enc, err := gopus.NewEncoder(gopus.EncoderConfig{
		SampleRate:  sampleRate,
		Channels:    channels,
		Application: gopus.ApplicationAudio,
	})
	if err != nil {
		log.Fatal(err)
	}

	dec, err := gopus.NewDecoder(gopus.DefaultDecoderConfig(sampleRate, channels))
	if err != nil {
		log.Fatal(err)
	}

	pcm := make([]float32, frameSize*channels) // your interleaved input
	packet := make([]byte, 4000)               // reusable encode buffer
	out := make([]float32, frameSize*channels) // reusable decode buffer

	n, err := enc.Encode(pcm, packet) // n = bytes written to packet
	if err != nil {
		log.Fatal(err)
	}

	samples, err := dec.Decode(packet[:n], out) // samples = per-channel samples
	if err != nil {
		log.Fatal(err)
	}
	_ = out[:samples*channels]
}

int16 and int24 PCM use the same caller-buffer shape — only the slice element type changes:

pcm16 := make([]int16, frameSize*channels) // interleaved 16-bit input
packet := make([]byte, 4000)
out16 := make([]int16, frameSize*channels)

n, err := enc.EncodeInt16(pcm16, packet)   // also EncodeInt24([]int32, …)
// …
samples, err := dec.DecodeInt16(packet[:n], out16) // also DecodeInt24(…, []int32)

Tune the encoder through libopus-style CTL methods (SetBitrate, SetVBR, SetComplexity, SetInBandFEC, SetDTX, …). Pass a nil packet to Decode to run packet-loss concealment for a dropped frame.

See examples/ for Ogg files, ffmpeg interop, RED loss recovery, WebRTC control, and benchmarks.

Features

Area gopus
Coding modes SILK, CELT, Hybrid, with automatic mode selection
Sample rates 8, 12, 16, 24, 48 kHz (native sub-48 kHz encode, no upsampling)
Channels Mono, stereo, multistream, projection / ambisonics
Frame sizes 2.5–120 ms
Bitrate control CBR, VBR, CVBR, low-delay, DTX
Resilience Packet loss concealment, in-band FEC / LBRR
PCM formats float32, int16, int24 (single-stream and multistream)
Containers container/ogg (Ogg read/write), container/red (RFC 2198 RTP RED parse/build/recover)
libopus surface Full public API: the libopus CTL surface, packet parsing, soft clipping, and matching error codes

Public API

The importable surface is four packages. Everything else lives under internal/ and is not importable.

Package Use it for
github.com/thesyncim/gopus Encoder / Decoder (float32 / int16 / int24), streaming Reader / Writer, multistream and DRED constructors, packet parsing, repacketizer, soft clip, CTLs, error codes
github.com/thesyncim/gopus/multistream Lower-level multistream Encoder / Decoder and projection / ambisonics (NewProjectionEncoder / NewProjectionDecoder)
github.com/thesyncim/gopus/container/ogg Read and write Ogg Opus files (RFC 7845)
github.com/thesyncim/gopus/container/red Encoder / Decoder structs (plus Build / Parse / FindRecovery) to build, parse, and recover RFC 2198 RTP RED payloads
github.com/thesyncim/gopus/types Shared Mode / Bandwidth / Signal enums

Multistream is reachable two ways: gopus.NewMultistreamEncoder / gopus.NewMultistreamDecoder (and the …Default constructors for 1–8 channels in Vorbis order) wrap the lower-level multistream package, which also carries the projection / ambisonics constructors (mapping families 0/1/3/255).

Write an Ogg Opus file with the container/ogg writer:

w, err := ogg.NewWriter(file, sampleRate, channels)
if err != nil {
	log.Fatal(err)
}
defer w.Close()

n, _ := enc.Encode(pcm, packet)
if err := w.WritePacket(packet[:n], frameSize); err != nil {
	log.Fatal(err)
}

Optional features behind build tags

The default build is core encode/decode/multistream/Ogg/RED — matching a default libopus ./configure. Optional features are exposed exactly the way libopus exposes them: behind a compile flag in libopus, behind the matching Go build tag here. The default build links ZERO of their code (enforced by TestDefaultBuildIsZeroCostForGatedFeatures).

gopus build tag libopus flag
gopus_dred --enable-dred
gopus_osce --enable-osce (+ ENABLE_DEEP_PLC)
gopus_qext --enable-qext
gopus_custom_modes --enable-custom-modes
gopus_fixed_point --enable-fixed-point

Under their tag these are parity-complete — none are experimental:

  • gopus_dred — DRED (RDOVAE), control + standalone surfaces.
  • gopus_osce — OSCE BWE / LACE / NoLACE plus the deep-PLC family (PitchDNN / FARGAN), exactly as --enable-osce.
  • gopus_qext — QEXT framing and native 96 kHz (Opus HD): decode is sample-exact, and the public Encode at Fs=96000 is byte-exact (TOC, padding, main CELT payload, reserved QEXT extension) vs libopus --enable-qext. 96 kHz is CELT-only fullband (mirroring libopus) and accepted only under this tag; default-build API rates stay 8/12/16/24/48 kHz.
  • gopus_custom_modes — Opus Custom standard modes.
  • gopus_fixed_point — integer CELT/SILK pipeline (libopus FIXED_POINT); public decode and encode are bit-exact vs the --enable-fixed-point oracle.

One more tag is orthogonal to the feature flags above and has no libopus equivalent:

  • purego — forces the scalar Go code path, disabling the architecture assembly kernels (arm64 NEON, amd64 AVX2). Output is identical to the default build except that this is the bit-exact tier on every architecture; use it when you want the reference numeric path or to build for a target without an asm kernel. The default build (no tag) already selects asm only where libopus does.

Default builds expose no optional extensions; SetDNNBlob(...) is a no-op returning ErrOptionalExtensionUnavailable. This matches a default libopus build, where the DNN / PitchDNN / FARGAN / RDOVAE neural code is empty and none of it is compiled; gopus keeps those packages out of the default import graph. DNN blob loading (USE_WEIGHTS_FILE model loading) requires -tags gopus_dred or -tags gopus_osce; QEXT requires -tags gopus_qext; DRED control/standalone surfaces require -tags gopus_dred; OSCE BWE/LACE/NoLACE require -tags gopus_osce. Under their build tag these are parity-complete and supported, exactly as libopus exposes them behind the corresponding compile flag.

Extension Status Probe
DNN blob loading Supported under gopus_dred / gopus_osce OptionalExtensionDNNBlob
QEXT Supported under gopus_qext OptionalExtensionQEXT
DRED Supported under gopus_dred (control + standalone) OptionalExtensionDRED
OSCE BWE Supported under gopus_osce OptionalExtensionOSCEBWE

The gopus_osce tag enables the OSCE and deep-PLC family exactly as libopus's --enable-osce does. These features are supported under the tag and link zero code into the default build.

go test -tags gopus_qext ./...
go test -tags gopus_dred ./...
go test -tags gopus_osce ./...
make test-dnn-blob-parity
make test-qext-parity
make test-dred-tag
make test-extra-controls-parity
make test-custom-parity

Performance

gopus is built for real-time use, where steady allocation is the enemy:

  • Zero-allocation hot paths. Encode / Decode (and their int16 / int24 variants) reuse caller-owned buffers; all scratch is pre-allocated at construction, so a steady-state encode or decode loop performs no heap allocations.
  • Allocation-free containers too. container/ogg (Reader.ReadPacketInto / Writer.WritePacket) and container/red (Decoder.Parse / Encoder.Encode) own their buffers and the redundant-frame history, so steady-state demux/mux and RED packetization allocate nothing once warm — each locked by an AllocsPerRun == 0 test.
  • SIMD where libopus has it. On amd64 the float pitch cross-correlation uses an AVX2 kernel that mirrors libopus's celt_pitch_xcorr_avx2, computing several correlation lags per FMA instead of one scalar FMA per element — bit-identical output, materially faster stereo CELT and Hybrid encode.

Run the benchmarks for numbers on your machine:

go run ./examples/bench-encode
go run ./examples/bench-decode

make bench-guard runs the benchmark guardrails used in CI.

Parity & testing

gopus is codec-complete against libopus 1.6.1: the full public API and CTL surface, plus the optional surface mirrored tag-for-flag (above). The pinned tmp_check/opus-1.6.1/ is the reference — when behavior is uncertain, gopus matches libopus unless fixture evidence says otherwise.

Parity is proven on two tiers, against a live libopus C oracle:

  • Bit-exact kernel oracles. Isolated kernels (range coder, NLSF/LPC/gain, PVQ/bands, MDCT/KISS-FFT, resamplers, DNN matmuls) are compared bit-for-bit against C. Every public decode entry point is two-sided differential-fuzzed against the same oracle.
  • opus_compare quality on real audio. End-to-end audio is judged by libopus's own opus_compare (RFC 8251's conformance metric), tier-matched so gopus tracks the reference at least as closely as libopus tracks itself across builds. SILK decode is bit-exact; CELT/Hybrid sit inside the near-exact envelope. The encoder precision guard runs on representative real recordings, where opus_compare Q is a genuine quality measure.

One residual is documented: a few CELT float kernels drift by ≤1 ULP on darwin/arm64 (a per-arch float budget). amd64/CI is bit-exact; the default arm64 build is quality-gated for that tail, exactly as libopus's NEON path is relative to its own scalar build.

Pre-v1: no release tagged yet (see Trust And Verification).

Verification

Run focused tests while iterating. Before merge-ready codec changes, run:

go test ./...
make test-doc-contract
make lint
make test-consumer-smoke
make test-examples-smoke
make verify-production
make verify-production-exhaustive
make release-evidence

Before a tag is published the tagged commit must be green on the required branch checks (below), and make release-evidence must produce a PASS summary.

Trust And Verification

Released version: none yet.

v0.1.0 is not a release until the tag and GitHub Release are both published.

Latest release evidence: none yet.

Required branch checks:

  • lint-static-analysis
  • test-linux
  • perf-linux
  • test-macos
  • test-windows

These aggregate gates make the libopus C-oracle parity suites mandatory across Linux, macOS, and Windows; each lane builds the pinned libopus C reference first under GOWORK=off GOPUS_TEST_TIER=parity GOPUS_STRICT_LIBOPUS_REF=1 and compares against committed arch-matched fixtures. They are the authoritative codec gate: release.yml publishes a tag only after verifying these checks are green on the tagged commit. make release-evidence then captures the supplementary safety and performance gates that are not in the required CI set, plus build provenance; it does not re-run the codec suites, since doing so against a live native libopus reference compares gopus's single portable float order against another toolchain's rounding rather than measuring a defect.

Security policy: SECURITY.md. Consumer smoke test: examples/external-consumer-smoke/smoke_test.go.

Docs

License

See LICENSE.

Documentation

Overview

Package gopus implements the Opus audio codec in pure Go.

It targets RFC 6716 compatibility with pinned libopus reference behavior, uses caller-owned buffers for the main encode/decode API, and requires no cgo dependency.

Quick Start

Encoding:

enc, err := gopus.NewEncoder(gopus.EncoderConfig{
    SampleRate:  48000,
    Channels:    2,
    Application: gopus.ApplicationAudio,
})
if err != nil {
    log.Fatal(err)
}

pcm := make([]float32, 960*2) // 20 ms stereo at 48 kHz
packet := make([]byte, 4000)
nPacket, err := enc.Encode(pcm, packet)
if err != nil {
    log.Fatal(err)
}
packet = packet[:nPacket]

Decoding:

cfg := gopus.DefaultDecoderConfig(48000, 2)
dec, err := gopus.NewDecoder(cfg)
if err != nil {
    log.Fatal(err)
}

pcmOut := make([]float32, cfg.MaxPacketSamples*cfg.Channels)
n, err := dec.Decode(packet, pcmOut)
if err != nil {
    log.Fatal(err)
}
pcmOut = pcmOut[:n*cfg.Channels]

PCM And Buffers

Float32 samples are normalized to [-1.0, 1.0]. Int16 helpers are available for common audio APIs. Stereo and multichannel PCM is interleaved.

Decode output needs room for up to 5760 samples per channel, the default 120 ms cap at 48 kHz. A 4000-byte encode buffer is sufficient for any Opus packet.

Packet Loss

Pass nil packet data to Decode to run packet loss concealment:

if packetLost {
    n, err = dec.Decode(nil, pcmOut)
} else {
    n, err = dec.Decode(packet, pcmOut)
}

Controls And Extensions

Standard Opus controls such as bitrate, complexity, bandwidth, FEC, DTX, gain, frame size, packet parsing, and multistream helpers are exposed on the top-level types.

Optional extension support is build dependent. Use SupportsOptionalExtension before relying on an extension surface, and treat README.md as the support matrix source of truth.

if SupportsOptionalExtension(OptionalExtensionQEXT) {
    _ = enc.SetQEXT(true)
}

Multistream

NewMultistreamEncoderDefault and NewMultistreamDecoderDefault support 1-8 channels with the standard Vorbis-style channel mappings used by Ogg Opus. Use the explicit multistream constructors for custom mappings.

Package Boundaries

The public surface is this top-level gopus package plus four importable packages: multistream (surround / ambisonics / projection), container/ogg (Ogg Opus read/write), container/red (RFC 2198 RTP RED), and types (shared Mode / Bandwidth / Signal enumerations). The top-level package re-exports the common multistream constructors, so most applications need only gopus and, if they handle files, container/ogg.

The SILK, CELT, Hybrid, range-coder, PLC, and DNN building blocks live under internal/ and are not importable; depend on the packages above instead.

Encoder and Decoder instances are not safe for concurrent use.

Example (RoundTrip)
package main

import (
	"fmt"
	"log"
	"math"

	"github.com/thesyncim/gopus"
)

func main() {
	// Complete encode-decode round trip
	enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 1, Application: gopus.ApplicationVoIP})
	if err != nil {
		log.Fatal(err)
	}
	cfg := gopus.DefaultDecoderConfig(48000, 1)
	dec, err := gopus.NewDecoder(cfg)
	if err != nil {
		log.Fatal(err)
	}
	pcmOut := make([]float32, cfg.MaxPacketSamples*cfg.Channels)

	// 20ms of mono audio at 48kHz
	input := make([]float32, 960)
	for i := range input {
		input[i] = float32(math.Sin(float64(i) * 0.02))
	}

	// Encode
	packetBuf := make([]byte, 4000)
	nPacket, err := enc.Encode(input, packetBuf)
	if err != nil {
		log.Fatal(err)
	}

	// Decode
	n, err := dec.Decode(packetBuf[:nPacket], pcmOut)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Round trip ok: %t\n", nPacket > 0 && n == len(input))
}
Output:
Round trip ok: true

Index

Examples

Constants

View Source
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
)
View Source
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
)
View Source
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
)
View Source
const (
	// BitrateAuto lets the encoder pick the bitrate from the sample rate,
	// channel count, and application (libopus OPUS_AUTO). It is the default.
	BitrateAuto = encoder.BitrateAuto
	// BitrateMax tells the encoder to use as many bits as the output buffer
	// allows for each frame (libopus OPUS_BITRATE_MAX).
	BitrateMax = encoder.BitrateMax
)
View Source
const (
	// InBandFECDisabled turns in-band forward error correction off (value 0).
	InBandFECDisabled = encoder.InBandFECDisabled
	// InBandFECEnabled enables in-band FEC for all signal types (value 1).
	InBandFECEnabled = encoder.InBandFECEnabled
	// InBandFECMusicSafe enables in-band FEC only for speech-like content,
	// leaving music frames untouched (value 2).
	InBandFECMusicSafe = encoder.InBandFECMusicSafe
)

In-band FEC modes for SetInBandFEC. These mirror the libopus OPUS_SET_INBAND_FEC values.

View Source
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.

View Source
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

View Source
var (
	// ErrInvalidSampleRate indicates a sample rate outside the Opus API set.
	// Valid sample rates are: 8000, 12000, 16000, 24000, 48000.
	ErrInvalidSampleRate = errors.New("gopus: invalid sample rate (must be 8000, 12000, 16000, 24000, or 48000)")

	// ErrInvalidChannels indicates an invalid channel count.
	// See the relevant constructor or control for the supported range.
	ErrInvalidChannels = errors.New("gopus: invalid channels")

	// ErrInvalidSampleFormat indicates an invalid streaming PCM format.
	ErrInvalidSampleFormat = errors.New("gopus: invalid sample format")

	// ErrInvalidMaxPacketSamples indicates an invalid max packet sample cap.
	ErrInvalidMaxPacketSamples = errors.New("gopus: invalid max packet samples (must be > 0)")

	// ErrInvalidMaxPacketBytes indicates an invalid max packet size cap.
	ErrInvalidMaxPacketBytes = errors.New("gopus: invalid max packet bytes (must be > 0)")

	// ErrPacketTooLarge indicates the packet exceeds configured limits.
	ErrPacketTooLarge = errors.New("gopus: packet exceeds configured limits")

	// ErrBufferTooSmall indicates the output buffer is too small for the decoded frame.
	// The buffer must be at least frameSize * channels samples.
	ErrBufferTooSmall = errors.New("gopus: output buffer too small")

	// ErrInvalidFrameSize indicates the input frame size doesn't match expected.
	// The PCM input length must be frameSize * channels.
	ErrInvalidFrameSize = errors.New("gopus: invalid frame size")

	// ErrInvalidBitrate indicates the bitrate is out of valid range.
	// See the relevant constructor or control for the supported range.
	ErrInvalidBitrate = errors.New("gopus: invalid bitrate")

	// ErrInvalidBitrateMode indicates an invalid bitrate mode.
	// Valid modes are BitrateModeVBR, BitrateModeCVBR, and BitrateModeCBR.
	ErrInvalidBitrateMode = errors.New("gopus: invalid bitrate mode")

	// ErrInvalidComplexity indicates the complexity is out of valid range.
	// Valid complexity values are 0 to 10.
	ErrInvalidComplexity = errors.New("gopus: invalid complexity (must be 0-10)")

	// ErrInvalidApplication indicates an invalid application hint.
	// Valid values include the standard application hints plus the restricted
	// libopus-compatible init-time hints.
	ErrInvalidApplication = errors.New("gopus: invalid application")

	// ErrInvalidPacketLoss indicates an invalid packet loss percentage.
	// Valid range is 0 to 100.
	ErrInvalidPacketLoss = errors.New("gopus: invalid packet loss percentage (must be 0-100)")

	// ErrInvalidFECConfig indicates an invalid in-band FEC configuration.
	ErrInvalidFECConfig = errors.New("gopus: invalid in-band FEC config")

	// ErrInvalidStreams indicates an invalid stream count for multistream encoding/decoding.
	// Valid stream counts are 1 to 255.
	ErrInvalidStreams = errors.New("gopus: invalid stream count (must be 1-255)")

	// ErrInvalidCoupledStreams indicates an invalid coupled streams count.
	// Coupled streams must be between 0 and total streams.
	ErrInvalidCoupledStreams = errors.New("gopus: invalid coupled streams (must be 0 to streams)")

	// ErrInvalidStreamIndex indicates a per-stream state lookup used an out-of-range index.
	ErrInvalidStreamIndex = errors.New("gopus: invalid stream index")

	// ErrInvalidMapping indicates an invalid channel mapping table.
	// The mapping table length must equal the channel count.
	ErrInvalidMapping = errors.New("gopus: invalid mapping table")

	// ErrInvalidBandwidth indicates an invalid bandwidth for the current mode.
	// For SILK-only mode, only NB, MB, and WB are valid (not SWB or FB).
	ErrInvalidBandwidth = errors.New("gopus: invalid bandwidth for mode")

	// ErrInvalidSignal indicates an invalid signal type hint.
	// Valid values are SignalAuto, SignalVoice, or SignalMusic.
	ErrInvalidSignal = errors.New("gopus: invalid signal type (must be SignalAuto, SignalVoice, or SignalMusic)")

	// ErrInvalidLSBDepth indicates an invalid LSB depth.
	// Valid range is 8 to 24 bits.
	ErrInvalidLSBDepth = errors.New("gopus: invalid LSB depth (must be 8-24)")

	// ErrInvalidForceChannels indicates an invalid force channels value.
	// Valid values are -1 (auto), 1 (mono), or 2 (stereo).
	ErrInvalidForceChannels = errors.New("gopus: invalid force channels (must be -1, 1, or 2)")

	// ErrInvalidArgument indicates one or more function arguments are invalid.
	ErrInvalidArgument = errors.New("gopus: invalid argument")

	// ErrNilPacketReader indicates a nil PacketReader was supplied to NewReader.
	ErrNilPacketReader = errors.New("gopus: nil packet reader")

	// ErrNilPacketSink indicates a nil PacketSink was supplied to NewWriter.
	ErrNilPacketSink = errors.New("gopus: nil packet sink")

	// ErrInvalidGain indicates an invalid decoder gain value.
	// Valid range is -32768 to 32767 (Q8 dB).
	ErrInvalidGain = errors.New("gopus: invalid gain (must be -32768 to 32767)")

	// ErrOptionalExtensionUnavailable indicates the requested optional libopus
	// build-time extension is not enabled in the current gopus build.
	ErrOptionalExtensionUnavailable = errors.New("gopus: optional extension unavailable in this build")

	// ErrUnimplemented indicates the requested functionality is not implemented yet.
	ErrUnimplemented = errors.New("gopus: feature not implemented")
)

Public error types for encoding and decoding operations.

View Source
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

func ConfigFromParams(mode Mode, bandwidth Bandwidth, frameSize int) int

ConfigFromParams returns the config index for given mode, bandwidth, and frame size. Returns -1 if the combination is invalid.

func ErrorString

func ErrorString(code int) string

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

func GenerateTOC(config uint8, stereo bool, frameCode uint8) byte

GenerateTOC creates a TOC byte from encoding parameters. config: Configuration index 0-31 (from configTable) stereo: True for stereo, false for mono frameCode: Frame count code 0-3

0: 1 frame
1: 2 equal-sized frames
2: 2 different-sized frames
3: arbitrary number of frames

func MultistreamPacketPad

func MultistreamPacketPad(data []byte, length, newLen, numStreams int) error

MultistreamPacketPad pads the final stream packet inside a multistream packet.

func MultistreamPacketUnpad

func MultistreamPacketUnpad(data []byte, length, numStreams int) (int, error)

MultistreamPacketUnpad removes padding from all streams in a multistream packet. It returns the new packet length.

func PCMSoftClip

func PCMSoftClip(pcm []float32, channels int, softclipMem []float32)

PCMSoftClip applies soft clipping to interleaved float32 PCM samples in-place.

pcm holds N*channels interleaved samples. channels is the number of audio channels. softclipMem is per-channel state of length channels; pass a zero-initialized slice for the first call and reuse it across successive calls on the same stream.

This mirrors opus_pcm_soft_clip() / opus_pcm_soft_clip_impl() from src/opus.c and celt/celt.c in libopus 1.6.1.

func PacketHasLBRR

func PacketHasLBRR(data []byte) bool

PacketHasLBRR reports whether an Opus packet carries in-band LBRR data for FEC recovery. It mirrors libopus opus_packet_has_lbrr().

func PacketPad

func PacketPad(data []byte, length, newLen int) error

PacketPad pads a packet in-place to newLen bytes.

data must have capacity for at least newLen bytes. length is the current packet length in data.

func PacketUnpad

func PacketUnpad(data []byte, length int) (int, error)

PacketUnpad removes packet padding in-place and returns the new packet length.

func SupportsOptionalExtension

func SupportsOptionalExtension(ext OptionalExtension) bool

SupportsOptionalExtension reports whether the current build makes ext part of the supported release surface for this build. Extra controls may be compiled for parity work while still reporting false here.

Example
package main

import (
	"fmt"

	"github.com/thesyncim/gopus"
)

func main() {
	fmt.Printf("dnn_blob: %v\n", gopus.SupportsOptionalExtension(gopus.OptionalExtensionDNNBlob))
	fmt.Printf("dred: %v\n", gopus.SupportsOptionalExtension(gopus.OptionalExtensionDRED))
	fmt.Printf("osce_bwe: %v\n", gopus.SupportsOptionalExtension(gopus.OptionalExtensionOSCEBWE))
	fmt.Printf("qext: %v\n", gopus.SupportsOptionalExtension(gopus.OptionalExtensionQEXT))
}
Output:
dnn_blob: false
dred: false
osce_bwe: false
qext: false

func ValidConfig

func ValidConfig(config uint8) bool

ValidConfig returns true if the configuration index is valid.

func VersionString

func VersionString() string

VersionString returns a human-readable version string for the gopus library.

The returned string identifies gopus, not libopus. It is analogous to opus_get_version_string() from celt/celt.c in libopus 1.6.1, which returns "libopus <version>". Applications that need to detect libopus at runtime should not use this function; it will not contain the substring "libopus".

Types

type Application

type Application int

Application hints the encoder for optimization.

const (
	// ApplicationVoIP optimizes for speech transmission with low latency.
	// Prefers SILK mode for speech frequencies.
	ApplicationVoIP Application = iota

	// ApplicationAudio optimizes for music and high-quality audio.
	// Prefers CELT/Hybrid mode for full-bandwidth audio.
	ApplicationAudio

	// ApplicationLowDelay minimizes algorithmic delay.
	// Uses CELT mode exclusively with small frame sizes.
	ApplicationLowDelay

	// ApplicationRestrictedSilk forces SILK-only encoding.
	// This matches libopus OPUS_APPLICATION_RESTRICTED_SILK init-time behavior.
	ApplicationRestrictedSilk

	// ApplicationRestrictedCelt forces CELT-only encoding with low-delay semantics.
	// This matches libopus OPUS_APPLICATION_RESTRICTED_CELT init-time behavior.
	ApplicationRestrictedCelt
)

type Bandwidth

type Bandwidth = types.Bandwidth

Bandwidth is an alias for types.Bandwidth representing the audio bandwidth.

type BitrateMode

type BitrateMode = encoder.BitrateMode

BitrateMode controls how the encoder sizes packets.

type Decoder

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

Decoder decodes Opus packets into PCM audio samples.

A Decoder instance maintains internal state and is NOT safe for concurrent use. Each goroutine should create its own Decoder instance.

The decoder supports all Opus modes (SILK, Hybrid, CELT) and automatically detects the mode from the TOC byte in each packet.

func NewDecoder

func NewDecoder(cfg DecoderConfig) (*Decoder, error)

NewDecoder creates a new Opus decoder.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	// Create a decoder for 48kHz stereo audio
	dec, err := gopus.NewDecoder(gopus.DefaultDecoderConfig(48000, 2))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Decoder: %dHz, %d channels\n", dec.SampleRate(), dec.Channels())
}
Output:
Decoder: 48000Hz, 2 channels

func (*Decoder) Bandwidth

func (d *Decoder) Bandwidth() 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) Channels

func (d *Decoder) Channels() int

Channels returns the number of audio channels (1 or 2).

func (*Decoder) Complexity

func (d *Decoder) Complexity() int

Complexity returns the current decoder complexity setting.

func (*Decoder) Decode

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

Decode decodes an Opus packet into float32 PCM samples.

data: Opus packet data, or nil for Packet Loss Concealment (PLC). pcm: Output buffer for decoded samples. Must be large enough to hold frameSize * frameCount * channels samples, where frameSize and frameCount are determined from the packet TOC and frame code.

Returns the number of samples per channel decoded, or an error.

When data is nil, the decoder performs packet loss concealment using the last successfully decoded frame parameters. Before the first packet has been decoded, cold PLC returns zeroed audio and a nil error.

Buffer sizing: For 60ms frames at 48kHz stereo, pcm must have at least 2880 * 2 = 5760 elements. For multi-frame packets (code 1/2/3), the buffer must be large enough for all frames combined.

Multi-frame packets (RFC 6716 Section 3.2):

  • Code 0: 1 frame (most common)
  • Code 1: 2 equal-sized frames
  • Code 2: 2 different-sized frames
  • Code 3: Arbitrary number of frames (1-48)
Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	// Create encoder and decoder
	enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
	if err != nil {
		log.Fatal(err)
	}
	cfg := gopus.DefaultDecoderConfig(48000, 2)
	dec, err := gopus.NewDecoder(cfg)
	if err != nil {
		log.Fatal(err)
	}
	pcmOut := make([]float32, cfg.MaxPacketSamples*cfg.Channels)

	// Encode one 20ms stereo frame.
	pcm := make([]float32, 960*2)
	packetBuf := make([]byte, 4000)
	nPacket, err := enc.Encode(pcm, packetBuf)
	if err != nil {
		log.Fatal(err)
	}

	// Decode the packet
	n, err := dec.Decode(packetBuf[:nPacket], pcmOut)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Decoded %d samples per channel\n", n)
}
Output:
Decoded 960 samples per channel
Example (PacketLoss)
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	cfg := gopus.DefaultDecoderConfig(48000, 2)
	dec, err := gopus.NewDecoder(cfg)
	if err != nil {
		log.Fatal(err)
	}
	pcmOut := make([]float32, cfg.MaxPacketSamples*cfg.Channels)

	// First, decode a real packet to initialize state
	enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
	if err != nil {
		log.Fatal(err)
	}
	pcm := make([]float32, 960*2)
	packetBuf := make([]byte, 4000)
	nPacket, err := enc.Encode(pcm, packetBuf)
	if err != nil {
		log.Fatal(err)
	}
	if _, err := dec.Decode(packetBuf[:nPacket], pcmOut); err != nil {
		log.Fatal(err)
	}

	// Simulate packet loss by passing nil. Request one frame of PLC output
	// (buffer sized to the last packet duration, matching libopus frame_size).
	plcBuf := make([]float32, 960*cfg.Channels)
	n, err := dec.Decode(nil, plcBuf)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("PLC generated %d samples per channel\n", n)
}
Output:
PLC generated 960 samples per channel

func (*Decoder) DecodeInt16

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

DecodeInt16 decodes an Opus packet into int16 PCM samples.

func (*Decoder) DecodeInt24

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

DecodeInt24 decodes an Opus packet into 24-bit PCM samples stored in int32.

data: Opus packet data, or nil for Packet Loss Concealment (PLC). pcm: Output buffer for decoded samples. Each element carries a signed 24-bit value in the range [-8388608, 8388607] (= ±2^23), right-justified in int32 — the same convention as libopus opus_decode24().

Returns the number of samples per channel decoded, or an error.

func (*Decoder) DecodeInt24Slice

func (d *Decoder) DecodeInt24Slice(data []byte) ([]int32, error)

DecodeInt24Slice decodes an Opus packet into 24-bit PCM samples and returns a new int32 slice. Each element carries a right-justified signed 24-bit value.

This is a convenience method that allocates the output buffer. For performance-critical code, use DecodeInt24 with a pre-allocated buffer.

func (*Decoder) DecodeWithFEC

func (d *Decoder) DecodeWithFEC(data []byte, pcm []float32, fec bool) (int, error)

DecodeWithFEC decodes an Opus packet, optionally recovering a lost frame using FEC.

This mirrors libopus decode_fec semantics: when fec is true, the decoder uses in-band LBRR data if present and otherwise falls back to packet loss concealment instead of returning a missing-FEC error.

func (*Decoder) FinalRange

func (d *Decoder) FinalRange() uint32

FinalRange returns the final range coder state after decoding. This matches libopus OPUS_GET_FINAL_RANGE and is used for bitstream verification. Must be called after Decode() to get a meaningful value.

Per libopus, the final range is XORed with any redundancy frame's range. If the packet length was <= 1, FinalRange returns 0.

func (*Decoder) Gain

func (d *Decoder) Gain() int

Gain returns the current decoder output gain in Q8 dB units.

func (*Decoder) IgnoreExtensions

func (d *Decoder) IgnoreExtensions() bool

IgnoreExtensions reports whether unknown packet extensions are ignored.

func (*Decoder) InDTX

func (d *Decoder) InDTX() bool

InDTX reports whether the most recently decoded packet was a DTX packet.

func (*Decoder) LastPacketDuration

func (d *Decoder) LastPacketDuration() int

LastPacketDuration returns the duration in samples per channel at the decoder API rate.

func (*Decoder) PhaseInversionDisabled

func (d *Decoder) PhaseInversionDisabled() bool

PhaseInversionDisabled reports whether CELT stereo phase inversion is disabled.

func (*Decoder) Pitch

func (d *Decoder) Pitch() int

Pitch returns the most recent decoded pitch period.

func (*Decoder) Reset

func (d *Decoder) Reset()

Reset clears the decoder state for a new stream. Call this when starting to decode a new audio stream.

func (*Decoder) SampleRate

func (d *Decoder) SampleRate() int

SampleRate returns the sample rate in Hz.

func (*Decoder) SetComplexity

func (d *Decoder) SetComplexity(complexity int) error

SetComplexity sets decoder complexity (0-10).

func (*Decoder) SetDNNBlob

func (d *Decoder) SetDNNBlob(_ []byte) error

SetDNNBlob reports that USE_WEIGHTS_FILE model loading is unavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable the model-loading control.

func (*Decoder) SetGain

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

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

func (d *Decoder) SetIgnoreExtensions(ignore bool)

SetIgnoreExtensions toggles whether unknown packet extensions should be ignored.

This mirrors libopus OPUS_SET_IGNORE_EXTENSIONS semantics.

func (*Decoder) SetPhaseInversionDisabled

func (d *Decoder) SetPhaseInversionDisabled(disabled bool)

SetPhaseInversionDisabled toggles CELT stereo phase inversion during decoding.

type DecoderConfig

type DecoderConfig struct {
	// SampleRate must be one of: 8000, 12000, 16000, 24000, 48000.
	SampleRate int
	// Channels must be 1 (mono) or 2 (stereo).
	Channels int
	// MaxPacketSamples caps the maximum decoded samples per channel per packet.
	// If zero, defaultMaxPacketSamples is used.
	MaxPacketSamples int
	// MaxPacketBytes caps the maximum Opus packet size in bytes.
	// If zero, defaultMaxPacketBytes is used.
	MaxPacketBytes int
}

DecoderConfig configures a Decoder instance.

func DefaultDecoderConfig

func DefaultDecoderConfig(sampleRate, channels int) DecoderConfig

DefaultDecoderConfig returns a config with default caps for the given stream format.

type Encoder

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

Encoder encodes PCM audio samples into Opus packets.

An Encoder instance maintains internal state and is NOT safe for concurrent use. Each goroutine should create its own Encoder instance.

The encoder supports three modes:

  • SILK: optimized for speech at lower bitrates
  • CELT: optimized for music and high-quality audio
  • Hybrid: combines SILK and CELT for wideband speech

The mode is automatically selected based on the Application hint and bandwidth settings.

Zero-allocation design: All scratch buffers are pre-allocated at construction time. The Encode and EncodeInt16 methods perform zero heap allocations in the hot path when called with properly sized caller-provided buffers.

func NewEncoder

func NewEncoder(cfg EncoderConfig) (*Encoder, error)

NewEncoder creates a new Opus encoder.

Returns an error if the config is invalid.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	// Create an encoder for 48kHz stereo audio
	enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
	if err != nil {
		log.Fatal(err)
	}

	// Configure encoder settings
	enc.SetBitrate(64000) // 64 kbps
	enc.SetComplexity(10) // Maximum quality

	fmt.Printf("Encoder: %dHz, %d channels\n", enc.SampleRate(), enc.Channels())
}
Output:
Encoder: 48000Hz, 2 channels

func (*Encoder) Application

func (e *Encoder) Application() Application

Application returns the current encoder application hint.

func (*Encoder) Bandwidth

func (e *Encoder) Bandwidth() Bandwidth

Bandwidth returns the currently configured target bandwidth.

func (*Encoder) Bitrate

func (e *Encoder) Bitrate() int

Bitrate returns the current target bitrate in bits per second.

func (*Encoder) BitrateMode

func (e *Encoder) BitrateMode() BitrateMode

BitrateMode returns the active encoder bitrate control mode.

func (*Encoder) Channels

func (e *Encoder) Channels() int

Channels returns the number of audio channels (1 or 2).

func (*Encoder) Complexity

func (e *Encoder) Complexity() int

Complexity returns the current complexity setting.

func (*Encoder) DTXEnabled

func (e *Encoder) DTXEnabled() bool

DTXEnabled returns whether DTX is enabled.

func (*Encoder) Encode

func (e *Encoder) Encode(pcm []float32, data []byte) (int, error)

Encode encodes float32 PCM samples into an Opus packet.

pcm: Input samples (interleaved if stereo). Length must be frameSize * channels. data: Output buffer for the encoded packet. Recommended size is 4000 bytes.

Returns the number of bytes written to data, or an error. When DTX is active during silence, returns a 1-byte TOC-only packet. Returns 0 bytes only when buffering (internal lookahead not yet filled).

Buffer sizing: 4000 bytes is sufficient for any Opus packet.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
	if err != nil {
		log.Fatal(err)
	}

	// Generate 20ms of stereo silence (960 samples per channel)
	pcm := make([]float32, 960*2)
	packetBuf := make([]byte, 4000)

	// Encode the frame
	n, err := enc.Encode(pcm, packetBuf)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Encoded %d PCM samples into packet: %t\n", len(pcm)/enc.Channels(), n > 0)
}
Output:
Encoded 960 PCM samples into packet: true

func (*Encoder) EncodeFloat32

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

EncodeFloat32 encodes float32 PCM samples and returns a new byte slice.

This is a convenience method that allocates the output buffer. For performance-critical code, use Encode with a pre-allocated buffer.

pcm: Input samples (interleaved if stereo).

Returns the encoded packet or an error.

func (*Encoder) EncodeInt16

func (e *Encoder) EncodeInt16(pcm []int16, data []byte) (int, error)

EncodeInt16 encodes int16 PCM samples into an Opus packet.

pcm: Input samples (interleaved if stereo). Length must be frameSize * channels. data: Output buffer for the encoded packet.

Returns the number of bytes written to data, or an error.

The samples are converted from int16 by dividing by 32768.

func (*Encoder) EncodeInt16Slice

func (e *Encoder) EncodeInt16Slice(pcm []int16) ([]byte, error)

EncodeInt16Slice encodes int16 PCM samples and returns a new byte slice.

This is a convenience method that allocates the output buffer. For performance-critical code, use EncodeInt16 with a pre-allocated buffer.

pcm: Input samples (interleaved if stereo).

Returns the encoded packet or an error.

func (*Encoder) EncodeInt24

func (e *Encoder) EncodeInt24(pcm []int32, data []byte) (int, error)

EncodeInt24 encodes 24-bit PCM samples stored in int32 values into an Opus packet.

pcm: Input samples (interleaved if stereo). Length must be frameSize * channels. data: Output buffer for the encoded packet.

Returns the number of bytes written to data, or an error.

The input values are interpreted with the same semantics as libopus opus_encode24(): right-justified signed 24-bit PCM carried in int32 containers with numeric range [-8388608, 8388607]. Left-shifted 24-in-32 input will be mis-scaled.

func (*Encoder) EncodeInt24Slice

func (e *Encoder) EncodeInt24Slice(pcm []int32) ([]byte, error)

EncodeInt24Slice encodes 24-bit PCM samples stored in int32 values and returns a new byte slice.

This is a convenience method that allocates the output buffer. For performance-critical code, use EncodeInt24 with a pre-allocated buffer.

func (*Encoder) ExpertFrameDuration

func (e *Encoder) ExpertFrameDuration() ExpertFrameDuration

ExpertFrameDuration returns the current expert frame duration policy.

func (*Encoder) FECEnabled

func (e *Encoder) FECEnabled() bool

FECEnabled returns whether FEC is enabled.

func (*Encoder) FinalRange

func (e *Encoder) FinalRange() uint32

FinalRange returns the final range coder state after encoding. This matches libopus OPUS_GET_FINAL_RANGE and is used for bitstream verification. Must be called after Encode() to get a meaningful value.

func (*Encoder) ForceChannels

func (e *Encoder) ForceChannels() int

ForceChannels returns the forced channel count (-1 = auto).

func (*Encoder) FrameSize

func (e *Encoder) FrameSize() int

FrameSize returns the current frame size in samples at the API sample rate. At 96 kHz, this is 2x the 48 kHz internal frame size.

func (*Encoder) InBandFEC

func (e *Encoder) InBandFEC() int

InBandFEC returns the current in-band FEC configuration.

func (*Encoder) InDTX

func (e *Encoder) InDTX() bool

InDTX reports whether the encoder is currently in DTX mode.

This matches libopus OPUS_GET_IN_DTX semantics.

func (*Encoder) LSBDepth

func (e *Encoder) LSBDepth() int

LSBDepth returns the current input bit depth setting.

func (*Encoder) Lookahead

func (e *Encoder) 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 (*Encoder) MaxBandwidth

func (e *Encoder) MaxBandwidth() Bandwidth

MaxBandwidth returns the current maximum bandwidth limit.

func (*Encoder) Mode

func (e *Encoder) Mode() EncoderMode

Mode returns the current forced coding mode.

func (*Encoder) PacketLoss

func (e *Encoder) PacketLoss() int

PacketLoss returns the configured expected packet loss percentage.

func (*Encoder) PhaseInversionDisabled

func (e *Encoder) PhaseInversionDisabled() bool

PhaseInversionDisabled returns whether stereo phase inversion is disabled.

func (*Encoder) PredictionDisabled

func (e *Encoder) PredictionDisabled() bool

PredictionDisabled returns whether inter-frame prediction is disabled.

func (*Encoder) Reset

func (e *Encoder) Reset()

Reset clears the encoder state for a new stream. Call this when starting to encode a new audio stream.

func (*Encoder) SampleRate

func (e *Encoder) SampleRate() int

SampleRate returns the sample rate in Hz.

func (*Encoder) SetApplication

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

SetApplication updates the encoder application hint.

Valid values are ApplicationVoIP, ApplicationAudio, and ApplicationLowDelay.

func (*Encoder) SetBandwidth

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

SetBandwidth sets the target audio bandwidth.

func (*Encoder) SetBandwidthAuto

func (e *Encoder) SetBandwidthAuto() error

SetBandwidthAuto restores automatic bandwidth selection.

func (*Encoder) SetBitrate

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

SetBitrate sets the target bitrate in bits per second.

Positive bitrates are clamped to the libopus range. Returns ErrInvalidBitrate for non-positive non-sentinel values.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
	if err != nil {
		log.Fatal(err)
	}

	// Set bitrate to 128 kbps
	err = enc.SetBitrate(128000)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Bitrate set to %d bps\n", enc.Bitrate())
}
Output:
Bitrate set to 128000 bps

func (*Encoder) SetBitrateMode

func (e *Encoder) SetBitrateMode(mode BitrateMode) error

SetBitrateMode sets the encoder bitrate control mode.

func (*Encoder) SetComplexity

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

SetComplexity sets the encoder's computational complexity.

complexity must be 0-10, where:

  • 0-1: Minimal processing, fastest encoding
  • 2-4: Basic analysis, good for real-time with limited CPU
  • 5-7: Moderate analysis, balanced quality/speed
  • 8-10: Thorough analysis, highest quality

Returns ErrInvalidComplexity if out of range.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
	if err != nil {
		log.Fatal(err)
	}

	// Set complexity to maximum quality
	err = enc.SetComplexity(10)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Complexity: %d\n", enc.Complexity())
}
Output:
Complexity: 10

func (*Encoder) SetDNNBlob

func (e *Encoder) SetDNNBlob(_ []byte) error

SetDNNBlob reports that USE_WEIGHTS_FILE model loading is unavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable the model-loading control.

func (*Encoder) SetDTX

func (e *Encoder) SetDTX(enabled bool)

SetDTX enables or disables Discontinuous Transmission.

When enabled, the encoder reduces bitrate during silence by:

  • Suppressing packets entirely during silence
  • Sending periodic comfort noise frames

DTX is useful for VoIP applications to reduce bandwidth.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 1, Application: gopus.ApplicationVoIP})
	if err != nil {
		log.Fatal(err)
	}

	// Enable DTX for bandwidth savings during silence
	enc.SetDTX(true)

	fmt.Printf("DTX enabled: %v\n", enc.DTXEnabled())
}
Output:
DTX enabled: true

func (*Encoder) SetExpertFrameDuration

func (e *Encoder) SetExpertFrameDuration(duration ExpertFrameDuration) error

SetExpertFrameDuration sets the preferred frame duration policy.

`ExpertFrameDurationArg` keeps using the current `FrameSize()` value. Fixed durations are applied during Encode when they fit within the current frame.

func (*Encoder) SetFEC

func (e *Encoder) SetFEC(enabled bool)

SetFEC enables or disables in-band Forward Error Correction.

When enabled, the encoder includes redundant information for loss recovery. FEC is most effective when the receiver can request retransmission of lost packets.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationVoIP})
	if err != nil {
		log.Fatal(err)
	}

	// Enable FEC for packet loss recovery
	enc.SetFEC(true)

	fmt.Printf("FEC enabled: %v\n", enc.FECEnabled())
}
Output:
FEC enabled: true

func (*Encoder) SetForceChannels

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

SetForceChannels forces the encoder to use a specific channel count.

channels must be one of:

  • -1: automatic (use input channels)
  • 1: force mono output
  • 2: force stereo output

Note: Forcing stereo on mono input will duplicate the channel. Forcing mono on stereo input will downmix to mono.

Returns ErrInvalidForceChannels if the value is not valid.

func (*Encoder) SetFrameSize

func (e *Encoder) SetFrameSize(samples int) error

SetFrameSize sets the frame size in samples at 48kHz.

Valid sizes depend on the encoding mode:

  • SILK: 480, 960, 1920, 2880, 3840, 4800, 5760 (10-120 ms)
  • CELT: 120, 240, 480, 960, 1920, 2880, 3840, 4800, 5760
  • Hybrid: 480, 960, 1920, 2880, 3840, 4800, 5760

Default is 960 (20ms).

func (*Encoder) SetInBandFEC

func (e *Encoder) SetInBandFEC(config int) error

SetInBandFEC sets the libopus-compatible in-band FEC configuration.

func (*Encoder) SetLSBDepth

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

SetLSBDepth sets the bit depth of the input signal.

depth must be 8-24. This affects DTX silence detection: lower bit depths have a higher noise floor, so the encoder adjusts its silence threshold accordingly.

Default is 24 (full precision). Returns ErrInvalidLSBDepth if out of range.

func (*Encoder) SetMaxBandwidth

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

SetMaxBandwidth sets the maximum audio bandwidth.

The encoder will not use a bandwidth higher than this limit. This is useful for limiting bandwidth without changing the sample rate.

Valid values are:

  • BandwidthNarrowband (4kHz)
  • BandwidthMediumband (6kHz)
  • BandwidthWideband (8kHz)
  • BandwidthSuperwideband (12kHz)
  • BandwidthFullband (20kHz)

func (*Encoder) SetMode

func (e *Encoder) SetMode(mode EncoderMode) error

SetMode sets the encoder's forced coding mode.

func (*Encoder) SetPacketLoss

func (e *Encoder) SetPacketLoss(lossPercent int) error

SetPacketLoss sets the expected packet loss percentage.

lossPercent must be in the range [0, 100].

func (*Encoder) SetPhaseInversionDisabled

func (e *Encoder) SetPhaseInversionDisabled(disabled bool)

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

func (e *Encoder) SetPredictionDisabled(disabled bool)

SetPredictionDisabled disables inter-frame prediction.

When disabled (true), each frame can be decoded independently, which improves error resilience at the cost of compression efficiency. This is useful for applications with high packet loss.

Default is false (prediction enabled).

func (*Encoder) SetSignal

func (e *Encoder) SetSignal(signal Signal) error

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

func (e *Encoder) 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 (*Encoder) SetVBRConstraint

func (e *Encoder) SetVBRConstraint(constrained bool)

SetVBRConstraint enables or disables VBR constraint.

This setting is remembered even while VBR is disabled.

func (*Encoder) Signal

func (e *Encoder) Signal() Signal

Signal returns the current signal type hint.

func (*Encoder) VADActivity

func (e *Encoder) VADActivity() int

VADActivity returns the current VAD speech activity level in Q8 (0-255).

func (*Encoder) VBR

func (e *Encoder) VBR() bool

VBR returns whether VBR mode is enabled.

func (*Encoder) VBRConstraint

func (e *Encoder) VBRConstraint() bool

VBRConstraint returns whether VBR constraint is enabled.

type EncoderConfig

type EncoderConfig struct {
	// SampleRate must be one of: 8000, 12000, 16000, 24000, 48000.
	SampleRate int
	// Channels must be 1 (mono) or 2 (stereo).
	Channels int
	// Application hints the encoder for optimization.
	Application Application
}

EncoderConfig configures an Encoder instance.

type EncoderMode

type EncoderMode = encoder.Mode

EncoderMode controls the encoder's forced coding mode.

type ExpertFrameDuration

type ExpertFrameDuration int

ExpertFrameDuration mirrors libopus OPUS_SET/GET_EXPERT_FRAME_DURATION values.

It selects the duration the encoder uses for each Opus frame, overriding the duration implied by the per-call sample count. A requested duration takes effect only when it fits within the samples passed to Encode; a longer duration than the input provides is rejected with ErrInvalidFrameSize. The numeric values match the libopus OPUS_FRAMESIZE_* constants.

const (
	// ExpertFrameDurationArg keeps the frame duration implied by the per-call
	// sample count (libopus OPUS_FRAMESIZE_ARG). This is the default.
	ExpertFrameDurationArg ExpertFrameDuration = 5000
	// ExpertFrameDuration2_5Ms forces 2.5 ms frames (CELT-capable modes only).
	ExpertFrameDuration2_5Ms ExpertFrameDuration = 5001
	// ExpertFrameDuration5Ms forces 5 ms frames (CELT-capable modes only).
	ExpertFrameDuration5Ms ExpertFrameDuration = 5002
	// ExpertFrameDuration10Ms forces 10 ms frames.
	ExpertFrameDuration10Ms ExpertFrameDuration = 5003
	// ExpertFrameDuration20Ms forces 20 ms frames.
	ExpertFrameDuration20Ms ExpertFrameDuration = 5004
	// ExpertFrameDuration40Ms forces 40 ms frames.
	ExpertFrameDuration40Ms ExpertFrameDuration = 5005
	// ExpertFrameDuration60Ms forces 60 ms frames.
	ExpertFrameDuration60Ms ExpertFrameDuration = 5006
	// ExpertFrameDuration80Ms forces 80 ms frames.
	ExpertFrameDuration80Ms ExpertFrameDuration = 5007
	// ExpertFrameDuration100Ms forces 100 ms frames.
	ExpertFrameDuration100Ms ExpertFrameDuration = 5008
	// ExpertFrameDuration120Ms forces 120 ms frames.
	ExpertFrameDuration120Ms ExpertFrameDuration = 5009
)

type Mode

type Mode = types.Mode

Mode is an alias for types.Mode representing the Opus coding mode.

type MultistreamDecoder

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

MultistreamDecoder decodes Opus multistream packets into multi-channel PCM audio.

A MultistreamDecoder instance maintains internal state and is NOT safe for concurrent use. Each goroutine should create its own MultistreamDecoder instance.

Multistream decoding is used for surround sound configurations (5.1, 7.1, etc.) where multiple coupled (stereo) and uncoupled (mono) streams are combined.

Reference: RFC 6716 Appendix B, RFC 7845 Section 5.1.1

func NewMultistreamDecoder

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

NewMultistreamDecoder creates a new multistream decoder with explicit configuration.

Parameters:

  • sampleRate: output sample rate (8000, 12000, 16000, 24000, or 48000 Hz)
  • channels: total output channels (1-255)
  • streams: total elementary streams (N, 1-255)
  • coupledStreams: number of coupled stereo streams (M, 0 to streams) with streams + coupledStreams <= 255
  • mapping: channel mapping table (length must equal channels)

Returns ErrInvalidChannels when channels is outside the explicit multistream range [1, 255].

The mapping table determines how decoded audio is routed to output channels:

  • Values 0 to 2*M-1: from coupled streams (even=left, odd=right of stereo pair)
  • Values 2*M to N+M-1: from uncoupled (mono) streams
  • Value 255: silent channel (output zeros)

func NewMultistreamDecoderDefault

func NewMultistreamDecoderDefault(sampleRate, channels int) (*MultistreamDecoder, error)

NewMultistreamDecoderDefault creates a multistream decoder with default Vorbis-style mapping for standard channel configurations (1-8 channels).

This is a convenience function that calls the internal DefaultMapping() to get the appropriate streams, coupledStreams, and mapping for the given channel count. Returns ErrInvalidChannels when channels is outside the default-mapping range [1, 8]. Use NewMultistreamDecoder with an explicit mapping for layouts above 8 channels.

Supported channel counts:

  • 1: mono (1 stream, 0 coupled)
  • 2: stereo (1 stream, 1 coupled)
  • 3: 3.0 (2 streams, 1 coupled)
  • 4: quad (2 streams, 2 coupled)
  • 5: 5.0 (3 streams, 2 coupled)
  • 6: 5.1 surround (4 streams, 2 coupled)
  • 7: 6.1 surround (4 streams, 3 coupled)
  • 8: 7.1 surround (5 streams, 3 coupled)

func (*MultistreamDecoder) Bandwidth

func (d *MultistreamDecoder) Bandwidth() Bandwidth

Bandwidth returns the bandwidth of the first elementary stream decoder.

func (*MultistreamDecoder) Channels

func (d *MultistreamDecoder) Channels() int

Channels returns the number of audio channels.

func (*MultistreamDecoder) Complexity

func (d *MultistreamDecoder) Complexity() int

Complexity returns the decoder complexity from the first elementary stream.

func (*MultistreamDecoder) CoupledStreams

func (d *MultistreamDecoder) CoupledStreams() int

CoupledStreams returns the number of coupled (stereo) streams.

func (*MultistreamDecoder) Decode

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

Decode decodes an Opus multistream packet into float32 PCM samples.

data: Opus multistream packet data, or nil for Packet Loss Concealment (PLC). pcm: Output buffer for decoded samples. Must be large enough to hold frameSize * channels samples.

Returns the number of samples per channel decoded, or an error.

When data is nil, the decoder performs packet loss concealment using the last successfully decoded frame parameters.

func (*MultistreamDecoder) DecodeInt16

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

DecodeInt16 decodes an Opus multistream packet into int16 PCM samples.

data: Opus multistream packet data, or nil for PLC. pcm: Output buffer for decoded samples.

Returns the number of samples per channel decoded, or an error.

func (*MultistreamDecoder) DecodeInt24

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

DecodeInt24 decodes an Opus multistream packet into 24-bit PCM samples stored in int32.

data: Opus multistream packet data, or nil for PLC. pcm: Output buffer for decoded samples. Each element carries a right-justified signed 24-bit value in the range [-8388608, 8388607] (= ±2^23), matching libopus opus_multistream_decode24().

Returns the number of samples per channel decoded, or an error.

func (*MultistreamDecoder) DecodeInt24Slice

func (d *MultistreamDecoder) DecodeInt24Slice(data []byte) ([]int32, error)

DecodeInt24Slice decodes an Opus multistream packet into 24-bit PCM samples and returns a new int32 slice. Each element carries a right-justified signed 24-bit value.

This is a convenience method that allocates the output buffer. For performance-critical code, use DecodeInt24 with a pre-allocated buffer.

func (*MultistreamDecoder) FinalRange

func (d *MultistreamDecoder) FinalRange() uint32

FinalRange returns the XOR of all elementary stream final range values.

func (*MultistreamDecoder) Gain

func (d *MultistreamDecoder) Gain() int

Gain returns the output gain from the first elementary stream decoder.

func (*MultistreamDecoder) GetFinalRange

func (d *MultistreamDecoder) GetFinalRange() uint32

GetFinalRange returns the XOR of all elementary stream final range values.

func (*MultistreamDecoder) IgnoreExtensions

func (d *MultistreamDecoder) IgnoreExtensions() bool

IgnoreExtensions reports whether unknown packet extensions are ignored.

func (*MultistreamDecoder) LastPacketDuration

func (d *MultistreamDecoder) LastPacketDuration() int

LastPacketDuration returns the last packet duration from the first stream decoder.

func (*MultistreamDecoder) PhaseInversionDisabled

func (d *MultistreamDecoder) PhaseInversionDisabled() bool

PhaseInversionDisabled reports the first stream decoder's phase inversion setting.

func (*MultistreamDecoder) Reset

func (d *MultistreamDecoder) Reset()

Reset clears the decoder state for a new stream. Call this when starting to decode a new audio stream.

func (*MultistreamDecoder) SampleRate

func (d *MultistreamDecoder) SampleRate() int

SampleRate returns the sample rate in Hz.

func (*MultistreamDecoder) SetComplexity

func (d *MultistreamDecoder) SetComplexity(complexity int) error

SetComplexity sets decoder complexity (0-10) on all elementary streams.

func (*MultistreamDecoder) SetDNNBlob

func (d *MultistreamDecoder) SetDNNBlob(_ []byte) error

SetDNNBlob reports that USE_WEIGHTS_FILE model loading is unavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable the model-loading control.

func (*MultistreamDecoder) SetGain

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

SetGain sets output gain in Q8 dB units on all elementary stream decoders.

func (*MultistreamDecoder) SetIgnoreExtensions

func (d *MultistreamDecoder) SetIgnoreExtensions(ignore bool)

SetIgnoreExtensions toggles whether unknown packet extensions should be ignored.

func (*MultistreamDecoder) SetPhaseInversionDisabled

func (d *MultistreamDecoder) SetPhaseInversionDisabled(disabled bool)

SetPhaseInversionDisabled toggles CELT stereo phase inversion on all streams.

func (*MultistreamDecoder) Streams

func (d *MultistreamDecoder) Streams() int

Streams returns the total number of elementary streams.

type MultistreamEncoder

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

MultistreamEncoder encodes multi-channel PCM audio into Opus multistream packets.

A MultistreamEncoder instance maintains internal state and is NOT safe for concurrent use. Each goroutine should create its own MultistreamEncoder instance.

Multistream encoding is used for surround sound configurations (5.1, 7.1, etc.) where multiple coupled (stereo) and uncoupled (mono) streams are combined.

Reference: RFC 6716 Appendix B, RFC 7845 Section 5.1.1

func NewMultistreamEncoder

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

NewMultistreamEncoder creates a new multistream encoder with explicit configuration.

Parameters:

  • sampleRate: input sample rate (8000, 12000, 16000, 24000, or 48000 Hz)
  • channels: total input channels (1-255)
  • streams: total elementary streams (N, 1-255)
  • coupledStreams: number of coupled stereo streams (M, 0 to streams) with streams + coupledStreams <= 255
  • mapping: channel mapping table (length must equal channels)
  • application: application hint for encoder optimization

Returns ErrInvalidChannels when channels is outside the explicit multistream range [1, 255].

The mapping table determines how input audio is routed to stream encoders:

  • Values 0 to 2*M-1: to coupled streams (even=left, odd=right of stereo pair)
  • Values 2*M to N+M-1: to uncoupled (mono) streams
  • Value 255: silent channel (input ignored)

Example for 5.1 surround (6 channels, 4 streams, 2 coupled):

mapping = [0, 4, 1, 2, 3, 5]
  Input 0 (FL): mapping[0]=0 -> coupled stream 0, left
  Input 1 (C):  mapping[1]=4 -> uncoupled stream 2 (2*2+0)
  Input 2 (FR): mapping[2]=1 -> coupled stream 0, right
  Input 3 (RL): mapping[3]=2 -> coupled stream 1, left
  Input 4 (RR): mapping[4]=3 -> coupled stream 1, right
  Input 5 (LFE): mapping[5]=5 -> uncoupled stream 3 (2*2+1)

func NewMultistreamEncoderDefault

func NewMultistreamEncoderDefault(sampleRate, channels int, application Application) (*MultistreamEncoder, error)

NewMultistreamEncoderDefault creates a multistream encoder with default Vorbis-style mapping for standard channel configurations (1-8 channels).

This is a convenience function that calls the internal DefaultMapping() to get the appropriate streams, coupledStreams, and mapping for the given channel count. Returns ErrInvalidChannels when channels is outside the default-mapping range [1, 8]. Use NewMultistreamEncoder with an explicit mapping for layouts above 8 channels.

Supported channel counts:

  • 1: mono (1 stream, 0 coupled)
  • 2: stereo (1 stream, 1 coupled)
  • 3: 3.0 (2 streams, 1 coupled)
  • 4: quad (2 streams, 2 coupled)
  • 5: 5.0 (3 streams, 2 coupled)
  • 6: 5.1 surround (4 streams, 2 coupled)
  • 7: 6.1 surround (4 streams, 3 coupled)
  • 8: 7.1 surround (5 streams, 3 coupled)

func (*MultistreamEncoder) Application

func (e *MultistreamEncoder) Application() Application

Application returns the current encoder application hint.

func (*MultistreamEncoder) Bandwidth

func (e *MultistreamEncoder) Bandwidth() Bandwidth

Bandwidth returns the currently configured target bandwidth.

func (*MultistreamEncoder) Bitrate

func (e *MultistreamEncoder) Bitrate() int

Bitrate returns the current total target bitrate in bits per second.

func (*MultistreamEncoder) BitrateMode

func (e *MultistreamEncoder) BitrateMode() BitrateMode

BitrateMode returns the active bitrate control mode.

func (*MultistreamEncoder) Channels

func (e *MultistreamEncoder) Channels() int

Channels returns the number of audio channels.

func (*MultistreamEncoder) Complexity

func (e *MultistreamEncoder) Complexity() int

Complexity returns the current complexity setting.

func (*MultistreamEncoder) CoupledStreams

func (e *MultistreamEncoder) CoupledStreams() int

CoupledStreams returns the number of coupled (stereo) streams.

func (*MultistreamEncoder) DTXEnabled

func (e *MultistreamEncoder) DTXEnabled() bool

DTXEnabled returns whether DTX is enabled.

func (*MultistreamEncoder) Encode

func (e *MultistreamEncoder) Encode(pcm []float32, data []byte) (int, error)

Encode encodes float32 PCM samples into an Opus multistream packet.

pcm: Input samples (interleaved). Length must be frameSize * channels. data: Output buffer for the encoded packet. Recommended size is 4000 bytes per stream.

Returns the number of bytes written to data, or an error. Returns 0 bytes written if DTX suppresses all frames (silence detected in all streams).

func (*MultistreamEncoder) EncodeFloat32

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

EncodeFloat32 encodes float32 PCM samples and returns a new byte slice.

This is a convenience method that allocates the output buffer. For performance-critical code, use Encode with a pre-allocated buffer.

pcm: Input samples (interleaved).

Returns the encoded packet or an error.

func (*MultistreamEncoder) EncodeInt16

func (e *MultistreamEncoder) EncodeInt16(pcm []int16, data []byte) (int, error)

EncodeInt16 encodes int16 PCM samples into an Opus multistream packet.

pcm: Input samples (interleaved). Length must be frameSize * channels. data: Output buffer for the encoded packet.

Returns the number of bytes written to data, or an error.

func (*MultistreamEncoder) EncodeInt16Slice

func (e *MultistreamEncoder) EncodeInt16Slice(pcm []int16) ([]byte, error)

EncodeInt16Slice encodes int16 PCM samples and returns a new byte slice.

This is a convenience method that allocates the output buffer. For performance-critical code, use EncodeInt16 with a pre-allocated buffer.

pcm: Input samples (interleaved).

Returns the encoded packet or an error.

func (*MultistreamEncoder) EncodeInt24

func (e *MultistreamEncoder) EncodeInt24(pcm []int32, data []byte) (int, error)

EncodeInt24 encodes 24-bit PCM samples stored in int32 values into an Opus multistream packet.

pcm: Input samples (interleaved). Length must be frameSize * channels. data: Output buffer for the encoded packet.

Returns the number of bytes written to data, or an error.

The input values are interpreted as right-justified signed 24-bit PCM carried in int32 containers with numeric range [-8388608, 8388607]. Left-shifted 24-in-32 input will be mis-scaled.

func (*MultistreamEncoder) EncodeInt24Slice

func (e *MultistreamEncoder) EncodeInt24Slice(pcm []int32) ([]byte, error)

EncodeInt24Slice encodes 24-bit PCM samples stored in int32 values and returns a new byte slice.

This is a convenience method that allocates the output buffer.

func (*MultistreamEncoder) ExpertFrameDuration

func (e *MultistreamEncoder) ExpertFrameDuration() ExpertFrameDuration

ExpertFrameDuration returns the current multistream expert frame duration policy.

func (*MultistreamEncoder) FECEnabled

func (e *MultistreamEncoder) FECEnabled() bool

FECEnabled returns whether FEC is enabled.

func (*MultistreamEncoder) FinalRange

func (e *MultistreamEncoder) FinalRange() uint32

FinalRange returns the final range coder state.

func (*MultistreamEncoder) ForceChannels

func (e *MultistreamEncoder) ForceChannels() int

ForceChannels returns the forced channel count (-1 = auto).

func (*MultistreamEncoder) FrameSize

func (e *MultistreamEncoder) FrameSize() int

FrameSize returns the current frame size in native-Fs samples.

func (*MultistreamEncoder) GetFinalRange

func (e *MultistreamEncoder) GetFinalRange() uint32

GetFinalRange returns the final range coder state for all streams. The values from all streams are XOR combined to produce a single verification value. This matches libopus OPUS_GET_FINAL_RANGE for multistream encoders. Must be called after Encode() to get a meaningful value.

func (*MultistreamEncoder) InBandFEC

func (e *MultistreamEncoder) InBandFEC() int

InBandFEC returns the current in-band FEC configuration.

func (*MultistreamEncoder) LSBDepth

func (e *MultistreamEncoder) LSBDepth() int

LSBDepth returns the current LSB depth setting.

func (*MultistreamEncoder) Lookahead

func (e *MultistreamEncoder) Lookahead() int

Lookahead returns the encoder's algorithmic delay in samples.

Matches libopus OPUS_GET_LOOKAHEAD behavior:

  • Base lookahead is Fs/400 (2.5ms)
  • Delay compensation Fs/250 is included for VoIP/Audio
  • Delay compensation is omitted for LowDelay

func (*MultistreamEncoder) MaxBandwidth

func (e *MultistreamEncoder) MaxBandwidth() Bandwidth

MaxBandwidth returns the maximum bandwidth limit.

func (*MultistreamEncoder) Mode

func (e *MultistreamEncoder) Mode() EncoderMode

Mode returns the forced coding mode from the first stream encoder.

func (*MultistreamEncoder) PacketLoss

func (e *MultistreamEncoder) PacketLoss() int

PacketLoss returns expected packet loss percentage.

func (*MultistreamEncoder) PhaseInversionDisabled

func (e *MultistreamEncoder) PhaseInversionDisabled() bool

PhaseInversionDisabled reports whether stereo phase inversion is disabled.

func (*MultistreamEncoder) PredictionDisabled

func (e *MultistreamEncoder) PredictionDisabled() bool

PredictionDisabled reports whether inter-frame prediction is disabled.

func (*MultistreamEncoder) Reset

func (e *MultistreamEncoder) Reset()

Reset clears the encoder state for a new stream. Call this when starting to encode a new audio stream.

func (*MultistreamEncoder) SampleRate

func (e *MultistreamEncoder) SampleRate() int

SampleRate returns the sample rate in Hz.

func (*MultistreamEncoder) SetApplication

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

SetApplication updates the encoder application hint.

Valid values are ApplicationVoIP, ApplicationAudio, and ApplicationLowDelay.

func (*MultistreamEncoder) SetBandwidth

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

SetBandwidth sets the target audio bandwidth.

func (*MultistreamEncoder) SetBandwidthAuto

func (e *MultistreamEncoder) SetBandwidthAuto() error

SetBandwidthAuto restores automatic bandwidth selection for all stream encoders.

func (*MultistreamEncoder) SetBitrate

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

SetBitrate sets the total target bitrate in bits per second.

The bitrate is distributed across streams with coupled streams getting proportionally more bits than mono streams.

Positive bitrates are clamped to 500*channels through 750000*channels.

func (*MultistreamEncoder) SetBitrateMode

func (e *MultistreamEncoder) SetBitrateMode(mode BitrateMode) error

SetBitrateMode sets the multistream encoder bitrate control mode.

func (*MultistreamEncoder) SetComplexity

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

SetComplexity sets the encoder's computational complexity for all streams.

complexity must be 0-10, where:

  • 0-1: Minimal processing, fastest encoding
  • 2-4: Basic analysis, good for real-time with limited CPU
  • 5-7: Moderate analysis, balanced quality/speed
  • 8-10: Thorough analysis, highest quality

Returns ErrInvalidComplexity if out of range.

func (*MultistreamEncoder) SetDNNBlob

func (e *MultistreamEncoder) SetDNNBlob(_ []byte) error

SetDNNBlob reports that USE_WEIGHTS_FILE model loading is unavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable the model-loading control.

func (*MultistreamEncoder) SetDTX

func (e *MultistreamEncoder) SetDTX(enabled bool)

SetDTX enables or disables Discontinuous Transmission for all streams.

When enabled, the encoders reduce bitrate during silence by emitting 1-byte TOC-only packets. The decoder handles CNG (Comfort Noise Generation).

func (*MultistreamEncoder) SetExpertFrameDuration

func (e *MultistreamEncoder) SetExpertFrameDuration(duration ExpertFrameDuration) error

SetExpertFrameDuration sets the preferred frame duration policy for multistream encoding.

func (*MultistreamEncoder) SetFEC

func (e *MultistreamEncoder) SetFEC(enabled bool)

SetFEC enables or disables in-band Forward Error Correction for all streams.

When enabled, the encoders include redundant information for loss recovery.

func (*MultistreamEncoder) SetForceChannels

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

SetForceChannels forces channel count on all stream encoders.

channels must be -1 (auto), 1 (mono), or 2 (stereo).

func (*MultistreamEncoder) SetFrameSize

func (e *MultistreamEncoder) SetFrameSize(samples int) error

SetFrameSize sets the frame size in native-Fs samples.

Valid sizes are the per-rate Opus frame sizes: (Fs/400)<<n (2.5/5/10 ms) and n*Fs/50 (20/40/60/80/100/120 ms). At 48 kHz these are 120, 240, 480, 960, 1920, 2880, 3840, 4800, and 5760.

func (*MultistreamEncoder) SetInBandFEC

func (e *MultistreamEncoder) SetInBandFEC(config int) error

SetInBandFEC sets the libopus-compatible in-band FEC configuration.

func (*MultistreamEncoder) SetLSBDepth

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

SetLSBDepth sets the input signal's LSB depth for all stream encoders. Valid range is 8-24 bits. This affects DTX sensitivity. Returns an error if the depth is out of range.

func (*MultistreamEncoder) SetMaxBandwidth

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

SetMaxBandwidth sets the maximum bandwidth limit for all stream encoders. The actual bandwidth will be clamped to this limit.

func (*MultistreamEncoder) SetMode

func (e *MultistreamEncoder) SetMode(mode EncoderMode) error

SetMode sets the forced coding mode for all stream encoders.

func (*MultistreamEncoder) SetPacketLoss

func (e *MultistreamEncoder) SetPacketLoss(lossPercent int) error

SetPacketLoss sets expected packet loss percentage for all stream encoders.

lossPercent must be in the range [0, 100].

func (*MultistreamEncoder) SetPhaseInversionDisabled

func (e *MultistreamEncoder) SetPhaseInversionDisabled(disabled bool)

SetPhaseInversionDisabled toggles stereo phase inversion on all stream encoders.

func (*MultistreamEncoder) SetPredictionDisabled

func (e *MultistreamEncoder) SetPredictionDisabled(disabled bool)

SetPredictionDisabled toggles inter-frame prediction on all stream encoders.

func (*MultistreamEncoder) SetSignal

func (e *MultistreamEncoder) SetSignal(signal Signal) error

SetSignal sets the signal type hint for all stream encoders. Use SignalVoice for speech content, SignalMusic for music content, or SignalAuto (default) for automatic detection.

func (*MultistreamEncoder) SetVBR

func (e *MultistreamEncoder) SetVBR(enabled bool)

SetVBR enables or disables VBR mode.

Disabling VBR switches to CBR. Enabling VBR restores VBR while preserving the current VBR constraint state.

func (*MultistreamEncoder) SetVBRConstraint

func (e *MultistreamEncoder) SetVBRConstraint(constrained bool)

SetVBRConstraint enables or disables constrained VBR mode. This setting is remembered even while VBR is disabled.

func (*MultistreamEncoder) Signal

func (e *MultistreamEncoder) Signal() Signal

Signal returns the current signal type hint. Returns SignalAuto, SignalVoice, or SignalMusic.

func (*MultistreamEncoder) Streams

func (e *MultistreamEncoder) Streams() int

Streams returns the total number of elementary streams.

func (*MultistreamEncoder) VBR

func (e *MultistreamEncoder) VBR() bool

VBR reports whether VBR mode is enabled.

func (*MultistreamEncoder) VBRConstraint

func (e *MultistreamEncoder) VBRConstraint() bool

VBRConstraint reports whether constrained VBR mode is enabled.

type OptionalExtension

type OptionalExtension string

OptionalExtension identifies a recognized libopus build-time extension surface.

const (
	// OptionalExtensionDRED identifies DRED controls and standalone DRED packet
	// helpers, which are supported only when built with -tags gopus_dred.
	OptionalExtensionDRED OptionalExtension = "dred"

	// OptionalExtensionDNNBlob identifies supported weights-file model blob loading.
	OptionalExtensionDNNBlob OptionalExtension = "dnn_blob"

	// OptionalExtensionQEXT identifies the optional extended-precision theta path,
	// which is supported only when built with -tags gopus_qext.
	OptionalExtensionQEXT OptionalExtension = "qext"

	// OptionalExtensionOSCEBWE identifies decoder-side OSCE BWE controls, which
	// remain parity-only extra controls rather than supported release surface.
	OptionalExtensionOSCEBWE OptionalExtension = "osce_bwe"
)

type PacketInfo

type PacketInfo struct {
	TOC        TOC   // Parsed TOC byte
	FrameCount int   // Number of frames (1-48 for code 3)
	FrameSizes []int // Size in bytes of each frame
	Padding    int   // Padding bytes (code 3 only)
	TotalSize  int   // Total packet size
}

PacketInfo contains parsed information about an Opus packet.

func ParsePacket

func ParsePacket(data []byte) (PacketInfo, error)

ParsePacket parses an Opus packet and returns information about its structure. It determines the frame boundaries based on the TOC byte's frame code (0-3).

type PacketReader

type PacketReader interface {
	// ReadPacketInto fills dst with the next Opus packet.
	//
	// granulePos is the source packet position in decoded-sample units when the
	// container provides one (for example Ogg Opus granule positions). Sources
	// that do not track positions should return 0.
	//
	// Returns io.EOF when stream ends. Return n=0, err=nil to trigger PLC.
	ReadPacketInto(dst []byte) (n int, granulePos uint64, err error)
}

PacketReader provides Opus packets for streaming decode. Implementations should return io.EOF when no more packets are available.

type PacketSink

type PacketSink interface {
	// WritePacket writes an encoded Opus packet.
	// Returns number of bytes written and any error.
	//
	// If the sink also implements io.Closer, Writer.Close forwards to it after
	// flushing any buffered audio.
	WritePacket(packet []byte) (int, error)
}

PacketSink receives encoded Opus packets from streaming encode.

type Reader

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

Reader decodes an Opus stream, implementing io.Reader. Output is PCM samples in the configured format.

The Reader handles frame boundaries internally, buffering decoded PCM samples and serving byte-oriented reads.

Example:

reader, err := gopus.NewReader(gopus.DefaultDecoderConfig(48000, 2), source, gopus.FormatFloat32LE)
io.Copy(audioOutput, reader)

func NewReader

func NewReader(cfg DecoderConfig, source PacketReader, format SampleFormat) (*Reader, error)

NewReader creates a streaming decoder.

Parameters:

  • cfg: decoder configuration
  • source: provides Opus packets for decoding
  • format: output sample format (FormatFloat32LE or FormatInt16LE)

func (*Reader) Channels

func (r *Reader) Channels() int

Channels returns the number of audio channels (1 or 2).

func (*Reader) LastGranulePos

func (r *Reader) LastGranulePos() uint64

LastGranulePos returns the most recent packet position reported by the source.

For Ogg Opus this is the granule position from the underlying page header. Sources that do not track positions may leave this at 0.

func (*Reader) Read

func (r *Reader) Read(p []byte) (int, error)

Read implements io.Reader, reading decoded PCM bytes.

The Reader handles frame boundaries internally, fetching and decoding packets as needed to fill the buffer.

func (*Reader) Reset

func (r *Reader) Reset()

Reset clears buffers and decoder state for a new stream.

func (*Reader) SampleRate

func (r *Reader) SampleRate() int

SampleRate returns the sample rate in Hz.

type Repacketizer

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

Repacketizer accumulates Opus packet frames and emits new packets assembled from any contiguous frame range.

It mirrors libopus repacketizer behavior:

  • all added packets must share TOC bits 7..2,
  • total stored duration must not exceed 120ms.

func NewRepacketizer

func NewRepacketizer() *Repacketizer

NewRepacketizer creates a new repacketizer state.

func (*Repacketizer) Cat

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

Cat adds one Opus packet to the repacketizer state.

func (*Repacketizer) NumFrames

func (r *Repacketizer) NumFrames() int

NumFrames returns the number of frames currently accumulated.

func (*Repacketizer) Out

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

Out assembles all accumulated frames into one Opus packet.

func (*Repacketizer) OutRange

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

OutRange assembles frames [begin, end) into one Opus packet.

func (*Repacketizer) Reset

func (r *Repacketizer) Reset()

Reset clears repacketizer state.

type SampleFormat

type SampleFormat int

SampleFormat specifies the PCM sample format for streaming.

const (
	// FormatFloat32LE is 32-bit float, little-endian (4 bytes per sample).
	FormatFloat32LE SampleFormat = iota
	// FormatInt16LE is 16-bit signed integer, little-endian (2 bytes per sample).
	FormatInt16LE
)

func (SampleFormat) BytesPerSample

func (f SampleFormat) BytesPerSample() int

BytesPerSample returns the number of bytes per sample for the format.

type Signal

type Signal = types.Signal

Signal represents a hint about the input signal type. This helps the encoder optimize for speech or music content.

type TOC

type TOC struct {
	Config    uint8     // Configuration 0-31
	Mode      Mode      // Derived from config
	Bandwidth Bandwidth // Derived from config
	FrameSize int       // Frame size in samples at 48kHz
	Stereo    bool      // True if stereo
	FrameCode uint8     // Code 0-3
}

TOC represents the parsed Table of Contents byte from an Opus packet.

func ParseTOC

func ParseTOC(b byte) TOC

ParseTOC parses a TOC byte and returns the decoded fields.

type Writer

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

Writer encodes PCM samples to an Opus stream, implementing io.WriteCloser. Input is PCM samples in the configured format.

The Writer buffers input samples until a complete frame is accumulated, then encodes and sends the packet to the sink.

Example:

writer, err := gopus.NewWriter(48000, 2, sink, gopus.FormatFloat32LE, gopus.ApplicationAudio)
io.Copy(writer, audioInput)
writer.Close() // flush remaining buffered samples

func NewWriter

func NewWriter(sampleRate, channels int, sink PacketSink, format SampleFormat, application Application) (*Writer, error)

NewWriter creates a streaming encoder.

Parameters:

  • sampleRate: input sample rate (8000, 12000, 16000, 24000, or 48000)
  • channels: number of audio channels (1 or 2)
  • sink: receives encoded Opus packets
  • format: input sample format (FormatFloat32LE or FormatInt16LE)
  • application: encoder application hint

func (*Writer) Channels

func (w *Writer) Channels() int

Channels returns the number of audio channels (1 or 2).

func (*Writer) Close

func (w *Writer) Close() error

Close flushes buffered samples and closes the underlying sink when supported.

If the sink implements io.Closer, Close forwards to it after a successful flush. Close is idempotent.

func (*Writer) Flush

func (w *Writer) Flush() error

Flush encodes any buffered samples. If samples don't fill a complete frame, they are zero-padded. Call Flush before closing the stream to ensure all audio is encoded.

func (*Writer) Reset

func (w *Writer) Reset()

Reset clears buffers and encoder state for a new stream. It also clears the closed flag so the writer can be reused with a reusable sink.

func (*Writer) SampleRate

func (w *Writer) SampleRate() int

SampleRate returns the sample rate in Hz.

func (*Writer) SetBitrate

func (w *Writer) SetBitrate(bitrate int) error

SetBitrate sets the target bitrate in bits per second. Valid range is 6000 to 510000 (6 kbps to 510 kbps).

func (*Writer) SetComplexity

func (w *Writer) SetComplexity(complexity int) error

SetComplexity sets the encoder's computational complexity (0-10).

func (*Writer) SetDTX

func (w *Writer) SetDTX(enabled bool)

SetDTX enables or disables Discontinuous Transmission.

func (*Writer) SetFEC

func (w *Writer) SetFEC(enabled bool)

SetFEC enables or disables in-band Forward Error Correction.

func (*Writer) Write

func (w *Writer) Write(p []byte) (int, error)

Write implements io.Writer, encoding PCM bytes to Opus packets.

The Writer buffers input samples until a complete frame is accumulated, then encodes and sends the packet to the sink.

Directories

Path Synopsis
container
ogg
Package ogg implements Ogg Opus container reading and writing.
Package ogg implements Ogg Opus container reading and writing.
red
Package red implements RFC 2198 RTP Payload for Redundant Audio Data.
Package red implements RFC 2198 RTP Payload for Redundant Audio Data.
examples
bench-decode command
Package main benchmarks Opus decode throughput for gopus vs libopus.
Package main benchmarks Opus decode throughput for gopus vs libopus.
bench-encode command
Package main benchmarks Opus encode throughput for gopus vs libopus.
Package main benchmarks Opus encode throughput for gopus vs libopus.
decode-play command
Package main demonstrates decoding an Ogg Opus file to WAV with optional playback.
Package main demonstrates decoding an Ogg Opus file to WAV with optional playback.
encode-play command
Package main demonstrates encoding audio with gopus and playing the result.
Package main demonstrates encoding audio with gopus and playing the result.
ffmpeg-interop command
Package main demonstrates gopus interoperability with ffmpeg.
Package main demonstrates gopus interoperability with ffmpeg.
low-delay command
Package main demonstrates low-delay, CELT-only encoding.
Package main demonstrates low-delay, CELT-only encoding.
mix-arrivals command
Package main demonstrates WebRTC-style speech mixing with real open-source clips.
Package main demonstrates WebRTC-style speech mixing with real open-source clips.
ogg-file command
Package main demonstrates Ogg Opus file creation and reading.
Package main demonstrates Ogg Opus file creation and reading.
packet-loss command
Package main demonstrates the two ways gopus recovers from a lost packet on a real (lossy) network: packet loss concealment and in-band forward error correction.
Package main demonstrates the two ways gopus recovers from a lost packet on a real (lossy) network: packet loss concealment and in-band forward error correction.
repacketizer command
Package main demonstrates the Opus repacketizer and packet-inspection helpers.
Package main demonstrates the Opus repacketizer and packet-inspection helpers.
roundtrip command
Package main demonstrates gopus encode-decode roundtrip with quality metrics.
Package main demonstrates gopus encode-decode roundtrip with quality metrics.
roundtrip-min command
Package main is the smallest useful gopus program: it encodes one frame of PCM to an Opus packet and decodes it straight back, using the caller-owned buffer Encode/Decode API.
Package main is the smallest useful gopus program: it encodes one frame of PCM to an Opus packet and decodes it straight back, using the caller-owned buffer Encode/Decode API.
sample-rates command
Package main demonstrates sample-rate handling and the int16 PCM API.
Package main demonstrates sample-rate handling and the int16 PCM API.
surround command
Package main demonstrates multistream (surround) encoding and decoding.
Package main demonstrates multistream (surround) encoding and decoding.
internal
benchutil
Package benchutil locates the pinned libopus reference binaries (opus_demo, opus_compare) and writes the raw-PCM and bitstream input files the parity and benchmark tooling feeds to them.
Package benchutil locates the pinned libopus reference binaries (opus_demo, opus_compare) and writes the raw-PCM and bitstream input files the parity and benchmark tooling feeds to them.
celt
Package celt implements the CELT decoder per RFC 6716 Section 4.3.
Package celt implements the CELT decoder per RFC 6716 Section 4.3.
cpufeat
Package cpufeat detects optional CPU instruction-set extensions at process start and exposes them through the AMD64 and ARM64 variables so the codec can gate its SIMD code paths at runtime.
Package cpufeat detects optional CPU instruction-set extensions at process start and exposes them through the AMD64 and ARM64 variables so the codec can gate its SIMD code paths at runtime.
dnnblob
Package dnnblob parses and validates the libopus USE_WEIGHTS_FILE neural weights blob and exposes typed views over its records.
Package dnnblob parses and validates the libopus USE_WEIGHTS_FILE neural weights blob and exposes typed views over its records.
dnnmath
Package dnnmath provides the activation, exponent and input-quantization kernels libopus' neural-network code (DRED, OSCE) relies on.
Package dnnmath provides the activation, exponent and input-quantization kernels libopus' neural-network code (DRED, OSCE) relies on.
dred
Package dred implements libopus Deep Redundancy (DRED): the in-band extension that carries a heavily compressed RDOVAE representation of recent speech so a decoder can recover audio lost to packet loss.
Package dred implements libopus Deep Redundancy (DRED): the in-band extension that carries a heavily compressed RDOVAE representation of recent speech so a decoder can recover audio lost to packet loss.
dred/rdovae
Package rdovae implements the libopus RDOVAE (rate-distortion-optimized variational auto-encoder) used by Deep Redundancy (DRED).
Package rdovae implements the libopus RDOVAE (rate-distortion-optimized variational auto-encoder) used by Deep Redundancy (DRED).
encoder
Package encoder implements the unified Opus encoder defined by RFC 6716.
Package encoder implements the unified Opus encoder defined by RFC 6716.
fixedpoint
Package fixedpoint is the gopus FIXED_POINT CELT codec: a pure-integer port of libopus' CELT encoder and decoder for the static 48000/960 mode.
Package fixedpoint is the gopus FIXED_POINT CELT codec: a pure-integer port of libopus' CELT encoder and decoder for the static 48000/960 mode.
hybrid
Package hybrid implements the Hybrid decoder for Opus.
Package hybrid implements the Hybrid decoder for Opus.
lpcnetplc
Package lpcnetplc implements the libopus LPCNet packet-loss concealment and DRED recovery decoder.
Package lpcnetplc implements the libopus LPCNet packet-loss concealment and DRED recovery decoder.
opusmath
Package opusmath holds the gopus floating-point math kernels shared by the CELT, SILK and Opus glue layers.
Package opusmath holds the gopus floating-point math kernels shared by the CELT, SILK and Opus glue layers.
osce/bwe
Package bwe implements the libopus OSCE blind-bandwidth-extension network (BBWENet), which extends 16 kHz decoded speech up to 48 kHz.
Package bwe implements the libopus OSCE blind-bandwidth-extension network (BBWENet), which extends 16 kHz decoded speech up to 48 kHz.
osce/lace
Package lace implements the libopus OSCE LACE and NoLACE neural postfilters that enhance decoded SILK speech.
Package lace implements the libopus OSCE LACE and NoLACE neural postfilters that enhance decoded SILK speech.
plc
Package plc implements Opus-level Packet Loss Concealment (PLC): the machinery that synthesizes plausible audio for frames whose packets were lost, dropped, or arrived too late.
Package plc implements Opus-level Packet Loss Concealment (PLC): the machinery that synthesizes plausible audio for frames whose packets were lost, dropped, or arrived too late.
qualitycompare
Package qualitycompare is the single, canonical quality comparator for gopus-vs-libopus parity tests.
Package qualitycompare is the single, canonical quality comparator for gopus-vs-libopus parity tests.
rangecoding
Package rangecoding implements the Opus range coder: the entropy encoder/decoder defined in RFC 6716 Section 4.1 and ported, bit for bit, from libopus celt/entenc.c (encoder) and celt/entdec.c (decoder), with constants from celt/mfrngcod.h and celt/entcode.h.
Package rangecoding implements the Opus range coder: the entropy encoder/decoder defined in RFC 6716 Section 4.1 and ported, bit for bit, from libopus celt/entenc.c (encoder) and celt/entdec.c (decoder), with constants from celt/mfrngcod.h and celt/entcode.h.
silk
Package silk implements the SILK speech layer of Opus (RFC 6716 Section 4.2), the low-level codec used by gopus for the SILK and Hybrid Opus modes.
Package silk implements the SILK speech layer of Opus (RFC 6716 Section 4.2), the low-level codec used by gopus for the SILK and Hybrid Opus modes.
util
Package util provides small, dependency-free helpers shared across the gopus codec packages.
Package util provides small, dependency-free helpers shared across the gopus codec packages.
Package multistream implements the Opus multistream engine: encoding and decoding of packets that carry several elementary Opus streams (each a normal SILK / CELT / Hybrid stream) which are decoded independently and routed to output channels via a channel-mapping table.
Package multistream implements the Opus multistream engine: encoding and decoding of packets that carry several elementary Opus streams (each a normal SILK / CELT / Hybrid stream) which are decoded independently and routed to output channels via a channel-mapping table.
Package testvectors provides utilities for parsing and validating against official RFC 8251 Opus test vectors.
Package testvectors provides utilities for parsing and validating against official RFC 8251 Opus test vectors.
tools
benchguard command
encoderbenchcmp command
qualityreport command
safety_soak command
Package types defines small, dependency-free enumerations shared across the gopus packages.
Package types defines small, dependency-free enumerations shared across the gopus packages.

Jump to

Keyboard shortcuts

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