Documentation
¶
Overview ¶
Package plc implements Opus-level Packet Loss Concealment (PLC): the machinery that synthesizes plausible audio for frames whose packets were lost, dropped, or arrived too late. Concealment avoids the jarring silence and clicks that would otherwise occur, which is essential for real-time audio over unreliable transports.
Layout ¶
The package is organized around the three Opus operating modes, matching how libopus 1.6.1 splits concealment between its two codec layers:
- State (this file) is the mode-agnostic loss bookkeeping and fade-out cadence: how many consecutive frames have been lost and the residual gain to apply. It coordinates which per-mode routine runs.
- silk_plc.go ports the SILK speech concealment from libopus silk/PLC.c (silk_PLC_conceal / silk_PLC_update) plus the fixed-point helpers from silk/Inlines.h and silk/MacroCount.h that it depends on. This is the bit-exact path used for SILK and the low band of Hybrid frames.
- celt_plc.go provides the CELT (music / fullband) concealment: band-energy decay with per-band noise fill and IMDCT resynthesis, mirroring the spectral-fold strategy of celt/celt_decoder.c celt_decode_lost. It also serves the high band of Hybrid frames (ConcealCELTHybrid).
libopus references ¶
- RFC 6716 Section 4.2.8 (Packet Loss Concealment)
- libopus silk/PLC.c, silk/PLC.h (SILK concealment + constants)
- libopus celt/celt_decoder.c (celt_decode_lost, the CELT loss path)
- libopus silk/dec_API.c (silk_Decode loss/FEC dispatch)
Type discipline ¶
State and SILKPLCState mirror the libopus C struct field widths exactly (opus_int32 -> int32, opus_int16 -> int16, opus_val16 -> float32), because the fixed-point SILK path relies on intermediate truncation and overflow behavior that only reproduces with matching integer widths. type_parity_test.go guards these widths.
Stability ¶
Most applications should use the top-level gopus decoder APIs, which drive this package internally with decoder-owned state. The interfaces and functions here are low-level implementation details and may change before the first release.
Index ¶
- Constants
- func ConcealCELT(dec CELTDecoderState, synth CELTSynthesizer, frameSize int, fadeFactor float32) []float32
- func ConcealCELTHybrid(dec CELTDecoderState, synth CELTSynthesizer, frameSize int, fadeFactor float32) []float32
- func ConcealCELTHybridRawInto(dst []float32, dec CELTDecoderState, synth CELTSynthesizer, frameSize int, ...)
- func ConcealSILK(dec SILKDecoderState, frameSize int, fadeFactor float32) []float32
- func ConcealSILKStereo(dec SILKDecoderState, frameSize int, fadeFactor float32) (left, right []float32)
- func ConcealSILKWithLTP(dec SILKDecoderStateExtended, plcState *SILKPLCState, lossCnt int, ...) []int16
- type CELTBandInfo
- type CELTDecoderState
- type CELTSynthesizer
- type Mode
- type SILKDecoderState
- type SILKDecoderStateExtended
- type SILKOutBufProvider
- type SILKPLCState
- type SILKPitchLagProvider
- type SILKSLPCQ14Provider
- type SILKSLPCQ14Setter
- type SILKSignalTypeProvider
- type State
- func (s *State) FadeFactor() float32
- func (s *State) IsExhausted() bool
- func (s *State) LastChannels() int
- func (s *State) LastFrameSize() int
- func (s *State) LostCount() int
- func (s *State) Mode() Mode
- func (s *State) RecordLoss() float32
- func (s *State) Reset()
- func (s *State) SetLastFrameParams(mode Mode, frameSize, channels int)
Constants ¶
const EnergyDecayPerFrame = 0.85
EnergyDecayPerFrame is the linear factor applied to each band's energy per lost CELT frame so the concealed spectrum fades over consecutive losses. This plays the role of the per-frame energy decay in celt_decode_lost (libopus celt/celt_decoder.c), here expressed directly on the linear band energies rather than libopus' log-domain backgroundLogE decay.
const FadePerFrame float32 = 0.57
FadePerFrame is the per-loss linear gain reduction applied by State.RecordLoss to its mode-agnostic fadeFactor. It is deliberately mild because the per-mode routines (SILK silk_PLC_conceal harm/rand attenuation, CELT band-energy decay) already fade their own output; this factor only coordinates an overall envelope and must not double-attenuate hard.
const MaxConcealedFrames = 5
MaxConcealedFrames is the consecutive-loss count past which State.IsExhausted reports the stream as concealed-out and callers should emit silence. Roughly 100ms at 20ms frames (5 frames). This is the gopus-level safety ceiling on top of the per-mode attenuation; libopus has no single equivalent constant but bounds concealment growth similarly (e.g. celt loss_duration clamping in celt/celt_decoder.c).
Variables ¶
This section is empty.
Functions ¶
func ConcealCELT ¶
func ConcealCELT(dec CELTDecoderState, synth CELTSynthesizer, frameSize int, fadeFactor float32) []float32
ConcealCELT generates a full-band concealment frame for a lost CELT packet, mirroring the spectral-fold loss path of libopus celt/celt_decoder.c celt_decode_lost:
- Decay the previous frame's per-band energies (EnergyDecayPerFrame).
- Refill every coded band with noise shaped to the decayed energy.
- Run the normal IMDCT + overlap-add synthesis.
- Apply de-emphasis, threading the decoder filter state.
The result keeps the spectral envelope of the last good frame while fading out, and the decoder's energy and RNG state are advanced so consecutive losses continue to decay. A nil decoder yields a silent mono frame; a fully faded gain yields silence sized for the decoder's channel count.
Parameters:
- dec: CELT decoder state from the last good frame (read and updated)
- synth: CELT synthesizer for IMDCT (nil yields silence)
- frameSize: samples to generate at 48 kHz (120, 240, 480, or 960)
- fadeFactor: overall gain multiplier (0.0 to 1.0)
Returns the concealed samples at 48 kHz, interleaved if stereo.
func ConcealCELTHybrid ¶
func ConcealCELTHybrid(dec CELTDecoderState, synth CELTSynthesizer, frameSize int, fadeFactor float32) []float32
ConcealCELTHybrid generates the CELT-layer concealment for a lost Hybrid frame, filling only the high bands (from CELTBandInfo.HybridStartBand, bands 17-21); the SILK path conceals the low band, matching the libopus Hybrid layer split (src/opus_decoder.c routing into celt/silk). It is otherwise the same decay + noise-fill + synthesis + de-emphasis pipeline as ConcealCELT.
Parameters:
- dec: CELT decoder state from the last good frame (read and updated)
- synth: CELT synthesizer for IMDCT (nil yields silence)
- frameSize: samples to generate at 48 kHz (480 or 960 for Hybrid)
- fadeFactor: overall gain multiplier (0.0 to 1.0)
Returns the concealed high-frequency samples at 48 kHz, interleaved if stereo.
func ConcealCELTHybridRawInto ¶
func ConcealCELTHybridRawInto(dst []float32, dec CELTDecoderState, synth CELTSynthesizer, frameSize int, fadeFactor float32)
ConcealCELTHybridRawInto writes Hybrid CELT concealment into the caller's dst buffer and, unlike ConcealCELTHybrid, does not apply de-emphasis. This lets a decoder-owned path interleave postfilter/comb-filter and de-emphasis in the exact libopus order (celt/celt_decoder.c) over the combined SILK+CELT signal. dst is written up to frameSize*channels samples and zero-padded beyond.
func ConcealSILK ¶
func ConcealSILK(dec SILKDecoderState, frameSize int, fadeFactor float32) []float32
ConcealSILK is the float fallback concealer for a lost SILK frame, used when only the minimal SILKDecoderState is available. It follows the RFC 6716 Section 4.2.8 strategy in floating point rather than the bit-exact fixed-point path:
- Reuse the previous frame's LPC envelope.
- Voiced: repeat the pitch period from output history with a decaying gain.
- Unvoiced: generate LPC-shaped comfort noise.
- Apply the overall fade factor.
This keeps transitions smooth by preserving the last good frame's spectral character, but it is NOT the byte-exact libopus path; prefer ConcealSILKWithLTP (a port of silk_PLC_conceal) when the extended decoder state is available.
Parameters:
- dec: SILK decoder state from the last good frame
- frameSize: samples to generate at the native SILK rate (8/12/16 kHz)
- fadeFactor: overall gain multiplier (0.0 to 1.0)
Returns the concealed mono samples at the native SILK rate.
func ConcealSILKStereo ¶
func ConcealSILKStereo(dec SILKDecoderState, frameSize int, fadeFactor float32) (left, right []float32)
ConcealSILKStereo conceals a stereo SILK frame using the float fallback path. It runs the mono concealer once and duplicates the result to both channels; it does not reconstruct the SILK mid/side stereo prediction, so it is a fallback for the simple SILKDecoderState only.
Parameters:
- dec: SILK decoder state, applied to both channels
- frameSize: samples per channel at the native SILK rate
- fadeFactor: overall gain multiplier (0.0 to 1.0)
Returns the left and right concealed channels.
func ConcealSILKWithLTP ¶
func ConcealSILKWithLTP(dec SILKDecoderStateExtended, plcState *SILKPLCState, lossCnt int, frameSize int) []int16
ConcealSILKWithLTP is the bit-exact SILK concealer: a Go port of silk_PLC_conceal (libopus silk/PLC.c) that generates one lost frame's residual and synthesizes it through the LPC filter, advancing plcState exactly as libopus does so consecutive losses behave identically. The pipeline is:
- Select loss-count attenuation gains (harm/rand) by voicing.
- Bandwidth-expand the cached LPC (silk_bwexpander) in place.
- On the first loss, set the random scale from the LTP gain (voiced) or downscale it by the LPC inverse prediction gain (unvoiced).
- Build the random-noise source from the lower-energy excitation subframe.
- Rewhiten and scale the LTP state, then run LTP synthesis per subframe, attenuating gains and drifting the pitch lag each subframe.
- Run LPC synthesis, scale by the previous gain, and saturate to int16.
When the decoder implements the optional SILKOutBufProvider / SILKSLPCQ14Provider / SILKSLPCQ14Setter interfaces, the integer outBuf and LPC synthesis history are used and written back, which is what makes the output byte-exact with libopus rather than approximate.
Parameters:
- dec: extended SILK decoder state from the last good frame
- plcState: persistent concealment state, updated in place
- lossCnt: consecutive lost-frame count (0 for the first loss)
- frameSize: samples to generate at the native SILK rate
Returns the concealed mono samples at the native SILK rate (int16 Q0).
Types ¶
type CELTBandInfo ¶
type CELTBandInfo struct {
// MaxBands is the maximum number of frequency bands.
MaxBands int
// HybridStartBand is the first band for hybrid mode (bands 17-21).
HybridStartBand int
// EffBands returns effective bands for a frame size.
EffBands func(frameSize int) int
// BandStart returns the starting bin for a band at given frame size.
BandStart func(band, frameSize int) int
// BandEnd returns the ending bin for a band at given frame size.
BandEnd func(band, frameSize int) int
// ValidFrameSize checks if frame size is valid.
ValidFrameSize func(frameSize int) bool
// Overlap is the overlap size for synthesis.
Overlap int
}
CELTBandInfo describes the CELT critical-band layout the concealer needs: how many bands exist, where the Hybrid high band starts, and the bin span of each band at a given frame size. It corresponds to the eBands / mode tables in libopus celt/modes.c and celt/static_modes_float.h, exposed here as plain callbacks so the plc package need not import the celt package.
type CELTDecoderState ¶
type CELTDecoderState interface {
// Channels returns the number of channels (1 or 2).
Channels() int
// PrevEnergy returns the previous frame's band energies.
PrevEnergy() []float32
// SetPrevEnergy updates the previous energy state.
SetPrevEnergy(energies []float32)
// RNG returns the current RNG state.
RNG() uint32
// SetRNG sets the RNG state.
SetRNG(seed uint32)
// PreemphState returns the de-emphasis filter state.
PreemphState() []float32
// OverlapBuffer returns the overlap buffer for synthesis.
OverlapBuffer() []float32
// SetOverlapBuffer sets the overlap buffer.
SetOverlapBuffer(samples []float32)
}
CELTDecoderState is the minimal view of a CELT decoder that concealment reads and writes: channel count, per-band energies (oldBandE in libopus celt/celt_decoder.c), the noise-fill RNG seed (st->rng), the de-emphasis filter memory, and the IMDCT overlap buffer. Exposing it as an interface lets the plc package conceal without importing the celt package (avoiding an import cycle), while still mutating the live decoder state across losses.
type CELTSynthesizer ¶
type CELTSynthesizer interface {
// SynthesizeFloat32 performs IMDCT synthesis for a mono frame.
SynthesizeFloat32(coeffs []float32, transient bool, shortBlocks int) []float32
// SynthesizeStereoFloat32 performs IMDCT synthesis for a stereo frame,
// returning interleaved L/R samples.
SynthesizeStereoFloat32(coeffsL, coeffsR []float32, transient bool, shortBlocks int) []float32
}
CELTSynthesizer turns the noise-filled MDCT coefficients into time-domain samples via IMDCT + windowing + overlap-add, the same back end the normal CELT decode uses (libopus celt/celt_decoder.c celt_synthesis). It is supplied by the decoder so concealment reuses the live window/overlap state.
type Mode ¶
type Mode int32
Mode indicates which Opus operating mode the last good frame used, and hence which concealment routine to drive for the lost frame. It corresponds to the SILK / CELT / Hybrid split that libopus selects in src/opus_decoder.c.
const ( // ModeSILK indicates SILK-only concealment. // Uses LPC extrapolation and pitch prediction for speech. ModeSILK Mode = iota // ModeCELT indicates CELT-only concealment. // Uses energy decay with noise fill for music/general audio. ModeCELT // ModeHybrid indicates combined SILK+CELT concealment. // Coordinates both layers for hybrid mode frames. ModeHybrid )
type SILKDecoderState ¶
type SILKDecoderState interface {
// PrevLPCValues returns the LPC filter state from the last frame.
PrevLPCValues() []float32
// LPCOrder returns the current LPC order (10 for NB/MB, 16 for WB).
LPCOrder() int
// IsPreviousFrameVoiced returns true if the last frame was voiced.
IsPreviousFrameVoiced() bool
// OutputHistory returns the output history buffer for pitch prediction.
OutputHistory() []float32
// HistoryIndex returns the current position in the history buffer.
HistoryIndex() int
}
SILKDecoderState is the minimal SILK decoder view required by the float fallback concealer (ConcealSILK): the previous LPC envelope, its order, the last voicing decision, and the output history for pitch repetition. It lets the plc package conceal without importing the silk package. The bit-exact concealer needs the richer SILKDecoderStateExtended instead.
type SILKDecoderStateExtended ¶
type SILKDecoderStateExtended interface {
SILKDecoderState
// GetLastSignalType returns 0=inactive, 1=unvoiced, 2=voiced.
GetLastSignalType() int
// GetLTPCoefficients returns the LTP coefficients from the last good frame.
// Returns 5 coefficients in Q14 format.
GetLTPCoefficients() [ltpOrder]int16
// GetPitchLag returns the pitch lag from the last good frame.
GetPitchLag() int
// GetLastGain returns the gain from the last subframe (Q16 format).
GetLastGain() int32
// GetLTPScale returns the LTP scale factor (Q14 format).
GetLTPScale() int32
// GetExcitationHistory returns the excitation signal history (Q14 format).
GetExcitationHistory() []int32
// GetLPCCoefficientsQ12 returns LPC coefficients in Q12 format.
GetLPCCoefficientsQ12() []int16
// GetSampleRateKHz returns the sample rate in kHz (8, 12, or 16).
GetSampleRateKHz() int
// GetSubframeLength returns the subframe length in samples.
GetSubframeLength() int
// GetNumSubframes returns the number of subframes (2 or 4).
GetNumSubframes() int
// GetLTPMemoryLength returns the LTP memory length in samples.
GetLTPMemoryLength() int
}
SILKDecoderStateExtended is the full SILK decoder view consumed by the bit-exact concealer ConcealSILKWithLTP. It exposes everything silk_PLC_conceal reads from silk_decoder_state / silk_decoder_control in libopus: LTP coefficients and scale, pitch lag, subframe gains, LPC coefficients, the excitation history (exc_Q14), and the frame geometry (sample rate, subframe length, subframe count, LTP memory length).
type SILKOutBufProvider ¶
type SILKOutBufProvider interface {
GetOutBufHistoryQ0() []int16
}
SILKOutBufProvider optionally exposes the decoder's output history in Q0 (libopus outBuf, the last ltp_mem_length samples) used for the LPC-analysis rewhitening step of silk_PLC_conceal. Preferred over the float OutputHistory because it is the exact integer input libopus rewhitens.
type SILKPLCState ¶
type SILKPLCState struct {
// LTP coefficients from the last good voiced frame (Q14)
LTPCoefQ14 [ltpOrder]int16
// Pitch lag in Q8 format for sub-sample precision
PitchLQ8 int32
// Previous gains from last 2 subframes (Q16)
PrevGainQ16 [2]int32
// Previous LPC coefficients (Q12)
PrevLPCQ12 [maxLPCOrder]int16
// Previous LTP scale factor (Q14)
PrevLTPScaleQ14 int32
// Random scale for noise mixing (Q14)
RandScaleQ14 int16
// Random seed for noise generation
RandSeed int32
// Sample rate in kHz
FsKHz int32
// Subframe length
SubfrLength int32
// Number of subframes
NbSubfr int32
// LPC order
LPCOrder int32
// Concealed frame energy for glue frames
ConcEnergy int32
ConcEnergyShift int32
// Flag indicating if last frame was lost
LastFrameLost bool
}
SILKPLCState is the persistent SILK concealment state carried across lost frames, a Go port of silk_PLC_struct from libopus silk/structs.h. Field Q-formats match the C struct exactly (see type_parity_test.go), because the concealer's fixed-point math depends on the precise widths. It is updated from each good frame by UpdateFromGoodFrame (silk_PLC_update) and advanced on each loss by ConcealSILKWithLTP (silk_PLC_conceal).
func NewSILKPLCState ¶
func NewSILKPLCState() *SILKPLCState
NewSILKPLCState returns a SILKPLCState initialized to the libopus silk_PLC_Reset defaults (unit gains, 16 kHz WB geometry, unit random scale, zero seed), with the pitch lag pre-seeded to half a 16 kHz 20 ms frame.
func (*SILKPLCState) Reset ¶
func (s *SILKPLCState) Reset(frameLength int)
Reset clears the PLC state for a new stream, mirroring libopus silk_PLC_Reset: the pitch lag is set to half the frame length in Q8, gains and random scale to unity, and the cached LTP/LPC coefficients and loss flag are zeroed.
func (*SILKPLCState) UpdateFromGoodFrame ¶
func (s *SILKPLCState) UpdateFromGoodFrame( signalType int, pitchL []int32, ltpCoefQ14 []int16, ltpScaleQ14 int32, gainsQ16 []int32, lpcQ12 []int16, fsKHz int, nbSubfr int, subfrLength int, )
UpdateFromGoodFrame refreshes the concealment state from a successfully decoded frame so a subsequent loss can extrapolate from it; call it after every good SILK frame. It is a port of silk_PLC_update (libopus silk/PLC.c): for voiced frames it picks the subframe with the strongest LTP gain, centers that gain on the middle tap, and clamps it to the [vPitchGainStartMinQ14, vPitchGainStartMaxQ14] band; for unvoiced frames it clears the LTP taps and sets an 18 ms default pitch lag. The last two subframe gains and the LPC coefficients are always cached.
type SILKPitchLagProvider ¶
type SILKPitchLagProvider interface {
GetLagPrev() int
}
SILKPitchLagProvider optionally exposes the decoder's most recent pitch lag (libopus lagPrev), letting the float fallback concealer use the tracked lag instead of re-estimating it by autocorrelation.
type SILKSLPCQ14Provider ¶
type SILKSLPCQ14Provider interface {
GetSLPCQ14HistoryQ14() []int32
}
SILKSLPCQ14Provider optionally exposes the decoder's LPC synthesis history in Q14 (libopus sLPC_Q14_buf, the most recent lpcOrder samples) so concealment can seed LPC synthesis from real decoder state rather than the float envelope.
type SILKSLPCQ14Setter ¶
type SILKSLPCQ14Setter interface {
SetSLPCQ14HistoryQ14(history []int32)
}
SILKSLPCQ14Setter optionally lets concealment write the advanced LPC synthesis history (Q14) back to the decoder's sLPC_Q14_buf, matching the state cadence libopus silk_PLC_conceal applies after each concealed frame.
type SILKSignalTypeProvider ¶
type SILKSignalTypeProvider interface {
GetLastSignalType() int
}
SILKSignalTypeProvider optionally exposes the libopus prevSignalType tracking: 0=inactive, 1=unvoiced, 2=voiced.
type State ¶
type State struct {
// contains filtered or unexported fields
}
State tracks mode-agnostic PLC bookkeeping across frames: the consecutive loss count, the last good frame's mode/size/channels, and the overall fade envelope. It is the gopus-level coordinator that decides which per-mode concealment routine (ConcealSILK / ConcealCELT / ConcealCELTHybrid) to drive and with what residual gain. The numerically exact loss state for SILK lives separately in SILKPLCState (the port of libopus silk_PLC_struct).
func NewState ¶
func NewState() *State
NewState creates a new PLC state with initial values. The state starts with full gain (fadeFactor = 1.0) and zero lost packet count.
func (*State) FadeFactor ¶
FadeFactor returns the current fade level (0.0 to 1.0), the gain to apply to concealment audio:
- 1.0: full volume, no loss recorded yet (or freshly reset)
- between 0 and 1: decaying after one or more consecutive losses
- 0.0: concealed out after several consecutive losses (silent)
func (*State) IsExhausted ¶
IsExhausted returns true if PLC has exceeded its maximum concealment. After this, the output should effectively be silence.
func (*State) LastChannels ¶
LastChannels returns the channel count from the last good packet.
func (*State) LastFrameSize ¶
LastFrameSize returns the frame size from the last good packet.
func (*State) LostCount ¶
LostCount returns the number of consecutive lost packets. This can be used to determine if we're in extended loss condition.
func (*State) RecordLoss ¶
RecordLoss records one lost packet and returns the updated fade factor to apply to the concealment audio for this frame. Call it once per lost frame before generating concealment.
The factor decays geometrically by FadePerFrame each call and is snapped to exactly 0 once it drops below 0.001, so extended loss settles to silence:
- First loss: fadeFactor = 1.0 * FadePerFrame
- Second loss: fadeFactor = FadePerFrame^2
- After several losses: fadeFactor == 0
func (*State) Reset ¶
func (s *State) Reset()
Reset clears PLC state after receiving a good packet. This should be called whenever a packet is successfully decoded. It resets the lost count and restores full gain.
func (*State) SetLastFrameParams ¶
SetLastFrameParams stores parameters from the last good frame. These parameters are used to generate concealment of the correct duration and channel configuration.
Parameters:
- mode: The Opus mode (SILK, CELT, or Hybrid)
- frameSize: Frame size in samples at 48kHz
- channels: Number of channels (1 or 2)