gopus

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: BSD-3-Clause Imports: 17 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

gopus encodes and decodes Opus audio in pure Go, without cgo or an external codec library. It supports voice and music, mono and stereo, multistream and ambisonics, Ogg files, and RTP RED recovery.

The packet APIs use caller-owned buffers for allocation-free processing after warmup. Ordinary builds use scalar Go; Go 1.27's experimental SIMD support adds CPU-specific kernels. Correctness is checked against pinned libopus 1.6.1 and the RFC 8251 test vectors; see parity and testing for the exact guarantees and tested configurations.

API reference · Quick start · Examples · Performance · Contributing

Install

This README describes master, which requires Go 1.27 or newer:

go get github.com/thesyncim/gopus@master

For the published release, use @v0.2.2 and its versioned documentation.

Quick start

Encode and decode a 20 ms stereo frame at 48 kHz. This complete program uses silence; replace pcm with your interleaved audio samples:

package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	const (
		sampleRate = 48000
		channels   = 2
		frameSize  = 960 // samples per channel
	)

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

	pcm := make([]float32, frameSize*channels) // interleaved input, normally [-1, 1]
	packet := make([]byte, cfg.MaxPacketBytes)
	out := make([]float32, cfg.MaxPacketSamples*channels)

	n, err := enc.Encode(pcm, packet) // bytes written
	if err != nil {
		log.Fatal(err)
	}
	samples, err := dec.Decode(packet[:n], out) // samples per channel
	if err != nil {
		log.Fatal(err)
	}
	decoded := out[:samples*channels]
	fmt.Printf("decoded %d samples per channel (%d total)\n", samples, len(decoded))
}

Working with audio

PCM and reusable buffers

Use one encoder and decoder per stream, and reuse their buffers. With enc, dec, and cfg from the quick start, the same round trip works with int16 PCM:

// Allocate once, outside the audio loop. FrameSize counts samples per channel.
input := make([]int16, enc.FrameSize()*channels) // 960 × 2 for 20 ms stereo
packetBuf := make([]byte, cfg.MaxPacketBytes)    // length sets the encode byte budget
output := make([]int16, cfg.MaxPacketSamples*channels)

// Stereo is interleaved: L0, R0, L1, R1, ... . Fill the rest from your audio source.
input[0], input[1] = 1200, -1200

bytesWritten, err := enc.EncodeInt16(input, packetBuf)
if err != nil {
	log.Fatal(err)
}
samples, err := dec.DecodeInt16(packetBuf[:bytesWritten], output)
if err != nil {
	log.Fatal(err)
}

// Decode returns samples per channel, so include both channels in the slice.
decoded := output[:samples*channels]
fmt.Printf("decoded %d interleaved values\n", len(decoded))
// Consume decoded before the next decode overwrites output.

Encode/Decode use float32 PCM, normally in [-1, 1]. The Int24 methods use right-justified signed 24-bit PCM in []int32; decode output is not clamped to 24 bits, so gain can produce values outside [-8,388,608, 8,388,607]. All formats use the same interleaved layout.

The default decoder limits are 5,760 samples per channel and 1,500 packet bytes. Configure larger limits before constructing the decoder when needed; for example, 120 ms at native 96 kHz needs 11,520 samples per channel.

Codec instances retain stream history and are not safe for concurrent calls. Reset starts a new stream with the same format and ordinary controls; encoder reset also disables DRED emission. Construction and initial warmup can allocate.

Packet loss

Choose one recovery path for each missing frame. Your application decides when a packet is lost and how long it can wait for the next one.

Conceal a loss immediately. Pass nil and size the output to the missing duration. Using the 48 kHz stereo decoder and out buffer from the quick start:

// Request exactly 20 ms: 960 samples per channel × 2 channels.
missingPCM := out[:960*channels]
samples, err := dec.Decode(nil, missingPCM)
if err != nil {
	log.Fatal(err)
}
concealed := missingPCM[:samples*channels]
fmt.Printf("concealed %d interleaved values\n", len(concealed))
// Consume concealed before reusing out for the next packet.

Passing the entire MaxPacketSamples*Channels buffer instead reuses the most recent output duration, when available.

Recover from the following packet. If your jitter buffer can wait one packet, use nextPacket to recover the loss first, then decode that same packet normally. Do this instead of the concealment call above:

// Allocate this alongside out, before the packet loop.
missingPCM := make([]float32, 960*channels)

// nextPacket follows the loss. Use its FEC, or PLC if it has no usable FEC.
recoveredSamples, err := dec.DecodeWithFEC(nextPacket, missingPCM, true)
if err != nil {
	log.Fatal(err)
}
recovered := missingPCM[:recoveredSamples*channels]

// The FEC call does not decode nextPacket's primary audio.
currentSamples, err := dec.Decode(nextPacket, out)
if err != nil {
	log.Fatal(err)
}
current := out[:currentSamples*channels]
fmt.Printf("play %d recovered values, then %d current values\n", len(recovered), len(current))
// Deliver recovered before current, and consume both before reusing their buffers.

In-band FEC is available in SILK/Hybrid packets when the sender includes it; enabling FEC does not guarantee redundancy in every packet. At native 96 kHz, DecodeWithFEC(..., true) uses concealment and ignores the supplied packet. Run the complete packet-loss example with go run ./examples/packet-loss.

Encoder controls

Set controls before encoding. For a voice stream, for example:

if err := enc.SetBitrate(32000); err != nil { // bits/second across all channels
	log.Fatal(err)
}
if err := enc.SetComplexity(5); err != nil { // 0–10; higher spends more CPU
	log.Fatal(err)
}
enc.SetVBR(true) // let packet sizes vary with the audio
enc.SetDTX(true) // reduce traffic during silence

enc.SetFEC(true)                              // allow redundancy in SILK/Hybrid packets
if err := enc.SetPacketLoss(10); err != nil { // estimated loss percentage, 0–100
	log.Fatal(err)
}

With DTX, Encode can return zero bytes with a nil error: there is no packet to send. Send nonempty packets, including short one- or two-byte DTX packets.

The default bitrate is 64 kbps. When comparing with libopus, set the same bitrate explicitly: libopus defaults to automatic selection. Bitrate() reports the configured target, including BitrateAuto/BitrateMax, rather than libopus's effective bitrate.

Voice activity

VAD and SpeechDetector score mono PCM frame by frame without an encoder. Each call takes exactly 10 or 20 ms of samples, advances the detector's state, and returns a score rather than a decision: choose the threshold and handle turn timing in your application. Neither is safe for concurrent use, and Reset starts a new stream. Construction can allocate; analysis calls do not.

  • VAD runs the SILK voice detector at 8, 12, or 16 kHz and returns activity in Q8 (0–255). It follows level against an adaptive noise estimate.
  • SpeechDetector runs the neural analysis inside the Opus encoder (libopus activity_probability) at 16, 24, or 48 kHz and returns a probability in [0, 1]. It scores spectral and temporal structure instead of level, so steady noise, hum, and clicks score low. Short bursts such as coughs, and other people talking, can score high.
det, err := gopus.NewSpeechDetector(16000)
if err != nil {
	log.Fatal(err)
}

frame := make([]int16, 320) // 20 ms at 16 kHz; fill from your audio source
probability, err := det.AnalyzeInt16(frame)
if err != nil {
	log.Fatal(err)
}
talking := probability >= 0.5

The speech probability comes from the encoder's analysis code and matches libopus for the same input. Its newest analysis window ends 10 ms before the newest sample, and the first ten windows (about 200 ms) after construction or Reset are warm-up. A window of exactly zero samples scores 0; the encoder repeats its previous estimate there. A 10 ms frame completes a window on every second call and repeats the previous result in between.

Examples

Start with a complete encode/decode using reusable buffers:

go run ./examples/roundtrip-min

Run these from the repository root with go run ./examples/<name>. Programs with command-line options accept -h for help.

Example Purpose
roundtrip-min Minimal caller-buffer encode/decode
packet-loss PLC and in-band FEC recovery ordering
ogg-file Ogg Opus reading, writing and seeking
sample-rates Int16 PCM at 8/12/16/24/48 kHz
low-delay Short CELT frames and algorithmic delay
repacketizer Frame merging, splitting and padding
surround Multistream 5.1 in Vorbis channel order
roundtrip Encode/decode quality across configurations
encode-play, decode-play Ogg encoding, WAV decoding and optional playback
ffmpeg-interop Interoperability with ffmpeg and ffprobe
mix-arrivals Timed speech mixing with loss and jitter
bench-encode, bench-decode File-based throughput estimates; see Performance

Most examples use the default build. Optional APIs require their matching build tag: QEXT uses -tags gopus_qext, DRED uses -tags gopus_dred, and OSCE uses -tags gopus_osce. These runnable examples demonstrate API usage; they do not imply that every optional feature and architecture has completed parity validation. Build the in-module examples with go build ./examples/....

For a local file round trip:

# Generate an Opus file, then decode it to 16-bit PCM in a WAV file.
go run ./examples/encode-play -duration 1 -out demo.opus
go run ./examples/decode-play -in demo.opus -out demo.wav

Playback is opt-in with -play; decode-play -pipe streams to ffplay. The file round trip above needs no external audio tools. ffmpeg-interop requires ffmpeg and ffprobe. mix-arrivals downloads its speech clips on first use and caches them; its -cache-dir flag selects the cache directory.

Three examples are separate modules; run their commands inside their directories:

Module Command Purpose
external-consumer-smoke go test ./... Downstream public API checks
webrtc-control go run . -addr 127.0.0.1:8080 Open http://127.0.0.1:8080 for browser audio controls
webrtc-dred-loopback go run . Desktop PLC/FEC/RED/DRED comparison; see its setup guide

Check the example packages and nested projects without opening an audio device:

make test-consumer-smoke test-examples-smoke

The loopback checks use a test-only headless build tag. Running its desktop or terminal demo requires the dependencies listed in its setup guide.

Packages

