celt

package
v0.2.10 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: BSD-3-Clause Imports: 10 Imported by: 0 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.

Documentation

Overview

Package celt implements the CELT decoder per RFC 6716 Section 4.3.

Package celt implements the CELT (Constrained-Energy Lapped Transform) layer of the Opus codec as specified in RFC 6716 Section 4.3.

Package celt implements the CELT transform-coding layer in RFC 6716 Section 4.3. It analyzes and reconstructs spectral frames using an MDCT, predictive band-energy coding, pulse-vector quantization, and overlap-add synthesis.

Encoder and Decoder retain per-stream prediction, overlap, filter, and concealment state. Keep one instance per stream and serialize access to it. Decoder.DecodeFrame initializes a range decoder for a CELT payload. Decoder.AccumulateFrameHybridWithPacketStereo is the Hybrid entry point: it continues from the range decoder after SILK and adds CELT output to the caller's low-band PCM. The encoder can use a range coder supplied with Encoder.SetRangeEncoder.

At 48 kHz, CELT frames contain 120, 240, 480, or 960 samples. In Hybrid mode, CELT starts at band 17; SILK carries the lower-frequency signal. The decoder also handles packet loss by evolving its band-energy and overlap history.

Package celt implements the CELT decoder per RFC 6716 Section 4.3.

Code generated by tools/gen_math_utils_tables.go; DO NOT EDIT.

Package celt implements the CELT decoder per RFC 6716 Section 4.3. CELT (Constrained Energy Lapped Transform) is the transform-based layer of Opus for music and general audio.

Code generated by tools/gen_window_tables.go; DO NOT EDIT.

Index

Constants

View Source
const (
	// MaxPVQK is the maximum number of pulses we support in PVQ coding.
	MaxPVQK = 128
	// MaxPVQN is the maximum number of dimensions we support.
	MaxPVQN = 256
)

Constants for CWRS

View Source
const BetaIntra opusVal16 = 4915.0 / 32768.0 // 0.15

BetaIntra is the inter-band prediction coefficient for INTRA-frame mode. No inter-frame prediction, only inter-band. Source: libopus celt/quant_bands.c

View Source
const BitRes = bitRes

BitRes is the Q3 fixed-point resolution used throughout CELT allocation math. This mirrors libopus BITRES.

View Source
const BitrateMax = -1

BitrateMax mirrors OPUS_BITRATE_MAX: the encoder fills its payload budget instead of targeting a bitrate.

View Source
const CELTSigScale = 32768.0

CELTSigScale is the internal signal scale used by CELT. Input samples in float range [-1.0, 1.0] are scaled up by this factor for internal processing, matching libopus CELT_SIG_SCALE.

View Source
const DB6 = 1.0

DB6 is the value corresponding to a 6 dB step in CELT's log2 energy units. In libopus, energies are stored in log2 units, so 6 dB = 1.0.

View Source
const DCRejectCutoffHz = 3

DCRejectCutoffHz is the cutoff frequency for the DC rejection high-pass filter. libopus uses 3 Hz at the Opus encoder level. Reference: libopus src/opus_encoder.c line 2008

View Source
const DecodeBufferSize = 2048

DecodeBufferSize matches libopus DEC_PITCH_BUF_SIZE (decode_mem length without overlap). This buffer is larger than any single frame to preserve history for short blocks.

View Source
const DelayCompensation = 192

DelayCompensation is the number of samples of lookahead for CELT. libopus uses Fs/250 = 192 samples at 48kHz (4ms). This provides a lookahead that allows for better transient handling. Reference: libopus src/opus_encoder.c delay_compensation

View Source
const HybridCELTStartBand = 17

HybridCELTStartBand is the first CELT band decoded in hybrid mode. Bands 0-16 are covered by SILK; CELT only decodes bands 17-21.

View Source
const IntensityDecay = 16384

IntensityDecay is the decay parameter for intensity stereo Laplace encoding. The decoder uses the same decay value when it reads the intensity band.

View Source
const MaxBands = 21

MaxBands is the maximum number of frequency bands in CELT. These are Bark-scale bands covering 0-20kHz at 48kHz sample rate.

View Source
const Overlap = 120

Overlap is the number of overlap samples at 48kHz (2.5ms window overlap). This is fixed for all CELT frame sizes.

View Source
const PreemphCoef = 0.8500061035

PreemphCoef is the de-emphasis filter coefficient. The encoder applies pre-emphasis; decoder applies inverse de-emphasis: y[n] = x[n] + PreemphCoef * y[n-1] Value matches libopus static_modes_float.h: 0.8500061035f

View Source
const SilkCELTDelay = 60

SilkCELTDelay is the delay compensation in samples at 48kHz for hybrid mode. SILK needs to be delayed relative to CELT for proper time alignment.

Variables

View Source
var (
	// ErrInvalidFrame indicates the frame data is invalid or corrupted.
	ErrInvalidFrame = errors.New("celt: invalid frame data")

	// ErrInvalidFrameSize indicates an invalid frame size.
	ErrInvalidFrameSize = errors.New("celt: invalid frame size")

	// ErrInvalidSampleRate indicates a sample rate outside the Opus API set.
	ErrInvalidSampleRate = errors.New("celt: invalid sample rate")

	// ErrOutputTooSmall indicates the caller-provided PCM buffer is too small.
	ErrOutputTooSmall = errors.New("celt: output buffer too small")

	// ErrNilDecoder indicates a nil range decoder was passed.
	ErrNilDecoder = errors.New("celt: nil range decoder")

	// ErrInvalidComplexity indicates the decoder complexity is out of range.
	ErrInvalidComplexity = errors.New("celt: invalid complexity (must be 0-10)")
)

Decoding errors

View Source
var (
	// ErrInvalidInputLength indicates the PCM input length doesn't match frame size.
	ErrInvalidInputLength = errors.New("celt: invalid input length")

	// ErrEncodingFailed indicates a general encoding failure.
	ErrEncodingFailed = errors.New("celt: encoding failed")
)

Encoding errors

View Source
var AlphaCoef = [4]opusVal16{
	29440.0 / 32768.0,
	26112.0 / 32768.0,
	21248.0 / 32768.0,
	16384.0 / 32768.0,
}

AlphaCoef contains inter-frame energy prediction coefficients by LM (log mode). Used for coarse energy decoding in inter-frame mode. Index corresponds to LM: 0=2.5ms, 1=5ms, 2=10ms, 3=20ms

Source: RFC 6716 Section 4.3.2, libopus celt/quant_bands.c

View Source
var BandAlloc = [11][21]int{

	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},

	{90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0},

	{110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0},

	{118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0},

	{126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0},

	{134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1},

	{144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1},

	{152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1},

	{162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1},

	{172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20},

	{200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104},
}

BandAlloc contains base bits per band at each quality level. Index: BandAlloc[quality][band] where quality is 0-10 (11 levels). Values represent bits in 1/32 bit/sample (as in libopus band_allocation). Source: libopus celt/modes.c band_allocation table.

View Source
var BetaCoefInter = [4]opusVal16{
	30147.0 / 32768.0,
	22282.0 / 32768.0,
	12124.0 / 32768.0,
	6554.0 / 32768.0,
}

BetaCoefInter contains inter-band energy prediction coefficients for INTER-frame mode. Values vary by LM (log mode / frame size). Source: libopus celt/quant_bands.c

View Source
var EBands = [22]int{
	0, 1, 2, 3, 4, 5, 6, 7, 8, 10,
	12, 14, 16, 20, 24, 28, 34, 40, 48, 60,
	78, 100,
}

EBands contains the MDCT bin indices for band edges at 48kHz with 5ms base frame. These 22 values define 21 bands. Each band spans from EBands[i] to EBands[i+1]. For other frame sizes, these indices are scaled appropriately.

Frequency boundaries (approximate): 0Hz, 200Hz, 400Hz, 600Hz, 800Hz, 1000Hz, 1200Hz, 1400Hz, 1600Hz, 2000Hz, 2400Hz, 2800Hz, 3200Hz, 4000Hz, 4800Hz, 5600Hz, 6800Hz, 8000Hz, 9600Hz, 12000Hz, 15600Hz, 20000Hz

Source: libopus celt/modes.c (eBand5ms table)

View Source
var EMeans = [25]celtGLog{
	6.437500, 6.250000, 5.750000, 5.312500, 5.062500,
	4.812500, 4.500000, 4.375000, 4.875000, 4.687500,
	4.562500, 4.437500, 4.875000, 4.625000, 4.312500,
	4.500000, 4.375000, 4.625000, 4.750000, 4.437500,
	3.750000, 3.750000, 3.750000, 3.750000, 3.750000,
}

EMeans contains the mean log-energy per band in libopus float-build width. These values are in log2 units (1.0 = 6 dB) and represent typical energy distribution across frequency bands. Source: libopus celt/quant_bands.c (float eMeans table, lines 56-62)

View Source
var LogN = [21]int{
	0, 0, 0, 0, 0, 0, 0, 0,
	8, 8, 8, 8,
	16, 16, 16,
	21, 21,
	24,
	29,
	34,
	36,
}

LogN contains log2 of band widths (in Q3 fixed-point) for bit allocation. This is used in the bit allocation algorithm to weight bands. For band i, width = EBands[i+1] - EBands[i], and LogN[i] = round(log2(width) * 256)

Source: libopus celt/modes.c (logN400 table)

View Source
var SmallDiv = [129]uint16{}/* 129 elements not displayed */

SmallDiv contains precomputed values for efficient small division in Laplace decoding. SmallDiv[i] = (1 << 16) / (i + 1) for i in 0..128 Used for energy decoding to avoid expensive division operations.

Source: libopus celt/laplace.c (ec_laplace_decode)

View Source
var SpreadICDF = spreadICDF

SpreadICDF exposes the spread entropy table for callers that need it.

View Source
var TrimICDF = trimICDF

TrimICDF exposes the allocation trim entropy table for callers that need it.

Functions

func AllocTrimAnalysis

func AllocTrimAnalysis(
	normCoeffs []celtNorm,
	bandLogE []celtGLog,
	nbBands int,
	lm int,
	channels int,
	normCoeffsRight []celtNorm,
	intensity int,
	tfEstimate opusVal16,
	equivRate int,
	surroundTrim celtGLog,
	tonalitySlope opusVal16,
) int

AllocTrimAnalysis returns the CELT allocation trim index in [0, 10]. Higher values favor lower frequency bands. It follows alloc_trim_analysis in libopus celt/celt_encoder.c.

normCoeffs contains normalized mono or left-channel MDCT coefficients; normCoeffsRight contains the right channel, or is nil for mono. bandLogE contains nbBands log energies per channel. intensity is the first band that uses intensity stereo, or nbBands when intensity stereo is disabled. lm is the log2 multiplier of the short-transform size.

equivRate is the equivalent bitrate in bits per second. tfEstimate is the transient-analysis estimate in [0, 1]; surroundTrim is the surround allocation adjustment. A zero tonalitySlope disables the optional analysis adjustment.

func ApplyWindow

func ApplyWindow(samples []float32, overlap int)

ApplyWindow applies the Vorbis window to IMDCT output. The window is applied to both the beginning and end overlap regions.

Parameters:

  • samples: IMDCT output (length 2*N where N is MDCT size)
  • overlap: overlap size (typically 120 for CELT)

The windowing is in-place to avoid allocation.

func BandWidth

func BandWidth(band int) int

BandWidth returns the number of MDCT bins in the given band at base frame size. For band i, this is EBands[i+1] - EBands[i].

func BitsToPulsesExport

func BitsToPulsesExport(band, lm, bitsQ3 int) int

BitsToPulsesExport exposes bitsToPulses for testing.

This helper exists for tests and codec-development tooling and may change.

func ClearCache

func ClearCache()

ClearCache is a no-op for compatibility. The new implementation uses a static table and doesn't need cache clearing.

func ClearCollapseMask

func ClearCollapseMask(mask *uint32)

ClearCollapseMask resets the collapse mask to zero.

func ComputeEquivRate

func ComputeEquivRate(nbCompressedBytes, channels, lm, targetBitrate int) int

ComputeEquivRate computes equiv_rate, the equivalent 20 ms bitrate the intensity hysteresis, allocation trim and signal-bandwidth floor read. This matches libopus celt_encoder.c:1925-1927.

Parameters:

  • nbCompressedBytes: payload budget of the frame in bytes
  • channels: number of coded channels (1 or 2)
  • lm: log mode (frame size index: 0=2.5ms, 1=5ms, 2=10ms, 3=20ms)
  • targetBitrate: st->bitrate in bps; BitrateMax (or any non-positive value) codes a fixed packet size

Returns: equivalent bitrate in bits per second

Reference: libopus celt/celt_encoder.c line 1925:

equiv_rate = ((opus_int32)nbCompressedBytes*8*50 << (3-LM)) - (40*C+20)*((400>>LM) - 50);
if (st->bitrate != OPUS_BITRATE_MAX)
   equiv_rate = IMIN(equiv_rate, st->bitrate - (40*C+20)*((400>>LM) - 50));

func ComputeImportance

func ComputeImportance(bandLogE, oldBandE []celtGLog, nbBands, channels, lm, lsbDepth, effectiveBytes int) []int32

ComputeImportance computes per-band importance weights for TF analysis. Importance weights affect how much each band's TF decision matters in the Viterbi search.

The importance is derived from: - Band log energies relative to a spectral follower curve - Noise floor based on band width and quantization depth - Masking effects from neighboring bands

Higher importance means the band's TF decision has more perceptual impact. Default value is 13 (when no analysis is performed).

Parameters:

  • bandLogE: log-domain band energies (mean-relative, from ComputeBandEnergies)
  • oldBandE: previous frame band energies (for temporal smoothing)
  • nbBands: number of bands
  • channels: number of audio channels
  • lm: log mode (frame size index)
  • lsbDepth: bit depth of input signal (typically 16 or 24)
  • effectiveBytes: available bytes for encoding

Returns: per-band importance weights (13 = neutral, higher = more important)

Reference: libopus celt/celt_encoder.c dynalloc_analysis() importance calculation

func ComputeLinearBandAmplitudesInto

func ComputeLinearBandAmplitudesInto(mdctCoeffs []float32, nbBands, frameSize int, bandE []celtEner)

ComputeLinearBandAmplitudesInto computes linear band amplitudes into the provided buffer. This is the zero-allocation version of ComputeLinearBandAmplitudes.

func ComputeLinearBandAmplitudesIntoF32

func ComputeLinearBandAmplitudesIntoF32(mdctCoeffs []float32, nbBands, frameSize int, bandE []celtEner)

ComputeLinearBandAmplitudesIntoF32 computes float-build linear band amplitudes into the provided buffer.

func ComputeMDCTWithHistory

func ComputeMDCTWithHistory(samples, history []float32, shortBlocks int) []float32

