Documentation
¶
Overview ¶
Package encoder implements the stateful Opus encoder described by RFC 6716. It coordinates SILK, CELT, and Hybrid coding, selects a mode and bandwidth for each frame, applies bitrate control, and assembles the packet.
A frame uses SILK for predictive speech coding, CELT for transform coding, or both in Hybrid mode. ModeAuto selects among them from the configured rate and the encoder's signal analysis. The frame path follows libopus 1.6.1's `src/opus_encoder.c` and `src/analysis.c`.
Encoder retains analysis, sub-encoder, and transition history across calls. Keep one encoder per stream and serialize access. Encoder.FinalRange exposes the entropy coder's final range for paired comparisons; packet and range claims apply to the matching reference configuration and tested cases. See the coverage summary in `reports/validation.md#coverage`.
Most applications should use the top-level gopus API, which owns this implementation state and packet framing.
Index ¶
- Constants
- Variables
- func BuildMultiFramePacket(frames [][]byte, mode types.Mode, bandwidth types.Bandwidth, frameSize int, ...) ([]byte, error)
- func BuildPacket(frameData []byte, mode types.Mode, bandwidth types.Bandwidth, frameSize int, ...) ([]byte, error)
- func BuildPacketInto(dst, frameData []byte, mode types.Mode, bandwidth types.Bandwidth, ...) (int, error)
- func ClampBitrate(bitrate int) int
- func ValidBitrate(bitrate int) bool
- func ValidFrameSize(frameSize int, mode Mode) bool
- type AnalysisDenseLayer
- type AnalysisGRULayer
- type AnalysisInfo
- type BitrateMode
- type EncodeInputFormat
- type Encoder
- func (e *Encoder) Bandwidth() types.Bandwidth
- func (e *Encoder) BeginEncodeCall(input EncodeInputFormat, frameSize int)
- func (e *Encoder) Bitrate() int
- func (e *Encoder) CELTEnergyMask() []float32
- func (e *Encoder) Channels() int
- func (e *Encoder) ClearFloatInputFrame()
- func (e *Encoder) Complexity() int
- func (e *Encoder) DNNBlobLoaded() bool
- func (e *Encoder) DTXEnabled() bool
- func (e *Encoder) Encode(pcm []float32, frameSize int) ([]byte, error)
- func (e *Encoder) EncodeFloat32(pcm []float32, frameSize int) ([]byte, error)
- func (e *Encoder) EncodeFloat32WithAnalysisMaxBytes(pcm []float32, frameSize int, analysisPCM []float32, maxDataBytes int) ([]byte, error)
- func (e *Encoder) EncodeShortMixedWithAnalysisMaxBytes(pcm []float32, frameSize int, analysisPCM []float32, maxDataBytes int) ([]byte, error)
- func (e *Encoder) EncodeWithAnalysis(pcm []float32, frameSize int, analysisPCM []float32) ([]byte, error)
- func (e *Encoder) EncodeWithAnalysisMaxBytes(pcm []float32, frameSize int, analysisPCM []float32, maxDataBytes int) ([]byte, error)
- func (e *Encoder) FECEnabled() bool
- func (e *Encoder) FinalRange() uint32
- func (e *Encoder) FirstFrameCoded() bool
- func (e *Encoder) ForceChannels() int
- func (e *Encoder) FrameSize() int
- func (e *Encoder) GetBitrateMode() BitrateMode
- func (e *Encoder) GetVADActivity() int
- func (e *Encoder) InBandFEC() int
- func (e *Encoder) InDTX() bool
- func (e *Encoder) Init(sampleRate, channels int)
- func (e *Encoder) LFE() bool
- func (e *Encoder) LSBDepth() int
- func (e *Encoder) LastOpusVADActive() bool
- func (e *Encoder) LastOpusVADProb() float32
- func (e *Encoder) Lookahead() int
- func (e *Encoder) LowDelay() bool
- func (e *Encoder) MaxBandwidth() types.Bandwidth
- func (e *Encoder) Mode() Mode
- func (e *Encoder) PacketLoss() int
- func (e *Encoder) PhaseInversionDisabled() bool
- func (e *Encoder) PredictionDisabled() bool
- func (e *Encoder) ReserveShortEncodeScratch(frameSize, maxDataBytes int)
- func (e *Encoder) Reset()
- func (e *Encoder) SampleRate() int
- func (e *Encoder) SetAllocatedBitrate(bitrate int)
- func (e *Encoder) SetBandwidth(bandwidth types.Bandwidth)
- func (e *Encoder) SetBandwidthAuto()
- func (e *Encoder) SetBitrate(bitrate int)
- func (e *Encoder) SetBitrateMode(mode BitrateMode)
- func (e *Encoder) SetCELTEnergyMask(mask []float32)
- func (e *Encoder) SetCELTEnergyMaskQ24(mask []int32)
- func (e *Encoder) SetComplexity(complexity int)
- func (e *Encoder) SetDNNBlob(blob *dnnblob.Blob)
- func (e *Encoder) SetDTX(enabled bool)
- func (e *Encoder) SetFEC(enabled bool)
- func (e *Encoder) SetFloatInputFrame(pcm []float32)
- func (e *Encoder) SetForceChannels(channels int)
- func (e *Encoder) SetFrameSize(frameSize int)
- func (e *Encoder) SetInBandFEC(config int) error
- func (e *Encoder) SetLFE(enabled bool)
- func (e *Encoder) SetLSBDepth(depth int)
- func (e *Encoder) SetLowDelay(enabled bool)
- func (e *Encoder) SetMaxBandwidth(bw types.Bandwidth)
- func (e *Encoder) SetMode(mode Mode)
- func (e *Encoder) SetPacketLoss(lossPercent int)
- func (e *Encoder) SetPhaseInversionDisabled(disabled bool)
- func (e *Encoder) SetPredictionDisabled(disabled bool)
- func (e *Encoder) SetRestrictedSilkApplication(enabled bool)
- func (e *Encoder) SetSignalType(signal types.Signal)
- func (e *Encoder) SetVBR(enabled bool)
- func (e *Encoder) SetVBRConstraint(constrained bool)
- func (e *Encoder) SetVoIPApplication(enabled bool)
- func (e *Encoder) SetVoiceRatio(ratio int) error
- func (e *Encoder) SignalType() types.Signal
- func (e *Encoder) VBR() bool
- func (e *Encoder) VBRConstraint() bool
- func (e *Encoder) VoIPApplication() bool
- func (e *Encoder) VoiceRatio() int
- type Mode
- type OpusVal16
- type OpusVal32
- type StereoWidthMem
- type TonalityAnalysisState
- func (s *TonalityAnalysisState) GetInfo() AnalysisInfo
- func (s *TonalityAnalysisState) Init(fs int)
- func (s *TonalityAnalysisState) Reset()
- func (s *TonalityAnalysisState) RunAnalysis(pcm []float32, frameSize int, channels int) AnalysisInfo
- func (s *TonalityAnalysisState) SetLSBDepth(depth int)
- func (s *TonalityAnalysisState) SpeechProbability(pcm []float32) float32
- type VADState
Constants ¶
const ( // NbFrames is the number of past short-time frames retained in the per-band // energy history rings (E/logE). Mirrors NB_FRAMES. NbFrames = 8 // NbTBands is the number of tonality sub-bands analysed by the detector. // Mirrors NB_TBANDS. NbTBands = 18 // NbTonalSkipBands is the number of low sub-bands skipped when summing // tonality (they are dominated by pitch). Mirrors NB_TONAL_SKIP_BANDS. NbTonalSkipBands = 9 // AnalysisBufSize is the analyzer input buffer length, 30ms at 24kHz. // Mirrors ANALYSIS_BUF_SIZE. AnalysisBufSize = 720 // 30ms at 24kHz // DetectSize is the depth of the per-frame AnalysisInfo ring used to defer // the music/speech decision behind the analyzer lookahead. Mirrors // DETECT_SIZE. DetectSize = 100 )
Tonality-analyzer dimensions mirroring the #defines in libopus src/analysis.h.
const ( BitrateAuto = -1000 BitrateMax = -1 MinBitrate = 500 // libopus OPUS_SET_BITRATE minimum MaxBitrate = 750000 // libopus OPUS_SET_BITRATE per-channel maximum )
Bitrate limits per RFC 6716
const ( // DTXFrameThresholdMs is the duration of silence before DTX activates. // Matches NB_SPEECH_FRAMES_BEFORE_DTX * 20 = 200ms. DTXFrameThresholdMs = 200 // DTXMaxConsecutiveMs is the maximum duration for DTX mode. // Matches MAX_CONSECUTIVE_DTX * 20 = 400ms. DTXMaxConsecutiveMs = 400 )
DTX Constants matching libopus silk/define.h and opus_encoder.c
const ( // InBandFECDisabled turns in-band forward error correction off. InBandFECDisabled = 0 // InBandFECEnabled enables LBRR-based FEC for all SILK/Hybrid frames that // carry speech (libopus value 1). InBandFECEnabled = 1 // InBandFECMusicSafe enables FEC but lets the encoder suppress it on frames // classified as music, trading resilience for quality (libopus value 2). InBandFECMusicSafe = 2 )
In-band FEC configuration values accepted by Encoder.SetInBandFEC, matching the libopus OPUS_SET_INBAND_FEC argument (src/opus_encoder.c).
const ( // LBRRBitrateFactor is the bitrate reduction for LBRR encoding. // LBRR uses ~60% of normal SILK bitrate. LBRRBitrateFactor = 0.6 // MinPacketLossForFEC is the minimum expected loss to enable FEC. // Below this, FEC overhead isn't worth it. MinPacketLossForFEC = 1 // MaxPacketLossForFEC is where FEC becomes less effective. // Above this, increasing primary bitrate is better. MaxPacketLossForFEC = 50 // MinSILKBitrate is the minimum bitrate for SILK encoding (6 kbps). MinSILKBitrate = 6000 )
FEC Constants
const ( // VADNBands is the number of frequency bands for VAD analysis. VADNBands = 4 // VADInternalSubframesLog2 is log2 of the number of internal subframes. VADInternalSubframesLog2 = 2 // VADInternalSubframes is the number of internal subframes (1 << 2 = 4). VADInternalSubframes = 1 << VADInternalSubframesLog2 // VADMinFrameLength is the smallest frame the band decimation can analyse. // The lowest band decimates the frame by 8 (>>3) and then splits it into // VADInternalSubframes subframes (>>VADInternalSubframesLog2), so the // per-subframe length is frameLength >> (3+VADInternalSubframesLog2). That // quotient must be at least 1, which requires frameLength >= 1<<5. VADMinFrameLength = 1 << (3 + VADInternalSubframesLog2) // VADNoiseLevelSmoothCoefQ16 is the noise level smoothing coefficient. // Must be < 4096. VADNoiseLevelSmoothCoefQ16 = 1024 // VADNoiseLevelsBias is the bias for noise level estimation. VADNoiseLevelsBias = 50 // VADNegativeOffsetQ5 is the sigmoid offset (sigmoid is 0 at -128). VADNegativeOffsetQ5 = 128 // VADSNRFactorQ16 is the SNR scaling factor. VADSNRFactorQ16 = 45000 // VADSNRSmoothCoefQ18 is the smoothing coefficient for SNR measurement. VADSNRSmoothCoefQ18 = 4096 // DTXActivityThreshold is the activity probability threshold for DTX. // Matches libopus DTX_ACTIVITY_THRESHOLD = 0.1f DTXActivityThreshold = 0.1 // NBSpeechFramesBeforeDTX is frames of speech required before DTX (200ms). NBSpeechFramesBeforeDTX = 10 // MaxConsecutiveDTX is maximum consecutive DTX frames (400ms). MaxConsecutiveDTX = 20 )
VAD Constants matching libopus silk/define.h
const CVBRTolerance float32 = 0.15 // +/- 15%
CVBR tolerance (percentage)
const MaxNeurons = 32
MaxNeurons is the maximum number of neurons in any layer.
const WeightsScale = 1.0 / 128.0
WeightsScale is used to dequantize the 8-bit weights from libopus.
Variables ¶
var ( // ErrInvalidSampleRate indicates a sample rate outside the Opus API set. ErrInvalidSampleRate = errors.New("encoder: invalid sample rate (must be 8000, 12000, 16000, 24000, or 48000)") // ErrInvalidChannels indicates an invalid channel count. ErrInvalidChannels = errors.New("encoder: invalid channels (must be 1 or 2)") // ErrInvalidFrameSize indicates an invalid frame size. ErrInvalidFrameSize = errors.New("encoder: invalid frame size") // ErrBufferTooSmall indicates the output budget cannot represent the frame. ErrBufferTooSmall = errors.New("encoder: output buffer too small") // ErrEncodingFailed indicates a general encoding failure. ErrEncodingFailed = errors.New("encoder: encoding failed") // ErrInvalidDREDDuration indicates DRED duration is outside libopus bounds. ErrInvalidDREDDuration = errors.New("encoder: invalid DRED duration") // ErrInvalidFECConfig indicates an invalid in-band FEC configuration. ErrInvalidFECConfig = errors.New("encoder: invalid in-band FEC config") // ErrInvalidVoiceRatio indicates a voice ratio outside libopus bounds. ErrInvalidVoiceRatio = errors.New("encoder: invalid voice ratio") )
Errors for the encoder.
var ( ErrInvalidConfig = errors.New("encoder: invalid config for mode/bandwidth/frameSize") ErrInvalidFrameCount = errors.New("encoder: frame count must be 1-48") )
Packet assembly errors.
Functions ¶
func BuildMultiFramePacket ¶
func BuildMultiFramePacket(frames [][]byte, mode types.Mode, bandwidth types.Bandwidth, frameSize int, stereo bool, vbr bool) ([]byte, error)
BuildMultiFramePacket creates a packet with multiple frames. frames: slice of encoded frame data vbr: true for variable bitrate (different frame sizes), false for CBR
func BuildPacket ¶
func BuildPacket(frameData []byte, mode types.Mode, bandwidth types.Bandwidth, frameSize int, stereo bool) ([]byte, error)
BuildPacket creates a complete Opus packet from encoded frame data. Uses frame code 0 (single frame).
func BuildPacketInto ¶
func BuildPacketInto(dst, frameData []byte, mode types.Mode, bandwidth types.Bandwidth, frameSize int, stereo bool) (int, error)
BuildPacketInto creates a complete Opus packet into the provided buffer. Returns the number of bytes written, or error if buffer is too small. Uses frame code 0 (single frame).
func ClampBitrate ¶
ClampBitrate ensures bitrate is within valid range.
func ValidBitrate ¶
ValidBitrate returns true if the bitrate is within Opus limits.
func ValidFrameSize ¶
ValidFrameSize returns true if the frame size is valid for the given mode.
Types ¶
type AnalysisDenseLayer ¶
type AnalysisDenseLayer struct {
// Bias holds one int8 bias per output neuron (libopus "bias").
Bias []int8
// InputWeights stores NbInputs rows of NbNeurons int8 weights (libopus
// "input_weights"); the neuron index is contiguous within each input row.
InputWeights []int8
// NbInputs is the layer input dimension (libopus "nb_inputs").
NbInputs int
// NbNeurons is the layer output dimension (libopus "nb_neurons").
NbNeurons int
// Sigmoid selects the output activation: true for logistic sigmoid, false for
// tansig (libopus "sigmoid").
Sigmoid bool
// contains filtered or unexported fields
}
AnalysisDenseLayer represents a fully connected layer in the analysis MLP. It mirrors libopus DenseLayer (src/mlp.h); weights are stored as the original 8-bit quantized values. The float32 cache stores those values without scaling.
func (*AnalysisDenseLayer) ComputeDense ¶
func (l *AnalysisDenseLayer) ComputeDense(output []float32, input []float32)
ComputeDense computes the output of a dense layer.
type AnalysisGRULayer ¶
type AnalysisGRULayer struct {
// Bias holds the int8 biases for the GRU gates (libopus "bias").
Bias []int8
// InputWeights is the int8 input-to-gate weight matrix (libopus
// "input_weights").
InputWeights []int8
// RecurrentWeights is the int8 state-to-gate weight matrix (libopus
// "recurrent_weights").
RecurrentWeights []int8
// NbInputs is the input dimension (libopus "nb_inputs").
NbInputs int
// NbNeurons is the hidden-state dimension (libopus "nb_neurons").
NbNeurons int
// contains filtered or unexported fields
}
AnalysisGRULayer represents a Gated Recurrent Unit layer of the music/speech classifier. It mirrors libopus GRULayer (src/mlp.h) and feeds its hidden state back through TonalityAnalysisState.RNNState across frames.
func (*AnalysisGRULayer) ComputeGRU ¶
func (l *AnalysisGRULayer) ComputeGRU(state []float32, input []float32)
ComputeGRU computes the state update of a GRU layer.
type AnalysisInfo ¶
type AnalysisInfo struct {
// Valid reports whether this entry holds a computed result (libopus "valid").
// A zero AnalysisInfo (Valid==false) means "analysis not run / disabled".
Valid bool
// Tonality is the frame tonality estimate in [0,1] (libopus "tonality").
Tonality float32
// TonalitySlope is the inter-band tonality slope (libopus "tonality_slope").
TonalitySlope float32
// NoisySpeech is the noisiness estimate; high values bias toward SILK/VoIP.
// Mirrors libopus "noisiness".
NoisySpeech float32
// StationarySpeech is the analyzer's stationary-speech estimate used by the
// SILK/CELT bridge heuristics.
StationarySpeech float32
// MusicProb is the smoothed probability that the frame is music, in [0,1]
// (libopus "music_prob"); the primary CELT-vs-SILK mode driver.
MusicProb float32
// MusicProbMin is the lower confidence bound of the music probability
// (libopus "music_prob_min").
MusicProbMin float32
// MusicProbMax is the upper confidence bound of the music probability
// (libopus "music_prob_max").
MusicProbMax float32
// VADProb is the analyzer voice-activity probability, libopus
// "activity_probability"; also feeds Opus-level DTX.
VADProb float32
// Loudness is the frame loudness estimate used by surround/level logic.
Loudness float32
// BandwidthIndex is the detected signal bandwidth as a sub-band index
// (libopus "bandwidth"); see Bandwidth for the decoded value.
BandwidthIndex int32
// Bandwidth is BandwidthIndex decoded to an Opus bandwidth used to clamp the
// encoder's chosen bandwidth.
Bandwidth types.Bandwidth
// Activity is the raw frame activity estimate (libopus "activity").
Activity float32
// MaxPitchRatio is the maximum cross-frame pitch ratio (libopus
// "max_pitch_ratio"), used by the CELT pitch/leak boost.
MaxPitchRatio float32
// LeakBoost holds the per-band Q6 leak-boost coefficients (libopus
// "leak_boost[LEAK_BANDS]") forwarded to CELT dynalloc.
LeakBoost [19]uint8
}
AnalysisInfo is the per-frame output of the tonality analyzer ("the brain"). It mirrors the AnalysisInfo struct in libopus celt/celt.h and carries the music/speech probability, tonality and bandwidth estimates that opus_encoder.c consumes for mode, bandwidth and rate decisions. The encoder keeps the most recent value in Encoder.lastAnalysisInfo.
type BitrateMode ¶
type BitrateMode int
BitrateMode specifies how the encoder manages packet sizes.
const ( // ModeVBR enables unconstrained variable bitrate encoding. // Packet sizes vary with the encoded content. ModeVBR BitrateMode = iota // ModeCVBR enables constrained variable bitrate encoding. // NewEncoder selects this mode by default. ModeCVBR // ModeCBR enables constant bitrate encoding. // The packet byte budget depends on the bitrate and frame duration. ModeCBR )
type EncodeInputFormat ¶ added in v0.2.0
type EncodeInputFormat uint8
EncodeInputFormat identifies the libopus public encode API used for a call. The conversion wrappers reject an invalid selected frame before entering opus_encode_native, while the native-format wrapper clears rangeFinal there.
const ( EncodeInputFloat32 EncodeInputFormat = iota EncodeInputInt16 EncodeInputInt24 )
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder is the unified Opus encoder that orchestrates SILK and CELT sub-encoders.
func NewEncoder ¶
NewEncoder creates an Opus encoder for sampleRate and channels. Unsupported sample rates fall back to 48 kHz; 96 kHz is retained when QEXT is enabled. Channel counts below one select mono, and counts above two select stereo.
func (*Encoder) BeginEncodeCall ¶ added in v0.2.0
func (e *Encoder) BeginEncodeCall(input EncodeInputFormat, frameSize int)
BeginEncodeCall applies the rangeFinal side effect of entering the matching libopus encode wrapper. Call it after validating the Go slice shape and before returning an expert-frame or output-budget error.
func (*Encoder) CELTEnergyMask ¶
CELTEnergyMask returns the current CELT energy mask.
func (*Encoder) ClearFloatInputFrame ¶
func (e *Encoder) ClearFloatInputFrame()
ClearFloatInputFrame clears the per-call float32 input override.
func (*Encoder) Complexity ¶
Complexity returns the current complexity setting.
func (*Encoder) DNNBlobLoaded ¶
DNNBlobLoaded reports whether a validated model blob is retained.
func (*Encoder) DTXEnabled ¶
DTXEnabled returns whether DTX is enabled.
func (*Encoder) EncodeFloat32 ¶
EncodeFloat32 encodes a frame of libopus float PCM audio to an Opus packet.
func (*Encoder) EncodeFloat32WithAnalysisMaxBytes ¶
func (e *Encoder) EncodeFloat32WithAnalysisMaxBytes(pcm []float32, frameSize int, analysisPCM []float32, maxDataBytes int) ([]byte, error)
EncodeFloat32WithAnalysisMaxBytes is the float32 PCM entrypoint matching libopus opus_encode_float().
func (*Encoder) EncodeShortMixedWithAnalysisMaxBytes ¶ added in v0.2.0
func (e *Encoder) EncodeShortMixedWithAnalysisMaxBytes(pcm []float32, frameSize int, analysisPCM []float32, maxDataBytes int) ([]byte, error)
EncodeShortMixedWithAnalysisMaxBytes encodes the opus_res samples produced by libopus's short input callback. analysisPCM contains the original short input channels, converted exactly to float32 by division by 32768 before routing; it is separate from any projection-mixed coding samples.
func (*Encoder) EncodeWithAnalysis ¶
func (e *Encoder) EncodeWithAnalysis(pcm []float32, frameSize int, analysisPCM []float32) ([]byte, error)
EncodeWithAnalysis encodes the selected frame while allowing analysis to see a larger caller frame, matching libopus expert-frame-duration handling.
func (*Encoder) EncodeWithAnalysisMaxBytes ¶
func (e *Encoder) EncodeWithAnalysisMaxBytes(pcm []float32, frameSize int, analysisPCM []float32, maxDataBytes int) ([]byte, error)
EncodeWithAnalysisMaxBytes encodes with a caller output budget. maxDataBytes mirrors libopus max_data_bytes after packet-size-cap clamping.
func (*Encoder) FECEnabled ¶
FECEnabled returns whether FEC is enabled.
func (*Encoder) FinalRange ¶
FinalRange returns the final range coder state after encoding.
func (*Encoder) FirstFrameCoded ¶
FirstFrameCoded reports whether a frame has been committed since the encoder was created or reset, mirroring libopus !st->first.
C ref: opus_encoder.c clears st->first = 0 only after a frame reaches the end of opus_encode_native (line 2562), AFTER the SILK nBytes==0 early return (line 2242) which leaves st->first = 1. OPUS_SET_APPLICATION uses !st->first to reject an application change once a frame has been coded.
func (*Encoder) ForceChannels ¶
ForceChannels returns the forced channel count (-1 = auto).
func (*Encoder) FrameSize ¶
FrameSize returns the configured per-channel frame size in samples at the input sample rate.
func (*Encoder) GetBitrateMode ¶
func (e *Encoder) GetBitrateMode() BitrateMode
BitrateMode returns the current bitrate mode.
func (*Encoder) GetVADActivity ¶
GetVADActivity returns the latest available Opus-level activity estimate in Q8 (0-255). It reads the existing frame decision and does not run another detector. It reports the analyzer or CELT fallback used by Opus activity decisions, not the separate SILK VAD state. It returns 0 before a decision, after Reset, or when the current activity decision is unavailable.
func (*Encoder) InDTX ¶
InDTX returns whether the encoder is currently in DTX mode, matching OPUS_GET_IN_DTX (src/opus_encoder.c): after a SILK or Hybrid frame coded with SILK's own DTX, SILK's no-speech run decides; otherwise the Opus-level inactivity run does.
func (*Encoder) Init ¶ added in v0.2.5
Init initializes e in place for sampleRate and channels so callers can embed encoder.Encoder inline without a separate heap allocation.
func (*Encoder) LastOpusVADActive ¶
LastOpusVADActive returns whether the Opus-level VAD classified the last frame as active.
func (*Encoder) LastOpusVADProb ¶
LastOpusVADProb returns the last Opus-level VAD probability (0..1).
func (*Encoder) Lookahead ¶
Lookahead returns the encoder's algorithmic delay in samples at its configured input sample rate.
func (*Encoder) MaxBandwidth ¶
MaxBandwidth returns the maximum bandwidth limit.
func (*Encoder) Mode ¶
Mode returns the configured encoding mode. ModeAuto lets the encoder select a coding mode for each frame.
func (*Encoder) PacketLoss ¶
PacketLoss returns the expected packet loss percentage.
func (*Encoder) PhaseInversionDisabled ¶
PhaseInversionDisabled returns whether stereo phase inversion is disabled.
func (*Encoder) PredictionDisabled ¶
PredictionDisabled returns whether inter-frame prediction is disabled.
func (*Encoder) ReserveShortEncodeScratch ¶ added in v0.2.0
ReserveShortEncodeScratch sizes the packet and CELT fallback scratch for a caller's short-input frame before mode selection can switch a child encoder from SILK to CELT. The first call performs any growth; later calls with the same frame and packet bounds reuse the backing storage.
func (*Encoder) SampleRate ¶
SampleRate returns the input sample rate.
func (*Encoder) SetAllocatedBitrate ¶
SetAllocatedBitrate sets a bitrate allocated by the multistream encoder.
func (*Encoder) SetBandwidth ¶
SetBandwidth sets the target audio bandwidth.
func (*Encoder) SetBandwidthAuto ¶
func (e *Encoder) SetBandwidthAuto()
SetBandwidthAuto clears an explicit bandwidth request and restores automatic selection.
func (*Encoder) SetBitrate ¶
SetBitrate sets the target bitrate in bits per second.
func (*Encoder) SetBitrateMode ¶
func (e *Encoder) SetBitrateMode(mode BitrateMode)
SetBitrateMode sets the bitrate mode (VBR, CVBR, or CBR).
func (*Encoder) SetCELTEnergyMask ¶
SetCELTEnergyMask sets per-band CELT surround masking (21 mono, 42 stereo).
func (*Encoder) SetCELTEnergyMaskQ24 ¶ added in v0.2.0
SetCELTEnergyMaskQ24 applies a fixed Q24 mask through the float CELT control when the fixed-point encoder is not compiled in.
func (*Encoder) SetComplexity ¶
SetComplexity sets encoder complexity (0-10).
func (*Encoder) SetDNNBlob ¶
func (*Encoder) SetFloatInputFrame ¶
SetFloatInputFrame exposes the current public float32 frame to the encoder hot path so analysis can consume it directly and 24-bit quantization can skip a no-op round-trip.
func (*Encoder) SetForceChannels ¶
SetForceChannels sets the forced channel count.
func (*Encoder) SetFrameSize ¶
SetFrameSize stores the per-channel frame size in samples at the configured input sample rate.
func (*Encoder) SetInBandFEC ¶
SetInBandFEC sets the libopus-compatible in-band FEC configuration.
func (*Encoder) SetLSBDepth ¶
SetLSBDepth sets the input signal's LSB depth (8-24 bits).
func (*Encoder) SetLowDelay ¶
SetLowDelay toggles low-delay application behavior.
When enabled, CELT delay compensation is disabled to match restricted low-delay semantics.
func (*Encoder) SetMaxBandwidth ¶
SetMaxBandwidth sets the maximum bandwidth limit.
func (*Encoder) SetPacketLoss ¶
SetPacketLoss sets the expected packet loss percentage (0-100).
func (*Encoder) SetPhaseInversionDisabled ¶
SetPhaseInversionDisabled disables stereo phase inversion.
func (*Encoder) SetPredictionDisabled ¶
SetPredictionDisabled disables inter-frame prediction (silk_mode.reducedDependency). CELT picks it up at the next CELT or hybrid frame (src/opus_encoder.c:2288-2295).
func (*Encoder) SetRestrictedSilkApplication ¶
SetRestrictedSilkApplication toggles restricted-SILK application behavior.
func (*Encoder) SetSignalType ¶
SetSignalType sets the signal type hint for mode selection.
func (*Encoder) SetVBR ¶
SetVBR enables/disables VBR while preserving the existing constraint setting.
func (*Encoder) SetVBRConstraint ¶
SetVBRConstraint toggles VBR constraint without forcing VBR on/off.
func (*Encoder) SetVoIPApplication ¶
SetVoIPApplication toggles VoIP application bias for mode decisions.
func (*Encoder) SetVoiceRatio ¶
SetVoiceRatio sets the private libopus voice-ratio control.
func (*Encoder) SignalType ¶
SignalType returns the current signal type hint.
func (*Encoder) VBRConstraint ¶
VBRConstraint reports whether constrained VBR is enabled.
func (*Encoder) VoIPApplication ¶
VoIPApplication reports whether VoIP application bias is enabled.
func (*Encoder) VoiceRatio ¶
VoiceRatio returns the current private libopus voice-ratio control value.
type Mode ¶
type Mode int
Mode represents the encoding mode.
const ( // ModeAuto automatically selects the best mode based on content and bandwidth. ModeAuto Mode = iota // ModeSILK uses SILK-only encoding (configs 0-11). ModeSILK // ModeHybrid uses combined SILK+CELT encoding (configs 12-15). ModeHybrid // ModeCELT uses CELT-only encoding (configs 16-31). ModeCELT )
type OpusVal16 ¶ added in v0.2.0
type OpusVal16 = opusVal16
OpusVal16 exposes the libopus float-build width in exported signatures.
type OpusVal32 ¶ added in v0.2.0
type OpusVal32 = opusVal32
OpusVal32 exposes the libopus float-build width in exported signatures.
type StereoWidthMem ¶
type StereoWidthMem struct {
// XX is the leaky-integrated left-channel auto-correlation energy (libopus
// "XX").
XX opusVal32
// XY is the leaky-integrated left/right cross-correlation energy (libopus
// "XY").
XY opusVal32
// YY is the leaky-integrated right-channel auto-correlation energy (libopus
// "YY").
YY opusVal32
// SmoothedWidth is the time-smoothed stereo-width estimate in [0,1] (libopus
// "smoothed_width").
SmoothedWidth opusVal16
// MaxFollower is the decaying peak-follower that limits how fast the width may
// drop (libopus "max_follower").
MaxFollower opusVal16
}
StereoWidthMem holds the running cross-correlation state for the stateful compute_stereo_width() estimator. It mirrors libopus StereoWidthState (src/opus_encoder.c) and persists across frames so the stereo->mono and bandwidth decisions see a smoothed width.
type TonalityAnalysisState ¶
type TonalityAnalysisState struct {
// Fs is the analyzer input sample rate in Hz (libopus "Fs").
Fs int32
// LSBDepth is the input bit depth (8..24) used to set the noise floor
// (libopus tracks this via the run_analysis lsb_depth argument).
LSBDepth int32
// Angle is the per-bin FFT phase from the previous analysis step (libopus
// "angle"); it begins the TONALITY_ANALYSIS_RESET_START region.
Angle [240]float32
// DAngle is the first difference of Angle, the per-bin phase rate (libopus
// "d_angle").
DAngle [240]float32
// D2Angle is the second difference of Angle, the per-bin phase acceleration
// used for the tonality estimate (libopus "d2_angle").
D2Angle [240]float32
// InMem is the analyzer input ring buffer (libopus "inmem").
InMem [AnalysisBufSize]float32
// MemFill is the number of usable samples currently in InMem (libopus
// "mem_fill").
MemFill int32
// PrevBandTonality carries the previous frame's per-band tonality for
// temporal smoothing (libopus "prev_band_tonality").
PrevBandTonality [NbTBands]float32
// PrevTonality carries the previous frame's summed tonality (libopus
// "prev_tonality").
PrevTonality float32
// PrevBandwidth is the previously detected bandwidth index (libopus
// "prev_bandwidth"), used for bandwidth hysteresis.
PrevBandwidth int32
// E is the NbFrames-deep ring of per-band linear energies (libopus "E").
E [NbFrames][NbTBands]float32
// SqrtE is a Go-side cache of the per-band magnitudes (sqrt of E) for the
// current frame, avoiding repeated square roots.
SqrtE [NbFrames][NbTBands]float32
// LogE is the NbFrames-deep ring of per-band log energies (libopus "logE").
LogE [NbFrames][NbTBands]float32
// LowE is the long-term per-band energy floor used by the noise/tone
// classifier (libopus "lowE").
LowE [NbTBands]float32
// HighE is the long-term per-band energy ceiling used by the noise/tone
// classifier (libopus "highE").
HighE [NbTBands]float32
// MeanE is the per-band running mean energy (libopus "meanE").
MeanE [NbTBands + 1]float32
// Mem is the feature smoothing memory feeding the MLP (libopus "mem").
Mem [32]float32
// CMean is the running mean of the first four BFCC coefficients (libopus "cmean").
CMean [8]float32
// Std stores running second moments of the temporal BFCC features (libopus "std").
Std [9]float32
// ETracker is the slow energy follower used for loudness/activity (libopus
// "Etracker").
ETracker float32
// LowECount is the fractional count of recent low-energy frames (libopus
// "lowECount").
LowECount float32
// ECount is the per-band energy ring write index (libopus "E_count").
ECount int32
// Count is the number of frames analysed since reset, saturating at
// ANALYSIS_COUNT_MAX (libopus "count").
Count int32
// AnalysisOffset is the sample offset between the analyzer position and the
// current encode frame, carried across RunAnalysis calls.
AnalysisOffset int32
// WritePos is the write index into the Info ring (libopus "write_pos").
WritePos int32
// ReadPos is the read index into the Info ring (libopus "read_pos").
ReadPos int32
// ReadSubframe is the subframe within the Info entry being consumed (libopus
// "read_subframe").
ReadSubframe int32
// HPEnerAccum accumulates high-pass energy for the loudness estimate
// (libopus "hp_ener_accum").
HPEnerAccum float32
// Initialized reports whether the slow init has run (libopus "initialized").
Initialized bool
// RNNState is the GRU hidden state of the music/speech classifier (libopus
// "rnn_state").
RNNState [MaxNeurons]float32
// DownmixState is the stereo->mono downmix filter memory (libopus
// "downmix_state").
DownmixState [3]float32
// Info is the DetectSize-deep ring of per-frame results, read back behind the
// analyzer lookahead (libopus "info").
Info [DetectSize]AnalysisInfo
// contains filtered or unexported fields
}
TonalityAnalysisState is the persistent state of the Opus tonality analyzer, mirroring the TonalityAnalysisState struct in libopus src/analysis.h. It holds the FFT phase history, per-band energy rings and the MLP/GRU recurrent state that produce a music/speech AnalysisInfo for each frame. Exported fields keep the libopus member names (CamelCased) so the port stays auditable against src/analysis.c; unexported scratch fields are Go-only reuse buffers and carry no analyzer state across Reset.
func NewTonalityAnalysisState ¶
func NewTonalityAnalysisState(fs int) *TonalityAnalysisState
NewTonalityAnalysisState allocates and initializes a tonality analyzer for the given input sample rate (Hz). It corresponds to libopus tonality_analysis_init() followed by tonality_analysis_reset(): LSBDepth defaults to 24 and all reset-scoped state is cleared.
func (*TonalityAnalysisState) GetInfo ¶
func (s *TonalityAnalysisState) GetInfo() AnalysisInfo
GetInfo returns the most recently written per-frame AnalysisInfo, i.e. the entry just behind WritePos in the Info ring. Unlike tonality_get_info() in libopus it does not advance or average over subframes; it is a read-only peek at the latest result for callers that drive RunAnalysis directly.
func (*TonalityAnalysisState) Init ¶ added in v0.2.5
func (s *TonalityAnalysisState) Init(fs int)
Init initializes s in place for sample rate fs so callers can embed TonalityAnalysisState inline without a separate heap allocation.
func (*TonalityAnalysisState) Reset ¶
func (s *TonalityAnalysisState) Reset()
Reset clears all reset-scoped analyzer state (the libopus TONALITY_ANALYSIS_RESET_START region onward) while preserving the configured sample rate, LSB depth and reusable scratch allocations. It mirrors libopus tonality_analysis_reset() and must be called on any input discontinuity.
func (*TonalityAnalysisState) RunAnalysis ¶
func (s *TonalityAnalysisState) RunAnalysis(pcm []float32, frameSize int, channels int) AnalysisInfo
RunAnalysis feeds one frame of interleaved float PCM through the tonality analyzer and returns the AnalysisInfo to use for the current frame. It mirrors libopus run_analysis() (src/analysis.c): the input is split into 20ms (Fs/50-sample) chunks fed to tonalityAnalysis, AnalysisOffset is advanced so the analyzer stays frameSize samples behind the encode position, and the matured result is read back via tonalityGetInfo. frameSize is the encode frame length in samples at Fs; channels is 1 or 2. Passing an empty pcm slice only reads back the buffered result without advancing the analyzer.
func (*TonalityAnalysisState) SetLSBDepth ¶
func (s *TonalityAnalysisState) SetLSBDepth(depth int)
SetLSBDepth sets the analyzer's assumed input bit depth, clamped to the Opus range [8,24]. It controls the noise floor used by the tonality estimator and mirrors the lsb_depth value libopus passes into run_analysis.
func (*TonalityAnalysisState) SpeechProbability ¶ added in v0.2.0
func (s *TonalityAnalysisState) SpeechProbability(pcm []float32) float32
SpeechProbability feeds one mono frame to the analyzer and returns the activity_probability (libopus AnalysisInfo) of the newest completed analysis window, the value RunAnalysis reports as VADProb. It is 0 until the first window completes and while the newest window is digital silence, for which libopus repeats the previous entry instead.
With no encoder lookahead the newest window ends 240 samples at 24 kHz (10 ms) before the last input sample. Frames shorter than 20 ms complete a window on every second call and repeat the previous result in between.
type VADState ¶
type VADState struct {
// Analysis filterbank states
AnaState [2]int32 // 0-8 kHz state
AnaState1 [2]int32 // 0-4 kHz state
AnaState2 [2]int32 // 0-2 kHz state
// Subframe energies from previous frame
XnrgSubfr [VADNBands]int32
// Smoothed energy-to-noise ratio per band (Q8)
NrgRatioSmthQ8 [VADNBands]int32
// High-pass filter state for lowest band differentiator
HPState int16
// Noise energy level per band
NL [VADNBands]int32
// Inverse noise energy level per band
InvNL [VADNBands]int32
// Noise level estimator bias per band
NoiseLevelBias [VADNBands]int32
// Frame counter for initial faster adaptation
Counter int32
// Speech activity probability (Q8, 0-255)
SpeechActivityQ8 int32
// Input quality bands (Q15)
InputQualityBandsQ15 [VADNBands]int32
// Input tilt (Q15)
InputTiltQ15 int32
// Hangover counter for smooth transitions
HangoverCount int
// Previous activity decision for hysteresis
PrevActivity bool
// contains filtered or unexported fields
}
VADState holds the state for Voice Activity Detection. This mirrors silk_VAD_state from libopus silk/structs.h.
func NewVADState ¶
func NewVADState() *VADState
NewVADState creates and initializes a new VAD state. Matches silk_VAD_Init from libopus.
func (*VADState) GetSpeechActivity ¶
GetSpeechActivity analyzes the input signal and returns speech activity level. This is the main VAD function matching silk_VAD_GetSA_Q8 from libopus.
Parameters:
- pcm: Input PCM samples (mono, 16-bit range scaled to int16)
- frameLength: Number of samples in the frame
- fsKHz: Sample rate in kHz (8, 12, or 16)
Returns:
- activityQ8: Speech activity level (0-255, Q8)
- isActive: True if speech activity detected
Source Files
¶
- analysis.go
- analysis_avgmod_default.go
- analysis_bins_default.go
- analysis_cmean_update_default.go
- analysis_down2_default.go
- analysis_fixedpoint_default.go
- analysis_mean_std_trace_off.go
- analysis_mlp.go
- analysis_mlp_data.go
- analysis_mlp_default.go
- analysis_mlp_gemm_default.go
- analysis_mlp_trace_off.go
- analysis_neon_default.go
- analysis_per_bin_trace_off.go
- analysis_slope_default.go
- analysis_spec_variability_default.go
- analysis_spec_variability_trace_off.go
- analysis_speech.go
- analysis_weighted_product_default.go
- auto_mode.go
- celt_encode_fixedpoint_default.go
- controls.go
- dred_fields_default.go
- dred_runtime_default.go
- dtx.go
- encode_call.go
- encoder.go
- encoder_hd96k_default.go
- fec.go
- fixed_outer_q8_default.go
- float_contract.go
- frame_native.go
- hybrid_coder_boundary_trace_default.go
- outer_target_default.go
- packet.go
- packet_parse.go
- qext_controls_default.go
- qext_fields_default.go
- scalar_types.go
- short_scratch.go
- short_scratch_default.go
- stereo_fade_default_target.go
- stereo_width_decorr_default.go
- vad.go