Package API
gopus Single-stream codec, streaming reader/writer, multistream facade, packet parsing, repacketizer and controls
multistream Multistream codec and projection/ambisonics
container/ogg Ogg Opus reading and writing (RFC 7845)
container/red RTP RED payload construction, parsing and recovery (RFC 2198)
types Shared mode, bandwidth and signal enums

The standard codec supports 8, 12, 16, 24 and 48 kHz PCM; SILK, CELT and Hybrid modes; CBR, VBR and constrained VBR; and frame durations from 2.5 to 120 ms, subject to mode constraints. Native 96 kHz and neural recovery use optional build tags.

Build options

Ordinary builds use scalar Go kernels. GOEXPERIMENT=simd compiles simd/archsimd kernels where implemented; runtime CPU checks select supported kernels and the rest use scalar code. -tags nosimd or -tags purego forces the scalar path, including the matching scalar C reference in oracle tests. Enable SIMD when building your application; for this repository:

GOEXPERIMENT=simd go build ./...

Optional features mirror libopus build flags and are excluded from the default build's import graph:

Go build tag libopus flag Feature
gopus_dred --enable-dred DRED controls and standalone recovery
gopus_osce --enable-osce (+ ENABLE_DEEP_PLC) OSCE BWE/LACE/NoLACE and deep PLC
gopus_qext --enable-qext QEXT and native 96 kHz
gopus_custom_modes --enable-custom-modes Opus Custom modes
gopus_fixed_point --enable-fixed-point Integer CELT/SILK pipeline

Default builds expose no optional extensions; SetDNNBlob(...) is a no-op returning ErrOptionalExtensionUnavailable. DNN model loading follows libopus's USE_WEIGHTS_FILE configuration. A build tag enables an implementation; it does not establish parity for every feature, architecture or packet sequence. Libopus rejects fixed-point combined with DRED/OSCE; those combinations have no matching supported C reference lane.

Extension Availability Probe
DNN blob loading Available under gopus_dred / gopus_osce OptionalExtensionDNNBlob
QEXT Available under gopus_qext OptionalExtensionQEXT
DRED Available under gopus_dred (control + standalone) OptionalExtensionDRED
OSCE BWE Extra controls under gopus_osce; support probe returns false OptionalExtensionOSCEBWE

SupportsOptionalExtension(OptionalExtensionOSCEBWE) reports false: these controls are exposed for parity work. DRED controls and standalone recovery APIs also compile with gopus_osce, while the supported DRED probe follows gopus_dred. Consult the validation reference for tested feature combinations. Run tagged tests with the matching reference:

go test -tags gopus_qext ./...
go test -tags gopus_dred ./...
go test -tags gopus_osce ./...

Performance

The table pairs C scalar with Go scalar and C SIMD with Go SIMD, using identical inputs and controls. Values are median ns/sample per channel (lower is faster) on AMD EPYC 7763, Go 1.27.1 and GCC 13.3.0, with GOAMD64=v3, PGO and candidate 4b660d668. Each case has three runs of at least 250 ms. Go reports zero allocations; C allocations are not measured.

Workload C scalar Go scalar C SIMD Go SIMD
Encode CELT, fullband, 20 ms stereo, 128 kbps 176.89 197.94 129.50 126.28
Encode CELT, fullband, 5 ms mono, 64 kbps 75.99 93.79 69.83 80.00
Encode SILK, wideband, 20 ms mono, 32 kbps 705.61 685.98 462.01 329.21
Encode Hybrid, fullband, 20 ms mono, 64 kbps 363.00 420.99 253.40 225.80
Encode Hybrid, fullband, 20 ms stereo, 96 kbps 200.37 227.97 145.10 139.57
Decode RFC vectors, float32 38.22 42.29 35.90 33.14
Decode RFC vectors, int16 42.23 46.80 38.83 37.64

Decoder rows aggregate 20,075 identical packets. Go SIMD takes 2.5–28.7% less time than matched C SIMD in four encoder cases and 14.6% more in the 5 ms CELT case. Float32 and int16 decode take 7.7% and 3.1% less time, respectively. Results apply to these workloads and the stated revision; they are not a speed guarantee for every stream or CPU.

The validation reference contains all 53 replacement routines, assembly/Go/nosimd comparisons, raw-run links, and measurements of later parity fixes. Its paired incremental measurement records public encoder time changes within 0.5%; measurements from different hosts are kept separate.

Use GOAMD64=v3 on a supporting CPU and select the same C compiler target:

GOAMD64=v3 GOEXPERIMENT=simd GOPUS_LIBOPUS_AMD64_TARGET=v3 go run ./tools/encoderbenchcmp
GOAMD64=v3 GOEXPERIMENT=simd GOPUS_LIBOPUS_AMD64_TARGET=v3 go run ./tools/testvectorbenchcmp -cases aggregate

These tools measure codec work with matched C and Go workloads. The file-based bench-encode and bench-decode examples include opus_demo process startup and file I/O in C timings, so they provide rough estimates.

For scalar comparisons, retain both target settings and use GOEXPERIMENT=nosimd. On ARM64, omit both AMD64 target settings. The optional v1/v2/v3 audit compares compiler targets on one native host; routine PR CI does not run that timing matrix.

Parity & testing

The parity contract requires exact API/protocol behavior and integer arithmetic, matching entropy ranges for identical packets and history, and preservation of established exact regressions. C and Go use the same features, controls, scalar widths and effective CPU instructions. SIMD Go versus scalar C is not a parity comparison.

Floating-point allowances require a reproducible rounding cause, a narrow kernel-specific bound, independent quality/recovery evidence and a reviewed executable regression. Unexplained mismatches remain failures. Exact oracle checks and real-audio opus_compare quality checks complement each other; neither proves every possible input and state sequence.

The coverage audit records the build configurations, inputs, and state sequences covered by exact comparisons, and identifies evidence gaps. The documented C reference boundary is an unsafe custom-QEXT history read at 96 kHz / 2,048 samples; Go uses bounded concealment and compares defined C behavior.

Use make test-fast for iteration, make test for the live C-oracle suite, and make test-build-contract for build boundaries. See CONTRIBUTING.md for the verification and release checklist.

Independent composite encode cases run concurrently, capped at four active cases and GOMAXPROCS, with fresh codec state and every selected frame. Use -parallel=1 to serialize their subtests. C oracle helper binaries reuse a digest of compiler identity, effective flags, preprocessed sources, and linked archive contents; each input still executes the live C helper. Builds with custom linker outputs bypass reuse.

Malformed multistream and projection sweeps send up to 128 independent requests per C helper process. Each request creates a fresh Go decoder and a fresh C decoder, including rejected packets; accepted results compare sample counts, PCM bits, and final ranges. PCM files use chunked little-endian writes, and the quality comparator serializes each request into one sized buffer. Independent end-to-end conformance cells run within Go's test parallelism bound. Encoder differentials reuse deterministic input templates and give every case a private PCM copy; shared oracle payloads append PCM in one bounded slice operation.

GOPUS_TEST_SHARD=INDEX/TOTAL partitions the runnable suite by top-level test, fuzz seed target, and example names. Each shard executes with -count=1 and emits its complete inventory with JSON results. tools/aggregate_go_test_shards.py requires every assigned test to complete exactly once before merging the suite. CI runs independent correctness lanes and four full-suite shards concurrently; paired benchmark samples for both revisions share one runner.

Trust And Verification

Released version: v0.2.2. The API is pre-v1.

v0.1.0 is retracted: it has no published GitHub Release. Latest release evidence: attached to the v0.2.2 release.

Required branch checks:

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

These checks build the pinned C reference with matching features and instructions and run mandatory parity suites on Linux, macOS and Windows. The release workflow requires green checks on the tagged commit; make release-evidence must also produce a PASS summary with safety, performance and build provenance.

Security reports: SECURITY.md. External API verification: examples/external-consumer-smoke/smoke_test.go. Contributions follow CONTRIBUTING.md and the code of conduct. See LICENSE for licensing.

Documentation

Overview

Package gopus implements Opus audio encoding and decoding in pure Go. It supports the SILK, CELT, and Hybrid modes defined by RFC 6716 and RFC 8251 without requiring cgo or an external codec library.

Streams and samples

Encoder and Decoder process mono or stereo streams. Use MultistreamEncoder and MultistreamDecoder for multichannel layouts. Codec instances retain stream history and are not safe for concurrent use. Each independent stream needs its own instance. Reset clears stream history; each Reset method documents which controls it preserves.

PCM is interleaved: each successive group of samples contains one sample per channel. Float32 methods use normalized full scale; integer input methods use signed 16-bit samples or right-justified 24-bit samples in int32 values. Decoder.DecodeInt24 writes int32 values at 24-bit PCM scale without clipping to the signed 24-bit range. Frame sizes and decoded sample counts are measured per channel at the configured sample rate. Encoders return packet byte counts.

Buffers and packet loss

Encode and Decode methods write into caller-provided buffers. Reusing codec instances and adequately sized buffers avoids steady-state allocations in the covered hot paths; constructors and initial warmup can allocate. A decode buffer sized to DecoderConfig.MaxPacketSamples times Channels holds the largest packet allowed by that configuration. Only the returned sample count times Channels elements contain decoded output.

An empty packet passed to Decoder.Decode requests packet-loss concealment. The output buffer length selects the requested duration, except that a full configured-size buffer uses the last decoded packet's duration when available. To recover a missing packet from the next packet's in-band FEC, call Decoder.DecodeWithFEC with fec set to true, then call Decode with the same packet to decode its primary audio. The decoder conceals the loss if FEC is unavailable. Native 96 kHz FEC requests always use concealment and ignore the supplied packet.

Reader and Writer adapt packet sources and sinks to little-endian PCM byte streams. They require packet-aware transport interfaces; they do not frame a byte stream of concatenated Opus packets. ParsePacket inspects packet framing, and Repacketizer combines or separates compatible frames without re-encoding.

Build configuration

Go 1.27 or later is required. Ordinary builds use scalar Go kernels. GOEXPERIMENT=simd enables Go SIMD kernels where implemented, with runtime CPU checks and scalar fallbacks. The nosimd and purego build tags force scalar kernels even when the experiment is enabled.