ComputeMDCTWithHistory computes MDCT using a history buffer for overlap. samples: current frame samples history: buffer containing previous frame's tail (will be updated with current frame's tail) shortBlocks: number of short blocks for transient mode

func DecodePulses

func DecodePulses(index uint32, n, k int) []int

DecodePulses converts a CWRS index to a pulse vector.

Parameters:

  • index: the combinatorial index (0 to V(n,k)-1)
  • n: number of dimensions (band width)
  • k: total number of pulses (sum of absolute values)

Returns: pulse vector of length n, where sum(|v[i]|) == k

The algorithm walks through positions, determining how many pulses go at each position by counting codewords in the combinatorial structure.

This implementation uses the precomputed table for O(1) lookups when possible.

Reference: libopus celt/cwrs.c decode_pulses() / cwrsi()

func DeinterleaveStereoInto

func DeinterleaveStereoInto(interleaved, left, right []celtNorm)

DeinterleaveStereoInto separates interleaved stereo samples into L and R slices. It processes len(interleaved)/2 samples per channel, ignoring a trailing unpaired sample. left and right must each have at least that length.

func DeinterleaveStereoIntoF32

func DeinterleaveStereoIntoF32(interleaved, left, right []float32)

DeinterleaveStereoIntoF32 separates interleaved float32 stereo samples into L and R slices. It processes len(interleaved)/2 samples per channel, ignoring a trailing unpaired sample. left and right must each have at least that length.

func EffectiveBandsForFrameSize

func EffectiveBandsForFrameSize(bw CELTBandwidth, frameSize int) int

EffectiveBandsForFrameSize returns the effective band count considering both bandwidth and frame size constraints.

func Encode

func Encode(pcm []float32, frameSize int) ([]byte, error)

Encode encodes mono PCM samples to a CELT packet. pcm: float32 samples at 48kHz frameSize: 120, 240, 480, or 960 samples Returns: encoded Opus CELT packet bytes

This is the simple public API for mono encoding. For more control, use NewEncoder() and call EncodeFrame() directly.

Reference: RFC 6716 Section 4.3

func EncodeFrames

func EncodeFrames(pcmFrames [][]float32, frameSize int) ([][]byte, error)

EncodeFrames encodes multiple consecutive frames. Useful for encoding a stream of audio data. pcmFrames: slice of PCM frames, each with frameSize samples frameSize: samples per frame (must be same for all frames) Returns: slice of encoded packets

func EncodePulses

func EncodePulses(y []int, n, k int) uint32

EncodePulses converts a pulse vector to a CWRS index. This is the inverse of DecodePulses, useful for testing round-trip.

Parameters:

  • y: pulse vector of length n
  • n: number of dimensions
  • k: total number of pulses (should equal sum(|y[i]|))

Returns: the combinatorial index (0 to V(n,k)-1)

func EncodePulses32Scratch added in v0.2.0

func EncodePulses32Scratch(y []int32, n, k int, uBuf *[]uint32) uint32

EncodePulses32Scratch converts a fixed-width signed pulse vector to its CWRS index. It mirrors celt/vq.c encode_pulses for FIXED_POINT callers and reuses the caller's CWRS scratch buffer when supplied.

func EncodePulsesScratch

func EncodePulsesScratch(y []int, n, k int, uBuf *[]uint32) uint32

EncodePulsesScratch is the scratch-aware version of EncodePulses. It uses a pre-allocated u buffer to avoid allocations in the hot path.

func EncodeSilence

func EncodeSilence(frameSize int, channels int) ([]byte, error)

EncodeSilence encodes a silent frame of the given size. Useful for generating comfort noise or filler packets.

func EncodeStereo

func EncodeStereo(pcm []float32, frameSize int) ([]byte, error)

EncodeStereo encodes stereo PCM samples to a CELT packet. pcm: interleaved L/R float32 samples at 48kHz frameSize: 120, 240, 480, or 960 samples per channel Returns: encoded Opus CELT packet bytes

The input should be interleaved: [L0, R0, L1, R1, ...] Total length should be frameSize * 2.

Stereo mode and intensity-band decisions follow the encoder's per-frame analysis and bit allocation.

Reference: RFC 6716 Section 4.3

func FillHybridTFResolution

func FillHybridTFResolution(tfRes []int32, end int, transient, weakTransient, allowWeakTransients bool) int

FillHybridTFResolution applies the libopus hybrid fixed-TF fallback used when variable TF analysis is disabled.

func FindFoldSource

func FindFoldSource(targetBand int, codedMask uint32, bandWidths []int) int

FindFoldSource finds the band to fold from for an uncoded band. targetBand: the band index that needs folding codedMask: bitmask of bands that have been coded (received pulses) bandWidths: array of band widths (from eBands table) Returns: index of source band to fold from, or -1 if none available.

The algorithm searches backwards from targetBand to find the most recent coded band that can serve as a reasonable source.

func GetCodedBandCount

func GetCodedBandCount(mask uint32) int

GetCodedBandCount returns the number of bands with pulses. mask: collapse mask Returns: count of coded bands.

func GetPulsesExport

func GetPulsesExport(q int) int

GetPulsesExport exposes getPulses for testing.

This helper exists for tests and codec-development tooling and may change.

func GetWindowBuffer

func GetWindowBuffer(overlap int) []float32

GetWindowBuffer returns the CELT window for overlap, as GetWindowBufferF32 does.

func GetWindowBufferF32

func GetWindowBufferF32(overlap int) []float32

GetWindowBufferF32 returns the CELT window for overlap. Overlaps of 120, 240, 480 and 960 share read-only tables; other sizes allocate a new window.

func GetWindowSquareBuffer

func GetWindowSquareBuffer(overlap int) []float32

GetWindowSquareBuffer returns precomputed w[i]^2 values for the overlap window. This avoids recomputing window[i]*window[i] inside hot comb-filter loops.

func GetWindowSquareBufferF32

func GetWindowSquareBufferF32(overlap int) []float32

GetWindowSquareBufferF32 returns float-build w[i]^2 values for comb-filter overlap interpolation.

func IMDCT

func IMDCT(spectrum []float32) []float32

IMDCT computes the inverse MDCT of frequency coefficients. Input: n frequency bins (spectrum) Output: 2*n time samples

