Documentation
¶
Overview ¶
Package encoder implements the unified Opus encoder defined by RFC 6716. It is a behavior-for-behavior Go port of the orchestration layer in libopus 1.6.1 (src/opus_encoder.c): it owns the SILK and CELT sub-encoders, decides which of the three coding modes to use for each frame, runs the rate/bandwidth control loop, and assembles the final Opus packet.
Coding modes ¶
Every Opus frame is coded in exactly one mode (RFC 6716 Section 2):
- SILK-only (configs 0-11): linear-prediction speech coder for narrowband through wideband, the lowest-rate VoIP path.
- Hybrid (configs 12-15): SILK codes the 0-8kHz core while CELT codes the 8-20kHz high band, for super-wideband and fullband speech.
- CELT-only (configs 16-31): transform coder for music and low-latency audio.
ModeAuto lets the encoder choose per frame from signal type, bitrate and the tonality analyzer, mirroring the decision chain in opus_encoder.c.
Pipeline ¶
Encode and its variants run the libopus opus_encode_native pipeline for one frame: optional variable high-pass / DC rejection on the input, the tonality analysis ("the brain", see TonalityAnalysisState), mode and bandwidth selection, delay compensation and mode-transition prefill, the SILK/CELT/Hybrid bridge, the VBR/CBR/CVBR rate controller, DTX activity detection, and packet assembly (see BuildPacket). Sub-encoders and large scratch buffers are created lazily and reused across frames so steady-state encoding is allocation-free.
Determinism and parity ¶
The package is written to match libopus output frame-for-frame: the internal numeric types deliberately mirror the C types (opus_val16/opus_val32/opus_res), and FinalRange exposes the range-coder state so output can be checked against a reference encoder. Set the same controls (bitrate, complexity, VBR, FEC, DTX, bandwidth) in the same order as libopus to reproduce its bitstream.
References: RFC 6716; libopus 1.6.1 src/opus_encoder.c, src/analysis.c.
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 ComputeStereoWidth(pcm []opusRes, frameSize, channels int) opusVal16
- func ValidBitrate(bitrate int) bool
- func ValidFrameSize(frameSize int, mode Mode) bool
- type AnalysisDenseLayer
- type AnalysisGRULayer
- type AnalysisInfo
- type BitrateMode
- type Encoder
- func (e *Encoder) Bandwidth() types.Bandwidth
- func (e *Encoder) Bitrate() int
- func (e *Encoder) CELTEnergyMask() []float32
- func (e *Encoder) CELTSurroundTrim() opusVal32
- 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) 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) LFE() bool
- func (e *Encoder) LSBDepth() int
- func (e *Encoder) LastOpusVADActive() bool
- func (e *Encoder) LastOpusVADProb() float32
- func (e *Encoder) LastSilkLTPCorr() float32
- func (e *Encoder) LastSilkVADActivity() int
- func (e *Encoder) LastSilkVADInputTiltQ15() int
- 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) 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) SetCELTCVBRBoundScale(scale float32)
- func (e *Encoder) SetCELTEnergyMask(mask []float32)
- func (e *Encoder) SetCELTPayloadCeilingActive(active bool)
- func (e *Encoder) SetCELTSurroundTrim(trim opusVal32)
- 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 HybridState
- type Mode
- type StereoWidthMem
- type TonalityAnalysisState
- 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 // Mode-specific typical ranges SILKMinBitrate = 6000 // 6 kbps SILKMaxBitrate = 40000 // 40 kbps (WB) CELTMinBitrate = 32000 // 32 kbps CELTMaxBitrate = 510000 // 510 kbps HybridMinBitrate = 12000 // 12 kbps HybridMaxBitrate = 128000 // 128 kbps typical )
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") // ErrInvalidHybridFrameSize indicates a frame size invalid for hybrid mode. ErrInvalidHybridFrameSize = errors.New("encoder: hybrid mode only supports 10ms (480) or 20ms (960) frames") // 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 ComputeStereoWidth ¶
func ComputeStereoWidth(pcm []opusRes, frameSize, channels int) opusVal16
ComputeStereoWidth computes the stereo width for hybrid mode encoding. At low bitrates, stereo width is reduced to improve coding efficiency. This matches libopus compute_stereo_width().
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 is the row-major NbInputs*NbNeurons int8 weight matrix
// (libopus "input_weights").
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 and dequantized with WeightsScale on first use.
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 is variable bitrate mode (default). // Packet size varies based on content complexity. // Provides best quality for a given average bitrate. ModeVBR BitrateMode = iota // ModeCVBR is constrained variable bitrate mode. // Packet size varies but stays within +/-15% of target. // Good balance of quality and bandwidth predictability. ModeCVBR // ModeCBR is constant bitrate mode. // Every packet is exactly the same size (or within 1 byte). // Required for some streaming protocols. ModeCBR )
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 a new unified Opus encoder.
func (*Encoder) CELTEnergyMask ¶
CELTEnergyMask returns the current CELT energy mask.
func (*Encoder) CELTSurroundTrim ¶
func (e *Encoder) CELTSurroundTrim() opusVal32
CELTSurroundTrim returns the current CELT alloc-trim surround bias.
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) 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) GetBitrateMode ¶
func (e *Encoder) GetBitrateMode() BitrateMode
BitrateMode returns the current bitrate mode.
func (*Encoder) GetVADActivity ¶
GetVADActivity returns the current VAD speech activity level (0-255).
func (*Encoder) InDTX ¶
InDTX returns whether the encoder is currently in DTX mode. This matches OPUS_GET_IN_DTX from libopus.
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) LastSilkLTPCorr ¶
LastSilkLTPCorr returns the last SILK pitch correlation estimate.
func (*Encoder) LastSilkVADActivity ¶
LastSilkVADActivity returns the last SILK VAD speech activity (Q8, 0-255).
func (*Encoder) LastSilkVADInputTiltQ15 ¶
LastSilkVADInputTiltQ15 returns the last SILK VAD input tilt (Q15).
func (*Encoder) MaxBandwidth ¶
MaxBandwidth returns the maximum bandwidth limit.
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) 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) SetCELTCVBRBoundScale ¶
SetCELTCVBRBoundScale scales CELT constrained-VBR burst bound. Valid range is [0, 1], where 1 keeps libopus single-stream behavior.
func (*Encoder) SetCELTEnergyMask ¶
SetCELTEnergyMask sets per-band CELT surround masking (21 mono, 42 stereo).
func (*Encoder) SetCELTPayloadCeilingActive ¶
SetCELTPayloadCeilingActive enables bounding the CELT-only range coder by max_data_bytes-1, used by the multistream encoder to honor per-stream curr_max ceilings. Single-stream encoders leave this unset.
func (*Encoder) SetCELTSurroundTrim ¶
func (e *Encoder) SetCELTSurroundTrim(trim opusVal32)
SetCELTSurroundTrim sets the CELT alloc-trim surround bias.
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 sets the frame size in samples at 48kHz.
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.
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 HybridState ¶
type HybridState struct {
// contains filtered or unexported fields
}
HybridState holds state for hybrid mode encoding. This is stored in the Encoder and persists across frames.
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 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 MLP feature vector (libopus "cmean").
CMean [8]float32
// Std is the running standard deviation of the MLP 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) 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.
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