Optional extensions require their matching build tags: gopus_qext for QEXT and native 96 kHz, gopus_dred for DRED, gopus_osce for OSCE and deep PLC, and gopus_custom_modes for Opus Custom. The gopus_fixed_point tag selects the integer codec pipeline. SupportsOptionalExtension reports the supported API surface of the current build; compiled extra controls may still report false. DRED controls and standalone recovery APIs also compile with gopus_osce, while the supported DRED probe requires gopus_dred.

Example (RoundTrip)
package main

import (
	"fmt"
	"log"
	"math"

	"github.com/thesyncim/gopus"
)

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

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

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

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

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

Index

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 asks the encoder to choose a bitrate from the stream format and
	// application (libopus OPUS_AUTO).
	BitrateAuto = encoder.BitrateAuto
	// BitrateMax tells the encoder to use as many bits as the output buffer
	// allows for each frame (libopus OPUS_BITRATE_MAX).
	BitrateMax = encoder.BitrateMax
)
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 accepted by SetInBandFEC.

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.
	// Rates are 8000, 12000, 16000, 24000, or 48000 Hz; builds with gopus_qext
	// also accept 96000 Hz.
	ErrInvalidSampleRate = errors.New("gopus: invalid sample rate (must be 8000, 12000, 16000, 24000, or 48000)")

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

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

	// ErrInvalidMaxPacketSamples indicates a negative max packet sample cap or
	// one whose decoder scratch length cannot fit in int-sized storage.
	ErrInvalidMaxPacketSamples = errors.New("gopus: invalid max packet samples (must be nonnegative and fit decoder scratch)")

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

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

	// ErrBufferTooSmall indicates an encode packet budget or decode PCM buffer is
	// too small for the operation. Decode buffers must hold frameSize * channels
	// samples; encode buffers must hold the resulting packet.
	ErrBufferTooSmall = errors.New("gopus: output buffer too small")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	// ErrInternalError indicates malformed packet extensions prevent a packet
	// operation from collecting extension data. Repacketizer.OutRange and
	// PacketPad return it for this extension-processing failure.
	ErrInternalError = errors.New("gopus: internal error")

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

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

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

	// 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 that the requested functionality is unsupported.
	ErrUnimplemented = errors.New("gopus: feature not implemented")
)

Errors returned by the public encoding, decoding, and streaming APIs.

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 TOC configuration index for mode, bandwidth, and frameSize. frameSize is measured in samples at 48 kHz. It returns -1 when the combination does not appear in the Opus configuration table.

func ErrorString

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 packs a configuration, channel flag, and frame-count code into a TOC byte. config contributes its low five bits, and frameCode contributes its low two bits:

0: 1 frame
1: 2 equal-sized frames
2: 2 different-sized frames
3: frame count is encoded in the packet

The function masks these fields; it does not validate their values.

func MultistreamPacketPad

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

MultistreamPacketPad pads the final stream packet in a multistream packet in place. length is the current packet length in bytes, newLen is the target length in bytes, and numStreams is the number of constituent Opus streams. The input slice must contain length bytes and have capacity for newLen bytes. If its original length is shorter, reslice the caller's slice to newLen after success.

func MultistreamPacketUnpad

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

MultistreamPacketUnpad removes padding from every stream in a multistream packet in place and returns the new packet length in bytes. length is the number of input bytes and numStreams is the number of constituent Opus streams; all but the final stream packet must use self-delimited framing. data must contain length bytes. The function does not extend data, so len(data) must also be large enough for the rebuilt output.

func PCMSoftClip

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

PCMSoftClip soft-clips interleaved float32 PCM in place. Samples should be normalized to roughly [-1, 1]. channels is the channel count, and softclipMem must hold at least one state value per channel. Pass zeroed state on the first call and reuse it for successive blocks from the same stream. The function processes complete interleaved frames; an incomplete trailing frame is ignored. Invalid channel counts or a short state slice leave pcm unchanged.

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

func PacketHasLBRR

func PacketHasLBRR(data []byte) bool

PacketHasLBRR reports whether the first SILK or Hybrid frame in data carries the LBRR flag for in-band FEC. It returns false for CELT and when the first frame cannot be extracted. This is a payload probe, not full packet framing validation; use ParsePacket to validate the complete packet.

func PacketPad

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

PacketPad pads a packet in place to exactly newLen bytes. length is the current packet length in bytes. data must contain length bytes and have capacity for newLen bytes. If len(data) is shorter, reslice the caller's slice to newLen after success. It returns ErrInternalError when packet extension data cannot be collected.

func PacketUnpad

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

PacketUnpad removes packet padding in place and returns the new packet length in bytes. length is the current packet length; data must contain that many bytes. Use data[:n] with the returned length n to access the unpadded packet.

func SupportsOptionalExtension

func SupportsOptionalExtension(ext OptionalExtension) bool

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

Example
package main

import (
	"fmt"

	"github.com/thesyncim/gopus"
)

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

func ValidConfig

func ValidConfig(config uint8) bool

ValidConfig returns true if the configuration index is valid.

func VersionString

func VersionString() string

VersionString returns gopus's compiled-in identification string.

Types

type Application

type Application int

Application selects the encoder's operating profile. The standard profiles tune encoding for speech, general audio, or low delay; the restricted profiles force SILK-only or CELT-only encoding and can be selected only at construction.