For power-of-2 sizes, uses FFT-based approach for O(n log n) complexity. For other sizes (like CELT's 120, 240, 480, 960), uses direct computation which is O(n^2) but handles any size correctly.

Reference: RFC 6716 Section 4.3.5, libopus celt/mdct.c

func IMDCTDirect

func IMDCTDirect(spectrum []float32) []float32

IMDCTDirect computes IMDCT per RFC 6716 Section 4.3.5. Formula: y[n] = sum_{k=0}^{N-1} X[k] * cos(pi/N * (n + 0.5 + N/2) * (k + 0.5)) Input: N frequency coefficients Output: 2*N time samples Normalization: matches libopus test_unit_mdct.c inverse (no extra scaling)

This is O(n^2) but mathematically exact and handles non-power-of-2 sizes (like CELT's 120, 240, 480, 960) that the FFT-based approach cannot.

func IMDCTOverlapWithPrev

func IMDCTOverlapWithPrev(spectrum, prevOverlap []float32, overlap int) []float32

IMDCTOverlapWithPrev computes CELT IMDCT using the provided overlap history. The returned slice includes frameSize+overlap samples.

func IMDCTShort

func IMDCTShort(coeffs []float32, shortBlocks int) []float32

IMDCTShort computes IMDCT for transient frames with multiple short blocks. coeffs: interleaved coefficients for shortBlocks MDCTs shortBlocks: number of short MDCTs (2, 4, or 8) Returns: interleaved time samples with proper overlap handling.

In transient mode, CELT uses multiple shorter MDCTs instead of one long MDCT. This provides better time resolution for transients (like drum hits) at the cost of reduced frequency resolution.

Reference: libopus celt/celt_decoder.c, transient mode handling

func InitCaps

func InitCaps(nbBands, lm, channels int) []int32

InitCaps initializes band caps for allocation. Exported for testing.

func InitCapsInto

func InitCapsInto(caps []int32, nbBands, lm, channels int)

InitCapsInto computes the same per-band caps into caller-owned storage. CELT's fixed encoder keeps this slice across frames to avoid a per-packet allocation in the custom mode path.

func IntensityStereo

func IntensityStereo(mono []float32, invert bool) (left, right []float32)

IntensityStereo creates stereo from mono with optional inversion. In intensity stereo mode, both channels share the same spectral shape but may have opposite signs. This is efficient for high-frequency content where the ear is less sensitive to phase.

Parameters:

  • mono: the mid channel coefficients
  • invert: if true, right channel is inverted (sign flipped)

Returns: left and right coefficient arrays

func InterleaveStereoF32

func InterleaveStereoF32(left, right []float32) []float32

InterleaveStereoF32 combines separate float-build L and R arrays into interleaved format.

func InterleaveStereoInto

func InterleaveStereoInto(left, right, interleaved []celtNorm)

InterleaveStereoInto combines the common prefix of separate L and R slices into interleaved stereo. interleaved must have length at least twice the common-prefix length. Extra destination elements remain unchanged; if the destination is too short or either source is empty, the function returns without writing.

func InterleaveStereoIntoF32

func InterleaveStereoIntoF32(left, right, interleaved []float32)

InterleaveStereoIntoF32 combines separate float-build L and R arrays into a pre-allocated interleaved slice.

func IsBandCoded

func IsBandCoded(mask uint32, band int) bool

IsBandCoded checks if a band was coded (received pulses). mask: collapse mask band: band index Returns: true if the band received non-zero bit allocation.

func KissFFT32ToScaledInterleaved added in v0.2.5

func KissFFT32ToScaledInterleaved(outRI []float32, x []complex64, scale float32)

KissFFT32ToScaledInterleaved mirrors libopus opus_fft_c and writes output directly as interleaved real/imag float32 pairs into outRI: [re0, im0, ...]. outRI must have length >= 2*len(x).

func KissFFT32ToScaledWithScratch

func KissFFT32ToScaledWithScratch(out []complex64, x []complex64, scale float32, scratch []float32)

KissFFT32ToScaledWithScratch mirrors libopus opus_fft_c: it applies the kiss_fft_state scale while bit-reversing input into the interleaved float32 FFT scratch (length >= 2*len(x) to avoid allocations).

func KissFFT32ToWithScratch

func KissFFT32ToWithScratch(out []complex64, x []complex64, scratch []float32)

KissFFT32ToWithScratch performs a forward complex FFT into out using caller- provided interleaved float32 scratch. scratch should have length >= 2*len(x) to avoid allocations.

func LMToFrameSize

func LMToFrameSize(lm int) int

LMToFrameSize converts LM (log mode) index to frame size in samples.

func LPCNetFIRXCorrKernel4Float32 added in v0.2.0

func LPCNetFIRXCorrKernel4Float32(x, y []float32, sum *[4]float32, length int)

LPCNetFIRXCorrKernel4Float32 runs the selected CELT xcorr kernel used by libopus celt_fir_c from dnn/lpcnet_enc.c. On amd64 SIMD builds this keeps the SSE even/odd accumulator order selected by celt/x86/x86_celt_map.c.

func LPCNetInnerProdFloat32 added in v0.2.0

func LPCNetInnerProdFloat32(x, y []float32, length int) float32

LPCNetInnerProdFloat32 runs the selected celt_inner_prod kernel at the same libopus compute_frame_features callsite.

func LibopusIMDCTF32

func LibopusIMDCTF32(spectrum []float32, prevOverlap []float32, overlap int) []float32

LibopusIMDCTF32 implements IMDCT following libopus clt_mdct_backward_c structure. This is the float32 version for exact matching with libopus's floating-point behavior.

Input: spectrum of length N2 (e.g., 960) Output: N2 + overlap samples (windowed IMDCT output) prevOverlap: previous frame's overlap buffer (length = overlap) overlap: overlap size (e.g., 120)

Returns: frame samples (length N2 + overlap)

func MDCT

func MDCT(samples []float32) []float32

MDCT computes the forward Modified Discrete Cosine Transform. For CELT-typical inputs (frameSize+Overlap), this uses the short-overlap algorithm from libopus. For legacy 2*N inputs, it falls back to the direct MDCT formula.

func MDCTForwardWithOverlapFloat32

func MDCTForwardWithOverlapFloat32(samples []float32, overlap int) []float32

MDCTForwardWithOverlapFloat32 computes the CELT float-build MDCT without widening caller-owned signal scratch.

func MDCTShort

func MDCTShort(samples []float32, shortBlocks int) []float32

MDCTShort computes the forward MDCT for transient frames with multiple short blocks. This processes multiple short MDCTs and interleaves the coefficients in the same format expected by IMDCTShort.

samples: interleaved time samples for shortBlocks MDCTs shortBlocks: number of short MDCTs (2, 4, or 8) Returns: interleaved frequency coefficients

In transient mode, CELT uses multiple shorter MDCTs instead of one long MDCT. This provides better time resolution for transients at the cost of reduced frequency resolution.

Reference: libopus celt/celt_encoder.c, transient mode handling

func MidSideToLR

func MidSideToLR(mid, side []float32, theta float32) (left, right []float32)

MidSideToLR converts mid-side stereo to left-right. The conversion uses a rotation matrix controlled by theta:

L = cos(theta) * M + sin(theta) * S
R = cos(theta) * M - sin(theta) * S

Parameters:

  • mid: mid channel coefficients (M = (L+R)/2)
  • side: side channel coefficients (S = (L-R)/2)
  • theta: stereo angle in radians (0 = mono, pi/2 = full stereo)

Returns: left and right channel coefficient arrays

func NeedsAntiCollapse

func NeedsAntiCollapse(mask uint32, band int) bool

NeedsAntiCollapse checks if a band collapsed (no pulses in transient frame). mask: collapse mask from current frame band: band index to check Returns: true if the band collapsed and needs anti-collapse noise injection.

Reference: RFC 6716 Section 4.3.5

func NormalizeBandsToArrayInto

func NormalizeBandsToArrayInto(mdctCoeffs []float32, nbBands, frameSize int, norm []celtNorm, bandE []celtEner)

NormalizeBandsToArrayInto normalizes bands into a provided contiguous array. This is the zero-allocation version - caller provides norm and bandE buffers.

Parameters:

  • mdctCoeffs: MDCT coefficients to normalize
  • nbBands: number of bands
  • frameSize: frame size in samples
  • norm: output buffer (length >= frameSize)
  • bandE: scratch buffer for celt_ener band amplitudes (length >= nbBands)

Reference: libopus celt/bands.c normalise_bands() (float path, lines 172-187)

func NormalizeBandsToArrayIntoF32

func NormalizeBandsToArrayIntoF32(mdctCoeffs []float32, nbBands, frameSize int, norm []celtNorm, bandE []celtEner)

NormalizeBandsToArrayIntoF32 normalizes float-build MDCT coefficients into a provided contiguous array.

func NormalizeBandsToArrayIntoF32BinMul

func NormalizeBandsToArrayIntoF32BinMul(mdctCoeffs []float32, nbBands, binMul int, norm []celtNorm, bandE []celtEner)

NormalizeBandsToArrayIntoF32BinMul normalizes float-build MDCT coefficients using an explicit bin multiplier M=1<<LM. Band edges are eBands[i]*M, matching compute_band_energies()/normalise_bands(). The 48 kHz path uses M=frameSize/120 via NormalizeBandsToArrayIntoF32; the native 96 kHz HD mode uses M=1<<LM.

func OverlapAdd

func OverlapAdd(current, prevOverlap []float32, overlap int) (output, newOverlap []float32)

OverlapAdd combines the current frame with the previous overlap. This is the core operation for continuous audio reconstruction in CELT.

Parameters:

  • current: windowed IMDCT output for current frame (2*frameSize samples)
  • prevOverlap: tail samples from previous frame (overlap region)
  • overlap: number of overlap samples (typically 120 for CELT)

Returns:

  • output: reconstructed samples (frameSize = len(current)/2)
  • newOverlap: tail to save for next frame's overlap-add

The MDCT/IMDCT overlap-add operation per RFC 6716: - IMDCT of N coefficients produces 2N windowed samples - Output per frame is N samples (frameSize) - First 'overlap' samples: sum current[0:overlap] + prevOverlap - Middle samples: copy from current[overlap:frameSize] - Save current[frameSize:frameSize+overlap] for next frame

func PVQ_U

func PVQ_U(n, k int) uint32

PVQ_U computes U(N,K), the number of codewords where the first position has no pulse. U(N,K) = V(N-1, K) for N > 1 U(1,K) = K (special handling in libopus)

Note: This returns the "counting" U function where U(N,K) = V(N-1,K), not the internal table U used in the recurrence relation.

func PVQ_V

func PVQ_V(n, k int) uint32

PVQ_V computes V(N,K), the total number of PVQ codewords with N dimensions and K pulses (where the sum of absolute values equals K).

V(N,K) = U(N,K) + U(N,K+1)

This uses O(1) table lookup when possible, falling back to computation only for values outside the table range.

Reference: RFC 6716 Section 4.3.4.1, libopus celt/cwrs.c

func PatchTransientDecisionWithScratch

func PatchTransientDecisionWithScratch(newE []celtGLog, oldE []celtGLog, nbEBands, historyStride, start, end, channels int, spreadOld []celtGLog) bool

PatchTransientDecisionWithScratch looks for sudden energy increases to decide whether to force short blocks, taking the spread-old-energy workspace from caller-owned scratch. It mirrors libopus celt/celt_encoder.c patch_transient_decision(). newE has nbEBands values per channel; oldE retains the mode's historyStride even when fewer bands are coded.

func PitchXCorrFloat32 added in v0.2.0

func PitchXCorrFloat32(dst, x, y []float32, length, maxPitch int)

PitchXCorrFloat32 runs the selected CELT pitch correlation kernel used by libopus dnn/nndsp.c:adaconv_process_frame and dnn/lpcnet_enc.c:compute_frame_features. The caller supplies len(x) >= length, len(y) >= length+maxPitch-1, and len(dst) >= maxPitch.

func PulsesToBitsExport

func PulsesToBitsExport(band, lm, pulses int) int

PulsesToBitsExport exposes pulsesToBits for testing.

This helper exists for tests and codec-development tooling and may change.

func QuantEnergyFinalise

func QuantEnergyFinalise(
	re *rangecoding.Encoder,
	start, end int,
	oldEBands, errorVal []celtGLog,
	fineQuant, finePriority []int,
	bitsLeft, channels int,
)

QuantEnergyFinalise uses remaining bits for additional energy refinement. This matches libopus quant_energy_finalise() in quant_bands.c.

Parameters:

  • re: range encoder
  • start, end: band range to encode
  • oldEBands: quantized energies (will be updated)
  • error: quantization error (will be updated)
  • fineQuant: fine bits already used per band
  • finePriority: priority for finalization (0 or 1)
  • bitsLeft: remaining bits to use
  • channels: number of audio channels

Reference: libopus celt/quant_bands.c quant_energy_finalise()

func QuantFineEnergy

func QuantFineEnergy(
	re *rangecoding.Encoder,
	start, end int,
	oldEBands, errorVal []celtGLog,
	prevQuant, extraQuant []int,
	channels int,
)

QuantFineEnergy encodes fine energy refinement bits. This matches libopus quant_fine_energy() in quant_bands.c.

Parameters:

  • re: range encoder
  • start, end: band range to encode
  • oldEBands: quantized energies (will be updated with fine refinement)
  • error: quantization error from coarse encoding (will be updated)
  • prevQuant: previous quantization bits per band (can be nil)
  • extraQuant: fine bits per band (0 = no refinement)
  • channels: number of audio channels

Reference: libopus celt/quant_bands.c quant_fine_energy()

func ScaledBandEnd

func ScaledBandEnd(band, frameSize int) int

ScaledBandEnd returns the scaled MDCT bin index for the end of a band.

func ScaledBandEndBase

func ScaledBandEndBase(band, frameSize, base int) int

ScaledBandEndBase returns the MDCT bin index for the end of a band given an explicit base short-MDCT size.

func ScaledBandStart

func ScaledBandStart(band, frameSize int) int

ScaledBandStart returns the scaled MDCT bin index for the start of a band. For frame sizes larger than 2.5ms, indices are scaled by (frameSize/120).

func ScaledBandStartBase

func ScaledBandStartBase(band, frameSize, base int) int

ScaledBandStartBase returns the MDCT bin index for the start of a band given an explicit base short-MDCT size. With base == 120 this matches ScaledBandStart for the static 48 kHz modes.

func ScaledBandWidth

func ScaledBandWidth(band, frameSize int) int

ScaledBandWidth returns the number of MDCT bins in a band for a given frame size.

func TFAnalysis

func TFAnalysis(X []celtNorm, N0, nbEBands int, isTransient bool, lm int, tfEstimate opusVal16, effectiveBytes int, importance []int32) (tfRes []int32, tfSelect int)

TFAnalysis performs time-frequency analysis to determine optimal TF resolution per band. It uses a Viterbi algorithm to find the best TF resolution settings.

Parameters:

  • X: normalized MDCT coefficients
  • N0: total number of coefficients (per channel)
  • nbEBands: number of bands to analyze
  • isTransient: whether frame uses short blocks
  • lm: log mode (frame size index)
  • tfEstimate: estimate of temporal vs frequency content (0.0 = time, 1.0 = freq)
  • effectiveBytes: available bytes for encoding (affects lambda)
  • importance: per-band importance weights (nil for uniform)

Returns:

  • tfRes: per-band TF resolution flags (0 or 1)
  • tfSelect: TF select flag for bitstream

Reference: libopus celt/celt_encoder.c tf_analysis()

func TFAnalysisWithScratch

func TFAnalysisWithScratch(X []celtNorm, N0, nbEBands int, isTransient bool, lm int, tfEstimate opusVal16, effectiveBytes int, importance []int32, scratch *TFAnalysisScratch, edges []int) (tfRes []int32, tfSelect int)

TFAnalysisWithScratch is the zero-allocation version of TFAnalysis.

func TFEncodeWithSelect

func TFEncodeWithSelect(re *rangecoding.Encoder, start, end int, isTransient bool, tfRes []int32, lm int, tfSelect int)

TFEncodeWithSelect encodes TF resolution with a specific tf_select value. This is called after TFAnalysis to encode the computed TF decisions.

Parameters:

  • re: range encoder
  • start, end: band range
  • isTransient: whether frame uses short blocks
  • tfRes: per-band TF resolution flags (0 or 1)
  • lm: log mode (frame size index)
  • tfSelect: TF select flag from TFAnalysis

Reference: libopus celt/celt_encoder.c tf_encode()

func UpdateCollapseMask

func UpdateCollapseMask(mask *uint32, band int)

UpdateCollapseMask marks a band as having received pulses. mask: pointer to collapse mask (modified in place) band: band index to mark as coded

The collapse mask tracks which bands received non-zero bit allocation. This is used for anti-collapse processing in transient frames.

func ValidFrameSize

func ValidFrameSize(frameSize int) bool

ValidFrameSize reports whether frameSize has an entry in GetModeConfig. It does not check the active sample rate, mode, or build configuration.

func VorbisWindow

func VorbisWindow(i, overlap int) float32

VorbisWindow computes the CELT Vorbis window value at position i for the given overlap length. This matches libopus's window generation.

This window is: - Power-complementary: w[i]^2 + w[overlap-1-i]^2 = 1 - Smooth: continuous first derivative - Good spectral properties: low sidelobe levels

Parameters:

  • i: position in window (0 to overlap-1)
  • overlap: window length (overlap region)

Returns: window value in [0, 1]

Types

type AllocEncodeScratch

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

AllocEncodeScratch holds the reusable output slices for ComputeAllocationWithEncoderStartInto so a caller can run the encode-side bit allocation without per-call allocation. The per-band working buffers inside cltComputeAllocationEncode are fixed-size and stack-allocated, so only these four result slices need to be owned by the caller.

type AllocationResult

type AllocationResult struct {
	BandBits     []int32 // PVQ bit budget per band in Q3 (a.k.a. pulses[] in libopus)
	FineBits     []int32 // Fine energy bits per band
	FinePriority []int32 // Fine energy priority flags per band
	Caps         []int32 // PVQ caps per band in Q3
	Balance      int     // Bit balance carried into quant_all_bands (Q3)
	CodedBands   int     // Number of coded bands
	Intensity    int     // Intensity stereo start band (0 when disabled)
	DualStereo   bool    // Dual stereo flag
}

AllocationResult holds the output of bit allocation computation.

func ComputeAllocation

func ComputeAllocation(totalBits, nbBands, channels int, cap, offsets []int32, trim int, intensity int, dualStereo bool, lm int) AllocationResult

ComputeAllocation computes bit allocation without consuming a range coder. This mirrors libopus clt_compute_allocation() math but skips entropy reads.

func ComputeAllocationWithDecoder

func ComputeAllocationWithDecoder(rd *rangecoding.Decoder, totalBits, nbBands, channels int, cap, offsets []int32, trim int, intensity int, dualStereo bool, lm int) AllocationResult

ComputeAllocationWithDecoder computes bit allocation and consumes the range decoder for skip/intensity/dual-stereo decisions.

func ComputeAllocationWithEncoder

func ComputeAllocationWithEncoder(re *rangecoding.Encoder, totalBitsQ3, nbBands, channels int, cap, offsets []int32, trim int, intensity int, dualStereo bool, lm int, prev int, signalBandwidth int) AllocationResult

ComputeAllocationWithEncoder computes bit allocation in Q3 and encodes the stereo params to the range encoder. This is the encoding counterpart to ComputeAllocationWithDecoder. prev is the last coded band count used for skip hysteresis (0 = no history). signalBandwidth is the highest band index considered to carry signal (>= start).

func ComputeAllocationWithEncoderStart

func ComputeAllocationWithEncoderStart(re *rangecoding.Encoder, start, totalBitsQ3, nbBands, channels int, cap, offsets []int32, trim int, intensity int, dualStereo bool, lm int, prev int, signalBandwidth int) AllocationResult

ComputeAllocationWithEncoderStart is ComputeAllocationWithEncoder for a band subset starting at start (start>0 is the hybrid-CELT case where SILK occupies the low band). It encodes the skip/intensity/dual-stereo decisions over [start,nbBands) to the range encoder.

func ComputeAllocationWithEncoderStartInto

func ComputeAllocationWithEncoderStartInto(sc *AllocEncodeScratch, re *rangecoding.Encoder, start, totalBitsQ3, nbBands, channels int, cap, offsets []int32, trim int, intensity int, dualStereo bool, lm int, prev int, signalBandwidth int) *AllocationResult

ComputeAllocationWithEncoderStartInto is the allocation-free counterpart to ComputeAllocationWithEncoderStart: it writes the result into caller-owned scratch slices (grown once) and returns a pointer into that scratch. It is byte-identical to ComputeAllocationWithEncoderStart; only the result storage differs.

type CELTBandwidth

type CELTBandwidth int

CELTBandwidth represents the audio bandwidth for CELT coding.

const (
	// CELTNarrowband represents 4kHz audio bandwidth (narrowband).
	CELTNarrowband CELTBandwidth = iota
	// CELTMediumband represents 6kHz audio bandwidth (mediumband).
	CELTMediumband
	// CELTWideband represents 8kHz audio bandwidth (wideband).
	CELTWideband
	// CELTSuperwideband represents 12kHz audio bandwidth (super-wideband).
	CELTSuperwideband
	// CELTFullband represents 20kHz audio bandwidth (fullband).
	CELTFullband
)

func BandwidthFromOpusConfig

func BandwidthFromOpusConfig(opusBandwidth int) CELTBandwidth

BandwidthFromOpusConfig returns the CELT bandwidth from an Opus TOC bandwidth field. Opus TOC bandwidth values: 0=NB, 1=MB, 2=WB, 3=SWB, 4=FB

func (CELTBandwidth) EffectiveBands

func (bw CELTBandwidth) EffectiveBands() int

EffectiveBands returns the number of coded bands for the given bandwidth. This is the maximum number of bands; actual coded bands may be fewer depending on frame size and bit allocation.

func (CELTBandwidth) MaxFrequency

func (bw CELTBandwidth) MaxFrequency() int

MaxFrequency returns the maximum audio frequency in Hz for this bandwidth.

func (CELTBandwidth) String

func (bw CELTBandwidth) String() string

String returns the string representation of the bandwidth.

type CeltEner

type CeltEner = celtEner

CeltEner exposes CELT's float-build celt_ener width to sibling packages that need to carry CELT-owned band-energy scratch without widening it.

func ComputeLinearBandAmplitudes

func ComputeLinearBandAmplitudes(mdctCoeffs []float32, nbBands, frameSize int) []CeltEner

ComputeLinearBandAmplitudes computes linear band amplitudes directly from MDCT coefficients. This matches libopus compute_band_energies() which returns sqrt(sum of squares) per band. The result is in LINEAR scale (not log), ready to use as normalization divisor.

CRITICAL: This function computes the ORIGINAL linear amplitude from MDCT coefficients, which must be used for normalization. Do NOT use log-domain energies converted back to linear, as that introduces quantization/roundtrip errors.

Reference: libopus celt/bands.c compute_band_energies() (float path, lines 154-170)

type CeltGLog added in v0.2.0

type CeltGLog = celtGLog

CeltGLog exposes CELT's float-build celt_glog width in exported signatures.

func Amp2Log2

func Amp2Log2(bandE []celtEner, effEnd, end, channels int) []CeltGLog

Amp2Log2 converts amplitude (sqrt energy) to log2 format for quantization. This matches libopus amp2Log2() in quant_bands.c.

The conversion:

bandLogE[i] = celt_log2_db(bandE[i]) - eMeans[i]

Parameters:

  • bandE: band amplitudes (sqrt energy)
  • effEnd: effective end band
  • channels: number of channels

Returns: bandLogE values suitable for quantization

Reference: libopus celt/quant_bands.c amp2Log2()

func ComputeBandEnergy

func ComputeBandEnergy(coeffs []celtNorm) CeltGLog

ComputeBandEnergy computes the per-band log2 amplitude. coeffs: MDCT coefficients for the band Returns: log2(sqrt(sum(x^2))) with libopus epsilon

type CeltNorm

type CeltNorm = celtNorm

CeltNorm exposes CELT's float-build celt_norm width to tests and sibling packages that need to pass normalized CELT vectors without widening them.

func ConvertMidSideToLR

func ConvertMidSideToLR(mid, side []celtNorm) (left, right []CeltNorm)

ConvertMidSideToLR converts mid/side to L/R representation. This is the inverse of ConvertToMidSide.

The conversion is:

left[i] = (mid[i] + side[i]) / sqrt(2)
right[i] = (mid[i] - side[i]) / sqrt(2)

The function processes the common prefix of mid and side.

func ConvertToMidSide

func ConvertToMidSide(left, right []celtNorm) (mid, side []CeltNorm)

ConvertToMidSide converts L/R stereo to mid/side representation.

The conversion is:

mid[i] = (left[i] + right[i]) / sqrt(2)
side[i] = (left[i] - right[i]) / sqrt(2)

The normalization preserves energy: |L|^2 + |R|^2 = |M|^2 + |S|^2. The function processes the common prefix of left and right.

Parameters:

  • left: left channel samples
  • right: right channel samples

Returns: mid and side channel arrays

Reference: RFC 6716 Section 4.3.4

func DenormalizeBand

func DenormalizeBand(shape []celtNorm, energy celtGLog) []CeltNorm

DenormalizeBand scales a normalized band vector by its energy. shape: normalized vector (unit L2 norm) energy: band energy in log2 units (1 = 6 dB) Returns: denormalized MDCT coefficients.

This matches libopus celt/bands.c denormalise_bands().

func FoldBand

func FoldBand(lowband []celtNorm, n int, seed *uint32) []CeltNorm

FoldBand generates a normalized celt_norm vector by folding from a lower band.

func NormalizeVector

func NormalizeVector(v []celtNorm) []CeltNorm

NormalizeVector scales a CELT norm vector to unit L2 norm. If the input vector has zero energy, returns the input unchanged.

type CustomModeConfig

type CustomModeConfig struct {
	Fs            int
	FrameSize     int
	ShortMdctSize int
	NbShortMdcts  int
	LM            int
	Overlap       int
	EffBands      int
	Preemph       [4]float32
}

CustomModeConfig describes an Opus Custom mode with Fs == 400*ShortMdctSize. These modes use the standard 48 kHz eBands, logN and allocation tables. ShortMdctSize determines band-bin scaling and overlap; Fs selects preemphasis.

Band edges use eBands[i] * (FrameSize / ShortMdctSize), equal to eBands[i] << LM, matching libopus celt/bands.c. Standard 48 kHz modes use size 120.

Reference: libopus celt/modes.c opus_custom_mode_create() (CUSTOM_MODES).

type Decoder

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

Decoder decodes CELT frame data and synthesizes PCM. It retains band-energy prediction, overlap, de-emphasis, postfilter, and loss history across frames. Its scratch and history are mutable, so use one decoder per stream and serialize access. See RFC 6716 Section 4.3.

func NewDecoder

func NewDecoder(channels int) *Decoder

NewDecoder creates a new CELT decoder with the given number of channels. Valid channel counts are 1 (mono) or 2 (stereo). The decoder is ready to process CELT frames after creation.

func (*Decoder) AccumulateFrameHybridWithPacketStereo added in v0.2.0

func (d *Decoder) AccumulateFrameHybridWithPacketStereo(rd *rangecoding.Decoder, dataLen, frameSize int, packetStereo bool, out []float32) error

AccumulateFrameHybridWithPacketStereo decodes CELT bands starting at band 17 from the range decoder positioned at the CELT payload, then accumulates the decoded signal onto out, which contains the SILK low band. dataLen is the main-payload length in bytes after redundancy parsing; frameSize is the per-channel CELT sample count at the active mode rate. out uses the decoder's configured API rate and channel layout. A payload length of at most one byte conceals only the CELT high band. This follows libopus opus_decoder.c:opus_decode_frame with celt_accum=1.

func (*Decoder) AccumulateFrameWithPacketStereoAtAPIRate added in v0.2.0

func (d *Decoder) AccumulateFrameWithPacketStereoAtAPIRate(data []byte, frameSize int, packetStereo bool, out []float32) error

AccumulateFrameWithPacketStereoAtAPIRate decodes a frame at the decoder's API sample rate and adds it onto out (libopus celt_accum). opus_decode_frame uses it for the 2.5 ms CELT silence frame that fades out the CELT overlap on a Hybrid->SILK transition.

func (*Decoder) Bandwidth

func (d *Decoder) Bandwidth() CELTBandwidth

Bandwidth returns the current CELT bandwidth setting.

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) DecodeBands

func (d *Decoder) DecodeBands(
	energies []celtGLog,
	bandBits []int,
	nbBands int,
	stereo bool,
	frameSize int,
) []CeltNorm

DecodeBands decodes all frequency bands from the bitstream. energies: per-band energy values (from coarse + fine energy decoding) bandBits: bits allocated per band (from bit allocation) nbBands: number of bands to decode stereo: true if stereo mode frameSize: frame size in samples (120, 240, 480, 960) Returns: MDCT coefficients (denormalized) of length frameSize.

The output is zero-padded to frameSize. Band coefficients fill bins 0 to totalBins-1, where totalBins = sum(ScaledBandWidth(i, frameSize) for i in 0..nbBands-1). Upper bins (totalBins to frameSize-1) remain zero, representing highest frequencies. This ensures IMDCT receives exactly frameSize coefficients, producing correct sample count.

func (*Decoder) DecodeBandsStereo

func (d *Decoder) DecodeBandsStereo(
	energiesL, energiesR []celtGLog,
	bandBits []int,
	nbBands int,
	frameSize int,
	intensity int,
) (left, right []CeltNorm)

DecodeBandsStereo decodes all frequency bands in stereo mode. energiesL/R: per-band energies for left/right channels bandBits: bits allocated per band nbBands: number of bands frameSize: frame size in samples intensity: intensity stereo start band (-1 if not used) Returns: left and right channel MDCT coefficients, each of length frameSize.

In stereo mode, bands can use: 1. Dual stereo: separate PVQ vectors for L and R 2. Mid-side: decode mid/side and rotate to L/R 3. Intensity: copy mono to both with sign flag

Output is zero-padded to frameSize per channel for correct IMDCT operation.

Reference: libopus celt/bands.c quant_all_bands() stereo path

func (*Decoder) DecodeCoarseEnergy

func (d *Decoder) DecodeCoarseEnergy(nbBands int, intra bool, lm int) []CeltGLog

DecodeCoarseEnergy decodes coarse band energies in log2 units (1 = 6 dB). intra=true: no inter-frame prediction (first frame or after loss) intra=false: uses alpha prediction from previous frame Reference: RFC 6716 Section 4.3.2, libopus celt/quant_bands.c unquant_coarse_energy()

func (*Decoder) DecodeCoarseEnergyWithDecoder

func (d *Decoder) DecodeCoarseEnergyWithDecoder(rd *rangecoding.Decoder, nbBands int, intra bool, lm int) []CeltGLog

DecodeCoarseEnergyWithDecoder decodes coarse energies using an explicit range decoder. This variant allows passing a range decoder directly rather than using d.rangeDecoder.

func (*Decoder) DecodeEnergyFinalise

func (d *Decoder) DecodeEnergyFinalise(energies []celtGLog, nbBands int, fineQuant []int32, finePriority []int32, bitsLeft int)

DecodeEnergyFinalise consumes leftover bits for additional energy refinement. This mirrors libopus unquant_energy_finalise(). For non-hybrid mode, use start=0.

func (*Decoder) DecodeEnergyFinaliseRange

func (d *Decoder) DecodeEnergyFinaliseRange(start, end int, energies []celtGLog, fineQuant []int32, finePriority []int32, bitsLeft int)

DecodeEnergyFinaliseRange consumes leftover bits for energy refinement in range [start, end). This mirrors libopus unquant_energy_finalise() which takes both start and end parameters. For hybrid mode, start should be HybridCELTStartBand (17).

func (*Decoder) DecodeEnergyRemainder

func (d *Decoder) DecodeEnergyRemainder(energies []celtGLog, nbBands int, remainderBits []int32)

DecodeEnergyRemainder uses remaining bits for additional energy precision. Called after all PVQ bands decoded, uses leftover bits from bit allocation. Reference: RFC 6716 Section 4.3.2, libopus celt/quant_bands.c unquant_energy_finalise()

func (*Decoder) DecodeEnergyRemainderWithDecoder

func (d *Decoder) DecodeEnergyRemainderWithDecoder(rd *rangecoding.Decoder, energies []celtGLog, nbBands int, remainderBits []int32)

DecodeEnergyRemainderWithDecoder uses remainder bits with an explicit range decoder.

func (*Decoder) DecodeFineEnergy

func (d *Decoder) DecodeFineEnergy(energies []celtGLog, nbBands int, fineBits []int32)

DecodeFineEnergy adds fine energy precision to coarse values. fineBits[band] specifies bits allocated for refinement (0 = no refinement). Reference: RFC 6716 Section 4.3.2, libopus celt/quant_bands.c unquant_fine_energy()

func (*Decoder) DecodeFineEnergyRange

func (d *Decoder) DecodeFineEnergyRange(energies []celtGLog, start, end int, fineBits []int32)

DecodeFineEnergyRange adds fine energy precision for bands in [start, end). For hybrid mode, start should be HybridCELTStartBand (17), matching libopus unquant_fine_energy().

func (*Decoder) DecodeFineEnergyWithDecoder

func (d *Decoder) DecodeFineEnergyWithDecoder(rd *rangecoding.Decoder, energies []celtGLog, nbBands int, fineBits []int32)

DecodeFineEnergyWithDecoder adds fine energy precision using an explicit range decoder.

func (*Decoder) DecodeFrame

func (d *Decoder) DecodeFrame(data []byte, frameSize int) ([]float32, error)

DecodeFrame decodes a CELT payload without Opus framing. frameSize is the per-channel sample count. Payloads of at most one byte request packet-loss concealment. The result is interleaved float32 PCM for stereo decoders.

func (*Decoder) DecodeFrameAtAPIRate

func (d *Decoder) DecodeFrameAtAPIRate(data []byte, frameSize int) ([]float32, error)

DecodeFrameAtAPIRate decodes a frame and returns PCM at the decoder's API sample rate, choosing packet stereo from the decoder channel count.

func (*Decoder) DecodeFrameWithDecoder

func (d *Decoder) DecodeFrameWithDecoder(rd *rangecoding.Decoder, frameSize int) ([]float32, error)

DecodeFrameWithDecoder decodes a CELT frame from an initialized range decoder, starting at band 0. Callers that need Hybrid band accumulation use Decoder.AccumulateFrameHybridWithPacketStereo.

func (*Decoder) DecodeFrameWithPacketStereo

func (d *Decoder) DecodeFrameWithPacketStereo(data []byte, frameSize int, packetStereo bool) ([]float32, error)

DecodeFrameWithPacketStereo decodes a CELT frame with explicit packet stereo flag. This handles the case where the packet's stereo flag differs from the decoder's configured channels.

func (*Decoder) DecodeFrameWithPacketStereoAtAPIRate

func (d *Decoder) DecodeFrameWithPacketStereoAtAPIRate(data []byte, frameSize int, packetStereo bool) ([]float32, error)

DecodeFrameWithPacketStereoAtAPIRate decodes frameSize samples per channel at the decoder's API rate. Standard modes below 48 kHz decode a frameSize times downsampleFactor block at 48 kHz and downsample it; native 96 kHz HD mode decodes at 96 kHz with no downsampling.

func (*Decoder) DecodeFrameWithPacketStereoToFloat32

func (d *Decoder) DecodeFrameWithPacketStereoToFloat32(data []byte, frameSize int, packetStereo bool, out []float32) error

DecodeFrameWithPacketStereoToFloat32 decodes frameSize samples per channel at the decoder's internal rate directly into out. Standard and downsampled modes use a 48 kHz internal rate; native 96 kHz HD mode uses 96 kHz.

func (*Decoder) DecodeFrameWithPacketStereoToFloat32AtAPIRate

func (d *Decoder) DecodeFrameWithPacketStereoToFloat32AtAPIRate(data []byte, frameSize int, packetStereo bool, out []float32) error

DecodeFrameWithPacketStereoToFloat32AtAPIRate decodes into out at the decoder's API sample rate, downsampling the 48 kHz internal block when needed. Native 96 kHz HD mode writes its 96 kHz samples without downsampling.

func (*Decoder) DecodeHybridFECPLC

func (d *Decoder) DecodeHybridFECPLC(frameSize int, out []float32) error

DecodeHybridFECPLC conceals a lost Hybrid-mode CELT frame of frameSize samples at the active CELT mode rate and accumulates the concealed highband onto out, which holds the SILK lowband: libopus celt_decode_with_ec(NULL) with celt_accum=1 (opus_decode_frame for a lost or FEC-recovered Hybrid frame). out is either frameSize*channels long or sized for the API rate, in which case the de-emphasis downsamples into it.

func (*Decoder) DecodeIntensityStereo

func (d *Decoder) DecodeIntensityStereo(mid []celtNorm) (left, right []CeltNorm)

DecodeIntensityStereo decodes intensity stereo for a band. mid: the mid channel coefficients Returns: left and right with optional sign inversion on right.

In intensity stereo, both channels share the same shape but may have opposite signs (determined by a single bit).

Reference: RFC 6716 Section 4.3.4.3

func (*Decoder) DecodeLaplaceTest

func (d *Decoder) DecodeLaplaceTest(fs int, decay int) int

DecodeLaplaceTest is an exported wrapper for testing.

This helper exists for tests and codec-development tooling and may change. It decodes a Laplace-distributed integer using the range coder.

func (*Decoder) DecodeMem added in v0.2.0

func (d *Decoder) DecodeMem(c int) []float32

DecodeMem returns channel c's synthesis delay line, libopus decode_mem[c]: the decoded history followed by the MDCT overlap of the next frame.

func (*Decoder) DecodePVQ

func (d *Decoder) DecodePVQ(n, k int) []CeltNorm

DecodePVQ decodes a PVQ codeword from the range decoder. n: band width (number of MDCT bins) k: number of pulses (from bit allocation) Returns: normalized celt_norm vector of length n with unit L2 norm.

If k == 0, returns a zero vector (caller should fold from another band).

func (*Decoder) DecodeStereoParams

func (d *Decoder) DecodeStereoParams(nbBands int) (intensity, dualStereo int)

DecodeStereoParams decodes stereo parameters (intensity and dual stereo). Reference: RFC 6716 Section 4.3.4, libopus celt/celt_decoder.c

func (*Decoder) DecodeStereoTheta

func (d *Decoder) DecodeStereoTheta(qn int) int

DecodeStereoTheta decodes theta with sign for stereo balance. qn: number of quantization steps (determines precision) Returns: itheta value (0 = pure mid, qn = pure side)

Reference: libopus celt/bands.c compute_theta()

func (*Decoder) EnablePLCStageTrace

func (d *Decoder) EnablePLCStageTrace(foldIndex int) *plcStageTrace

EnablePLCStageTrace arms noise-PLC concealment-stage capture for the foldIndex-th prefilter-and-fold consumed during subsequent decoding. Test-only.

func (*Decoder) EnablePerModeTables

func (d *Decoder) EnablePerModeTables(nbEBands, scaleBase int, eBands []int16, logN []int16, allocVectors []uint8, cacheIndex []int16, cacheBits, cacheCaps []uint8)

EnablePerModeTables installs the per-mode CELT tables for a non-standard Opus Custom mode whose band layout differs from the static 21-band 48 kHz tables. It must be called only for a mode that is neither standard nor in the Fs==400*shortMdctSize family; the standard, family, hybrid and QEXT paths leave perMode nil and stay byte-identical.

eBands has length nbEBands+1; bandAlloc is the 11 x nbEBands allocation matrix (row-major in allocVectors); cacheCaps is (maxLM+1)*2*nbEBands; cacheIndex / cacheBits are the pulse cache. scaleBase is the mode short-MDCT size.

func (*Decoder) EnableSynthesisStageTrace

func (d *Decoder) EnableSynthesisStageTrace() *synthesisStageTrace

EnableSynthesisStageTrace arms intermediate-stage capture for the next decoded frame. Test-only. The returned value is also stored on the decoder; call SynthesisStageTrace after decoding to read the captured buffers.

func (*Decoder) FinalRange

func (d *Decoder) FinalRange() uint32

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

func (*Decoder) GetEnergy

func (d *Decoder) GetEnergy(band, channel int) float32

GetEnergy returns the energy for a specific band and channel from prevEnergy.

func (*Decoder) Init added in v0.2.5

func (d *Decoder) Init(channels int)

Init initializes d in place for channels (1 or 2) so callers can embed celt.Decoder inline without a separate heap allocation.

func (*Decoder) LastPLCFrameWasNeural

func (d *Decoder) LastPLCFrameWasNeural() bool

LastPLCFrameWasNeural reports whether the retained CELT lost-frame cadence is currently in a neural/DRED state.

func (*Decoder) NextRNG

func (d *Decoder) NextRNG() uint32

NextRNG advances the RNG and returns the new value. Uses the same LCG as libopus for deterministic behavior.

func (*Decoder) PLCStageTrace

func (d *Decoder) PLCStageTrace() *plcStageTrace

PLCStageTrace returns the active PLC stage trace, if any.

func (*Decoder) PhaseInversionDisabled

func (d *Decoder) PhaseInversionDisabled() bool

PhaseInversionDisabled reports whether stereo phase inversion is disabled.

func (*Decoder) PostfilterGain

func (d *Decoder) PostfilterGain() float32

PostfilterGain returns the comb filter gain.

func (*Decoder) PostfilterPeriod

func (d *Decoder) PostfilterPeriod() int

PostfilterPeriod returns the pitch period for the postfilter.

func (*Decoder) PostfilterState

func (d *Decoder) PostfilterState() PostfilterState

PostfilterState returns the current and previous postfilter parameters. It returns the zero value when d is nil.

func (*Decoder) PostfilterTapset

func (d *Decoder) PostfilterTapset() int

PostfilterTapset returns the filter tap configuration.

func (*Decoder) PreemphState

func (d *Decoder) PreemphState() []float32

PreemphState returns the de-emphasis filter state. One value per channel.

func (*Decoder) PrevEnergy

func (d *Decoder) PrevEnergy() []float32

PrevEnergy returns the previous frame's band energies. Used for inter-frame energy prediction in coarse energy decoding. Layout: [band0_ch0, band1_ch0, ..., band20_ch0, band0_ch1, ..., band20_ch1]

func (*Decoder) RNG

func (d *Decoder) RNG() uint32

RNG returns the current RNG state.

func (*Decoder) RangeDecoder

func (d *Decoder) RangeDecoder() *rangecoding.Decoder

RangeDecoder returns the current range decoder.

func (*Decoder) Reset

func (d *Decoder) Reset()

Reset clears decoder state for a new stream. It clears frame, synthesis, prediction, and PLC history while retaining the channel count, sample rate, and mode geometry. It resets bandwidth to CELTFullband.

func (*Decoder) SampleRate

func (d *Decoder) SampleRate() int

SampleRate returns the configured API output sample rate.

func (*Decoder) SetAPISampleRate

func (d *Decoder) SetAPISampleRate(sampleRate int) error

SetAPISampleRate selects a standard CELT API output rate: 48, 24, 16, 12, or 8 kHz. Rates below 48 kHz use the corresponding downsample factor from the 48 kHz CELT core; this control does not enable native 96 kHz HD mode.

func (*Decoder) SetBandwidth

func (d *Decoder) SetBandwidth(bw CELTBandwidth)

SetBandwidth sets the CELT bandwidth derived from the Opus TOC.

func (*Decoder) SetComplexity

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

SetComplexity sets decoder complexity (0-10).

func (*Decoder) SetCustomEndBand added in v0.2.0

func (d *Decoder) SetCustomEndBand(endBand int)

SetCustomEndBand selects an explicit CELT end band from a custom frame header. A non-positive value restores the mode's configured/default end.

func (*Decoder) SetDownsample

func (d *Decoder) SetDownsample(factor int)

SetDownsample sets the libopus CELT downsample factor used for lower-rate Opus decoder APIs. Invalid factors fall back to the 48 kHz path.

func (*Decoder) SetEnergy

func (d *Decoder) SetEnergy(band, channel int, energy float32)

SetEnergy sets the energy for a specific band and channel.

func (*Decoder) SetPhaseInversionDisabled

func (d *Decoder) SetPhaseInversionDisabled(disabled bool)

SetPhaseInversionDisabled toggles stereo phase inversion during CELT decoding.

func (*Decoder) SetPostfilter

func (d *Decoder) SetPostfilter(period int, gain float32, tapset int)

SetPostfilter sets the postfilter parameters.

func (*Decoder) SetPreemphState

func (d *Decoder) SetPreemphState(samples []float32)

SetPreemphState copies the given samples to the de-emphasis memory.

func (*Decoder) SetPrevEnergy

func (d *Decoder) SetPrevEnergy(energies []float32)

SetPrevEnergy copies the given energies to the previous energy buffer.

func (*Decoder) SetRNG

func (d *Decoder) SetRNG(seed uint32)

SetRNG sets the RNG state.

func (*Decoder) SetRangeDecoder

func (d *Decoder) SetRangeDecoder(rd *rangecoding.Decoder)

SetRangeDecoder sets the range decoder for the current frame. This must be called before decoding each frame.

func (*Decoder) SnapshotPLCState

func (d *Decoder) SnapshotPLCState() PLCStateSnapshot

SnapshotPLCState returns the current CELT PLC cadence state.

func (*Decoder) SnapshotPreemphasisState

func (d *Decoder) SnapshotPreemphasisState() [2]float32

SnapshotPreemphasisState returns the retained CELT deemphasis memory that libopus keeps in preemph_memD across decode and PLC/DRED loss handling.

func (*Decoder) SynthesisStageTrace

func (d *Decoder) SynthesisStageTrace() *synthesisStageTrace

SynthesisStageTrace returns the active synthesis-stage trace, if any.

func (*Decoder) SynthesizeFloat32

func (d *Decoder) SynthesizeFloat32(coeffs []float32, transient bool, shortBlocks int) []float32

SynthesizeFloat32 runs celt_synthesis for one mono frame of coeffs against decode_mem's MDCT overlap and returns the len(coeffs) output samples. It stores the frame's new MDCT overlap in decode_mem and leaves the decoded history unchanged. It implements plc.CELTSynthesizer.

func (*Decoder) SynthesizeStereoFloat32

func (d *Decoder) SynthesizeStereoFloat32(coeffsL, coeffsR []float32, transient bool, shortBlocks int) []float32

SynthesizeStereoFloat32 is SynthesizeFloat32 for a stereo frame, returning interleaved L/R output in decoder scratch.

type DynallocResult

type DynallocResult struct {
	// MaxDepth is the maximum signal level relative to noise floor (in dB).
	// Used for floor_depth calculation in VBR.
	// Reference: libopus celt_encoder.c lines 1682-1693
	MaxDepth celtGLog

	// Offsets contains per-band allocation offsets for dynamic bit allocation.
	// Bands with high energy variance get extra bits.
	Offsets []int32

	// SpreadWeight contains per-band masking weights for spread decision.
	// Higher values indicate more perceptually important bands.
	SpreadWeight []int32

	// Importance contains per-band importance values (0-13 typically).
	// Used for bit allocation prioritization.
	Importance []int32

	// TotBoost is the total boost in bits (Q3 format).
	// Represents extra bits allocated beyond base target.
	TotBoost int
}

DynallocResult contains the output of dynalloc_analysis. These values are used for VBR target computation and bit allocation.

func DynallocAnalysis

func DynallocAnalysis(
	bandLogE, bandLogE2 []celtGLog,
	oldBandE []celtGLog,
	nbBands, start, end, channels, lsbDepth, lm int,
	logN []int16,
	effectiveBytes int,
	isTransient, vbr, constrainedVBR, lfe bool,
	toneFreq, toneishness float32,
	surroundDynalloc []celtGLog,
	analysisValid bool,
	analysisLeakBoost []uint8,
) DynallocResult

DynallocAnalysis performs dynamic allocation analysis to compute: 1. maxDepth: signal depth relative to noise floor (for VBR floor_depth) 2. offsets: per-band bit allocation offsets 3. spread_weight: per-band masking weights for spread decision 4. importance: per-band importance for allocation prioritization 5. tot_boost: total boost bits for VBR target

Parameters:

  • bandLogE: current frame band energies (log2 domain), [channels * nbBands]
  • bandLogE2: secondary band energies (from second MDCT for transients), [channels * nbBands]
  • oldBandE: previous frame band energies, [channels * nbBands]
  • nbBands: number of frequency bands
  • start: starting band (usually 0)
  • end: ending band (usually nbBands or less)
  • channels: number of audio channels (1 or 2)
  • lsbDepth: bit depth of input (16-24)
  • lm: log2 of frame size multiplier (0=2.5ms, 1=5ms, 2=10ms, 3=20ms)
  • logN: per-band log2 of width in Q8 format
  • effectiveBytes: total available bytes for encoding
  • isTransient: true if frame is transient
  • vbr: true if using variable bitrate
  • constrainedVBR: true if using constrained VBR
  • toneFreq: detected tone frequency in radians/sample (-1 if none)
  • toneishness: tone purity metric (0.0-1.0)

Reference: libopus celt/celt_encoder.c lines 1049-1273

func DynallocAnalysisWithScratch

func DynallocAnalysisWithScratch(
	bandLogE, bandLogE2 []celtGLog,
	oldBandE []celtGLog,
	nbBands, start, end, channels, lsbDepth, lm int,
	logN []int16,
	effectiveBytes int,
	isTransient, vbr, constrainedVBR, lfe bool,
	toneFreq, toneishness float32,
	surroundDynalloc []celtGLog,
	analysisValid bool,
	analysisLeakBoost []uint8,
	scratch *DynallocScratch,
	edges []int,
) DynallocResult

DynallocAnalysisWithScratch is the zero-allocation version of DynallocAnalysis: dynalloc_analysis from celt_encoder.c over the caller's scratch. bandLogE and bandLogE2 hold channels bands of stride nbBands (a nil bandLogE2 reads bandLogE); missing trailing energies read as zero.

type DynallocScratch

type DynallocScratch struct {

	// Result arrays (caller provides these in result struct)
	Offsets      []int32
	SpreadWeight []int32
	Importance   []int32

	// Libopus-width scratch buffers.
	NoiseFloor []float32

	// Masking model buffers
	Mask      []float32
	Sig       []float32
	Follower  []float32
	BandLogE3 []float32
	// contains filtered or unexported fields
}

DynallocScratch holds pre-allocated buffers for DynallocAnalysis.

func (*DynallocScratch) EnsureDynallocScratch

func (s *DynallocScratch) EnsureDynallocScratch(nbBands, channels int)

EnsureDynallocScratch ensures scratch buffers are large enough.

type EncodeOptions

type EncodeOptions struct {
	ForceIntra bool // Force intra mode (no inter-frame prediction)
	Bitrate    int  // Target bitrate in bits per second (0 = default)
}

EncodeOptions provides encoding control options.

type Encoder

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

Encoder encodes audio frames using CELT transform coding. It maintains state across frames for proper audio continuity via energy prediction and overlap-add analysis.

The encoder state mirrors the decoder state to ensure synchronized prediction. This includes: - Energy arrays for inter-frame prediction - Overlap buffer for MDCT overlap-add - Pre-emphasis filter state - RNG state for deterministic folding decisions

Reference: RFC 6716 Section 4.3

func NewEncoder

func NewEncoder(channels int) *Encoder

NewEncoder creates a new CELT encoder with the given number of channels. Valid channel counts are 1 (mono) or 2 (stereo). The encoder is ready to process CELT frames after creation.

The initialization mirrors libopus encoder reset state: - prevEnergy starts at 0.0 (oldBandE cleared) - RNG seed 0 (matches libopus initialization)

func (*Encoder) AnalysisBandwidth

func (e *Encoder) AnalysisBandwidth() int

AnalysisBandwidth returns the current analysis-derived bandwidth index.

func (*Encoder) ApplyDCReject

func (e *Encoder) ApplyDCReject(pcm []float32) []float32

ApplyDCReject applies a DC rejection (high-pass) filter to remove DC offset. This matches libopus dc_reject() which is applied before CELT encoding.

The filter is a simple first-order high-pass:

coef = 6.3 * cutoffHz / sampleRate
out[i] = x[i] - m
m = coef*x[i] + (1-coef)*m

Reference: libopus src/opus_encoder.c dc_reject()

func (*Encoder) ApplyPreemphasis

func (e *Encoder) ApplyPreemphasis(pcm []float32) []float32

ApplyPreemphasis applies the pre-emphasis filter to PCM input samples. Pre-emphasis boosts high frequencies to improve coding efficiency.

The filter equation is:

y[n] = x[n] - PreemphCoef * x[n-1]

This is the inverse of the decoder's de-emphasis filter:

y[n] = x[n] + PreemphCoef * y[n-1]

The filter state is maintained in e.preemphState for frame continuity.

Parameters:

  • pcm: input PCM samples (interleaved if stereo)

Returns: pre-emphasized samples

Reference: RFC 6716 Section 4.3.5, libopus celt/celt_encoder.c Uses PreemphCoef = 0.85 (D03-05-03)

func (*Encoder) ApplyPreemphasisInPlace

func (e *Encoder) ApplyPreemphasisInPlace(pcm []float32)

ApplyPreemphasisInPlace applies pre-emphasis in-place to the input samples. This is more efficient when a copy is not needed.

func (*Encoder) ApplyPreemphasisWithScaling

func (e *Encoder) ApplyPreemphasisWithScaling(pcm []float32) []float32

ApplyPreemphasisWithScaling applies pre-emphasis with signal scaling. Input samples are first scaled from float range [-1.0, 1.0] to signal scale (multiplied by CELTSigScale = 32768), then the pre-emphasis filter is applied.

This matches libopus celt_preemphasis() behavior where samples are scaled and filtered together. The decoder later divides back by the same scale.

func (*Encoder) Bandwidth

func (e *Encoder) Bandwidth() CELTBandwidth

Bandwidth returns the active CELT bandwidth cap.

func (*Encoder) Bitrate

func (e *Encoder) Bitrate() int

Bitrate returns the current target bitrate in bits per second.

func (*Encoder) BitrateToBits

func (e *Encoder) BitrateToBits(frameSize int) int

BitrateToBits returns bitrate_to_bits(st->bitrate, mode->Fs, frameSize) for the configured bitrate.

func (*Encoder) Channels

func (e *Encoder) Channels() int

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

func (*Encoder) Complexity

func (e *Encoder) Complexity() int

Complexity returns the current complexity setting.

func (*Encoder) ComputeBandEnergies

func (e *Encoder) ComputeBandEnergies(mdctCoeffs []float32, nbBands, frameSize int) []CeltGLog

ComputeBandEnergies computes energy for each frequency band from MDCT coefficients. Returns energies in log2 scale, RELATIVE TO MEAN (same as libopus). energies[c*nbBands + band] = log2(amplitude) - eMeans[band]

The energy computation extracts loudness per frequency band: 1. For each band, sum squares of MDCT coefficients 2. Convert to log2 scale: energy = 0.5 * log2(sumSq) 3. Subtract eMeans to make values mean-relative (like libopus amp2Log2)

The decoder adds eMeans back during denormalization, recovering the original. This ensures encoder and decoder use matching gain values.

Reference: RFC 6716 Section 4.3.2, libopus celt/quant_bands.c amp2Log2()

func (*Encoder) ComputeBandEnergiesFloat32Into

func (e *Encoder) ComputeBandEnergiesFloat32Into(mdctCoeffs []float32, nbBands, frameSize int, dst []float32)

ComputeBandEnergiesFloat32Into computes CELT band energies in libopus float-build storage for callers that already carry celt_sig/celt_glog data.

func (*Encoder) ComputeBandEnergiesInto

func (e *Encoder) ComputeBandEnergiesInto(mdctCoeffs []float32, nbBands, frameSize int, dst []celtGLog)

ComputeBandEnergiesInto computes band energies into the provided destination buffer. Use this instead of ComputeBandEnergies when you need to avoid buffer aliasing.

func (*Encoder) ConsecTransient

func (e *Encoder) ConsecTransient() int

ConsecTransient returns the number of consecutive transient frames.

func (*Encoder) ConstrainedVBR

func (e *Encoder) ConstrainedVBR() bool

ConstrainedVBR reports whether VBR is constrained by the configured target.

func (*Encoder) DCRejectEnabled

func (e *Encoder) DCRejectEnabled() bool

DCRejectEnabled reports whether dc_reject is applied in EncodeFrame.

func (*Encoder) DecideIntraMode

func (e *Encoder) DecideIntraMode(energies []celtGLog, startBand, nbBands int, lm int) bool

DecideIntraMode runs libopus-style two-pass intra/inter selection for coarse energy. It performs trial encodes on a saved range coder state and restores state before returning. startBand specifies the first band to encode (0 for CELT-only, 17 for hybrid mode). This matches libopus quant_coarse_energy which iterates from start to end.

func (*Encoder) DelayCompensationEnabled

func (e *Encoder) DelayCompensationEnabled() bool

DelayCompensationEnabled reports whether EncodeFrame applies lookahead delay compensation.

func (*Encoder) DetectTransient

func (e *Encoder) DetectTransient(pcm []float32, frameSize int) bool

DetectTransient analyzes PCM for sudden energy changes. Returns true if the frame should use short MDCT blocks.

Transient detection identifies frames with: - Sharp attacks (drum hits, plucks) - Sudden silence - Energy jumps > 6dB between adjacent sub-blocks

When transient is detected, the encoder uses multiple short MDCTs instead of one long MDCT for better time resolution at the cost of frequency resolution.

Parameters:

  • pcm: pre-emphasized samples, planar like celt_encode_with_ec's in buffer: channel c occupies pcm[c*len(pcm)/channels:]
  • frameSize: frame size in samples (120, 240, 480, or 960)

Returns: true if transient detected and short blocks should be used

Reference: RFC 6716 Section 4.3.1, libopus celt/celt_encoder.c

func (*Encoder) EnablePerModeTables

func (e *Encoder) EnablePerModeTables(nbEBands, scaleBase int, eBands []int16, logN []int16, allocVectors []uint8, cacheIndex []int16, cacheBits, cacheCaps []uint8)

EnablePerModeTables installs the per-mode CELT tables on the encoder for a non-standard Opus Custom mode whose band layout differs from the static 21-band 48 kHz tables. It mirrors Decoder.EnablePerModeTables and must be called only for a mode that is neither standard nor in the Fs==400*shortMdctSize family; the standard, family, hybrid and QEXT encode paths leave perMode nil and stay byte-identical.

func (*Encoder) EncodeBandPVQ

func (e *Encoder) EncodeBandPVQ(shape []CeltNorm, n, k int)

EncodeBandPVQ encodes a normalized band shape using PVQ. k is the number of pulses (determined by bit allocation via bitsToKEncode).

Parameters:

  • shape: normalized band shape (unit L2 norm)
  • n: band width (number of MDCT bins)
  • k: number of pulses

The encoded data consists of a single PVQ index encoded uniformly with V(n,k) possible values.

Reference: libopus celt/bands.c quant_band()

func (*Encoder) EncodeBands

func (e *Encoder) EncodeBands(shapesL, shapesR [][]CeltNorm, bandBits []int, nbBands, frameSize int)

EncodeBands encodes all bands using PVQ. shapesL, shapesR: normalized band shapes for Left/Right (R is nil for mono) bandBits: bit allocation per band from ComputeAllocation nbBands: number of bands frameSize: frame size in samples (120, 240, 480, 960)

For each band: - If bits <= 0: skip (band will be folded by decoder) - Otherwise: compute k from bits and encode via EncodeBandPVQ - For stereo, bits are split between L and R (Dual Stereo)

Reference: libopus celt/bands.c quant_all_bands()

func (*Encoder) EncodeBandsHybrid

func (e *Encoder) EncodeBandsHybrid(shapesL, shapesR [][]CeltNorm, bandBits []int, nbBands, frameSize, startBand int)

EncodeBandsHybrid encodes bands for hybrid mode (starting from startBand). In hybrid mode, bands 0 to startBand-1 are handled by SILK. Only bands from startBand onwards are PVQ encoded.

Reference: RFC 6716 Section 3.2 - Hybrid mode uses start_band=17 for CELT

func (*Encoder) EncodeCoarseEnergy

func (e *Encoder) EncodeCoarseEnergy(energies []celtGLog, nbBands int, intra bool, lm int) []CeltGLog

EncodeCoarseEnergy encodes coarse (6dB step) band energies. This mirrors decoder's DecodeCoarseEnergy exactly (in reverse). intra=true: no inter-frame prediction (first frame or after loss) intra=false: uses alpha prediction from previous frame

Returns the quantized energies (after encoding) for use by fine energy encoding.

Reference: RFC 6716 Section 4.3.2, libopus celt/quant_bands.c quant_coarse_energy()

func (*Encoder) EncodeCoarseEnergyHybrid

func (e *Encoder) EncodeCoarseEnergyHybrid(energies []celtGLog, nbBands int, intra bool, lm int, startBand int) []CeltGLog

EncodeCoarseEnergyHybrid encodes coarse energies for hybrid mode. Only encodes bands from startBand onwards (typically band 17).

func (*Encoder) EncodeCoarseEnergyRange

func (e *Encoder) EncodeCoarseEnergyRange(energies []celtGLog, start, end int, intra bool, lm int) []CeltGLog

EncodeCoarseEnergyRange encodes coarse energies for bands in [start, end). This mirrors EncodeCoarseEnergy but only processes the specified band range. Bands outside the range keep their previous energy values.

func (*Encoder) EncodeCoarseEnergyWithEncoder

func (e *Encoder) EncodeCoarseEnergyWithEncoder(re *rangecoding.Encoder, energies []celtGLog, nbBands int, intra bool, lm int) []CeltGLog

EncodeCoarseEnergyWithEncoder encodes coarse energies using an explicit range encoder. This variant allows passing a range encoder directly rather than using e.rangeEncoder.

func (*Encoder) EncodeEnergyFinalise

func (e *Encoder) EncodeEnergyFinalise(energies []celtGLog, quantizedEnergies []celtGLog, nbBands int, fineQuant []int32, finePriority []int32, bitsLeft int)

EncodeEnergyFinalise consumes leftover bits for additional energy refinement. This mirrors decoder's DecodeEnergyFinalise (libopus quant_energy_finalise). energies: original target energies quantizedEnergies: current quantized energies (coarse + fine) fineQuant/finePriority: allocation outputs bitsLeft: remaining whole bits available in the packet

func (*Encoder) EncodeEnergyFinaliseRange

func (e *Encoder) EncodeEnergyFinaliseRange(energies []celtGLog, quantizedEnergies []celtGLog, start, end int, fineQuant []int32, finePriority []int32, bitsLeft int)

EncodeEnergyFinaliseRange consumes leftover bits for energy refinement in [start, end).

func (*Encoder) EncodeEnergyFinaliseRangeFromError

func (e *Encoder) EncodeEnergyFinaliseRangeFromError(quantizedEnergies []celtGLog, start, end int, fineQuant []int32, finePriority []int32, bitsLeft int)

EncodeEnergyFinaliseRangeFromError mirrors libopus quant_energy_finalise() for hybrid range coding, consuming the in-place residual state from coarse/fine.

func (*Encoder) EncodeEnergyRemainder

func (e *Encoder) EncodeEnergyRemainder(energies []celtGLog, quantizedEnergies []celtGLog, nbBands int, remainderBits []int)

EncodeEnergyRemainder encodes any leftover precision bits. Called after PVQ bands decoded, uses leftover bits from bit allocation. This mirrors decoder's DecodeEnergyRemainder exactly (in reverse).

Reference: RFC 6716 Section 4.3.2, libopus celt/quant_bands.c quant_energy_finalise()

func (*Encoder) EncodeEnergyRemainderWithEncoder

func (e *Encoder) EncodeEnergyRemainderWithEncoder(re *rangecoding.Encoder, energies []celtGLog, quantizedEnergies []celtGLog, nbBands int, remainderBits []int)

EncodeEnergyRemainderWithEncoder encodes remainder bits using an explicit range encoder.

func (*Encoder) EncodeFineEnergy

func (e *Encoder) EncodeFineEnergy(energies []celtGLog, quantizedCoarse []celtGLog, nbBands int, fineBits []int32)

EncodeFineEnergy encodes fine energy refinement bits. This adds fractional precision to coarse energy values. fineBits[band] specifies bits allocated for refinement (0 = no refinement).

This mirrors decoder's DecodeFineEnergy exactly (in reverse).

Reference: RFC 6716 Section 4.3.2, libopus celt/quant_bands.c quant_fine_energy()

func (*Encoder) EncodeFineEnergyHybrid

func (e *Encoder) EncodeFineEnergyHybrid(energies []celtGLog, quantizedCoarse []celtGLog, nbBands int, fineBits []int32, startBand int)

EncodeFineEnergyHybrid encodes fine energies for hybrid mode. Only encodes bands from startBand onwards.

func (*Encoder) EncodeFineEnergyRange

func (e *Encoder) EncodeFineEnergyRange(energies []celtGLog, quantizedCoarse []celtGLog, start, end int, fineBits []int32)

EncodeFineEnergyRange encodes fine energies for bands in [start, end).

func (*Encoder) EncodeFineEnergyRangeFromError

func (e *Encoder) EncodeFineEnergyRangeFromError(quantizedEnergies []celtGLog, start, end int, fineBits []int32)

EncodeFineEnergyRangeFromError mirrors libopus quant_fine_energy() for hybrid range coding, consuming the in-place coarse error residual state.

func (*Encoder) EncodeFineEnergyWithEncoder

func (e *Encoder) EncodeFineEnergyWithEncoder(re *rangecoding.Encoder, energies []celtGLog, quantizedCoarse []celtGLog, nbBands int, fineBits []int32)

EncodeFineEnergyWithEncoder encodes fine energies using an explicit range encoder.

func (*Encoder) EncodeFrame

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

EncodeFrame encodes one CELT frame of float32 PCM into its own range coder and returns the packet bytes: celt_encode_with_ec with enc == NULL and the payload budget set with SetMaxPayloadBytes (or the budget opus_encode_native hands CELT without one). pcm is interleaved when the encoder is stereo. frameSize is given at the encoder's API sample rate; at sub-48 kHz rates the input is upsampled to the 48 kHz core block internally.

func (*Encoder) EncodeFrameWithOptions

func (e *Encoder) EncodeFrameWithOptions(pcm []float32, frameSize int, opts EncodeOptions) ([]byte, error)

EncodeFrameWithOptions encodes a frame with additional control options.

func (*Encoder) EncodeStereoFrame

func (e *Encoder) EncodeStereoFrame(left, right []float32, frameSize int) ([]byte, error)

EncodeStereoFrame encodes a stereo frame from separate L/R channels. left: left channel samples right: right channel samples frameSize: 120, 240, 480, or 960 samples per channel

func (*Encoder) EncodeStereoParams

func (e *Encoder) EncodeStereoParams(nbBands int) int

EncodeStereoParams encodes a no-intensity stereo parameter set with dual stereo enabled. It writes nbBands as the intensity band, then writes a dual-stereo flag of 1. It returns -1 to indicate that intensity stereo is disabled. If no range encoder is active, it returns -1 without writing.

DecodeStereoParams reads the intensity band before the dual-stereo flag.

func (*Encoder) EncodeStereoParamsWithIntensity

func (e *Encoder) EncodeStereoParamsWithIntensity(nbBands, intensityBand int, dualStereo bool) int

EncodeStereoParamsWithIntensity encodes stereo parameters with optional intensity stereo. intensityBand selects the first intensity-stereo band when it is in [0, nbBands); any other value disables intensity stereo. dualStereo selects independent channel coding below the intensity band, or for all bands when intensity stereo is disabled. The return value is intensityBand when enabled, or -1 when disabled. If no range encoder is active, it returns -1 without writing.

func (*Encoder) EncodeWithEC added in v0.2.0

func (e *Encoder) EncodeWithEC(pcm []float32, frameSize, nbCompressedBytes int, enc *rangecoding.Encoder) ([]byte, error)

EncodeWithEC ports celt_encode_with_ec with a caller-owned range coder (enc != NULL): the frame continues the stream enc already holds (the SILK layer of a hybrid frame), nbCompressedBytes is the payload budget of the whole range coder (nb_compr_bytes), and the bytes enc filled on entry count against it. It finishes enc (ec_enc_done) and returns its nbCompressedBytes payload bytes.

func (*Encoder) EnergyMask

func (e *Encoder) EnergyMask() []float32

EnergyMask returns the current per-band surround mask.

func (*Encoder) EnsureScratch

func (e *Encoder) EnsureScratch(frameSize int)

EnsureScratch ensures all scratch buffers are properly sized for the given frame size. Call this before using the encoder's scratch-aware methods from an external path (e.g., hybrid encoding) that does not go through EncodeFrame.

func (*Encoder) FinalRange

func (e *Encoder) FinalRange() uint32

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

func (*Encoder) FrameCount

func (e *Encoder) FrameCount() int

FrameCount returns the number of frames encoded.

func (*Encoder) GetEnergy

func (e *Encoder) GetEnergy(band, channel int) float32

GetEnergy returns the energy for a specific band and channel from prevEnergy.

func (*Encoder) GetLastBandLogE

func (e *Encoder) GetLastBandLogE() []CeltGLog

GetLastBandLogE returns the last frame's primary band log-energies. These are the bandLogE values passed to DynallocAnalysis.

func (*Encoder) GetLastBandLogE2

func (e *Encoder) GetLastBandLogE2() []CeltGLog

GetLastBandLogE2 returns the last frame's secondary band log-energies. For transients, this is from the long MDCT; otherwise same as bandLogE.

func (*Encoder) GetLastDynalloc

func (e *Encoder) GetLastDynalloc() DynallocResult

GetLastDynalloc returns the last computed dynalloc result. This is computed during encoding and stored for the next frame's VBR decisions.

func (*Encoder) HFAverage

func (e *Encoder) HFAverage() int

HFAverage returns the high-frequency average used for tapset decision. This is updated during SpreadingDecision when updateHF=true.

func (*Encoder) IncrementFrameCount

func (e *Encoder) IncrementFrameCount()

IncrementFrameCount increments the frame counter. Call this after successfully encoding a frame.

func (*Encoder) IsHybrid

func (e *Encoder) IsHybrid() bool

IsHybrid returns true if the encoder is in hybrid mode.

func (*Encoder) IsIntraFrame

func (e *Encoder) IsIntraFrame() bool

IsIntraFrame returns a conservative pre-encode advisory value.

The actual intra/inter decision is made inside EncodeFrame once band energies are available, so this helper is intentionally not a packet-exact predictor of the libopus-style two-pass coarse-energy search.

func (*Encoder) LFE

func (e *Encoder) LFE() bool

LFE reports whether LFE mode constraints are enabled.

func (*Encoder) LSBDepth

func (e *Encoder) LSBDepth() int

LSBDepth returns the current input signal LSB depth.

func (*Encoder) LSBQuantizationEnabled

func (e *Encoder) LSBQuantizationEnabled() bool

LSBQuantizationEnabled reports whether EncodeFrame applies the CELT-local LSB-depth rounding step.

func (*Encoder) LastCodedBands

func (e *Encoder) LastCodedBands() int

LastCodedBands returns the last coded band count used for allocation skip decisions.

func (*Encoder) LastTonality

func (e *Encoder) LastTonality() OpusVal16

LastTonality returns the most recently computed tonality estimate. The value ranges from 0 (noise-like spectrum) to 1 (pure tone). This is used by computeVBRTarget for bit allocation decisions.

func (*Encoder) NextRNG

func (e *Encoder) NextRNG() uint32

NextRNG advances the RNG and returns the new value. Uses the same LCG as libopus for deterministic behavior (D03-04-03).

func (*Encoder) NormalizeBands

func (e *Encoder) NormalizeBands(mdctCoeffs []CeltNorm, energies []celtGLog, nbBands, frameSize int) [][]CeltNorm

NormalizeBands divides each band's MDCT coefficients by its energy, producing unit-norm shapes ready for PVQ quantization. Returns shapes[band] = normalized coefficients for that band.

The decoder does: output = shape * gain (denormalization) So encoder does: shape = input / gain (normalization)

Parameters:

  • mdctCoeffs: MDCT coefficients for all bands concatenated
  • energies: per-band energy values (log2 scale from coarse + fine energy)
  • nbBands: number of bands to process
  • frameSize: frame size in samples (120, 240, 480, 960)

Returns: shapes[band] = normalized CELT vector with unit L2 norm

Reference: RFC 6716 Section 4.3.4.1

func (*Encoder) NormalizeBandsToArray

func (e *Encoder) NormalizeBandsToArray(mdctCoeffs []float32, energies []celtGLog, nbBands, frameSize int) []CeltNorm

NormalizeBandsToArray normalizes bands into a single contiguous array (length = frameSize). This mirrors libopus normalise_bands(): divide by the per-band LINEAR amplitude.

Linear band amplitudes are computed directly from mdctCoeffs, matching compute_band_energies followed by normalise_bands in libopus. The energies argument is unused; normalization does not round-trip through log energies.

Reference: libopus celt/bands.c normalise_bands() (float path, lines 172-187)

func (*Encoder) OverlapBuffer

func (e *Encoder) OverlapBuffer() []float32

OverlapBuffer returns the overlap buffer for MDCT analysis. Size is Overlap * channels samples.

func (*Encoder) PacketLoss

func (e *Encoder) PacketLoss() int

PacketLoss returns the expected packet loss percentage.

func (*Encoder) PhaseInversionDisabled

func (e *Encoder) PhaseInversionDisabled() bool

PhaseInversionDisabled returns whether stereo phase inversion is disabled.

func (*Encoder) Prediction

func (e *Encoder) Prediction() int

Prediction returns the active CELT prediction mode (0, 1, or 2).

func (*Encoder) PreemphState

func (e *Encoder) PreemphState() []float32

PreemphState returns the pre-emphasis filter state. One value per channel.

func (*Encoder) PrevBandLogEnergy

func (e *Encoder) PrevBandLogEnergy() []CeltGLog

PrevBandLogEnergy returns the previous frame's band log-energies. Used for spectral flux computation in tonality analysis.

func (*Encoder) PrevEnergy

func (e *Encoder) PrevEnergy() []CeltGLog

PrevEnergy returns the previous frame's band energies. Used for inter-frame energy prediction in coarse energy encoding. Layout: [band0_ch0, band1_ch0, ..., band20_ch0, band0_ch1, ..., band20_ch1]

func (*Encoder) PrevEnergy2

func (e *Encoder) PrevEnergy2() []CeltGLog

PrevEnergy2 returns the encoder's oldLogE2 band history.

func (*Encoder) RNG

func (e *Encoder) RNG() uint32

RNG returns the current RNG state. After encoding, this contains the final range coder state for verification.

func (*Encoder) ReserveEncodeScratch added in v0.2.0

func (e *Encoder) ReserveEncodeScratch(frameSize int)

ReserveEncodeScratch sizes the buffers reached when an Opus child encoder switches into CELT, including the analysis buffers that EncodeFrame grows after its ordinary frame scratch has been prepared.

func (*Encoder) Reset

func (e *Encoder) Reset()

Reset clears encoder state for a new stream. It clears frame and analysis history while retaining the active channel, sample-rate, and mode configuration.

func (*Encoder) SampleRate

func (e *Encoder) SampleRate() int

SampleRate returns the active CELT mode's sample rate in hertz.

func (*Encoder) SetAnalysisBandwidth

func (e *Encoder) SetAnalysisBandwidth(bandwidth int, valid bool)

SetAnalysisBandwidth provides the analysis-derived bandwidth index (1..20) used by allocation gating in clt_compute_allocation().

func (*Encoder) SetAnalysisInfo

func (e *Encoder) SetAnalysisInfo(bandwidth int, leakBoost [leakBands]uint8, activity, tonalitySlope opusVal16, maxPitchRatio opusVal16, valid bool)

SetAnalysisInfo provides analysis-derived state from the top-level Opus analysis pipeline. This mirrors libopus use of AnalysisInfo in CELT dynalloc.

func (*Encoder) SetAnalysisInfoWithTonality

func (e *Encoder) SetAnalysisInfoWithTonality(bandwidth int, leakBoost [leakBands]uint8, activity, tonality, tonalitySlope opusVal16, maxPitchRatio opusVal16, valid bool)

SetAnalysisInfoWithTonality provides the full AnalysisInfo subset used by libopus CELT decisions, including analysis.tonality for compute_vbr().

func (*Encoder) SetBandwidth

func (e *Encoder) SetBandwidth(bw CELTBandwidth)

SetBandwidth sets the CELT bandwidth cap used for band allocation.

func (*Encoder) SetBitrate

func (e *Encoder) SetBitrate(bps int)

SetBitrate sets st->bitrate, the rate in bits per second the VBR target and the CBR payload size derive from; BitrateMax makes the encoder fill its payload budget. It stores the rate as given: callers forwarding OPUS_SET_BITRATE apply the range checks of celt_encoder_ctl.

func (*Encoder) SetComplexity

func (e *Encoder) SetComplexity(complexity int)

SetComplexity sets encoder complexity (0-10). Higher values use more CPU for better quality.

func (*Encoder) SetConstrainedVBR

func (e *Encoder) SetConstrainedVBR(enabled bool)

SetConstrainedVBR enables or disables constrained VBR mode.

func (*Encoder) SetCustomSignalling added in v0.2.0

func (e *Encoder) SetCustomSignalling(enabled bool)

SetCustomSignalling mirrors st->signalling for opus_custom_encode. The signalled header consumes one byte from finite bitrate accounting; the caller still supplies the payload cap after removing that byte.

func (*Encoder) SetDCRejectEnabled

func (e *Encoder) SetDCRejectEnabled(enabled bool)

SetDCRejectEnabled controls whether EncodeFrame applies dc_reject(). For Opus-level encoding, this should be false because dc_reject is already applied.

func (*Encoder) SetDelayCompensationEnabled

func (e *Encoder) SetDelayCompensationEnabled(enabled bool)

SetDelayCompensationEnabled controls whether EncodeFrame prepends Fs/250 lookahead history before CELT analysis/quantization.

func (*Encoder) SetEnergy

func (e *Encoder) SetEnergy(band, channel int, energy float32)

SetEnergy sets the energy for a specific band and channel.

func (*Encoder) SetEnergyMask

func (e *Encoder) SetEnergyMask(mask []float32)

SetEnergyMask sets per-band surround masking for CELT surround control. Expected sizes: 21 values for mono, 42 values for stereo. Invalid sizes clear the mask.

func (*Encoder) SetFrameBitsForTest

func (e *Encoder) SetFrameBitsForTest(bits int)

SetFrameBitsForTest exposes frameBits for testing.

func (*Encoder) SetHybrid

func (e *Encoder) SetHybrid(hybrid bool)

SetHybrid sets the hybrid mode flag. When true, postfilter flag encoding is skipped per RFC 6716 Section 3.2. Reference: libopus celt_encoder.c line 2047-2048:

if(!hybrid && tell+16<=total_bits) ec_enc_bit_logp(enc, 0, 1);

func (*Encoder) SetLFE

func (e *Encoder) SetLFE(enabled bool)

SetLFE enables or disables LFE mode constraints.

func (*Encoder) SetLSBDepth

func (e *Encoder) SetLSBDepth(depth int)

SetLSBDepth sets the input signal LSB depth (8-24 bits). This affects masking/spread decisions at low bitrates.

func (*Encoder) SetLSBQuantizationEnabled

func (e *Encoder) SetLSBQuantizationEnabled(enabled bool)

SetLSBQuantizationEnabled controls whether EncodeFrame rounds inputs to the configured LSB depth before CELT-local processing.

func (*Encoder) SetLastTonality

func (e *Encoder) SetLastTonality(tonality opusVal16)

SetLastTonality sets the tonality estimate (for testing or manual override). Valid range is [0, 1] where 0 = noise and 1 = pure tone.

func (*Encoder) SetMaxPayloadBytes

func (e *Encoder) SetMaxPayloadBytes(maxPayloadBytes int)

SetMaxPayloadBytes sets an optional payload cap for the next CELT frame. The value excludes the Opus TOC byte. A value <= 0 disables the cap.

func (*Encoder) SetOverlapBuffer

func (e *Encoder) SetOverlapBuffer(samples []float32)

SetOverlapBuffer copies the given samples to the overlap buffer.

func (*Encoder) SetPacketLoss

func (e *Encoder) SetPacketLoss(lossPercent int)

SetPacketLoss sets the expected packet loss percentage (0-100). This affects the prefilter gain for improved loss resilience.

func (*Encoder) SetPhaseInversionDisabled

func (e *Encoder) SetPhaseInversionDisabled(disabled bool)

SetPhaseInversionDisabled disables stereo phase inversion. When true, the encoder will not use phase inversion for stereo decorrelation. This can improve compatibility with some audio processing chains.

func (*Encoder) SetPrediction

func (e *Encoder) SetPrediction(mode int)

SetPrediction controls CELT inter-frame prediction behavior. Valid modes mirror libopus CELT_SET_PREDICTION: - 0: disable prediction and force intra (disable_pf=1, force_intra=1) - 1: disable prefilter only (disable_pf=1, force_intra=0) - 2: normal prediction (disable_pf=0, force_intra=0)

func (*Encoder) SetPrevEnergy

func (e *Encoder) SetPrevEnergy(energies []celtGLog)

SetPrevEnergy advances the encoder energy history as a non-transient frame.

func (*Encoder) SetPrevEnergyWithPrev

func (e *Encoder) SetPrevEnergyWithPrev(prev, energies []celtGLog)

SetPrevEnergyWithPrev advances CELT energy history from the supplied oldBandE and current band energies as a non-transient frame.

func (*Encoder) SetRNG

func (e *Encoder) SetRNG(seed uint32)

SetRNG sets the RNG state.

func (*Encoder) SetRangeEncoder

func (e *Encoder) SetRangeEncoder(re *rangecoding.Encoder)

SetRangeEncoder sets the range encoder for the current frame. This must be called before encoding each frame.

func (*Encoder) SetSilkInfo

func (e *Encoder) SetSilkInfo(signalType, offset int)

SetSilkInfo stores the current SILK signal classification for hybrid CELT. This mirrors libopus CELT_SET_SILK_INFO.

func (*Encoder) SetStreamChannels

func (e *Encoder) SetStreamChannels(channels int)

SetStreamChannels mirrors libopus CELT_SET_CHANNELS.

func (*Encoder) SetTapsetDecision

func (e *Encoder) SetTapsetDecision(tapset int)

SetTapsetDecision sets the tapset decision value. Valid values are 0, 1, or 2.

func (*Encoder) SetTopLevelDelayCompensatedInput

func (e *Encoder) SetTopLevelDelayCompensatedInput(alreadyCompensated bool)

SetTopLevelDelayCompensatedInput tells the standalone CELT core whether the Opus wrapper has already supplied delay-compensated input.

func (*Encoder) SetUpsample

func (e *Encoder) SetUpsample(factor int)

SetUpsample sets the CELT input upsample factor, mirroring libopus CELTEncoder.upsample = resampling_factor(Fs). At sub-48 kHz API rates the encoder consumes native-Fs frame sizes and the CELT core block is frameSize*upsample (the input is zero-stuffed in pre-emphasis). Factor 1 (or 0) is the 48 kHz path.

func (*Encoder) SetVBR

func (e *Encoder) SetVBR(enabled bool)

SetVBR enables or disables variable bitrate mode.

func (*Encoder) SpreadingDecision

func (e *Encoder) SpreadingDecision(normX []celtNorm, nbBands, channels, frameSize int, updateHF bool) int

SpreadingDecision analyzes the normalized MDCT coefficients to decide the optimal spread parameter for PVQ quantization.

The spread parameter controls how pulses are distributed across the band: - SPREAD_AGGRESSIVE (3): More spreading, better for tonal signals - SPREAD_NORMAL (2): Default spreading - SPREAD_LIGHT (1): Less spreading - SPREAD_NONE (0): No spreading, for very noisy signals

The algorithm counts how many coefficients fall below certain thresholds relative to the band energy. Tonal signals have energy concentrated in few bins (low counts), while noisy signals have energy spread across many bins (high counts).

Parameters:

  • normX: normalized MDCT coefficients (unit-norm per band)
  • nbBands: number of bands to analyze
  • channels: number of audio channels (1 or 2)
  • frameSize: frame size in samples (determines M scaling)
  • updateHF: whether to update high-frequency average for tapset decision

Returns: spread decision (0=SPREAD_NONE, 1=SPREAD_LIGHT, 2=SPREAD_NORMAL, 3=SPREAD_AGGRESSIVE)

Reference: libopus celt/bands.c spreading_decision()

func (*Encoder) SpreadingDecisionWithWeights

func (e *Encoder) SpreadingDecisionWithWeights(normX []celtNorm, nbBands, channels, frameSize int, updateHF bool, spreadWeight []int32) int

SpreadingDecisionWithWeights analyzes the normalized MDCT coefficients to decide the optimal spread parameter for PVQ quantization, using precomputed spread weights.

The spread parameter controls how pulses are distributed across the band: - SPREAD_AGGRESSIVE (3): More spreading, better for tonal signals - SPREAD_NORMAL (2): Default spreading - SPREAD_LIGHT (1): Less spreading - SPREAD_NONE (0): No spreading, for very noisy signals

Parameters:

  • normX: normalized MDCT coefficients (unit-norm per band)
  • nbBands: number of bands to analyze
  • channels: number of audio channels (1 or 2)
  • frameSize: frame size in samples (determines M scaling)
  • updateHF: whether to update high-frequency average for tapset decision
  • spreadWeight: per-band weights from computeSpreadWeights

Returns: spread decision (0=SPREAD_NONE, 1=SPREAD_LIGHT, 2=SPREAD_NORMAL, 3=SPREAD_AGGRESSIVE)

Reference: libopus celt/bands.c spreading_decision()

func (*Encoder) StreamChannels

func (e *Encoder) StreamChannels() int

StreamChannels returns the coded channel count.

func (*Encoder) TapsetDecision

func (e *Encoder) TapsetDecision() int

TapsetDecision returns the current tapset decision (0, 1, or 2). The tapset controls the window taper used in the prefilter/postfilter comb filter: - 0: Narrow taper (concentrated energy) - 1: Medium taper (balanced) - 2: Wide taper (spread energy) This is computed during SpreadingDecision when updateHF=true. Reference: libopus celt/bands.c spreading_decision() and celt/celt.c comb_filter()

func (*Encoder) TestEncodeLaplace

func (e *Encoder) TestEncodeLaplace(val, fs, decay int) int

TestEncodeLaplace exposes encodeLaplace for testing.

This helper exists for tests and codec-development tooling and may change.

func (*Encoder) TransientAnalysis

func (e *Encoder) TransientAnalysis(pcm []float32, frameSize int, allowWeakTransients bool) TransientAnalysisResult

TransientAnalysis performs full transient analysis matching libopus. This computes:

  • Whether the frame is transient (should use short blocks)
  • tf_estimate: bias for TF resolution analysis (0 = time, 1 = freq)
  • tf_chan: which channel has the strongest transient

The algorithm uses a high-pass filter followed by forward/backward masking to detect temporal energy variations. The mask_metric measures how much the signal energy varies over time relative to a masked threshold.

Parameters:

  • pcm: pre-emphasized samples, planar like celt_encode_with_ec's in buffer: channel c occupies pcm[c*len(pcm)/channels:]
  • frameSize: frame size in samples (120, 240, 480, or 960)
  • allowWeakTransients: for hybrid mode at low bitrate

Returns: TransientAnalysisResult with all metrics

Reference: libopus celt/celt_encoder.c transient_analysis()

func (*Encoder) TransientAnalysisF32

func (e *Encoder) TransientAnalysisF32(pcm []float32, frameSize int, allowWeakTransients bool) TransientAnalysisResult

TransientAnalysisF32 is an alias for TransientAnalysis kept for the float32 naming convention used elsewhere in the encoder API.

func (*Encoder) VBR

func (e *Encoder) VBR() bool

VBR reports whether variable bitrate mode is enabled.

type FrameBudget added in v0.2.0

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

FrameBudget holds the celt_encode_with_ec byte budget of one frame. The fields mirror the C locals of the same names (celt/celt_encoder.c).

func (*FrameBudget) TotalBits added in v0.2.0

func (b *FrameBudget) TotalBits() int

TotalBits returns total_bits = nbCompressedBytes*8.

type MDCTForwardScratch added in v0.2.0

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

MDCTForwardScratch holds the CELT float MDCT working buffers for callers that perform repeated transforms outside an Encoder.

func (*MDCTForwardScratch) ForwardWithOverlapFloat32Into added in v0.2.0

func (s *MDCTForwardScratch) ForwardWithOverlapFloat32Into(samples []float32, overlap int, coeffs []float32)

ForwardWithOverlapFloat32Into writes the same coefficients as MDCTForwardWithOverlapFloat32 into caller-owned storage. Once the scratch has reached the required frame size, this path does not allocate.

type ModeConfig

type ModeConfig struct {
	FrameSize   int // Samples per channel for the active mode.
	ShortBlocks int // Number of short MDCTs if transient: 1, 2, 4, 8
	LM          int // Log mode index: 0, 1, 2, 3
	EffBands    int // Effective number of bands for this frame size
	MDCTSize    int // MDCT window size for long blocks
}

ModeConfig contains frame-size-dependent configuration for CELT decoding. Parameters vary based on frame duration (2.5ms to 20ms).

func GetModeConfig

func GetModeConfig(frameSize int) ModeConfig

GetModeConfig returns the mode configuration for a CELT frame size. It recognizes 120, 240, 480, 960, and 1920 samples per channel and returns the 960-sample configuration for any other value. The 1920-sample geometry is used by native 96 kHz HD mode. This lookup does not check the active mode or build configuration; the caller validates those separately.

type OpusVal16 added in v0.2.0

type OpusVal16 = opusVal16

OpusVal16 exposes libopus's float-build opus_val16 width in exported signatures.

func ThetaToGains

func ThetaToGains(itheta, qn int) (mid, side OpusVal16)

ThetaToGains converts itheta to mid and side gains. itheta: quantized angle (0 to qn) qn: number of quantization steps Returns: mid gain, side gain (both in [0, 1])

Reference: libopus celt/bands.c

func UpdateStereoSaving

func UpdateStereoSaving(prev opusVal16, normL, normR []celtNorm, nbBands, lm, intensity int, edges []int) OpusVal16

UpdateStereoSaving updates the running stereo_saving estimate used by libopus compute_vbr(). The state is updated once per frame after alloc-trim analysis: stereo_saving = min(stereo_saving+0.25, -logXC2/2) (celt/celt_encoder.c:919). The state is unbounded; compute_vbr caps the value it reads at 1.

type PLCStateSnapshot

type PLCStateSnapshot struct {
	LastFrameType    int
	LossDuration     int
	PLCDuration      int
	LastPitchPeriod  int
	SkipPLC          bool
	PrefilterAndFold bool
}

PLCStateSnapshot exposes the libopus-shaped CELT PLC cadence state needed by parity tests around periodic/noise/neural/DRED concealment.

type PostfilterState

type PostfilterState struct {
	Period         int
	Gain           float32
	Tapset         int
	PreviousPeriod int
	PreviousGain   float32
	PreviousTapset int
}

PostfilterState is a snapshot of the decoder postfilter parameters for the current and previous frame.

type QuantCoarseEnergyParams

type QuantCoarseEnergyParams struct {
	// Start is the first band to encode (typically 0, or 17 for hybrid).
	Start int
	// End is the last band to encode (exclusive).
	End int
	// EffEnd is the effective end for distortion computation.
	EffEnd int
	// LM is the log mode (0=2.5ms, 1=5ms, 2=10ms, 3=20ms).
	LM int
	// Channels is the number of audio channels (1 or 2).
	Channels int
	// Budget is the total bit budget for encoding.
	Budget int
	// NBAvailableBytes is the number of bytes available for encoding.
	NBAvailableBytes int
	// ForceIntra forces intra mode regardless of analysis.
	ForceIntra bool
	// TwoPass enables two-pass encoding comparing intra vs inter.
	TwoPass bool
	// LossRate is the packet loss rate (0-100).
	LossRate int
	// LFE indicates low-frequency effects mode.
	LFE bool
}

QuantCoarseEnergyParams holds parameters for coarse energy quantization.

type QuantCoarseEnergyResult

type QuantCoarseEnergyResult struct {
	// QuantizedEnergy is the quantized energy per band per channel.
	// Layout: [ch0_band0, ch0_band1, ..., ch1_band0, ch1_band1, ...]
	QuantizedEnergy []celtGLog

	// Error is the quantization error per band per channel (for fine energy).
	// error[i] = original - quantized (in DB6 units)
	Error []celtGLog

	// Intra indicates whether intra mode was used.
	Intra bool
}

QuantCoarseEnergyResult holds the result of coarse energy quantization.

func QuantCoarseEnergy

func QuantCoarseEnergy(
	re *rangecoding.Encoder,
	eBands []celtGLog,
	oldEBands []celtGLog,
	params QuantCoarseEnergyParams,
	delayedIntra *float32,
) QuantCoarseEnergyResult

QuantCoarseEnergy quantizes coarse band energies with two-pass comparison. This is the main entry point matching libopus quant_coarse_energy().

The algorithm: 1. Optionally encode with intra mode (no inter-frame prediction) 2. Encode with inter mode (using inter-frame prediction) 3. Compare results and pick the better one (when two_pass is enabled)

Reference: libopus celt/quant_bands.c quant_coarse_energy()

type StereoMode

type StereoMode int

StereoMode specifies the stereo coding mode for a band.

const (
	// StereoMidSide uses mid-side encoding with theta rotation.
	// Good for correlated stereo content (most music).
	StereoMidSide StereoMode = iota

	// StereoIntensity uses mono with optional sign inversion.
	// Used for high frequency bands to save bits.
	StereoIntensity

	// StereoDual encodes left and right independently.
	// Used when channels are uncorrelated.
	StereoDual
)

func GetStereoMode

func GetStereoMode(band, intensityBand int, dualStereo bool) StereoMode

GetStereoMode determines the stereo mode for a band. The mode depends on:

  • band index relative to intensity stereo start band
  • whether dual stereo mode is enabled
  • bit allocation for the band

Parameters:

  • band: band index (0 to nbBands-1)
  • intensityBand: band where intensity stereo starts (-1 if not used)
  • dualStereo: true if dual stereo mode is enabled

Returns: the stereo mode to use for this band

func (StereoMode) String

func (sm StereoMode) String() string

String returns the string representation of the stereo mode.

type TFAnalysisScratch

type TFAnalysisScratch struct {
	// Levels holds one band's coefficients at each Haar level tf_analysis
	// measures: level 0, the transient -1 level, and one level per k step.
	Levels               []celtNorm
	TfRes                []int32 // Output buffer
	Metric, Path0, Path1 []int32
	// contains filtered or unexported fields
}

TFAnalysisScratch holds pre-allocated buffers for TF analysis.

Standard layouts keep metric and Viterbi paths on the stack. Wider custom layouts reuse Metric, Path0, and Path1. Output and transform buffers live here.

func (*TFAnalysisScratch) EnsureTFAnalysisScratch

func (s *TFAnalysisScratch) EnsureTFAnalysisScratch(nbEBands, maxBandWidth, lm int)

EnsureTFAnalysisScratch ensures scratch buffers are large enough.

type TransientAnalysisResult

type TransientAnalysisResult struct {
	IsTransient   bool    // Whether a transient was detected
	TfEstimate    float32 // Time-frequency estimate (0.0 = time, 1.0 = freq) for TF analysis bias
	TfChannel     int     // Which channel had the strongest transient (0 or 1)
	MaskMetric    float32 // Raw mask metric value.
	WeakTransient bool    // Whether this is a "weak" transient (for hybrid mode)
	ToneFreq      float32 // Detected tone frequency in radians/sample (-1 if no tone)
	Toneishness   float32 // How "pure" the tone is (0.0-1.0, higher = purer)
}

TransientAnalysisResult holds the results of transient analysis. This provides both the transient decision and the tf_estimate metric.

Source Files

Jump to

Keyboard shortcuts

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