const (
	// ApplicationVoIP tunes the encoder for interactive speech.
	ApplicationVoIP Application = iota

	// ApplicationAudio tunes the encoder for general audio.
	ApplicationAudio

	// ApplicationLowDelay minimizes algorithmic delay.
	ApplicationLowDelay

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

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

type Bandwidth

type Bandwidth = types.Bandwidth

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

type BitrateMode

type BitrateMode = encoder.BitrateMode

BitrateMode selects variable, constrained-variable, or constant bitrate.

type Decoder

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

Decoder decodes Opus packets into PCM samples. It retains stream state and is not safe for concurrent use; use one Decoder per stream. Construct it with NewDecoder; the zero value is not ready for use.

func NewDecoder

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

NewDecoder returns a Decoder configured by cfg. It returns an error if the sample rate, channel count, or packet limits are invalid.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

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

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

func (*Decoder) Bandwidth

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 data into interleaved float32 PCM in pcm. The buffer length is measured in samples across all channels; the returned sample count is per channel, and the first n*Channels elements contain the output.

An empty data slice performs packet-loss concealment. Its requested duration comes from len(pcm)/Channels and must be a positive multiple of 2.5 ms. If pcm has exactly DecoderConfig.MaxPacketSamples*Channels elements and a packet has already been decoded or concealed, Decode uses the most recent output duration as the concealment request. Before the first decode, a valid full-buffer request returns zeroed PCM.

Deliberately sized PLC requests larger than MaxPacketSamples are honored; MaxPacketSamples and MaxPacketBytes limit coded packets. Decode returns an error for malformed packets, packet-limit violations, invalid PLC durations, or a short output buffer.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

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

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

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

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

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

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

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

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

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

func (*Decoder) DecodeInt16

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

DecodeInt16 decodes data into interleaved signed 16-bit PCM in pcm. The returned sample count is per channel; pcm must hold n*Channels elements, and the first n*Channels elements contain the output. An empty data slice performs packet-loss concealment, with the requested duration derived from pcm's per-channel length.

func (*Decoder) DecodeInt24

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

DecodeInt24 decodes data into interleaved 24-bit-scale PCM stored in pcm. Each int32 holds a right-justified signed value; the nominal 24-bit range is [-8388608, 8388607]. The libopus RES2INT24 conversion does not soft-clip or clamp to that range: a +1.0 sample maps to 8388608, and output gain can also produce values outside the nominal 24-bit interval. The returned sample count is per channel; pcm must hold n*Channels elements. An empty data slice performs packet-loss concealment.

func (*Decoder) DecodeInt24Slice

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

DecodeInt24Slice decodes data into a newly allocated, caller-owned interleaved PCM slice. Each int32 holds a right-justified signed 24-bit-scale value using the same unsaturated conversion as DecodeInt24. The slice contains n*Channels elements for n samples per channel. For empty data, it requests the most recent output duration, or MaxPacketSamples when LastPacketDuration is zero.

func (*Decoder) DecodeWithFEC

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

DecodeWithFEC decodes data into interleaved float32 PCM and returns samples per channel. When fec is false, it behaves like Decode. When fec is true, data is the packet received after a loss and len(pcm)/Channels requests the missing duration; the request must be a positive multiple of 2.5 ms. The decoder recovers in-band FEC when usable LBRR is present and otherwise performs packet-loss concealment. Empty data also performs concealment. This call does not decode the supplied packet's primary frame: call Decode with the same packet afterward.

Example
package main

import (
	"fmt"
	"log"
	"math"

	"github.com/thesyncim/gopus"
)

func main() {
	const frameSize = 960 // 20 ms at 48 kHz, per channel
	enc, err := gopus.NewEncoder(gopus.EncoderConfig{
		SampleRate:  48000,
		Channels:    1,
		Application: gopus.ApplicationVoIP,
	})
	if err != nil {
		log.Fatal(err)
	}
	enc.SetFEC(true)
	if err := enc.SetPacketLoss(20); err != nil {
		log.Fatal(err)
	}
	cfg := gopus.DefaultDecoderConfig(48000, 1)
	dec, err := gopus.NewDecoder(cfg)
	if err != nil {
		log.Fatal(err)
	}
	input := make([]float32, frameSize)
	packet := make([]byte, cfg.MaxPacketBytes)
	output := make([]float32, cfg.MaxPacketSamples*cfg.Channels)

	// Deliver the first packet, lose the second, and receive the third.
	for frame := range 3 {
		for i := range input {
			input[i] = float32(0.5 * math.Sin(2*math.Pi*440*float64(frame*frameSize+i)/48000))
		}
		n, err := enc.Encode(input, packet)
		if err != nil {
			log.Fatal(err)
		}
		if frame == 0 {
			if _, err := dec.Decode(packet[:n], output); err != nil {
				log.Fatal(err)
			}
		}
		if frame != 2 {
			continue
		}

		// Request the missing duration first. The decoder uses PLC if the
		// following packet does not carry FEC for this loss.
		recovered, err := dec.DecodeWithFEC(packet[:n], output[:frameSize], true)
		if err != nil {
			log.Fatal(err)
		}
		// Consume the recovered output before reusing its storage below.
		fmt.Printf("recovered %d samples\n", recovered)
		decoded, err := dec.Decode(packet[:n], output)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("decoded %d samples\n", decoded)
	}
}
Output:
recovered 960 samples
decoded 960 samples

func (*Decoder) FinalRange

func (d *Decoder) FinalRange() uint32

FinalRange reports the decoder's captured range state, matching libopus OPUS_GET_FINAL_RANGE. It is useful for bitstream verification.

The main decode range is XORed with any redundancy-frame range. The result is zero when the decoded frame is empty or has at most one payload byte, including an empty or one-byte final frame in a multi-frame packet.

func (*Decoder) 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 supported packet-extension payloads are ignored during decoding.

func (*Decoder) InDTX

func (d *Decoder) InDTX() bool

InDTX reports the libopus DTX indication from the recorded decode-data length. It is true for a recorded length of one or two bytes. Normal decoding records the packet length; FEC recovery records the recovered first-frame payload length. It is false before decoding and after packet-loss concealment.

func (*Decoder) LastPacketDuration

func (d *Decoder) LastPacketDuration() int

LastPacketDuration returns the most recent decoded or concealed duration in samples per channel at the decoder API rate. It is zero before the first decode and after Reset.

func (*Decoder) PhaseInversionDisabled

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 decoded pitch period in 48 kHz-equivalent samples, matching libopus OPUS_GET_PITCH. CELT reports its postfilter period; SILK reports a lag only for voiced audio. It returns zero when neither decoder has a usable pitch.

func (*Decoder) Reset

func (d *Decoder) Reset()

Reset clears codec, packet, PLC, FEC, soft-clip, and optional recovery history and resets last-packet metadata. It preserves the decoder configuration and controls, including the sample rate, channels, packet limits, output gain, complexity, phase-inversion setting, extension policy, and loaded model blobs. Call it when starting a new audio stream on the same Decoder.

func (*Decoder) SampleRate

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 returns ErrOptionalExtensionUnavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable model loading.

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 controls whether packet-extension payloads supported by enabled optional features are used during decoding. Enabling it also clears any cached DRED payload. This mirrors libopus OPUS_SET_IGNORE_EXTENSIONS semantics.

func (*Decoder) SetPhaseInversionDisabled

func (d *Decoder) SetPhaseInversionDisabled(disabled bool)

SetPhaseInversionDisabled toggles CELT stereo phase inversion during decoding.

type DecoderConfig

type DecoderConfig struct {
	// SampleRate must be 8000, 12000, 16000, 24000, or 48000 Hz.
	// Builds with gopus_qext also accept 96000 Hz.
	SampleRate int
	// Channels must be 1 (mono) or 2 (stereo).
	Channels int
	// MaxPacketSamples caps the maximum decoded samples per channel per packet.
	// Zero selects 5,760 samples, or 120 ms at 48 kHz. The limit must fit
	// the decoder work buffers; [NewDecoder] rejects overflowing sizes.
	MaxPacketSamples int
	// MaxPacketBytes caps the maximum Opus packet size in bytes.
	// Zero selects 1,500 bytes.
	MaxPacketBytes int
}

DecoderConfig sets the sample rate, channel count, and packet limits for a Decoder.

func DefaultDecoderConfig

func DefaultDecoderConfig(sampleRate, channels int) DecoderConfig

DefaultDecoderConfig returns a DecoderConfig with default packet limits for the given stream format. It allows up to 5,760 decoded samples per channel and 1,500 packet bytes; set MaxPacketSamples or MaxPacketBytes to raise a limit.

type Encoder

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

Encoder encodes one interleaved PCM stream into Opus packets. Construct it with NewEncoder; the zero value is not ready for use. Encoder retains codec state across calls and is not safe for concurrent use, so use one Encoder per stream. Encode, EncodeInt16, and EncodeInt24 write packets into caller-provided buffers; the Slice methods return owned packet slices.

func NewEncoder

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

NewEncoder returns an initialized Encoder for cfg. Its configured frame size starts at 20 ms and its target bitrate starts at 64,000 bits per second. A zero-valued Application selects ApplicationVoIP. It returns ErrInvalidSampleRate, ErrInvalidChannels, or ErrInvalidApplication when cfg contains an unsupported value.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

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

	if err := enc.SetBitrate(64000); err != nil { // bits per second
		log.Fatal(err)
	}
	if err := enc.SetComplexity(10); err != nil {
		log.Fatal(err)
	}

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

func (*Encoder) Application

func (e *Encoder) Application() Application

Application returns the configured encoder application profile.

func (*Encoder) Bandwidth

func (e *Encoder) Bandwidth() Bandwidth

Bandwidth returns the bandwidth currently selected by the encoder. It can differ from the explicit request made by SetBandwidth until a frame is encoded.

func (*Encoder) Bitrate

func (e *Encoder) Bitrate() int

Bitrate returns the configured target bitrate, including BitrateAuto and BitrateMax when either sentinel mode is selected.

func (*Encoder) BitrateMode

func (e *Encoder) BitrateMode() BitrateMode

BitrateMode returns the active encoder bitrate control mode.

func (*Encoder) Channels

func (e *Encoder) Channels() int

Channels returns the configured input channel count: 1 for mono or 2 for stereo. SetForceChannels can request fewer coded output channels.

func (*Encoder) Complexity

func (e *Encoder) Complexity() int

Complexity returns the current complexity setting.

func (*Encoder) DTXEnabled

func (e *Encoder) DTXEnabled() bool

DTXEnabled reports whether the DTX setting is enabled; InDTX reports whether the encoder is currently in its DTX state.

func (*Encoder) Encode

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

Encode encodes one interleaved float32 PCM frame. pcm must contain exactly FrameSize()*Channels() samples. A fixed ExpertFrameDuration can select a shorter prefix, but pcm must still contain the configured frame. len(data) is both the packet byte budget and destination; Encode copies the packet there and returns the number of bytes written. It returns ErrInvalidFrameSize for invalid frame geometry and ErrBufferTooSmall when the output budget cannot hold the packet. During DTX, silence can produce a one-byte TOC-only packet.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

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

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

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

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

func (*Encoder) EncodeFloat32

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

EncodeFloat32 encodes one interleaved float32 PCM frame and returns a newly allocated packet slice that remains valid across later Encode calls. pcm must contain exactly FrameSize()*Channels() samples.

func (*Encoder) EncodeInt16

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

EncodeInt16 encodes one interleaved signed 16-bit PCM frame. pcm must contain exactly FrameSize()*Channels() samples. Each input sample is scaled by 1/32768. len(data) is both the packet byte budget and destination. It returns the number of bytes written, ErrInvalidFrameSize for an incorrect input length or selected frame, or ErrBufferTooSmall when the packet cannot fit.

func (*Encoder) EncodeInt16Slice

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

EncodeInt16Slice encodes one interleaved signed 16-bit PCM frame and returns a newly allocated packet slice that remains valid across later Encode calls. pcm must contain exactly FrameSize()*Channels() samples; input is scaled by 1/32768.

func (*Encoder) EncodeInt24

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

EncodeInt24 encodes one interleaved signed 24-bit PCM frame. Each int32 in pcm must be right-justified in [-8388608, 8388607], and pcm must contain exactly FrameSize()*Channels() samples. len(data) is both the packet byte budget and destination. It returns the number of bytes written, ErrInvalidFrameSize for invalid input geometry, or ErrBufferTooSmall when the packet cannot fit.

func (*Encoder) EncodeInt24Slice

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

EncodeInt24Slice encodes one interleaved signed 24-bit PCM frame and returns a newly allocated packet slice that remains valid across later Encode calls. Each int32 sample must be right-justified in [-8388608, 8388607], and pcm must contain exactly FrameSize()*Channels() samples.

func (*Encoder) ExpertFrameDuration

func (e *Encoder) ExpertFrameDuration() ExpertFrameDuration

ExpertFrameDuration returns the current expert frame duration policy.

func (*Encoder) FECEnabled

func (e *Encoder) FECEnabled() bool

FECEnabled reports whether an in-band FEC policy is enabled. It does not indicate whether a particular packet contains redundancy.

func (*Encoder) FinalRange

func (e *Encoder) FinalRange() uint32

FinalRange returns the range coder state from the most recent encode, matching libopus OPUS_GET_FINAL_RANGE. Reset sets it to zero.

func (*Encoder) ForceChannels

func (e *Encoder) ForceChannels() int

ForceChannels returns the configured output-channel request: -1 follows the input channel count, while 1 or 2 forces that coded channel count.

func (*Encoder) FrameSize

func (e *Encoder) FrameSize() int

FrameSize returns the configured input frame size in samples per channel at the API rate. A fixed ExpertFrameDuration can make an Encode call code a shorter prefix. At 96 kHz, FrameSize is twice the 48 kHz-equivalent size.

func (*Encoder) InBandFEC

func (e *Encoder) InBandFEC() int

InBandFEC returns the configured in-band FEC policy.

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 delay in samples per channel at the API sample rate, matching libopus OPUS_GET_LOOKAHEAD. The base delay is 2.5 ms; VoIP, Audio, and RestrictedSilk add 4 ms of compensation. LowDelay and RestrictedCelt omit that compensation.

func (*Encoder) MaxBandwidth

func (e *Encoder) MaxBandwidth() Bandwidth

MaxBandwidth returns the current maximum bandwidth limit.

func (*Encoder) Mode

func (e *Encoder) Mode() EncoderMode

Mode returns the configured coding mode. EncoderModeAuto means the encoder selects a mode for each frame.

func (*Encoder) PacketLoss

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 codec and analysis history, resets the final range, and restarts first-frame processing for a new stream. It retains the sample rate, channel count, configured frame size, application, and ordinary controls. The selected bandwidth is reinitialized; an explicit bandwidth request remains configured. In builds with DRED controls, Reset sets DREDDuration to zero, disabling DRED emission.

func (*Encoder) SampleRate

func (e *Encoder) SampleRate() int

SampleRate returns the configured input sample rate in Hz.

func (*Encoder) SetApplication

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

SetApplication changes the encoder application profile. Valid values are ApplicationVoIP, ApplicationAudio, and ApplicationLowDelay; restricted profiles can only be selected with NewEncoder. A different profile can be selected only before the encoder commits its first frame. Reapplying the current standard profile remains valid after encoding starts. SetApplication returns ErrInvalidApplication for an unsupported profile or a late change.

func (*Encoder) SetBandwidth

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

SetBandwidth requests a target audio bandwidth. The selected bandwidth can differ until a frame is encoded. It returns ErrInvalidBandwidth for an unsupported value.

func (*Encoder) SetBandwidthAuto

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 values are clamped to the range supported by libopus for this stream. BitrateAuto and BitrateMax select the corresponding libopus sentinel modes. It returns ErrInvalidBitrate for other non-positive values.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

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

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

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

func (*Encoder) SetBitrateMode

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

SetBitrateMode selects variable (VBR), constrained-variable (CVBR), or constant (CBR) packet sizing. It returns ErrInvalidBitrateMode for an unsupported mode.

func (*Encoder) SetComplexity

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

SetComplexity sets encoder analysis and coding effort from 0 through 10. Higher values spend more CPU on analysis and search, but do not guarantee a better result for every input. It returns ErrInvalidComplexity outside this range.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

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

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

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

func (*Encoder) SetDNNBlob

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

SetDNNBlob returns ErrOptionalExtensionUnavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable model loading.

func (*Encoder) SetDTX

func (e *Encoder) SetDTX(enabled bool)

SetDTX enables or disables discontinuous transmission during silence. During DTX, Encode can return no packet or a short one- or two-byte packet. DTXEnabled reports the configured setting; InDTX reports encoder activity.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

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

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

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

func (*Encoder) SetExpertFrameDuration

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

SetExpertFrameDuration selects the frame duration used by Encode. The ExpertFrameDurationArg setting uses FrameSize(); a fixed duration selects that duration from the configured input frame. Encode still requires the full configured frame and uses the selected prefix. A duration longer than the configured frame fails with ErrInvalidFrameSize. Unsupported values return ErrInvalidArgument.

func (*Encoder) SetFEC

func (e *Encoder) SetFEC(enabled bool)

SetFEC enables or disables in-band Forward Error Correction. When the encoder produces redundancy, it carries SILK data for a preceding frame in a later SILK or Hybrid packet. SetPacketLoss supplies the expected loss percentage used by the encoder.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

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

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

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

func (*Encoder) SetForceChannels

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

SetForceChannels selects the coded channel count: -1 follows the configured input count, 1 forces mono, and 2 forces stereo. The requested count cannot exceed the configured input count; forcing mono from stereo downmixes the input. It returns ErrInvalidForceChannels for an unsupported or unavailable count.

func (*Encoder) SetFrameSize

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

SetFrameSize sets the input frame size in samples per channel at the API rate. At 96 kHz the wrapper stores a 48 kHz-equivalent count while the core receives the native-rate size. It returns ErrInvalidFrameSize for a duration that Opus does not support or that violates the restricted-SILK minimum.

func (*Encoder) SetInBandFEC

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

SetInBandFEC selects the in-band FEC policy: InBandFECDisabled, InBandFECEnabled, or InBandFECMusicSafe. The last policy lets the encoder omit redundancy for music-classified frames. It returns ErrInvalidFECConfig for any other value.

func (*Encoder) SetLSBDepth

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

SetLSBDepth sets the nominal input precision in bits, from 8 through 24. The value informs digital-silence detection and CELT noise-floor decisions; it does not rescale PCM samples. The default is 24. It returns ErrInvalidLSBDepth outside this range.

func (*Encoder) SetMaxBandwidth

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

SetMaxBandwidth caps the bandwidth selected for encoded audio without changing the input sample rate. It returns ErrInvalidBandwidth for an unsupported bandwidth.

func (*Encoder) SetMode

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

SetMode selects automatic mode choice or forces SILK, Hybrid, or CELT coding where the application and frame duration permit it. EncoderModeAuto restores automatic selection. It returns ErrInvalidArgument for an unsupported mode.

func (*Encoder) SetPacketLoss

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

SetPacketLoss sets the expected packet loss percentage from 0 through 100. The estimate informs redundancy decisions when in-band FEC is enabled. It returns ErrInvalidPacketLoss outside this range.

func (*Encoder) SetPhaseInversionDisabled

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. This reduces dependence on preceding frames and can improve resilience to packet loss at the cost of compression efficiency. The default is false.

func (*Encoder) SetSignal

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 latest available Opus-level activity estimate in Q8 (0-255), not a percentage or the standalone SILK VAD result. It reads the most recent encoder decision without analyzing new PCM. It returns 0 before the first decision, after Reset, or when no Opus activity decision is available.

func (*Encoder) 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 8000, 12000, 16000, 24000, or 48000 Hz.
	// Builds with gopus_qext also accept 96000 Hz.
	SampleRate int
	// Channels must be 1 (mono) or 2 (stereo).
	Channels int
	// Application selects the operating profile. Its zero value, ApplicationVoIP,
	// is used when the field is omitted. Restricted profiles force one coding mode
	// and can be selected only when NewEncoder creates the encoder.
	Application Application
}

EncoderConfig describes the input format and application profile for an Encoder.

type EncoderMode

type EncoderMode = encoder.Mode

EncoderMode selects automatic coding-mode selection or forces a coding mode.

type ExpertFrameDuration

type ExpertFrameDuration int

ExpertFrameDuration mirrors libopus OPUS_SET/GET_EXPERT_FRAME_DURATION values.

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

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

type 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 interleaved PCM. It retains stream state and is not safe for concurrent use; use one decoder per stream.

func NewMultistreamDecoder

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

NewMultistreamDecoder returns a decoder for an explicit channel mapping. sampleRate is in hertz and must be 8, 12, 16, 24, or 48 kHz; 96 kHz is available in builds tagged gopus_qext. channels is the number of output channels (1–255), streams is the number of elementary streams (1–255), and coupledStreams is the number of initial stereo streams (0–streams). The sum streams+coupledStreams must not exceed 255.

mapping must contain one entry per output channel. Values 0 through 2*coupledStreams-1 select left or right channels of coupled streams (even is left, odd is right); subsequent values select mono streams. Repeated values duplicate a decoded channel, and 255 produces silence. The constructor copies mapping.

The constructor returns an error for an unsupported rate, invalid count, or invalid mapping.

func NewMultistreamDecoderDefault

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

NewMultistreamDecoderDefault returns a decoder with the Vorbis mapping for 1–8 output channels. Use NewMultistreamDecoder for other layouts. It returns an error for an unsupported sample rate or channel count.

func (*MultistreamDecoder) Bandwidth

func (d *MultistreamDecoder) Bandwidth() Bandwidth

Bandwidth returns the bandwidth of the first elementary stream decoder.

func (*MultistreamDecoder) Channels

func (d *MultistreamDecoder) Channels() int

Channels returns the number of audio channels.

func (*MultistreamDecoder) Complexity

func (d *MultistreamDecoder) Complexity() int

Complexity returns the decoder complexity from the first elementary stream.

func (*MultistreamDecoder) CoupledStreams

func (d *MultistreamDecoder) CoupledStreams() int

CoupledStreams returns the number of coupled (stereo) streams.

func (*MultistreamDecoder) Decode

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

Decode decodes a packet into interleaved float32 PCM, or performs packet loss concealment (PLC) when data is nil or empty. It returns the number of samples per channel written. For a packet, pcm must have room for that packet's duration; a larger buffer is allowed, and its unused tail is left unchanged.

For PLC, the per-channel request size is inferred from len(pcm)/Channels(), not from the previous packet. The buffer length must contain whole interleaved frames; requests above 120 ms are capped to 120 ms. A buffer too small for a packet or a PLC frame returns ErrBufferTooSmall. A malformed PLC frame length returns ErrInvalidFrameSize.

func (*MultistreamDecoder) DecodeInt16

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

DecodeInt16 decodes a packet into interleaved signed 16-bit PCM, or performs PLC when data is nil or empty. It returns the number of samples per channel written. For a packet, pcm must have room for its duration; for PLC, the per-channel request size is inferred from the whole interleaved frames in pcm and is capped at 120 ms. A short buffer returns ErrBufferTooSmall.

func (*MultistreamDecoder) DecodeInt24

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

DecodeInt24 decodes a packet into interleaved signed 24-bit PCM stored in int32 values, or performs PLC when data is nil or empty. Values use the right-justified 24-bit PCM scale; output gain can exceed that range. The method returns the number of samples per channel written. For a packet, pcm must have room for its duration; for PLC, the per-channel request size is inferred from the whole interleaved frames in pcm and is capped at 120 ms. A short buffer returns ErrBufferTooSmall.

func (*MultistreamDecoder) DecodeInt24Slice

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

DecodeInt24Slice decodes a packet into interleaved signed 24-bit PCM stored in a newly allocated int32 slice. Values are right-justified. For nil or empty data it requests 60 ms of PLC. Use DecodeInt24 with a reusable buffer to avoid the output allocation.

func (*MultistreamDecoder) FinalRange

func (d *MultistreamDecoder) FinalRange() uint32

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

func (*MultistreamDecoder) Gain

func (d *MultistreamDecoder) Gain() int

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

func (*MultistreamDecoder) GetFinalRange

func (d *MultistreamDecoder) GetFinalRange() uint32

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

func (*MultistreamDecoder) IgnoreExtensions

func (d *MultistreamDecoder) IgnoreExtensions() bool

IgnoreExtensions reports whether unknown packet extensions are ignored.

func (*MultistreamDecoder) LastPacketDuration

func (d *MultistreamDecoder) LastPacketDuration() int

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

func (*MultistreamDecoder) PhaseInversionDisabled

func (d *MultistreamDecoder) PhaseInversionDisabled() bool

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

func (*MultistreamDecoder) Reset

func (d *MultistreamDecoder) Reset()

Reset clears codec, concealment, extension-payload, and soft-clipping history for a new stream. It preserves the decoder's sample rate, channel layout, gain, and extension-handling setting.

func (*MultistreamDecoder) SampleRate

func (d *MultistreamDecoder) SampleRate() int

SampleRate returns the sample rate in Hz.

func (*MultistreamDecoder) SetComplexity

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

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

func (*MultistreamDecoder) SetDNNBlob

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

SetDNNBlob returns ErrOptionalExtensionUnavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable model loading.

func (*MultistreamDecoder) SetGain

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

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

func (*MultistreamDecoder) SetIgnoreExtensions

func (d *MultistreamDecoder) SetIgnoreExtensions(ignore bool)

SetIgnoreExtensions toggles whether unknown packet extensions should be ignored.

func (*MultistreamDecoder) SetPhaseInversionDisabled

func (d *MultistreamDecoder) SetPhaseInversionDisabled(disabled bool)

SetPhaseInversionDisabled toggles CELT stereo phase inversion on all streams.

func (*MultistreamDecoder) Streams

func (d *MultistreamDecoder) Streams() int

Streams returns the total number of elementary streams.

type MultistreamEncoder

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

MultistreamEncoder encodes interleaved multichannel PCM into Opus multistream packets. It retains stream state and is not safe for concurrent use; use one encoder per stream.

func NewMultistreamEncoder

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

NewMultistreamEncoder returns an encoder for an explicit channel mapping. sampleRate is in hertz and must be 8, 12, 16, 24, or 48 kHz; 96 kHz is available in builds tagged gopus_qext. channels is the number of input channels (1–255), streams is the number of elementary streams (1–255), and coupledStreams is the number of initial stereo streams (0–streams). The sum streams+coupledStreams must not exceed 255.

mapping must contain one entry per input channel. Values 0 through 2*coupledStreams-1 select left or right channels of coupled streams (even is left, odd is right); subsequent values select mono streams. The value 255 omits an input channel. Every stream must receive input, and both channels of every coupled stream must be mapped. The constructor copies mapping.

The constructor returns an error for an unsupported rate, invalid count, mapping or layout, or invalid application.

func NewMultistreamEncoderDefault

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

NewMultistreamEncoderDefault returns an encoder with the Vorbis mapping for 1–8 input channels. Use NewMultistreamEncoder for other layouts. It returns an error for an unsupported sample rate, channel count, or application.

func (*MultistreamEncoder) Application

func (e *MultistreamEncoder) Application() Application

Application returns the current encoder application hint.

func (*MultistreamEncoder) Bandwidth

func (e *MultistreamEncoder) Bandwidth() Bandwidth

Bandwidth returns the currently configured target bandwidth.

func (*MultistreamEncoder) Bitrate

func (e *MultistreamEncoder) Bitrate() int

Bitrate returns the configured total target, including BitrateAuto or BitrateMax when selected. Libopus OPUS_GET_BITRATE instead sums the effective targets of its child encoders.

func (*MultistreamEncoder) BitrateMode

func (e *MultistreamEncoder) BitrateMode() BitrateMode

BitrateMode returns the active bitrate control mode.

func (*MultistreamEncoder) Channels

func (e *MultistreamEncoder) Channels() int

Channels returns the number of audio channels.

func (*MultistreamEncoder) Complexity

func (e *MultistreamEncoder) Complexity() int

Complexity returns the current complexity setting.

func (*MultistreamEncoder) CoupledStreams

func (e *MultistreamEncoder) CoupledStreams() int

CoupledStreams returns the number of coupled (stereo) streams.

func (*MultistreamEncoder) DTXEnabled

func (e *MultistreamEncoder) DTXEnabled() bool

DTXEnabled returns whether DTX is enabled.

func (*MultistreamEncoder) Encode

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

Encode encodes interleaved float32 PCM. pcm must contain exactly FrameSize()*Channels() samples; ExpertFrameDuration may select a shorter coded frame from that input. data is the packet buffer, and its length is the total byte budget shared by all elementary streams. A 4,000-byte-per-stream buffer is sufficient for a maximum packet. Encode returns the number of bytes written or an error; a buffer that is too small returns ErrBufferTooSmall. The steady-state path is allocation-free.

func (*MultistreamEncoder) EncodeFloat32

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

EncodeFloat32 encodes interleaved float32 PCM and returns a newly allocated packet slice. The input must contain exactly FrameSize()*Channels() samples; ExpertFrameDuration may select a shorter coded frame from that input. For allocation-free steady-state encoding, use Encode with a reusable packet buffer.

func (*MultistreamEncoder) EncodeInt16

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

EncodeInt16 encodes interleaved signed 16-bit PCM. pcm must contain exactly FrameSize()*Channels() samples; ExpertFrameDuration may select a shorter coded frame from that input. data is the packet buffer, and its length is the total byte budget shared by all elementary streams. It returns the number of bytes written or an error; a buffer that is too small returns ErrBufferTooSmall. Samples are scaled by 1/32768 and coded with a 16-bit LSB depth, matching opus_multistream_encode().

func (*MultistreamEncoder) EncodeInt16Slice

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

EncodeInt16Slice encodes interleaved signed 16-bit PCM and returns a newly allocated packet slice. The input must contain exactly FrameSize()*Channels() samples; ExpertFrameDuration may select a shorter coded frame. For allocation-free steady-state encoding, use EncodeInt16 with a reusable packet buffer.

func (*MultistreamEncoder) EncodeInt24

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

EncodeInt24 encodes interleaved signed 24-bit PCM carried in int32 values. pcm must contain exactly FrameSize()*Channels() values; ExpertFrameDuration may select a shorter coded frame from that input. data is the packet buffer, and its length is the total byte budget shared by all elementary streams. It returns the number of bytes written or an error; a buffer that is too small returns ErrBufferTooSmall.

Each input value must be right-justified in the range [-8388608, 8388607]. Left-shifted 24-in-32 PCM is mis-scaled. Values are converted to float32 by dividing by 8388608 and coded at a 24-bit LSB depth.

func (*MultistreamEncoder) EncodeInt24Slice

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

EncodeInt24Slice encodes interleaved right-justified signed 24-bit PCM stored in int32 values and returns a newly allocated packet slice. The input must contain exactly FrameSize()*Channels() values; ExpertFrameDuration may select a shorter coded frame. For allocation-free steady-state encoding, use EncodeInt24 with a reusable packet buffer.

func (*MultistreamEncoder) ExpertFrameDuration

func (e *MultistreamEncoder) ExpertFrameDuration() ExpertFrameDuration

ExpertFrameDuration returns the current multistream expert frame duration policy.

func (*MultistreamEncoder) FECEnabled

func (e *MultistreamEncoder) FECEnabled() bool

FECEnabled returns whether FEC is enabled.

func (*MultistreamEncoder) FinalRange

func (e *MultistreamEncoder) FinalRange() uint32

FinalRange returns the final range coder state.

func (*MultistreamEncoder) ForceChannels

func (e *MultistreamEncoder) ForceChannels() int

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

func (*MultistreamEncoder) FrameSize

func (e *MultistreamEncoder) FrameSize() int

FrameSize returns the configured input frame size in samples per channel at the encoder's native sample rate. ExpertFrameDuration can select a shorter coded frame from each input frame.

func (*MultistreamEncoder) GetFinalRange

func (e *MultistreamEncoder) GetFinalRange() uint32

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

func (*MultistreamEncoder) InBandFEC

func (e *MultistreamEncoder) InBandFEC() int

InBandFEC returns the current in-band FEC configuration.

func (*MultistreamEncoder) LSBDepth

func (e *MultistreamEncoder) LSBDepth() int

LSBDepth returns the current LSB depth setting.

func (*MultistreamEncoder) Lookahead

func (e *MultistreamEncoder) Lookahead() int

Lookahead returns the encoder's algorithmic delay in samples.

Matches libopus OPUS_GET_LOOKAHEAD behavior:

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

func (*MultistreamEncoder) MaxBandwidth

func (e *MultistreamEncoder) MaxBandwidth() Bandwidth

MaxBandwidth returns the maximum bandwidth limit.

func (*MultistreamEncoder) Mode

func (e *MultistreamEncoder) Mode() EncoderMode

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

func (*MultistreamEncoder) PacketLoss

func (e *MultistreamEncoder) PacketLoss() int

PacketLoss returns expected packet loss percentage.

func (*MultistreamEncoder) PhaseInversionDisabled

func (e *MultistreamEncoder) PhaseInversionDisabled() bool

PhaseInversionDisabled reports whether stereo phase inversion is disabled.

func (*MultistreamEncoder) PredictionDisabled

func (e *MultistreamEncoder) PredictionDisabled() bool

PredictionDisabled reports whether inter-frame prediction is disabled.

func (*MultistreamEncoder) Reset

func (e *MultistreamEncoder) Reset()

Reset clears codec and analysis history for a new stream. It preserves the encoder's sample rate, channel layout, frame size, and expert frame-duration policy.

func (*MultistreamEncoder) SampleRate

func (e *MultistreamEncoder) SampleRate() int

SampleRate returns the sample rate in Hz.

func (*MultistreamEncoder) SetApplication

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

SetApplication changes the encoder application hint before any stream has committed a frame. Reapplying the current hint remains valid afterward. An encode that returns a low-space packet without committing a child frame leaves the application mutable.

Valid values are ApplicationVoIP, ApplicationAudio, and ApplicationLowDelay.

func (*MultistreamEncoder) SetBandwidth

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

SetBandwidth sets the target audio bandwidth.

func (*MultistreamEncoder) SetBandwidthAuto

func (e *MultistreamEncoder) SetBandwidthAuto() error

SetBandwidthAuto restores automatic bandwidth selection for all stream encoders.

func (*MultistreamEncoder) SetBitrate

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

SetBitrate sets the total target bitrate in bits per second.

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

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

func (*MultistreamEncoder) SetBitrateMode

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

SetBitrateMode sets the multistream encoder bitrate control mode.

func (*MultistreamEncoder) SetComplexity

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

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

complexity must be 0-10, where:

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

Returns ErrInvalidComplexity if out of range.

func (*MultistreamEncoder) SetDNNBlob

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

SetDNNBlob returns ErrOptionalExtensionUnavailable in the default build. Build with -tags gopus_dred or -tags gopus_osce to enable model loading.

func (*MultistreamEncoder) SetDTX

func (e *MultistreamEncoder) SetDTX(enabled bool)

SetDTX enables or disables Discontinuous Transmission for all streams.

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

func (*MultistreamEncoder) SetExpertFrameDuration

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

SetExpertFrameDuration sets the preferred frame duration policy for multistream encoding.

func (*MultistreamEncoder) SetFEC

func (e *MultistreamEncoder) SetFEC(enabled bool)

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

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

func (*MultistreamEncoder) SetForceChannels

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

SetForceChannels forces the channel count on stream encoders in order.

channels must be -1 (auto), 1 (mono), or 2 (stereo). A mixed layout returns ErrInvalidForceChannels when its first mono stream rejects 2; earlier coupled streams retain the stereo setting, matching libopus.

func (*MultistreamEncoder) SetFrameSize

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

SetFrameSize sets the input frame size in samples per channel at the encoder's native sample rate. Encode methods require this many samples for each channel.

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 CELT QEXT encoder extension,
	// which is supported only when built with -tags gopus_qext.
	OptionalExtensionQEXT OptionalExtension = "qext"

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

type PacketInfo

type PacketInfo struct {
	TOC        TOC   // Parsed TOC byte.
	FrameCount int   // Number of frames in the packet.
	FrameSizes []int // Frame payload sizes in bytes, excluding headers and padding.
	Padding    int   // Trailing padding bytes; nonzero only for code 3 packets.
	TotalSize  int   // Complete packet size in bytes, including headers and padding.
}

PacketInfo describes an Opus packet's TOC and frame layout.

func ParsePacket

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

ParsePacket parses a complete Opus packet and returns its frame layout. FrameSizes contains payload lengths in packet order; packet headers and trailing padding are reported separately. It returns an error for truncated, malformed, overlong, or over-duration packets.

type PacketReader

type PacketReader interface {
	// ReadPacketInto writes the next packet into dst and returns its byte length.
	// The caller may reuse dst after this call returns.
	//
	// granulePos is the source position in decoded samples at 48 kHz when the
	// container provides one, as with an Ogg Opus granule position. Return 0
	// when positions are unavailable.
	//
	// Return io.EOF when the stream ends. A final complete packet may be
	// returned with n > 0 and io.EOF; Reader drains its PCM before returning EOF.
	// Return n=0, err=nil to request packet loss concealment for one frame.
	ReadPacketInto(dst []byte) (n int, granulePos uint64, err error)
}

PacketReader provides Opus packets for streaming decode. ReadPacketInto writes the next packet into dst and returns its byte length; callers may reuse dst after the call. Return io.EOF when the stream ends.

type PacketSink

type PacketSink interface {
	// WritePacket writes one encoded Opus packet and returns the number of bytes
	// accepted. Writer does not retry; a short count returns io.ErrShortWrite,
	// except that an error returned with zero bytes is preserved. The packet buffer
	// is reused after this method returns, so copy packet if retaining it.
	//
	// If the sink also implements io.Closer, Writer.Close calls it at most once
	// after attempting a flush, or after an earlier sink write error.
	WritePacket(packet []byte) (int, error)
}

PacketSink receives encoded Opus packets from streaming encode.

type Reader

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

Reader decodes packets from a PacketReader and exposes PCM as an io.Reader. Read returns little-endian samples in the configured format. A Reader is not safe for concurrent use.

func NewReader

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

NewReader creates a Reader that decodes packets from source into format. It returns ErrNilPacketReader for a nil source, ErrInvalidSampleFormat for an unsupported format, or the decoder configuration error.

func (*Reader) 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 computed granule position of that packet. 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 and returns decoded PCM bytes in the format passed to NewReader. Each call decodes at most one packet, so a short read at a packet boundary is normal. It returns io.EOF after the source ends and buffered PCM has been consumed. An empty destination does not advance the source or buffered PCM; it returns io.EOF only when EOF is already known and no PCM remains.

func (*Reader) Reset

func (r *Reader) Reset()

Reset clears buffered PCM and decoder state. It does not reset or replace the PacketReader, so subsequent reads continue from that source's current position.

func (*Reader) SampleRate

func (r *Reader) SampleRate() int

SampleRate returns the sample rate in Hz.

type Repacketizer

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

Repacketizer copies frames from Opus packets and assembles packets from contiguous frame ranges. Added packets must have the same TOC configuration and channel flag (bits 7 through 2); their frame-count codes may differ. The accumulator accepts at most 48 frames and 120 ms of audio. Repacketizer is not safe for concurrent use.

func NewRepacketizer

func NewRepacketizer() *Repacketizer

NewRepacketizer creates an empty repacketizer.

func (*Repacketizer) Cat

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

Cat parses packet and copies its encoded frame data into the accumulator. The caller may reuse packet after Cat returns. It returns an error for an invalid packet, incompatible TOC configuration or channel flag, or an accumulator that would exceed its frame-count or duration limits.

func (*Repacketizer) NumFrames

func (r *Repacketizer) NumFrames() int

NumFrames returns the number of accumulated audio frames, not the number of packets passed to Cat.

func (*Repacketizer) Out

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

Out assembles all accumulated frames into one Opus packet. data must have enough length for the output packet; the returned count is the number of bytes written.

func (*Repacketizer) OutRange

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

OutRange assembles the accumulated frame range [begin, end) into one Opus packet. end is exclusive. data must have enough length for the output; the returned count is the number of bytes written. It returns ErrInvalidArgument for an empty or out-of-range range, ErrInternalError for malformed packet extensions, and ErrBufferTooSmall when data is short.

func (*Repacketizer) Reset

func (r *Repacketizer) Reset()

Reset discards all accumulated frames so the repacketizer can be reused.

type SampleFormat

type SampleFormat int

SampleFormat specifies the PCM sample format for streaming.

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

func (SampleFormat) BytesPerSample

func (f SampleFormat) BytesPerSample() int

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

type Signal

type Signal = types.Signal

Signal is a hint about the input signal type.

type SpeechDetector added in v0.2.0

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

SpeechDetector scores how likely mono PCM is speech with the neural analysis that Opus runs inside its encoder (libopus activity_probability). Unlike VAD, which follows level against a noise estimate, the network scores spectral and temporal structure over several windows, so steady noise, hum, and isolated clicks score low even when loud. It does not separate speech from every other foreground sound: a cough or other people talking can score high. It keeps a recurrent network state and is not safe for concurrent use.

func NewSpeechDetector added in v0.2.0

func NewSpeechDetector(sampleRate int) (*SpeechDetector, error)

NewSpeechDetector creates a detector for 16, 24, or 48 kHz mono PCM, the rates of the Opus analysis. It returns an error for other sample rates.

func (*SpeechDetector) AnalyzeFloat32 added in v0.2.0

func (d *SpeechDetector) AnalyzeFloat32(pcm []float32) (float32, error)

AnalyzeFloat32 is AnalyzeInt16 for float32 PCM where 1.0 is full scale, the scale Encoder.Encode uses. Samples beyond twice full scale are clamped.

func (*SpeechDetector) AnalyzeInt16 added in v0.2.0

func (d *SpeechDetector) AnalyzeInt16(pcm []int16) (float32, error)

AnalyzeInt16 analyzes one mono frame of signed 16-bit PCM and returns the speech probability in [0, 1], not a speech/no-speech boolean. The caller chooses the threshold and handles turn timing. PCM must use the rate passed to NewSpeechDetector and contain exactly 10 or 20 ms of samples; each successful call advances the detector state.

The network works on 20 ms windows and completes one for every 20 ms of input. The newest window ends 10 ms before the newest sample, and the network's recurrent output smooths over earlier windows. A 10 ms frame completes a window on every second call and repeats the previous result in between. The result is 0 until the first window completes and while the newest window is exactly zero, where the encoder repeats its previous estimate. The first ten windows (about 200 ms) after construction or Reset are a warm-up in which the estimate is less reliable.

Example
package main

import (
	"fmt"
	"log"

	"github.com/thesyncim/gopus"
)

func main() {
	det, err := gopus.NewSpeechDetector(16000)
	if err != nil {
		log.Fatal(err)
	}

	// One 20 ms frame of 16 kHz mono PCM. Real audio replaces the zeros.
	frame := make([]int16, 320)
	probability, err := det.AnalyzeInt16(frame)
	if err != nil {
		log.Fatal(err)
	}

	// Compare against a threshold of your choosing; exact digital silence scores 0.
	fmt.Printf("speech probability %.2f\n", probability)
}
Output:
speech probability 0.00

func (*SpeechDetector) Reset added in v0.2.0

func (d *SpeechDetector) Reset()

Reset clears the analysis and network state for a new audio stream.

type TOC

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

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

func ParseTOC

func ParseTOC(b byte) TOC

ParseTOC decodes the configuration, channel flag, and frame-count code in b. Every byte value has a TOC interpretation; the returned FrameSize is in samples at 48 kHz.

type VAD added in v0.1.2

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

VAD analyzes mono PCM at 8, 12, or 16 kHz with Opus's SILK voice detector. It keeps an adaptive noise estimate across frames and is not safe for concurrent use.

func NewVAD added in v0.1.2

func NewVAD(sampleRate int) (*VAD, error)

NewVAD creates a detector for 8, 12, or 16 kHz mono PCM. It returns an error for other sample rates.

func (*VAD) AnalyzeInt16 added in v0.1.2

func (v *VAD) AnalyzeInt16(pcm []int16) (int, error)

AnalyzeInt16 analyzes one mono frame of signed 16-bit PCM and returns SILK speech activity in Q8 (0-255), not a speech/no-speech boolean. The caller chooses the activity threshold and handles turn timing. PCM must use the rate passed to NewVAD and contain exactly 10 or 20 ms of samples; each successful call advances the detector state.

func (*VAD) Reset added in v0.1.2

func (v *VAD) Reset()

Reset clears the adaptive noise estimate for a new audio stream.

type Writer

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

Writer encodes PCM bytes from io.Writer calls into Opus packets for a PacketSink. It buffers incomplete frames and is not safe for concurrent use.

func NewWriter

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

NewWriter creates a Writer that encodes interleaved PCM at sampleRate with channels and sends packets to sink. format selects little-endian float32 or signed int16 input, and application selects the encoder's intended use. The writer uses a 20 ms frame duration by default. It returns an error for a nil sink, unsupported format, or invalid encoder configuration.

func (*Writer) 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 attempts to flush buffered samples and closes the underlying sink when supported, including when flushing fails. If both flushing and closing fail, the returned error matches both. Repeated calls return nil and do not retry the sink close.

func (*Writer) Flush

func (w *Writer) Flush() error

Flush encodes buffered PCM. A partial final frame is zero-padded to the configured frame size. With no buffered PCM, Flush has no effect.

func (*Writer) Reset

func (w *Writer) Reset()

Reset clears buffered PCM and encoder state and clears the closed flag. It retains the PacketSink without resetting or reopening it, so the sink must be reusable if the Writer is reused.

func (*Writer) SampleRate

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. Positive values are clamped to the encoder's supported range. BitrateAuto and BitrateMax select automatic and output-buffer-limited bitrates; other nonpositive values return ErrInvalidBitrate.

func (*Writer) SetComplexity

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 for interleaved little-endian PCM in the format passed to NewWriter. It buffers incomplete frames and encodes each complete frame. On success it consumes all of p. On error, the returned count covers only input bytes in frames handled before the error; packets sent before an error are not rolled back. A sink error closes the Writer.

Directories

Path Synopsis
container
ogg
Package ogg reads and writes Ogg Opus streams.
Package ogg reads and writes Ogg Opus streams.
red
Package red implements RFC 2198 redundancy for RTP payloads.
Package red implements RFC 2198 redundancy for RTP payloads.
examples
bench-decode command
Package main benchmarks Opus decode throughput for gopus vs libopus.
Package main benchmarks Opus decode throughput for gopus vs libopus.
bench-encode command
Package main benchmarks Opus encode throughput for gopus vs libopus.
Package main benchmarks Opus encode throughput for gopus vs libopus.
decode-play command
Package main demonstrates decoding an Ogg Opus file to WAV with optional playback.
Package main demonstrates decoding an Ogg Opus file to WAV with optional playback.
encode-play command
Package main demonstrates encoding audio with gopus and playing the result.
Package main demonstrates encoding audio with gopus and playing the result.
ffmpeg-interop command
Package main demonstrates gopus interoperability with ffmpeg.
Package main demonstrates gopus interoperability with ffmpeg.
internal/cleanup
Package cleanup reports errors from deferred example cleanup operations.
Package cleanup reports errors from deferred example cleanup operations.
internal/wav
Package wav writes interleaved float32 PCM to classic RIFF/WAVE files.
Package wav writes interleaved float32 PCM to classic RIFF/WAVE files.
low-delay command
Package main demonstrates low-delay, CELT-only encoding.
Package main demonstrates low-delay, CELT-only encoding.
mix-arrivals command
Package main demonstrates WebRTC-style speech mixing with real open-source clips.
Package main demonstrates WebRTC-style speech mixing with real open-source clips.
ogg-file command
Package main demonstrates Ogg Opus file creation and reading.
Package main demonstrates Ogg Opus file creation and reading.
packet-loss command
Package main demonstrates the two ways gopus recovers from a lost packet on a real (lossy) network: packet loss concealment and in-band forward error correction.
Package main demonstrates the two ways gopus recovers from a lost packet on a real (lossy) network: packet loss concealment and in-band forward error correction.
repacketizer command
Package main demonstrates the Opus repacketizer and packet-inspection helpers.
Package main demonstrates the Opus repacketizer and packet-inspection helpers.
roundtrip command
Package main demonstrates gopus encode-decode roundtrip with quality metrics.
Package main demonstrates gopus encode-decode roundtrip with quality metrics.
roundtrip-min command
Package main is the smallest useful gopus program: it encodes one frame of PCM to an Opus packet and decodes it straight back, using the caller-owned buffer Encode/Decode API.
Package main is the smallest useful gopus program: it encodes one frame of PCM to an Opus packet and decodes it straight back, using the caller-owned buffer Encode/Decode API.
sample-rates command
Package main demonstrates sample-rate handling and the int16 PCM API.
Package main demonstrates sample-rate handling and the int16 PCM API.
surround command
Package main demonstrates multistream (surround) encoding and decoding.
Package main demonstrates multistream (surround) encoding and decoding.
internal
arena
Package arena provides a generic single-type bump allocator used to back many logical scratch buffers with one contiguous allocation.
Package arena provides a generic single-type bump allocator used to back many logical scratch buffers with one contiguous allocation.
benchutil
Package benchutil locates the pinned libopus reference binaries (opus_demo, opus_compare) and writes the raw-PCM and bitstream input files the parity and benchmark tooling feeds to them.
Package benchutil locates the pinned libopus reference binaries (opus_demo, opus_compare) and writes the raw-PCM and bitstream input files the parity and benchmark tooling feeds to them.
celt
Package celt implements the CELT decoder per RFC 6716 Section 4.3.
Package celt implements the CELT decoder per RFC 6716 Section 4.3.
cpufeat
Package cpufeat exposes architecture feature flags.
Package cpufeat exposes architecture feature flags.
dnnblob
Package dnnblob parses the USE_WEIGHTS_FILE format read by libopus `dnn/parse_lpcnet_weights.c`.
Package dnnblob parses the USE_WEIGHTS_FILE format read by libopus `dnn/parse_lpcnet_weights.c`.
dnnmath
Package dnnmath provides float32 activation, exponent, quantization, and small-vector kernels used by the optional DRED, OSCE, and LPCNet networks.
Package dnnmath provides float32 activation, exponent, quantization, and small-vector kernels used by the optional DRED, OSCE, and LPCNet networks.
dred
Package dred implements the experimental Opus Deep Redundancy (DRED) extension.
Package dred implements the experimental Opus Deep Redundancy (DRED) extension.
dred/rdovae
Package rdovae implements the libopus RDOVAE (rate-distortion-optimized variational auto-encoder) used by Deep Redundancy (DRED).
Package rdovae implements the libopus RDOVAE (rate-distortion-optimized variational auto-encoder) used by Deep Redundancy (DRED).
encoder
Package encoder implements the stateful Opus encoder described by RFC 6716.
Package encoder implements the stateful Opus encoder described by RFC 6716.
fixedpoint
Package fixedpoint contains integer CELT math helpers and the FIXED_POINT CELT encoder and decoder.
Package fixedpoint contains integer CELT math helpers and the FIXED_POINT CELT encoder and decoder.
hybrid
Package hybrid implements the Opus Hybrid-mode decoder.
Package hybrid implements the Opus Hybrid-mode decoder.
lpcnetplc
Package lpcnetplc implements the LPCNet feature prediction, pitch analysis, and FARGAN synthesis used by libopus's neural packet-loss concealment and DRED recovery paths.
Package lpcnetplc implements the LPCNet feature prediction, pitch analysis, and FARGAN synthesis used by libopus's neural packet-loss concealment and DRED recovery paths.
opusmath
Package opusmath holds the gopus floating-point math kernels shared by the CELT, SILK and Opus glue layers.
Package opusmath holds the gopus floating-point math kernels shared by the CELT, SILK and Opus glue layers.
osce/bwe
Package bwe implements the libopus OSCE blind-bandwidth-extension network (BBWENet), which extends 16 kHz decoded speech up to 48 kHz.
Package bwe implements the libopus OSCE blind-bandwidth-extension network (BBWENet), which extends 16 kHz decoded speech up to 48 kHz.
osce/lace
Package lace implements the libopus OSCE LACE and NoLACE neural postfilters that enhance decoded SILK speech.
Package lace implements the libopus OSCE LACE and NoLACE neural postfilters that enhance decoded SILK speech.
plc
Package plc implements the codec-specific concealment used after a lost Opus frame.
Package plc implements the codec-specific concealment used after a lost Opus frame.
qualitycompare
Package qualitycompare provides the shared quality comparator for gopus and libopus parity tests.
Package qualitycompare provides the shared quality comparator for gopus and libopus parity tests.
rangecoding
Package rangecoding implements the Opus range coder in RFC 6716 Section 4.1.
Package rangecoding implements the Opus range coder in RFC 6716 Section 4.1.
silk
Package silk implements the SILK speech layer in RFC 6716 Section 4.2.
Package silk implements the SILK speech layer in RFC 6716 Section 4.2.
util
Package util provides small, dependency-free helpers shared across the gopus codec packages.
Package util provides small, dependency-free helpers shared across the gopus codec packages.
Package multistream encodes and decodes Opus packets with multiple elementary streams, as used for surround sound and ambisonics.
Package multistream encodes and decodes Opus packets with multiple elementary streams, as used for surround sound and ambisonics.
scripts
benchmarks
Package benchmarks holds source templates that the native A/B workflow installs into the CELT package for architecture-specific measurements.
Package benchmarks holds source templates that the native A/B workflow installs into the CELT package for architecture-specific measurements.
Package testvectors parses opus_demo bitstreams and supports quality checks against the RFC 8251 Opus test vectors.
Package testvectors parses opus_demo bitstreams and supports quality checks against the RFC 8251 Opus test vectors.
tools
benchguard command
encoderbenchcmp command
qualityreport command
safety_soak command
Package types defines the Mode, Bandwidth, and Signal values shared by gopus packages.
Package types defines the Mode, Bandwidth, and Signal values shared by gopus packages.

Jump to

Keyboard shortcuts

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