silk

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: BSD-3-Clause Imports: 9 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package silk implements the SILK speech layer of Opus (RFC 6716 Section 4.2), the low-level codec used by gopus for the SILK and Hybrid Opus modes.

Most applications should use the top-level gopus encoder/decoder APIs rather than this package directly. The symbols exported here are advanced implementation details and may change before the first release.

Relationship to libopus

This package is a behaviour-for-behaviour Go port of the reference SILK implementation in libopus 1.6.1 (the silk/ directory of the libopus source tree). The fixed-point decode path is bit-exact with libopus: identical range-coded input produces identical PCM, including the saturating fixed-point arithmetic, Q-format scaling and per-subframe state carried across frames. Where a Go file mirrors a specific libopus translation unit, its doc comments name that source file (for example silk/decode_core.c or silk/NLSF2A.c) so the two can be diffed.

Decoder

The decode path is structured as in libopus:

  • Decode / DecodeStereo (silk.go) — public per-packet entry points, mirroring silk/dec_API.c silk_Decode. They parse the SILK header (VAD + LBRR flags), decode each 20 ms frame, run mid/side to left/right stereo unmixing, and resample from the internal SILK rate (8/12/16 kHz) to the decoder API rate.
  • decodeFrameCoreInto (frame_decode_helpers.go) — one SILK frame, mirroring silk/decode_frame.c silk_decode_frame: decode indices, decode pulses, dequantize parameters, run the LTP/LPC synthesis core.
  • silkDecodeIndices / silkDecodeParameters / silkDecodeCore / silkDecodePulses (libopus_decode.go) — port silk/decode_indices.c, silk/decode_parameters.c, silk/decode_core.c and silk/decode_pulses.c.
  • LBRR / Forward Error Correction (lbrr_decode.go) — DecodeFEC mirrors silk_Decode with lostFlag = FLAG_DECODE_LBRR.
  • Packet Loss Concealment (silk.go, cng.go, plc_glue.go, plc package) — ports silk/PLC.c and silk/CNG.c; invoked when Decode is called with nil data for a lost packet.
  • Resampler (resample_libopus.go) — ports silk/resampler*.c.

All public decode entry points are written to tolerate malformed, truncated or otherwise hostile input without panicking: the range decoder keeps returning symbols past the end of the buffer, so out-of-range indices are bounded inside the SILK decoder. Valid input remains bit-exact with libopus; the decode-path fuzz targets in this package assert the no-panic contract.

Package silk implements LBRR (Low Bitrate Redundancy) encoding for FEC. LBRR provides forward error correction by including redundant data for the previous frame at a lower quality in the current packet.

Reference: libopus silk/encode_frame_FLP.c silk_LBRR_encode_FLP

Code generated from libopus tables. DO NOT EDIT.

Package silk implements SILK Noise Shaping Quantization (NSQ). Reference: libopus silk/NSQ.c and silk/NSQ_del_dec.c

Package silk implements the SILK audio decoder per RFC 6716 Section 4.2.

Index

Constants

View Source
const (
	MaxFramesPerPacket = maxFramesPerPacket
)
View Source
const SilkSampleScale = silkSampleScale

SilkSampleScale exposes the internal sample scaling factor used by the SILK float path.

Variables

View Source
var (
	// ErrInvalidResampleRate indicates an invalid source rate for resampling.
	ErrInvalidResampleRate = errors.New("silk: invalid resample rate")

	// ErrMismatchedLengths indicates mismatched slice lengths in stereo unmixing.
	ErrMismatchedLengths = errors.New("silk: mismatched slice lengths")

	// ErrNoLBRRData indicates no LBRR (FEC) data is available in the packet.
	// LBRR data is only encoded when the encoder has FEC enabled and speech activity
	// exceeds the threshold.
	ErrNoLBRRData = errors.New("silk: no LBRR data available for FEC recovery")
)
View Source
var (
	ErrInvalidBandwidth = errors.New("silk: invalid bandwidth for SILK mode")
	ErrDecodeFailed     = errors.New("silk: frame decode failed")
)

Errors for SILK decoding

View Source
var CosineTable = [129]int32{}/* 129 elements not displayed */

CosineTable - cosine values in Q12 format.

View Source
var ErrInvalidPacket = errors.New("silk: invalid packet")

ErrInvalidPacket indicates the packet data is malformed.

View Source
var GainDequantTable = [64]int32{
	81920, 96256, 112640, 131072, 153600, 180224, 210944, 246784,
	286720, 335872, 397312, 464896, 540672, 634880, 745472, 872448,
	1019904, 1187840, 1392640, 1646592, 1925120, 2244608, 2621440, 3080192,
	3604480, 4194304, 4915200, 5767168, 6782976, 7929856, 9240576, 10813440,
	12713984, 14876672, 17301504, 20316160, 23855104, 28049408, 32768000, 38273024,
	44826624, 52690944, 61603840, 71827456, 83886080, 98566144, 115867648, 135266304,
	158334976, 185597952, 217055232, 253755392, 295698432, 346030080, 406847488, 480247808,
	557842432, 654311424, 767557632, 897581056, 1048576000, 1224736768, 1434451968, 1686110208,
}

GainDequantTable - dequantization table for gain values. Q16 format. Generated from libopus gain_quant.c formula:

logQ7 = SMULWB(INV_SCALE_Q16, idx) + OFFSET
gain_Q16 = log2lin(min(logQ7, 3967))

where INV_SCALE_Q16 = 1907825, OFFSET = 2090

View Source
var ICDFDeltaGain = []uint16{
	256, 250, 245, 239, 230, 219, 203, 180, 149, 111, 73, 41, 20, 8, 2, 0,
}

ICDFDeltaGain - delta gain between subframes. Centered at 4, so delta = decoded - 4.

View Source
var ICDFExcitationLSB = []uint16{
	256, 136, 0,
}

ICDFExcitationLSB - LSB for pulse magnitudes.

View Source
var ICDFExcitationPulseCount = []uint16{
	256, 240, 224, 208, 192, 176, 160, 144, 128, 112, 96, 80, 64, 48, 32, 16, 0,
}

ICDFExcitationPulseCount - pulse count per shell block.

View Source
var ICDFExcitationSign = [3][2][6][]uint16{

	{
		{icdfExcitationSign_0_0_1, icdfExcitationSign_0_0_2, icdfExcitationSign_0_0_3,
			icdfExcitationSign_0_0_4, icdfExcitationSign_0_0_5, icdfExcitationSign_0_0_6},
		{icdfExcitationSign_0_1_1, icdfExcitationSign_0_1_2, icdfExcitationSign_0_1_3,
			icdfExcitationSign_0_1_4, icdfExcitationSign_0_1_5, icdfExcitationSign_0_1_6},
	},

	{
		{icdfExcitationSign_1_0_1, icdfExcitationSign_1_0_2, icdfExcitationSign_1_0_3,
			icdfExcitationSign_1_0_4, icdfExcitationSign_1_0_5, icdfExcitationSign_1_0_6},
		{icdfExcitationSign_1_1_1, icdfExcitationSign_1_1_2, icdfExcitationSign_1_1_3,
			icdfExcitationSign_1_1_4, icdfExcitationSign_1_1_5, icdfExcitationSign_1_1_6},
	},

	{
		{icdfExcitationSign_2_0_1, icdfExcitationSign_2_0_2, icdfExcitationSign_2_0_3,
			icdfExcitationSign_2_0_4, icdfExcitationSign_2_0_5, icdfExcitationSign_2_0_6},
		{icdfExcitationSign_2_1_1, icdfExcitationSign_2_1_2, icdfExcitationSign_2_1_3,
			icdfExcitationSign_2_1_4, icdfExcitationSign_2_1_5, icdfExcitationSign_2_1_6},
	},
}

ICDFExcitationSign indexed by [signalType][quantOffset][pulseCount-1]. Note: pulseCount 0 doesn't need sign decoding.

View Source
var ICDFExcitationSplit = [][]uint16{
	icdfExcitationSplit0, icdfExcitationSplit1, icdfExcitationSplit2, icdfExcitationSplit3,
	icdfExcitationSplit4, icdfExcitationSplit5, icdfExcitationSplit6, icdfExcitationSplit7,
	icdfExcitationSplit8, icdfExcitationSplit9, icdfExcitationSplit10, icdfExcitationSplit11,
	icdfExcitationSplit12, icdfExcitationSplit13, icdfExcitationSplit14, icdfExcitationSplit15,
	icdfExcitationSplit16,
}

ICDFExcitationSplit indexed by pulse count.

View Source
var ICDFFrameTypeVADActive = []uint16{232, 158, 10, 0}

ICDFFrameTypeVADActive - frame type for VAD active frames. From libopus silk_type_offset_VAD_iCDF = {232, 158, 10, 0} Encodes (signalType-1)*2 + quantOffset with 4 outcomes: 0: unvoiced low, 1: unvoiced high, 2: voiced low, 3: voiced high

View Source
var ICDFFrameTypeVADInactive = []uint16{230, 0}

ICDFFrameTypeVADInactive - frame type for VAD inactive frames (no VAD). From libopus silk_type_offset_no_VAD_iCDF = {230, 0} Symbol 0 = inactive with probability 230/256 ≈ 90%

View Source
var ICDFGainDelta = ICDFDeltaGain

ICDFGainDelta - delta gain between subframes (same as ICDFDeltaGain).

View Source
var ICDFGainHighBits = [][]uint16{

	{256, 224, 192, 160, 128, 96, 64, 32, 0},

	{256, 204, 153, 102, 51, 0},

	{256, 255, 244, 220, 186, 145, 100, 56, 20, 0},
}

ICDFGainHighBits - high bits of absolute gain indexed by signal type.

View Source
var ICDFGainLSB = []uint16{
	256, 224, 192, 160, 128, 96, 64, 32, 0,
}

ICDFGainLSB - gain LSB (3 bits = 8 values).

View Source
var ICDFGainMSBInactive = []uint16{
	256, 224, 192, 160, 128, 96, 64, 32, 0,
}

ICDFGainMSBInactive - gain MSB for inactive signal type.

View Source
var ICDFGainMSBUnvoiced = []uint16{
	256, 204, 154, 102, 51, 0,
}

ICDFGainMSBUnvoiced - gain MSB for unvoiced signal type.

View Source
var ICDFGainMSBVoiced = []uint16{
	256, 255, 244, 220, 186, 145, 100, 56, 20, 0,
}

ICDFGainMSBVoiced - gain MSB for voiced signal type.

View Source
var ICDFLBRRFlag = []uint16{
	256, 205, 0,
}

ICDFLBRRFlag - LBRR (Low Bitrate Redundancy) flag decoding.

View Source
var ICDFLBRRFlags2 = []uint16{
	256, 217, 188, 65, 0,
}

ICDFLBRRFlags2 - LBRR flags for 2 frames.

View Source
var ICDFLBRRFlags3 = []uint16{
	256, 226, 204, 183, 132, 108, 66, 17, 0,
}

ICDFLBRRFlags3 - LBRR flags for 3 frames.

View Source
var ICDFLCGSeed = []uint16{
	256, 192, 128, 64, 0,
}

ICDFLCGSeed - uniform 4-symbol distribution for LCG seed.

View Source
var ICDFLSFInterpolation = []uint16{
	256, 200, 150, 100, 50, 0,
}

ICDFLSFInterpolation - LSF interpolation weight index. 5 possible interpolation values (0, 0.25, 0.5, 0.75, 1).

View Source
var ICDFLSFStage1NBMBUnvoiced = []uint16{
	256, 239, 223, 208, 193, 178, 163, 149, 135, 122, 109, 96,
	84, 72, 61, 51, 42, 33, 25, 18, 12, 7, 3, 0,
}

ICDFLSFStage1NBMBUnvoiced - LSF stage 1 codebook index for NB/MB unvoiced.

View Source
var ICDFLSFStage1NBMBVoiced = []uint16{
	256, 240, 226, 214, 202, 190, 178, 166, 154, 142, 130, 118,
	106, 94, 82, 70, 58, 48, 40, 32, 24, 17, 11, 6, 2, 0,
}

ICDFLSFStage1NBMBVoiced - LSF stage 1 codebook index for NB/MB voiced.

View Source
var ICDFLSFStage1WBUnvoiced = []uint16{
	256, 238, 221, 205, 190, 175, 161, 148, 135, 123, 111, 100,
	89, 79, 69, 60, 51, 43, 35, 28, 21, 15, 10, 6, 3, 1, 0,
}

ICDFLSFStage1WBUnvoiced - LSF stage 1 codebook index for WB unvoiced.

View Source
var ICDFLSFStage1WBVoiced = []uint16{
	256, 238, 221, 204, 188, 173, 158, 144, 131, 118, 106, 95,
	84, 74, 65, 56, 47, 39, 32, 25, 19, 13, 8, 4, 1, 0,
}

ICDFLSFStage1WBVoiced - LSF stage 1 codebook index for WB voiced.

View Source
var ICDFLSFStage2NBMB = [8][]uint16{
	{256, 212, 168, 127, 85, 42, 0},
	{256, 235, 195, 146, 90, 37, 0},
	{256, 218, 175, 133, 91, 47, 0},
	{256, 226, 185, 139, 91, 43, 0},
	{256, 231, 192, 147, 96, 44, 0},
	{256, 238, 206, 164, 113, 58, 0},
	{256, 232, 196, 155, 107, 54, 0},
	{256, 228, 190, 148, 101, 50, 0},
}

ICDFLSFStage2NBMB - LSF stage 2 residual tables for NB/MB. 8 tables, each with varying number of symbols.

View Source
var ICDFLSFStage2WB = [8][]uint16{
	{256, 212, 168, 127, 85, 42, 0},
	{256, 235, 195, 146, 90, 37, 0},
	{256, 218, 175, 133, 91, 47, 0},
	{256, 226, 185, 139, 91, 43, 0},
	{256, 231, 192, 147, 96, 44, 0},
	{256, 238, 206, 164, 113, 58, 0},
	{256, 232, 196, 155, 107, 54, 0},
	{256, 228, 190, 148, 101, 50, 0},
}

ICDFLSFStage2WB - LSF stage 2 residual tables for WB. 8 tables with potentially different symbol counts.

View Source
var ICDFLTPFilterIndexHighPeriod = []uint16{
	256, 206, 157, 109, 63, 21, 0,
}

ICDFLTPFilterIndexHighPeriod - LTP filter periodicity index (high period).

View Source
var ICDFLTPFilterIndexLowPeriod = []uint16{
	256, 185, 114, 43, 0,
}

ICDFLTPFilterIndexLowPeriod - LTP filter periodicity index (low period).

View Source
var ICDFLTPFilterIndexMidPeriod = []uint16{
	256, 196, 138, 83, 36, 0,
}

ICDFLTPFilterIndexMidPeriod - LTP filter periodicity index (mid period).

View Source
var ICDFLTPGainHigh = []uint16{
	256, 248, 240, 232, 224, 216, 208, 200, 192, 184, 176, 168, 160, 152, 144, 136,
	128, 120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0,
}

ICDFLTPGainHigh - LTP gain index for high periodicity.

View Source
var ICDFLTPGainLow = []uint16{
	256, 224, 192, 160, 128, 96, 64, 32, 0,
}

ICDFLTPGainLow - LTP gain index for low periodicity.

View Source
var ICDFLTPGainMid = []uint16{
	256, 240, 224, 208, 192, 176, 160, 144, 128, 112, 96, 80, 64, 48, 32, 16, 0,
}

ICDFLTPGainMid - LTP gain index for mid periodicity.

View Source
var ICDFPitchContourMB = []uint16{
	256, 178, 110, 55, 0,
}

ICDFPitchContourMB - pitch contour for mediumband.

View Source
var ICDFPitchContourNB = []uint16{
	256, 235, 215, 195, 175, 155, 135, 115, 95, 75, 55, 35, 17, 10, 5, 2, 0,
}

ICDFPitchContourNB - pitch contour for narrowband (16 values).

View Source
var ICDFPitchContourWB = []uint16{
	256, 178, 110, 55, 0,
}

ICDFPitchContourWB - pitch contour for wideband.

View Source
var ICDFPitchDelta = []uint16{
	256, 232, 204, 171, 128, 85, 52, 24, 0,
}

ICDFPitchDelta - pitch lag delta for contour coding.

View Source
var ICDFPitchLagMB = []uint16{
	256, 237, 218, 199, 181, 162, 144, 127, 109, 92, 76, 60, 45, 30, 15, 0,
}

ICDFPitchLagMB - pitch lag MSB for mediumband.

View Source
var ICDFPitchLagNB = []uint16{
	256, 230, 204, 178, 153, 128, 102, 76, 51, 0,
}

ICDFPitchLagNB - pitch lag MSB for narrowband. 8 values for high/contour parts.

View Source
var ICDFPitchLagWB = []uint16{
	256, 245, 234, 223, 213, 203, 193, 183, 173, 163, 153, 143,
	133, 124, 115, 106, 97, 88, 79, 70, 62, 54, 46, 38, 30, 22, 15, 8, 0,
}

ICDFPitchLagWB - pitch lag MSB for wideband.

View Source
var ICDFPitchLowBitsQ2 = []uint16{
	256, 192, 128, 64, 0,
}

ICDFPitchLowBitsQ2 - low bits (Q2) of pitch lag.

View Source
var ICDFPitchLowBitsQ3 = []uint16{
	256, 224, 192, 160, 128, 96, 64, 32, 0,
}

ICDFPitchLowBitsQ3 - low bits (Q3) of pitch lag.

View Source
var ICDFPitchLowBitsQ4 = []uint16{
	256, 240, 224, 208, 192, 176, 160, 144, 128, 112, 96, 80, 64, 48, 32, 16, 0,
}

ICDFPitchLowBitsQ4 - low bits (Q4) of pitch lag.

View Source
var ICDFRateLevelUnvoiced = []uint16{
	256, 241, 221, 193, 159, 118, 72, 31, 0,
}

ICDFRateLevelUnvoiced - rate level index for unvoiced.

View Source
var ICDFRateLevelVoiced = []uint16{
	256, 232, 200, 162, 120, 78, 42, 14, 0,
}

ICDFRateLevelVoiced - rate level index for voiced.

View Source
var ICDFShellBlocks = [][]uint16{
	icdfShellBlock0, icdfShellBlock1, icdfShellBlock2, icdfShellBlock3,
	icdfShellBlock4, icdfShellBlock5, icdfShellBlock6, icdfShellBlock7,
	icdfShellBlock8, icdfShellBlock9, icdfShellBlock10, icdfShellBlock11,
	icdfShellBlock12, icdfShellBlock13, icdfShellBlock14, icdfShellBlock15,
	icdfShellBlock16, icdfShellBlock17,
}

ICDFShellBlocks indexed by total pulse count.

View Source
var ICDFStereoOnlyFlag = []uint16{
	256, 128, 0,
}

ICDFStereoOnlyFlag - stereo-only flag (side channel present).

View Source
var ICDFStereoPredWeight = []uint16{
	256, 223, 191, 159, 127, 95, 63, 31, 0,
}

ICDFStereoPredWeight - stereo prediction weight index.

View Source
var ICDFStereoPredWeightDelta = []uint16{
	256, 244, 220, 180, 126, 72, 36, 12, 0,
}

ICDFStereoPredWeightDelta - stereo prediction weight delta.

View Source
var ICDFVADFlag = []uint16{
	256, 155, 0,
}

ICDFVADFlag - VAD flag decoding (per frame).

View Source
var LSFCodebookNBMB = [32][10]uint8{
	{12, 35, 60, 83, 108, 132, 157, 180, 206, 228},
	{15, 32, 55, 77, 101, 125, 151, 175, 201, 225},
	{19, 42, 66, 89, 114, 137, 162, 184, 209, 230},
	{12, 25, 50, 72, 97, 120, 147, 172, 200, 223},
	{26, 44, 69, 90, 114, 135, 159, 180, 205, 225},
	{13, 22, 53, 80, 106, 130, 156, 180, 205, 228},
	{15, 25, 44, 64, 90, 115, 142, 168, 196, 222},
	{19, 24, 62, 82, 100, 120, 145, 168, 190, 214},
	{22, 31, 50, 79, 103, 120, 151, 170, 203, 227},
	{21, 29, 45, 65, 106, 124, 150, 171, 196, 224},
	{30, 49, 75, 97, 121, 142, 165, 186, 209, 229},
	{19, 25, 52, 70, 93, 116, 143, 166, 192, 219},
	{26, 34, 62, 75, 97, 118, 145, 167, 194, 217},
	{25, 33, 56, 70, 91, 113, 143, 165, 196, 223},
	{21, 34, 51, 72, 97, 117, 145, 171, 196, 222},
	{20, 29, 50, 67, 90, 117, 144, 168, 197, 221},
	{22, 31, 48, 66, 95, 117, 146, 168, 196, 222},
	{24, 33, 51, 77, 116, 134, 158, 180, 200, 224},
	{21, 28, 70, 87, 106, 124, 149, 170, 194, 217},
	{26, 33, 53, 64, 83, 117, 152, 173, 204, 225},
	{27, 34, 65, 95, 108, 129, 155, 174, 210, 225},
	{20, 26, 72, 99, 113, 131, 154, 176, 200, 219},
	{34, 43, 61, 78, 93, 114, 155, 170, 201, 227},
	{23, 29, 54, 97, 124, 138, 163, 179, 209, 229},
	{30, 38, 56, 89, 118, 129, 158, 178, 200, 231},
	{21, 29, 49, 63, 85, 111, 142, 163, 193, 222},
	{27, 48, 77, 103, 133, 158, 179, 196, 215, 232},
	{29, 47, 74, 99, 124, 151, 176, 198, 220, 237},
	{33, 42, 61, 76, 93, 121, 155, 174, 207, 225},
	{29, 53, 87, 112, 136, 154, 170, 188, 208, 227},
	{24, 30, 52, 84, 131, 150, 166, 186, 203, 229},
	{37, 48, 64, 84, 104, 118, 156, 177, 201, 230},
}

LSFCodebookNBMB - LSF stage 1 codebook for NB/MB (10 coefficients, 32 vectors). Each vector represents a set of 10 Line Spectral Frequencies.

View Source
var LSFCodebookWB = [32][16]uint8{
	{7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239},
	{13, 25, 41, 55, 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236},
	{15, 21, 34, 51, 61, 78, 92, 106, 126, 136, 152, 167, 185, 205, 225, 240},
	{10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, 189, 205, 221, 237},
	{17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240},
	{10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236},
	{8, 21, 37, 51, 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218},
	{12, 15, 34, 55, 63, 78, 87, 108, 118, 131, 148, 167, 185, 203, 219, 236},
	{16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, 186, 204, 220, 237},
	{11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241},
	{6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225},
	{11, 19, 30, 44, 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234},
	{15, 22, 35, 52, 67, 82, 97, 112, 127, 142, 157, 172, 187, 202, 217, 233},
	{8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239},
	{11, 23, 41, 59, 73, 87, 104, 118, 131, 145, 160, 175, 190, 205, 220, 236},
	{12, 17, 29, 46, 57, 71, 86, 101, 115, 130, 145, 160, 176, 191, 207, 223},
	{17, 23, 35, 51, 68, 80, 95, 105, 125, 134, 146, 164, 182, 201, 221, 237},
	{9, 16, 29, 40, 56, 71, 86, 101, 119, 131, 146, 162, 178, 195, 211, 228},
	{29, 36, 50, 66, 78, 92, 107, 123, 138, 153, 168, 183, 198, 213, 228, 243},
	{8, 25, 42, 59, 70, 87, 98, 114, 125, 138, 155, 168, 182, 196, 210, 223},
	{13, 17, 31, 43, 53, 70, 81, 96, 112, 127, 142, 157, 175, 191, 212, 231},
	{17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240},
	{8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239},
	{13, 16, 41, 66, 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241},
	{17, 25, 37, 52, 63, 75, 92, 102, 119, 132, 144, 160, 175, 191, 212, 231},
	{19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 175, 190, 203, 218, 233, 247},
	{20, 26, 40, 54, 64, 77, 91, 104, 117, 131, 145, 160, 174, 190, 206, 223},
	{30, 37, 50, 66, 78, 88, 103, 110, 125, 137, 153, 171, 189, 205, 222, 237},
	{8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239},
	{17, 24, 41, 55, 66, 77, 91, 104, 119, 131, 147, 163, 179, 196, 214, 232},
	{16, 22, 36, 48, 63, 77, 93, 107, 123, 137, 154, 169, 187, 202, 220, 235},
	{25, 31, 45, 58, 72, 85, 99, 116, 133, 151, 167, 184, 200, 215, 231, 245},
}

LSFCodebookWB - LSF stage 1 codebook for WB (16 coefficients, 32 vectors).

View Source
var LSFMinSpacingNBMB = [11]int{
	250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461,
}

LSFMinSpacingNBMB - minimum spacing between LSF coefficients for NB/MB. 11 values (d_LPC + 1).

View Source
var LSFMinSpacingWB = [17]int{
	100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347,
}

LSFMinSpacingWB - minimum spacing between LSF coefficients for WB. 17 values (d_LPC + 1).

View Source
var LSFOrderingNBMB = [10]uint8{0, 9, 6, 3, 4, 5, 8, 1, 2, 7}

LSFOrderingNBMB - ordering indices for NB/MB LSF coefficients.

View Source
var LSFOrderingWB = [16]uint8{0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1}

LSFOrderingWB - ordering indices for WB LSF coefficients.

View Source
var LSFPredWeightsNBMB = [2][9]uint8{
	{179, 116, 85, 68, 58, 52, 46, 42, 37},
	{116, 85, 68, 58, 52, 46, 42, 37, 32},
}

LSFPredWeightsNBMB - LSF prediction weights for NB/MB (2 orderings x 9 weights).

View Source
var LSFPredWeightsWB = [2][15]uint8{
	{175, 114, 83, 66, 56, 48, 42, 38, 34, 30, 27, 24, 22, 20, 18},
	{114, 83, 66, 56, 48, 42, 38, 34, 30, 27, 24, 22, 20, 18, 16},
}

LSFPredWeightsWB - LSF prediction weights for WB (2 orderings x 15 weights).

View Source
var LSFStage2ResNBMB = [8][9][10]int8{

	{
		{-3, -3, -3, -3, -3, -3, -3, -3, -3, -3},
		{-2, -2, -2, -2, -2, -2, -2, -2, -2, -2},
		{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
		{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
		{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
		{2, 2, 2, 2, 2, 2, 2, 2, 2, 2},
		{3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
		{4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
		{5, 5, 5, 5, 5, 5, 5, 5, 5, 5},
	},

	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
	},
}

LSFStage2ResNBMB - LSF stage 2 residual codebooks for NB/MB. 8 maps x 9 vectors x 10 coefficients. NOTE: Maps 1-7 are intentionally identical per RFC 6716 Section 4.2.7.5.2. The duplication is required for indexed access during decoding; do not consolidate.

View Source
var LSFStage2ResWB = [8][9][16]int8{

	{
		{-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3},
		{-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2},
		{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
		{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
		{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
		{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},
		{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
		{4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
		{5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5},
	},

	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
	},
	{
		{-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
		{-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13},
		{-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14},
		{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
		{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17},
		{3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18},
		{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
		{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
	},
}

LSFStage2ResWB - LSF stage 2 residual codebooks for WB. 8 maps x 9 vectors x 16 coefficients. NOTE: Maps 1-7 are intentionally identical per RFC 6716 Section 4.2.7.5.2. The duplication is required for indexed access during decoding; do not consolidate.

View Source
var LSFWeightSelectNBMB = [32][9]uint8{
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1},
}

LSFWeightSelectNBMB - weight selection for NB/MB (32 vectors x 9 weights).

View Source
var LSFWeightSelectWB = [32][15]uint8{
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
	{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
}

LSFWeightSelectWB - weight selection for WB (32 vectors x 15 weights).

View Source
var LTPFilterHigh = [32][5]int8{
	{-6, 27, 61, 39, 5},
	{-11, 42, 88, 4, 1},
	{-2, 60, 65, 6, -4},
	{-1, -5, 73, 56, 1},
	{-9, 19, 94, 29, -9},
	{0, 12, 99, 6, 4},
	{8, -19, 102, 46, -13},
	{3, 2, 13, 3, 2},
	{9, -21, 84, 72, -18},
	{-11, 46, 104, -22, 8},
	{18, 38, 48, 23, 0},
	{-16, 70, 83, -21, 11},
	{5, -11, 117, 22, -8},
	{-6, 23, 117, -12, 3},
	{3, -8, 95, 28, 4},
	{-10, 15, 77, 60, -15},
	{-1, 4, 124, 2, -4},
	{3, 38, 84, 24, -25},
	{2, 13, 42, 13, 31},
	{21, -4, 56, 46, -1},
	{-1, 35, 79, -13, 19},
	{-7, 65, 88, -9, -14},
	{20, 4, 81, 49, -29},
	{20, 0, 75, 3, -17},
	{5, -9, 44, 92, -8},
	{1, -3, 22, 69, 31},
	{-6, 95, 41, -12, 5},
	{39, 67, 16, -4, 1},
	{0, -6, 120, 55, -36},
	{-13, 44, 122, 4, -24},
	{81, 5, 11, 3, 7},
	{2, 0, 9, 10, 88},
}

LTPFilterHigh - LTP filter taps for high periodicity (32 entries x 5 taps).

View Source
var LTPFilterLow = [8][5]int8{
	{4, 6, 24, 7, 5},
	{0, 0, 2, 0, 0},
	{12, 28, 41, 13, -4},
	{-9, 15, 42, 25, 14},
	{1, -2, 62, 41, -9},
	{-10, 37, 65, -4, 3},
	{-6, 4, 66, 7, -8},
	{16, 14, 38, -3, 33},
}

LTPFilterLow - LTP filter taps for low periodicity (8 entries x 5 taps).

View Source
var LTPFilterMid = [16][5]int8{
	{13, 22, 39, 23, 12},
	{-1, 36, 64, 27, -6},
	{-7, 10, 55, 43, 17},
	{1, 1, 8, 1, 1},
	{6, -11, 74, 53, -9},
	{-12, 55, 76, -12, 8},
	{-3, 3, 93, 27, -4},
	{26, 39, 59, 3, -8},
	{2, 0, 77, 11, 9},
	{-8, 22, 44, -6, 7},
	{40, 9, 26, 3, 9},
	{-7, 20, 101, -7, 4},
	{3, -8, 42, 26, 0},
	{-15, 33, 68, 2, 23},
	{-2, 55, 46, -2, 15},
	{3, -1, 21, 16, 41},
}

LTPFilterMid - LTP filter taps for mid periodicity (16 entries x 5 taps).

View Source
var PitchContourMB10ms = [4][2]int8{
	{0, 0}, {0, 1}, {0, -1}, {1, 0},
}

PitchContourMB10ms - pitch contour for MB 10ms frames (4 entries x 2 subframes).

View Source
var PitchContourMB20ms = [4][4]int8{
	{0, 0, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}, {0, 0, -1, 0},
}

PitchContourMB20ms - pitch contour for MB 20ms frames (4 entries x 4 subframes).

View Source
var PitchContourNB10ms = [16][2]int8{
	{0, 0}, {0, 1}, {0, -1}, {1, 0},
	{1, 1}, {-1, 0}, {0, 2}, {1, -1},
	{0, -2}, {-1, 1}, {2, 0}, {-1, -1},
	{1, 2}, {-2, 0}, {2, 1}, {-1, 2},
}

PitchContourNB10ms - pitch contour for NB 10ms frames (16 entries x 2 subframes).

View Source
var PitchContourNB20ms = [16][4]int8{
	{0, 0, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}, {0, 0, -1, 0},
	{0, 0, 0, -1}, {0, 0, 1, 1}, {0, 0, -1, -1}, {0, 1, 0, 0},
	{0, 0, 1, -1}, {0, 0, -1, 1}, {0, 1, 1, 0}, {0, -1, 0, 0},
	{0, 1, 0, 1}, {0, 1, -1, 0}, {0, -1, 1, 0}, {0, -1, 0, 1},
}

PitchContourNB20ms - pitch contour for NB 20ms frames (16 entries x 4 subframes).

View Source
var PitchContourWB10ms = [4][2]int8{
	{0, 0}, {0, 1}, {0, -1}, {1, 0},
}

PitchContourWB10ms - pitch contour for WB 10ms frames (4 entries x 2 subframes).

View Source
var PitchContourWB20ms = [4][4]int8{
	{0, 0, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}, {0, 0, -1, 0},
}

PitchContourWB20ms - pitch contour for WB 20ms frames (4 entries x 4 subframes).

Functions

func DecodeStereoEncoded

func DecodeStereoEncoded(encoded []byte, bandwidth Bandwidth) (left, right []float32, err error)

DecodeStereoEncoded decodes a range-coded SILK stereo packet back to separate left/right channel float32 slices at 48 kHz.

The input must be a complete SILK stereo bitstream produced by EncodeStereoWithEncoder (or the equivalent libopus stereo encoder). The packet contains range-coded VAD/LBRR header bits, stereo prediction indices, mid and side channel frame data.

Returns left and right channels (each 48 kHz, length = frameSizeSamples).

func Encode

func Encode(pcm []float32, bandwidth Bandwidth, vadFlag bool) ([]byte, error)

Encode encodes mono PCM audio to SILK frame. pcm: Input samples at encoder's configured sample rate vadFlag: True if frame contains voice activity Returns: Encoded SILK frame bytes

func EncodeStereo

func EncodeStereo(left, right []float32, bandwidth Bandwidth, vadFlag bool) ([]byte, error)

EncodeStereo encodes stereo PCM audio to SILK frame. left, right: Input samples for each channel bandwidth: Target bandwidth vadFlag: True if frame contains voice activity Returns: Encoded SILK frame bytes for combined mid/side channels

Note: This function allocates new encoders per call. For zero-allocation encoding, use EncodeStereoWithEncoder.

func EncodeStereoIndices

func EncodeStereoIndices(enc *rangecoding.Encoder, ix StereoQuantIndices)

EncodeStereoIndices encodes pre-computed stereo quantization indices. Use this when you've already called QuantizeStereoWeights.

func EncodeStereoMidOnly

func EncodeStereoMidOnly(enc *rangecoding.Encoder, midOnly int)

EncodeStereoMidOnly encodes the stereo "mid-only" flag. This is only encoded when the side channel VAD flag is inactive. midOnly=1 means side channel is not coded.

func EncodeStereoWithEncoder

func EncodeStereoWithEncoder(enc, sideEnc *Encoder, left, right []float32, bandwidth Bandwidth, vadFlag bool) ([]byte, error)

EncodeStereoWithEncoder encodes stereo PCM audio using pre-existing encoders into a single SILK stereo bitstream that matches the libopus format.

The output is a valid SILK stereo packet containing:

  • VAD/LBRR header bits for both channels (patched at end)
  • LBRR data for both channels
  • Stereo prediction indices (range coded)
  • Mid-only flag (when side VAD is inactive)
  • Mid channel frame data (range coded)
  • Side channel frame data (range coded, if not mid-only)

This matches libopus enc_API.c silk_Encode() for nChannelsInternal == 2.

enc: Pre-allocated encoder for mid channel sideEnc: Pre-allocated encoder for side channel left, right: Input samples for each channel at SILK sample rate bandwidth: Target bandwidth vadFlag: True if frame contains voice activity Returns: Encoded SILK stereo frame bytes

func EncodeStereoWithEncoderVADAnalyzersWithSide

func EncodeStereoWithEncoderVADAnalyzersWithSide(
	enc, sideEnc *Encoder,
	left, right []float32,
	bandwidth Bandwidth,
	vadFlags []bool,
	vadStates []VADFrameState,
	midAnalyzer VADFrameAnalyzer,
	sideVADFlags []bool,
	sideVADStates []VADFrameState,
	sideAnalyzer VADFrameAnalyzer,
) ([]byte, error)

EncodeStereoWithEncoderVADAnalyzersWithSide is like EncodeStereoWithEncoderVADFlagsAndStatesWithSide, but lets callers compute VAD from the transformed mid/side frames after stereo_LR_to_MS, matching libopus enc_API.c packet control cadence.

func EncodeStereoWithEncoderVADFlags

func EncodeStereoWithEncoderVADFlags(enc, sideEnc *Encoder, left, right []float32, bandwidth Bandwidth, vadFlags []bool) ([]byte, error)

EncodeStereoWithEncoderVADFlags is the multi-frame variant of EncodeStereoWithEncoder. It accepts per-20ms VAD flags for 40/60ms packets.

func EncodeStereoWithEncoderVADFlagsAndStatesWithSide

func EncodeStereoWithEncoderVADFlagsAndStatesWithSide(
	enc, sideEnc *Encoder,
	left, right []float32,
	bandwidth Bandwidth,
	vadFlags []bool,
	vadStates []VADFrameState,
	sideVADFlags []bool,
	sideVADStates []VADFrameState,
) ([]byte, error)

EncodeStereoWithEncoderVADFlagsAndStatesWithSide is like EncodeStereoWithEncoderVADFlagsWithSide, but also applies optional per-frame VAD-derived state for mid/side encoders.

func EncodeStereoWithEncoderVADFlagsWithSide

func EncodeStereoWithEncoderVADFlagsWithSide(enc, sideEnc *Encoder, left, right []float32, bandwidth Bandwidth, vadFlags []bool, sideVADFlags []bool) ([]byte, error)

EncodeStereoWithEncoderVADFlagsWithSide is like EncodeStereoWithEncoderVADFlags, but accepts optional side-channel VAD flags. When sideVADFlags is nil, side VAD defaults to mid VAD gating for backward compatibility.

func GainQ16FromPCM

func GainQ16FromPCM(pcm []int16, subframeSamples int) int32

GainQ16FromPCM computes Q16 gain from PCM samples using libopus method. This computes the subframe energy and converts to gain matching libopus.

libopus flow (silk/float/process_gains_FLP.c): 1. Gains[k] = sqrt(residual_energy) -> linear amplitude in int16 range (0-32767) 2. pGains_Q16[k] = Gains[k] * 65536.0f -> Q16 format

For raw PCM (without LPC prediction), gain = RMS amplitude of signal.

func GetQuantizationOffset

func GetQuantizationOffset(signalType, quantOffsetType int) int

GetQuantizationOffset returns the quantization offset Q10 value for a given signal type and quantization offset type. This matches libopus silk_Quantization_Offsets_Q10[signalType>>1][quantOffsetType].

func HPCutoffCoefsQ28

func HPCutoffCoefsQ28(cutoffHz, fs int32) (bQ28 [3]int32, aQ28 [2]int32)

HPCutoffCoefsQ28 computes the second-order high-pass biquad coefficients (Q28) for a given cutoff frequency and sample rate, matching the coefficient derivation in hp_cutoff() (src/opus_encoder.c):

Fc_Q19 = silk_DIV32_16( silk_SMULBB( SILK_FIX_CONST(1.5*pi/1000,19), cutoff_Hz ), Fs/1000 )
r_Q28  = SILK_FIX_CONST(1.0,28) - silk_MUL( SILK_FIX_CONST(0.92,9), Fc_Q19 )
b = r * [1; -2; 1]
a = [ -r*(2 - Fc*Fc); r^2 ]   (in the SILK biquad sign convention)

func InitVariableHPSmth2Q15

func InitVariableHPSmth2Q15() int32

InitVariableHPSmth2Q15 returns the Opus-level init value for variable_HP_smth2_Q15 (src/opus_encoder.c opus_encoder_init):

silk_LSHIFT( silk_lin2log( VARIABLE_HP_MIN_CUTOFF_HZ ), 8 )

func InterpolatePredictorsFloat

func InterpolatePredictorsFloat(prevPred, currPred [2]float32, prevWidth, currWidth float32,
	mid, side []float32, frameLength, fsKHz int) []float32

InterpolatePredictorsFloat applies 8ms smooth predictor interpolation using float arithmetic. This is a cleaner implementation for testing and understanding the interpolation algorithm.

The function linearly interpolates from prevPred to currPred over the first interpSamples (8ms * fsKHz), then uses currPred for the remainder.

Parameters:

  • prevPred: previous frame's predictor [LP, HP] as float
  • currPred: current frame's predictor [LP, HP] as float
  • prevWidth: previous frame's stereo width (0.0-1.0)
  • currWidth: current frame's stereo width (0.0-1.0)
  • mid: mid channel samples (length frameLength+2, with history)
  • side: side channel samples (length frameLength+2, with history)
  • frameLength: number of output samples
  • fsKHz: sample rate in kHz

Returns:

  • sideOut: side channel with interpolated prediction applied

func MinCutoffLogSmth2Q15

func MinCutoffLogSmth2Q15() int32

MinCutoffLogSmth2Q15 returns the smth2 seed used when SILK is in CELT-only mode: silk_LSHIFT( silk_lin2log( VARIABLE_HP_MIN_CUTOFF_HZ ), 8 ). Identical to InitVariableHPSmth2Q15; named for the opus_encoder.c MODE_CELT_ONLY branch.

func NoiseShapeQuantize

func NoiseShapeQuantize(nsq *NSQState, input []int16, params *NSQParams) ([]int8, []int16)

NoiseShapeQuantize performs noise shaping quantization on input samples. This is the main NSQ function matching libopus silk_NSQ_c.

Parameters:

  • nsq: NSQ state (modified)
  • input: Input signal (Q0, scaled)
  • params: NSQ parameters

Returns:

  • pulses: Quantized pulse signal (int8 per sample)
  • xq: Quantized/reconstructed signal

func NoiseShapeQuantizeDelDec

func NoiseShapeQuantizeDelDec(nsq *NSQState, input []int16, params *NSQParams) ([]int8, []int16, int)

NoiseShapeQuantizeDelDec performs delayed-decision noise shaping quantization. Returns pulses, reconstructed samples, and the seed to encode.

func Sigmoid

func Sigmoid(x float32) float32

Sigmoid computes the sigmoid function: 1 / (1 + exp(-x)).

Reference: libopus silk/float/SigProc_FLP.h silk_sigmoid():

return (silk_float)( 1.0 / ( 1.0 + exp( -x ) ) );

The exp() and the reciprocal are evaluated in double precision, with a single round-to-float32 on the final result, matching the C cast semantics.

func SmoothVariableHPSmth2Q15

func SmoothVariableHPSmth2Q15(smth2, hpFreqSmth1 int32) int32

SmoothVariableHPSmth2Q15 advances the Opus-level smth2 state toward hpFreqSmth1 and returns the new value (src/opus_encoder.c):

variable_HP_smth2_Q15 = silk_SMLAWB( variable_HP_smth2_Q15,
    hp_freq_smth1 - variable_HP_smth2_Q15, SILK_FIX_CONST(VARIABLE_HP_SMTH_COEF2,16) )

func VariableHPCutoffHz

func VariableHPCutoffHz(smth2 int32) int32

VariableHPCutoffHz converts a smth2 (log2 domain, Q15) value to a cutoff frequency in Hz: silk_log2lin( silk_RSHIFT( variable_HP_smth2_Q15, 8 ) ).

Types

type Bandwidth

type Bandwidth uint8

Bandwidth represents SILK audio bandwidth. SILK supports three bandwidths for speech coding.

const (
	// BandwidthNarrowband is 8kHz sample rate, used for low-bandwidth speech.
	BandwidthNarrowband Bandwidth = iota
	// BandwidthMediumband is 12kHz sample rate, used for medium-bandwidth speech.
	BandwidthMediumband
	// BandwidthWideband is 16kHz sample rate, used for high-quality speech.
	BandwidthWideband
)

func BandwidthFromOpus

func BandwidthFromOpus(opusBandwidth int) (Bandwidth, bool)

BandwidthFromOpus converts Opus bandwidth to SILK bandwidth. SILK only supports NB, MB, WB. SWB and FB use Hybrid mode.

Returns the SILK bandwidth and true if valid, or (0, false) for SWB/FB.

func (Bandwidth) String

func (bw Bandwidth) String() string

String returns the string representation of the bandwidth.

type BandwidthConfig

type BandwidthConfig struct {
	// SampleRate is the output sample rate in Hz (8000, 12000, or 16000).
	SampleRate int
	// LPCOrder is the number of LPC coefficients (10 for NB/MB, 16 for WB).
	LPCOrder int
	// SubframeSamples is the number of samples per 5ms subframe.
	SubframeSamples int
	// PitchLagMin is the minimum pitch lag in samples.
	PitchLagMin int
	// PitchLagMax is the maximum pitch lag in samples.
	PitchLagMax int
}

BandwidthConfig holds bandwidth-dependent parameters for SILK decoding. These values are fixed per RFC 6716.

func GetBandwidthConfig

func GetBandwidthConfig(bw Bandwidth) BandwidthConfig

GetBandwidthConfig returns the configuration for the given bandwidth.

type Decoder

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

Decoder decodes SILK frames from an Opus packet. It maintains state across frames for proper speech continuity.

SILK is the speech layer of Opus, using Linear Predictive Coding (LPC) for efficient speech compression. The decoder reconstructs audio by: 1. Parsing frame headers (VAD, signal type, quantization offset) 2. Decoding parameters (gains, LSF/LPC coefficients, pitch lags) 3. Reconstructing excitation signal 4. Applying LTP (voiced) and LPC synthesis filters

Reference: RFC 6716 Section 4.2

func NewDecoder

func NewDecoder() *Decoder

NewDecoder creates a new SILK decoder with proper initial state. The decoder is ready to process SILK frames after creation.

func (*Decoder) AdvanceDeepPLCLowbandMono

func (d *Decoder) AdvanceDeepPLCLowbandMono(concealed []float32) bool

AdvanceDeepPLCLowbandMono feeds concealed low-band samples through the mono wideband resampler to advance the decoder's resampler state, returning false if the decoder, input, or resampler is unavailable.

func (*Decoder) ApplyDeepPLCLossMono

func (d *Decoder) ApplyDeepPLCLossMono(concealed, rendered []float32, lagPrev int) int

ApplyDeepPLCLossMono records a mono lost frame whose concealment was produced externally (the deep/neural PLC), writing concealed into rendered and updating the channel-0 SILK loss state, pitch lag and LPC history so a following good frame glues correctly. It still advances the standard SILK PLC state to keep the pitch lag consistent. Returns the number of samples written. Used by the hybrid DRED/DeepPLC path; the standard SILK concealment is decodePLC.

func (*Decoder) ArmPLCLowbandCapture

func (d *Decoder) ArmPLCLowbandCapture(buf []int16)

ArmPLCLowbandCapture arms (or, with buf==nil, disarms) capture of the next decodePLC / decodePLCStereo call's resampled int16 SILK lowband into buf (interleaved by channel, length frameSize*channels). After the PLC decode the caller reads PLCLowbandCaptured for the number of interleaved samples filled. It is used only by the FIXED_POINT integer hybrid PLC path.

func (*Decoder) BuildMonoResamplerInput

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

BuildMonoResamplerInput prepares the mono resampler input using libopus-style sMid buffering. It updates the internal sMid state based on the current samples.

func (*Decoder) BuildMonoResamplerInputInt16

func (d *Decoder) BuildMonoResamplerInputInt16(samples []int16) []int16

BuildMonoResamplerInputInt16 prepares mono resampler input with libopus-style sMid buffering. This int16 variant is used by decoder hot paths to avoid float32->int16 reconversion.

func (*Decoder) Decode

func (d *Decoder) Decode(
	data []byte,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
) ([]float32, error)

Decode decodes one SILK mono packet and returns PCM at the decoder API rate. If data is nil it performs Packet Loss Concealment (PLC) for a lost packet instead of decoding. Mirrors the mono path of libopus silk/dec_API.c silk_Decode followed by the SILK resampler.

The function never panics on malformed or truncated data: the range decoder keeps producing symbols past the end of the buffer, and the resulting out-of-range indices are bounded inside the SILK decoder. Valid input is bit-exact with libopus.

Parameters:

  • data: raw SILK frame data (without TOC byte), or nil for PLC
  • bandwidth: NB, MB, or WB (from TOC)
  • frameSizeSamples: frame size in samples at the decoder API rate
  • vadFlag: voice activity flag (from bitstream header)

Returns float32 samples in range [-1, 1] at the decoder API rate.

func (*Decoder) DecodeFEC

func (d *Decoder) DecodeFEC(
	data []byte,
	bandwidth Bandwidth,
	frameSizeSamples int,
	stereo bool,
	outputChannels int,
) ([]float32, error)

DecodeFEC decodes LBRR (Low Bitrate Redundancy) frames for Forward Error Correction. This function decodes the FEC data from a packet to recover a lost frame.

Parameters:

  • data: The Opus packet data containing LBRR
  • bandwidth: Audio bandwidth (NB/MB/WB)
  • frameSizeSamples: Expected frame size in samples at the decoder API rate
  • stereo: Whether the packet contains stereo data
  • outputChannels: Number of output channels (1 or 2)

Returns decoded samples at the decoder API rate, or an error if no LBRR data available.

Reference: libopus silk/dec_API.c silk_Decode with lostFlag=FLAG_DECODE_LBRR

func (*Decoder) DecodeFrame

func (d *Decoder) DecodeFrame(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	duration FrameDuration,
	vadFlag bool,
) ([]float32, error)

DecodeFrame decodes a single SILK mono frame from the bitstream. Returns decoded samples at native SILK sample rate (8/12/16kHz).

The output includes libopus-compatible delay compensation: - 1 sample from sMid history buffer prepended before resampler - N samples of resampler input delay (varies by sample rate) This matches libopus's exact output timing for test vector compliance.

Parameters:

  • rd: Range decoder initialized with the SILK bitstream
  • bandwidth: Audio bandwidth (NB/MB/WB)
  • duration: Frame duration (10/20/40/60ms)
  • vadFlag: Voice Activity Detection flag from header

For 40/60ms frames, the frame is decoded as multiple 20ms sub-blocks.

func (*Decoder) DecodeFrameRaw

func (d *Decoder) DecodeFrameRaw(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	duration FrameDuration,
	vadFlag bool,
) ([]float32, error)

DecodeFrameRaw decodes a single SILK mono frame from the bitstream. Returns decoded samples at native SILK sample rate (8/12/16kHz) as float32.

Unlike DecodeFrame, this does NOT apply libopus-compatible delay compensation. The caller is responsible for handling sMid buffering before resampling. This is used by Decode, DecodeWithDecoder, and the Hybrid decoder.

Parameters:

  • rd: Range decoder initialized with the SILK bitstream
  • bandwidth: Audio bandwidth (NB/MB/WB)
  • duration: Frame duration (10/20/40/60ms)
  • vadFlag: Voice Activity Detection flag from header

For 40/60ms frames, the frame is decoded as multiple 20ms sub-blocks.

func (*Decoder) DecodeFrameRawInt16

func (d *Decoder) DecodeFrameRawInt16(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	duration FrameDuration,
	vadFlag bool,
) ([]int16, error)

DecodeFrameRawInt16 decodes a single SILK mono frame at native SILK sample rate as int16. This is an int16-native variant used by hot paths that resample immediately.

func (*Decoder) DecodeFrameType

func (d *Decoder) DecodeFrameType(vadFlag bool) (signalType, quantOffset int)

DecodeFrameType decodes a frame's signal type and quantization offset from the decoder's current range-decoder position, selecting the active or inactive iCDF by vadFlag (RFC 6716 Section 4.2.7.3). This is the same first step that silkDecodeIndices performs inline; it mirrors the frame-type decode at the top of libopus silk/decode_indices.c silk_decode_indices and is provided as a standalone helper.

For inactive frames (vadFlag=false) it returns signal type in {0,1} with the low/high quantization offset; for active frames (vadFlag=true) signal type is 1 (unvoiced) or 2 (voiced).

func (*Decoder) DecodeMonoToStereo

func (d *Decoder) DecodeMonoToStereo(
	data []byte,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
	stereoToMono bool,
) ([]float32, error)

DecodeMonoToStereo decodes a mono SILK frame and returns stereo PCM at the decoder API rate. When stereoToMono is true (stereo -> mono transition), the right channel is resampled using its own resampler state instead of simple duplication to match libopus behavior.

func (*Decoder) DecodeMonoToStereoWithDecoder

func (d *Decoder) DecodeMonoToStereoWithDecoder(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
	stereoToMono bool,
) ([]float32, error)

DecodeMonoToStereoWithDecoder decodes a mono SILK frame to stereo using a pre-initialized range decoder. stereoToMono mirrors libopus behavior for stereo->mono transitions.

func (*Decoder) DecodeMonoToStereoWithDecoderInto

func (d *Decoder) DecodeMonoToStereoWithDecoderInto(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
	stereoToMono bool,
	output []float32,
) (int, error)

DecodeMonoToStereoWithDecoderInto decodes a mono SILK frame into a caller-owned interleaved stereo buffer.

func (*Decoder) DecodePLCInto

func (d *Decoder) DecodePLCInto(bandwidth Bandwidth, frameSizeSamples int, output []float32) (int, error)

DecodePLCInto generates mono SILK concealment audio for a lost packet and writes the resampled API-rate PCM into output. It is the zero-allocation counterpart of decodePLC: the caller owns the destination buffer, which must hold at least frameSizeSamples samples. Returns the number of samples written.

func (*Decoder) DecodePLCStereoInto

func (d *Decoder) DecodePLCStereoInto(bandwidth Bandwidth, frameSizeSamples int, output []float32) (int, error)

DecodePLCStereoInto generates stereo SILK concealment audio for a lost packet and writes the interleaved [L0,R0,L1,R1,...] API-rate PCM into output. It is the zero-allocation counterpart of decodePLCStereo: the caller owns the destination buffer, which must hold at least 2*frameSizeSamples samples. Returns the number of interleaved samples written.

func (*Decoder) DecodeStereo

func (d *Decoder) DecodeStereo(
	data []byte,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
) ([]float32, error)

DecodeStereo decodes one SILK stereo packet and returns PCM at the decoder API rate. If data is nil it performs Packet Loss Concealment (PLC) for a lost packet instead of decoding. Mirrors the stereo path of libopus silk/dec_API.c silk_Decode (mid/side decode plus silk/stereo_MS_to_LR.c) followed by the SILK resampler. Like Decode it never panics on malformed input and is bit-exact with libopus on valid input.

Returns interleaved stereo samples [L0, R0, L1, R1, ...] at the decoder API rate.

func (*Decoder) DecodeStereoFrame

func (d *Decoder) DecodeStereoFrame(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	duration FrameDuration,
	vadFlag bool,
) (left, right []float32, err error)

DecodeStereoFrame decodes a SILK stereo frame from the bitstream. Returns left and right channel samples at native sample rate.

Stereo SILK uses mid-side coding with prediction. The mid channel is decoded first, then the side channel, and finally they are unmixed to left and right.

func (*Decoder) DecodeStereoFrameInt16Into

func (d *Decoder) DecodeStereoFrameInt16Into(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	duration FrameDuration,
	vadFlag bool,
	leftNative, rightNative []int16,
) (int, error)

DecodeStereoFrameInt16Into decodes a SILK stereo frame at native rate into caller-provided planar int16 buffers.

func (*Decoder) DecodeStereoFrameToMono

func (d *Decoder) DecodeStereoFrameToMono(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	duration FrameDuration,
	vadFlag bool,
) ([]float32, error)

DecodeStereoFrameToMono decodes a stereo SILK frame and returns the mid channel at native sample rate. The side channel is still decoded to keep the bitstream aligned.

func (*Decoder) DecodeStereoToInt16

func (d *Decoder) DecodeStereoToInt16(
	data []byte,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
) ([]int16, error)

DecodeStereoToInt16 decodes stereo and converts to int16 PCM. Returns interleaved stereo samples [L0, R0, L1, R1, ...] as int16.

func (*Decoder) DecodeStereoToMono

func (d *Decoder) DecodeStereoToMono(
	data []byte,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
) ([]float32, error)

DecodeStereoToMono decodes a SILK stereo frame and returns mono PCM at the decoder API rate. This matches libopus behavior when the decoder is configured for mono output.

func (*Decoder) DecodeStereoToMonoWithDecoder

func (d *Decoder) DecodeStereoToMonoWithDecoder(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
) ([]float32, error)

DecodeStereoToMonoWithDecoder decodes a SILK stereo frame to mono using a pre-initialized range decoder.

func (*Decoder) DecodeStereoWithDecoder

func (d *Decoder) DecodeStereoWithDecoder(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
) ([]float32, error)

DecodeStereoWithDecoder decodes a SILK stereo frame using a pre-initialized range decoder.

func (*Decoder) DecodeStereoWithDecoderInto

func (d *Decoder) DecodeStereoWithDecoderInto(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
	output []float32,
) (int, error)

DecodeStereoWithDecoderInto decodes a SILK stereo frame into a caller-owned interleaved stereo buffer.

func (*Decoder) DecodeToInt16

func (d *Decoder) DecodeToInt16(
	data []byte,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
) ([]int16, error)

DecodeToInt16 decodes and converts to int16 PCM. This is a convenience wrapper for common audio output formats.

func (*Decoder) DecodeWithDecoder

func (d *Decoder) DecodeWithDecoder(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
) ([]float32, error)

DecodeWithDecoder decodes a SILK mono frame using a pre-initialized range decoder. This mirrors Decode() but avoids re-initializing the range decoder.

func (*Decoder) DecodeWithDecoderInto

func (d *Decoder) DecodeWithDecoderInto(
	rd *rangecoding.Decoder,
	bandwidth Bandwidth,
	frameSizeSamples int,
	vadFlag bool,
	output []float32,
) (int, error)

DecodeWithDecoderInto decodes a SILK mono frame into a caller-provided buffer. This is the zero-allocation version of DecodeWithDecoder. Returns the number of samples written to the output buffer.

func (*Decoder) FillMonoOutBufTailFloat

func (d *Decoder) FillMonoOutBufTailFloat(dst []float32, samples int) int

FillMonoOutBufTailFloat copies the most recent samples of the channel-0 output history into dst as float32 in [-1, 1), returning the number written (0 if the request cannot be satisfied). Used to prime concealment from past output.

func (*Decoder) FinalRange

func (d *Decoder) FinalRange() uint32

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

func (*Decoder) GetExcitationHistory

func (d *Decoder) GetExcitationHistory() []int32

GetExcitationHistory returns the channel-0 decoder's most recent excitation (Q14), the lookback PLC uses to extrapolate a concealed frame.

func (*Decoder) GetLPCCoefficientsQ12

func (d *Decoder) GetLPCCoefficientsQ12() []int16

GetLPCCoefficientsQ12 returns the channel-0 PLC state's last LPC short-term prediction coefficients (Q12).

func (*Decoder) GetLTPCoefficients

func (d *Decoder) GetLTPCoefficients() [ltpOrder]int16

GetLTPCoefficients returns the channel-0 PLC state's last long-term-prediction filter coefficients (Q14), used to seed pitch-based concealment.

func (*Decoder) GetLTPMemoryLength

func (d *Decoder) GetLTPMemoryLength() int

GetLTPMemoryLength returns the channel-0 LTP memory length in samples.

func (*Decoder) GetLTPScale

func (d *Decoder) GetLTPScale() int32

GetLTPScale returns the channel-0 PLC state's last LTP scaling factor (Q14).

func (*Decoder) GetLagPrev

func (d *Decoder) GetLagPrev() int

GetLagPrev returns the previous pitch lag tracked by SILK decode state.

func (*Decoder) GetLastGain

func (d *Decoder) GetLastGain() int32

GetLastGain returns the channel-0 most recent subframe gain (Q16).

func (*Decoder) GetLastSignalType

func (d *Decoder) GetLastSignalType() int

GetLastSignalType returns the signal type from the last decoded frame. Returns: 0=inactive, 1=unvoiced, 2=voiced

func (*Decoder) GetNumSubframes

func (d *Decoder) GetNumSubframes() int

GetNumSubframes returns the channel-0 number of subframes for the last frame.

func (*Decoder) GetOutBufHistoryQ0

func (d *Decoder) GetOutBufHistoryQ0() []int16

GetOutBufHistoryQ0 returns the channel-0 decoder output history buffer (out_buf, Q0 int16), the past output PLC and LTP read back from.

func (*Decoder) GetPitchLag

func (d *Decoder) GetPitchLag() int

GetPitchLag returns the channel-0 pitch lag (samples) carried for concealment.

func (*Decoder) GetResampler

func (d *Decoder) GetResampler(bandwidth Bandwidth) *LibopusResampler

GetResampler returns the libopus-compatible resampler for the given bandwidth. This returns the left/mono resampler.

func (*Decoder) GetResamplerForChannel

func (d *Decoder) GetResamplerForChannel(bandwidth Bandwidth, channel int) *LibopusResampler

GetResamplerForChannel returns the resampler for the specified channel and bandwidth.

func (*Decoder) GetResamplerRightChannel

func (d *Decoder) GetResamplerRightChannel(bandwidth Bandwidth) *LibopusResampler

GetResamplerRightChannel returns the right channel resampler for the given bandwidth.

func (*Decoder) GetResamplerScratch

func (d *Decoder) GetResamplerScratch(frameSize int) []float32

GetResamplerScratch returns a pre-allocated buffer for resampler output (left channel). This is used by the Hybrid decoder for zero-allocation SILK upsampling.

func (*Decoder) GetResamplerScratchR

func (d *Decoder) GetResamplerScratchR(frameSize int) []float32

GetResamplerScratchR returns a pre-allocated buffer for right channel resampler output. This is used by the Hybrid decoder for zero-allocation stereo SILK upsampling.

func (*Decoder) GetSLPCQ14HistoryQ14

func (d *Decoder) GetSLPCQ14HistoryQ14() []int32

GetSLPCQ14HistoryQ14 returns a copy of the channel-0 LPC synthesis filter state (sLPC_Q14), the order samples of history the next frame filters from.

func (*Decoder) GetSampleRateKHz

func (d *Decoder) GetSampleRateKHz() int

GetSampleRateKHz returns the channel-0 internal SILK sample rate in kHz.

func (*Decoder) GetStereoInt16Scratch

func (d *Decoder) GetStereoInt16Scratch(samples int) (left, right []int16, ok bool)

GetStereoInt16Scratch returns decoder-owned native-rate stereo scratch buffers. The returned slices are invalidated by the next decode call.

func (*Decoder) GetSubframeLength

func (d *Decoder) GetSubframeLength() int

GetSubframeLength returns the channel-0 subframe length in samples.

func (*Decoder) HandleBandwidthChange

func (d *Decoder) HandleBandwidthChange(bandwidth Bandwidth) bool

HandleBandwidthChange checks if bandwidth has changed. This must be called before BuildMonoResamplerInput when bandwidth may have changed. Returns true if bandwidth changed.

Note: libopus does NOT reset sMid on bandwidth change. Only the resampler internal state is zeroed. sMid values from the previous bandwidth are preserved for continuity.

func (*Decoder) HasLBRR

func (d *Decoder) HasLBRR(data []byte, bandwidth Bandwidth, frameSizeSamples int) bool

HasLBRR checks if the given packet contains LBRR (FEC) data. This can be used to check if FEC recovery is possible before attempting it.

func (*Decoder) HaveDecoded

func (d *Decoder) HaveDecoded() bool

HaveDecoded returns whether at least one frame has been decoded. Used to determine if delta coding should be applied for gains.

func (*Decoder) HistoryIndex

func (d *Decoder) HistoryIndex() int

HistoryIndex returns the current write position in the history buffer.

func (*Decoder) IsPreviousFrameVoiced

func (d *Decoder) IsPreviousFrameVoiced() bool

IsPreviousFrameVoiced returns whether the previous frame was voiced. Used for LTP filter application.

func (*Decoder) LPCOrder

func (d *Decoder) LPCOrder() int

LPCOrder returns the current LPC order (10 for NB/MB, 16 for WB).

func (*Decoder) LatestDecoderControl

func (d *Decoder) LatestDecoderControl(channel int) (LatestDecoderControl, bool)

LatestDecoderControl returns the per-frame SILK decoder control state for the most recent good-frame decode on `channel` (0 = mono / mid / left, 1 = side / right). Returns (zero, false) when no decoded ctrl has been cached (e.g. before the first decode, after a Reset, or for PLC frames which bypass `finalizeDecodedChannelFrame`).

The accessor exists so optional decoder-side post-processing -- in particular the OSCE LACE / NoLACE postfilter feature extractor -- can read libopus' per-frame `silk_decoder_control` fields without performing a second decode pass.

func (*Decoder) LatestNativeMid

func (d *Decoder) LatestNativeMid() ([]int16, int)

LatestNativeMid returns the most recent native-rate internal SILK channel 0 samples before stereo MS->LR conversion.

This is distinct from LatestNativeStereo, which exposes post-MS->LR left/right lowband output. libopus feeds decoder-side DeepPLC/DRED from SILK channel 0 only, so callers matching that path should prefer this accessor when a true stereo packet was decoded.

func (*Decoder) LatestNativeMono

func (d *Decoder) LatestNativeMono() ([]int16, int)

LatestNativeMono returns the most recent native-rate (pre-resample) int16 mono SILK output produced by decodeFrameRawInt16 (also used by DecodeWithDecoderInto), along with the native sample rate in kHz.

The returned slice aliases internal scratch storage and must be consumed synchronously, before the next decode call. Returns (nil, 0) when no mono decode has run since the last Reset.

This accessor exists for the optional OSCE BWE forward pass: libopus runs the BWE on the 16 kHz lowband produced by SILK, before silk_resampler upsamples to 48 kHz. The gopus equivalent path consumes this buffer directly so the BWE input matches libopus without performing a second decode pass.

func (*Decoder) LatestNativeStereo

func (d *Decoder) LatestNativeStereo() (left, right []int16, samplesPerChannel, fsKHz int, ok bool)

LatestNativeStereo returns the most recent native-rate (pre-resample) int16 left/right SILK output produced by `DecodeStereoFrameInt16Into` (used by the public `DecodeStereoWithDecoderInto`), along with the per-channel sample count and native sample rate in kHz.

The returned slices alias internal scratch storage and must be consumed synchronously, before the next decode call. Returns (nil, nil, 0, 0, false) when no stereo decode has run since the last Reset.

This accessor exists for the optional OSCE BWE forward pass: libopus runs the BWE on the 16 kHz lowband produced by SILK on each channel independently (one `silk_OSCE_BWE_struct` per `silk_channel_state`), before `silk_resampler` upsamples to 48 kHz. The gopus equivalent path consumes these buffers directly so the BWE input matches libopus without performing a second decode pass.

func (*Decoder) MarkDecoded

func (d *Decoder) MarkDecoded()

MarkDecoded marks that a frame has been successfully decoded. This enables delta coding for subsequent frames.

func (*Decoder) NotifyBandwidthChange

func (d *Decoder) NotifyBandwidthChange(bandwidth Bandwidth)

NotifyBandwidthChange updates bandwidth tracking and resets the resampler if needed. This should be called by the Hybrid decoder before using SILK to ensure proper resampler state when transitioning between SILK-only and Hybrid modes.

When Hybrid mode uses SILK at BandwidthWideband, calling this method ensures that: 1. The prevBandwidth is updated to WB 2. If transitioning TO WB, the WB resampler is reset 3. When later transitioning back to SILK NB/MB, the correct resampler will be reset

func (*Decoder) OutputHistory

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

OutputHistory returns the output buffer for LTP lookback.

func (*Decoder) PLCLowbandCaptured

func (d *Decoder) PLCLowbandCaptured() int

PLCLowbandCaptured returns the number of interleaved int16 samples written to the capture buffer armed via ArmPLCLowbandCapture by the most recent PLC decode.

func (*Decoder) PrevLPCValues

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

PrevLPCValues returns the LPC filter state for continuity.

func (*Decoder) PrevLSFQ15

func (d *Decoder) PrevLSFQ15() []int16

PrevLSFQ15 returns the previous frame's LSF coefficients.

func (*Decoder) PrevStereoWeights

func (d *Decoder) PrevStereoWeights() [2]int16

PrevStereoWeights returns the previous stereo weights.

func (*Decoder) PreviousLogGain

func (d *Decoder) PreviousLogGain() int32

PreviousLogGain returns the previous frame's log gain value. Used for delta gain decoding.

func (*Decoder) RecordPLCLossMono

func (d *Decoder) RecordPLCLossMono(concealed []float32)

RecordPLCLossMono records a mono SILK PLC loss event for glue-frame tracking. This mirrors the state bookkeeping performed by decodePLC.

func (*Decoder) RecordPLCLossStereo

func (d *Decoder) RecordPLCLossStereo(left, right []float32)

RecordPLCLossStereo records stereo SILK PLC loss events for glue-frame tracking. This mirrors the state bookkeeping performed by decodePLCStereo.

func (*Decoder) Reset

func (d *Decoder) Reset()

Reset clears decoder state for a new stream. Call this when starting to decode a new audio stream.

func (*Decoder) ResetSideChannel

func (d *Decoder) ResetSideChannel()

ResetSideChannel resets the mono->stereo bitstream transition state. This mirrors libopus silk/dec_API.c for nChannelsInternal 1 -> 2: re-init the side decoder, clear the stereo side/predictor history, and reset the right-channel resampler before copying left-channel history over.

func (*Decoder) RestoreDeepPLCLowbandMono

func (d *Decoder) RestoreDeepPLCLowbandMono(s *DeepPLCLowbandSnapshot)

RestoreDeepPLCLowbandMono restores the mono low-band decoder state previously captured by SnapshotDeepPLCLowbandMono. It is a no-op for a nil decoder or snapshot.

func (*Decoder) SetAPISampleRate

func (d *Decoder) SetAPISampleRate(sampleRate int)

SetAPISampleRate sets the decoder output rate used by the libopus SILK resampler. It must be called before decoding any packets.

func (*Decoder) SetDeepPLCLossMonoHook

func (d *Decoder) SetDeepPLCLossMonoHook(_ DeepPLCLossMonoHook)

SetDeepPLCLossMonoHook is a no-op in the default build; the deep-PLC loss hook is only wired under the gopus_dred or gopus_osce tags.

func (*Decoder) SetHistoryIndex

func (d *Decoder) SetHistoryIndex(idx int)

SetHistoryIndex sets the write position in the history buffer.

func (*Decoder) SetLPCOrder

func (d *Decoder) SetLPCOrder(order int)

SetLPCOrder sets the LPC order based on bandwidth.

func (*Decoder) SetPrevLSFQ15

func (d *Decoder) SetPrevLSFQ15(lsf []int16)

SetPrevLSFQ15 copies LSF coefficients for interpolation with next frame.

func (*Decoder) SetPrevStereoWeights

func (d *Decoder) SetPrevStereoWeights(weights [2]int16)

SetPrevStereoWeights sets the stereo weights for the next frame.

func (*Decoder) SetPreviousFrameVoiced

func (d *Decoder) SetPreviousFrameVoiced(voiced bool)

SetPreviousFrameVoiced sets the voiced state for the previous frame.

func (*Decoder) SetPreviousLogGain

func (d *Decoder) SetPreviousLogGain(gain int32)

SetPreviousLogGain sets the log gain for delta coding.

func (*Decoder) SetRangeDecoder

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

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

func (*Decoder) SetRawMonoFrameHook

func (d *Decoder) SetRawMonoFrameHook(_ RawMonoFrameHook)

SetRawMonoFrameHook is a no-op in the default build; the raw mono frame hook is only wired under the gopus_dred or gopus_osce tags.

func (*Decoder) SetSLPCQ14HistoryQ14

func (d *Decoder) SetSLPCQ14HistoryQ14(history []int32)

SetSLPCQ14HistoryQ14 restores the channel-0 LPC synthesis filter state (sLPC_Q14) from the trailing samples of history.

func (*Decoder) ShouldUseStereoToMonoHistory

func (d *Decoder) ShouldUseStereoToMonoHistory(bandwidth Bandwidth, prevPacketStereo bool) bool

ShouldUseStereoToMonoHistory mirrors libopus silk/dec_API.c stereo_to_mono. The right-channel resampler history is only valid when the previous internal stream was stereo and the internal sample rate did not change.

func (*Decoder) SnapshotDeepPLCLowbandMono

func (d *Decoder) SnapshotDeepPLCLowbandMono() *DeepPLCLowbandSnapshot

SnapshotDeepPLCLowbandMono captures the current mono low-band decoder state for later restore, returning nil if the decoder or its wideband resampler is unavailable.

type DeepPLCLossMonoHook

type DeepPLCLossMonoHook func(concealed []float32) (ok bool, lagPrev int)

DeepPLCLossMonoHook fires during mono 16 kHz PLC before SILK updates its retained loss/output history. The hook fills concealed with one lost lowband frame in normalized float32 units and may optionally return a lagPrev value to retain for the next good packet.

type DeepPLCLowbandSnapshot

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

DeepPLCLowbandSnapshot is an opaque capture of the mono low-band decoder state (channel 0, including the wideband resampler and SILK PLC state) taken before deep-PLC concealment so the decoder can be rolled back and advanced over concealed samples.

type DownsamplingResampler

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

DownsamplingResampler implements the libopus down_FIR resampling algorithm. This is used for encoder mode (48kHz -> SILK rates).

func NewDownsamplingResampler

func NewDownsamplingResampler(fsIn, fsOut int) *DownsamplingResampler

NewDownsamplingResampler creates a new downsampling resampler for encoder mode. Supports: 48kHz -> 8/12/16 kHz, 24kHz -> 8/12/16 kHz, etc.

func (*DownsamplingResampler) CopyFrom

func (r *DownsamplingResampler) CopyFrom(src *DownsamplingResampler)

CopyFrom copies src's configuration and filter state into r, leaving r ready to continue resampling exactly as src would. It is a no-op if either receiver or src is nil.

func (*DownsamplingResampler) Process

func (r *DownsamplingResampler) Process(in []float32) []float32

Process resamples input samples and returns output samples.

func (*DownsamplingResampler) ProcessInt16Into

func (r *DownsamplingResampler) ProcessInt16Into(in []int16, out []float32) int

ProcessInt16Into resamples int16 input into the pre-allocated float32 buffer out and returns the number of samples written. It mirrors ProcessInto but takes the input directly as int16, avoiding a float conversion on the way in.

func (*DownsamplingResampler) ProcessInto

func (r *DownsamplingResampler) ProcessInto(in []float32, out []float32) int

ProcessInto resamples into a pre-allocated buffer.

func (*DownsamplingResampler) SetState

SetState restores the resampler state from a snapshot.

func (*DownsamplingResampler) State

State returns a snapshot of the current resampler state.

type DownsamplingResamplerState

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

DownsamplingResamplerState holds the internal state of the downsampling resampler.

type Encoder

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

Encoder encodes PCM audio to SILK frames. It maintains state across frames that mirrors the decoder for proper synchronized prediction of gains, LSF, and stereo weights.

Reference: RFC 6716 Section 5.2, draft-vos-silk-01

func NewEncoder

func NewEncoder(bandwidth Bandwidth) *Encoder

NewEncoder creates a new SILK encoder with proper initial state.

func (*Encoder) AllowBandwidthSwitch

func (e *Encoder) AllowBandwidthSwitch() bool

AllowBandwidthSwitch reports the libopus SILK packet-level allowBandwidthSwitch gate used by Opus auto-bandwidth selection.

func (*Encoder) Bandwidth

func (e *Encoder) Bandwidth() Bandwidth

Bandwidth returns the current bandwidth setting.

func (*Encoder) BitsExceeded

func (e *Encoder) BitsExceeded() int

BitsExceeded returns packet-level bit reservoir excess state.

func (*Encoder) Complexity

func (e *Encoder) Complexity() int

Complexity returns the current SILK complexity setting.

func (*Encoder) EncodeFrame

func (e *Encoder) EncodeFrame(pcm []float32, lookahead []float32, vadFlag bool) []byte

EncodeFrame encodes a complete SILK frame to bitstream. Returns encoded bytes. If a range encoder was pre-set via SetRangeEncoder(), it will be used (for hybrid mode) and nil is returned since the caller manages the shared encoder.

Reference: libopus silk/float/encode_frame_FLP.c

func (*Encoder) EncodeLBRRData

func (e *Encoder) EncodeLBRRData(re *rangecoding.Encoder, nChannels int, includeHeader bool)

EncodeLBRRData encodes LBRR data with optional header placeholder. If includeHeader is false, the caller is responsible for reserving header bits.

func (*Encoder) EncodePacketWithFEC

func (e *Encoder) EncodePacketWithFEC(pcm []float32, lookahead []float32, vadFlags []bool) []byte

EncodePacketWithFEC encodes one SILK packet (up to maxFramesPerPacket 20 ms frames) from pcm, prepending in-band FEC (LBRR) for the previous frame. lookahead supplies the analysis tail and vadFlags the per-frame voice-activity decisions. It is shorthand for EncodePacketWithFECWithVADStates with no explicit VAD states.

func (*Encoder) EncodePacketWithFECWithVADStates

func (e *Encoder) EncodePacketWithFECWithVADStates(pcm []float32, lookahead []float32, vadFlags []bool, vadStates []VADFrameState) []byte

EncodePacketWithFECWithVADStates is EncodePacketWithFEC with externally supplied per-frame VAD states; when vadStates is nil the encoder derives the VAD decisions from vadFlags and its own analysis.

func (*Encoder) EncodeStereoLRToMS

func (e *Encoder) EncodeStereoLRToMS(left, right []float32, frameLength, fsKHz int) (mid, side []float32, predQ13 [2]int32)

EncodeStereoLRToMS is the public method that matches libopus stereo_LR_to_MS. It converts stereo L/R to M/S with proper LP filtering for predictor analysis. This should be used instead of EncodeStereoMidSide for proper libopus compatibility.

Parameters:

  • left, right: input stereo signals
  • frameLength: number of samples (e.g., 160 for 10ms at 16kHz)
  • fsKHz: sample rate in kHz

Returns:

  • mid, side: output mid/side signals (with 2 history samples prepended)
  • predQ13: prediction coefficients [0]=LP predictor, [1]=HP predictor

func (*Encoder) EncodeStereoMidSide

func (e *Encoder) EncodeStereoMidSide(left, right []float32) (mid []float32, side []float32, weights [2]int32)

EncodeStereoMidSide is the public method to convert stereo to mid-side and compute prediction weights. Used by hybrid mode encoder.

func (*Encoder) EncodeStereoWeightsToRange

func (e *Encoder) EncodeStereoWeightsToRange(weights [2]int32)

EncodeStereoWeightsToRange encodes stereo prediction weights to the range encoder. Used by hybrid mode encoder.

func (*Encoder) FECEnabled

func (e *Encoder) FECEnabled() bool

FECEnabled returns whether FEC (LBRR) is enabled.

func (*Encoder) FinalRange

func (e *Encoder) FinalRange() uint32

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

func (*Encoder) FindLPCWithInterpolation

func (e *Encoder) FindLPCWithInterpolation(x []float32, prevNLSFQ15 []int16, useInterp, firstFrame bool, nbSubfr int) ([]int16, int)

FindLPCWithInterpolation performs LPC analysis with NLSF interpolation search. This matches libopus silk_find_LPC_FLP behavior.

Returns: NLSF Q15 coefficients and interpolation index (0-4)

func (*Encoder) FixedLastVADFlag

func (e *Encoder) FixedLastVADFlag() bool

FixedLastVADFlag is always false in the default build (no integer encode path).

func (*Encoder) GetInterpolationState

func (e *Encoder) GetInterpolationState() (predPrevQ13 [2]int16, widthPrevQ14 int16)

GetInterpolationState returns the current interpolation state from the encoder. This allows external code to track the interpolation state.

func (*Encoder) GetLPState

func (e *Encoder) GetLPState() LPState

GetLPState returns a copy of the LP variable cutoff filter state.

func (*Encoder) GetRangeEncoderPtr

func (e *Encoder) GetRangeEncoderPtr() *rangecoding.Encoder

GetRangeEncoderPtr returns the current range encoder pointer. Used to share range encoder between mid and side channel encoders.

func (*Encoder) HasLBRRData

func (e *Encoder) HasLBRRData() bool

HasLBRRData reports whether there is pending LBRR data to encode.

func (*Encoder) HaveEncoded

func (e *Encoder) HaveEncoded() bool

HaveEncoded returns whether at least one frame has been encoded.

func (*Encoder) InWBModeWithoutVariableLP

func (e *Encoder) InWBModeWithoutVariableLP() bool

InWBModeWithoutVariableLP returns true when the SILK encoder is in wideband (16kHz) mode with the variable LP filter inactive (mode==0). This matches libopus silk_mode.inWBmodeWithoutVariableLP.

func (*Encoder) InputBuffer

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

InputBuffer returns the input sample buffer.

func (*Encoder) IsPreviousFrameVoiced

func (e *Encoder) IsPreviousFrameVoiced() bool

IsPreviousFrameVoiced returns whether the previous frame was voiced.

func (*Encoder) LBRREnabled

func (e *Encoder) LBRREnabled() bool

LBRREnabled returns whether LBRR is currently active. LBRR may be disabled even when FEC is enabled if bitrate is too low.

func (*Encoder) LPCOrder

func (e *Encoder) LPCOrder() int

LPCOrder returns the LPC order for current bandwidth.

func (*Encoder) LPCState

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

LPCState returns the LPC filter state.

func (*Encoder) LPMode

func (e *Encoder) LPMode() int

LPMode returns the LP variable cutoff filter mode. 0 = idle, <0 = switching down, >0 = switching up.

func (*Encoder) LTPCorr

func (e *Encoder) LTPCorr() float32

LTPCorr returns the last pitch correlation estimate.

func (*Encoder) LastEncodedSignalInfo

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

LastEncodedSignalInfo returns the signal type and quantization offset from the most recently encoded frame. Used by the hybrid encoder to provide silk_info feedback to CELT (libopus celt_encoder.c line 2466-2467).

The offset is computed from silk_Quantization_Offsets_Q10[signalType>>1][quantOffsetType]:

Unvoiced Low:  100, Unvoiced High: 240
Voiced Low:     32, Voiced High:   100

func (*Encoder) MarkEncoded

func (e *Encoder) MarkEncoded()

MarkEncoded marks that a frame has been successfully encoded.

func (*Encoder) PacketLoss

func (e *Encoder) PacketLoss() int

PacketLoss returns the configured packet loss percentage.

func (*Encoder) PrefillFrame

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

PrefillFrame primes SILK analysis/history buffers without coding a payload. This mirrors libopus prefill behavior used on CELT->SILK/HYBRID transitions.

func (*Encoder) PrevLSFQ15

func (e *Encoder) PrevLSFQ15() []int16

PrevLSFQ15 returns the previous frame's LSF coefficients.

func (*Encoder) PrevStereoWeights

func (e *Encoder) PrevStereoWeights() [2]int16

PrevStereoWeights returns the previous stereo weights.

func (*Encoder) PreviousLogGain

func (e *Encoder) PreviousLogGain() int32

PreviousLogGain returns the previous frame's log gain value.

func (*Encoder) ReducedDependency

func (e *Encoder) ReducedDependency() bool

ReducedDependency reports whether reduced dependency coding is enabled.

func (*Encoder) Reset

func (e *Encoder) Reset()

Reset clears encoder state for a new stream.

func (*Encoder) ResetPacketState

func (e *Encoder) ResetPacketState()

ResetPacketState resets per-packet encoder state for standalone/shared encoding. This mirrors the standalone EncodeFrame() packet initialization.

func (*Encoder) ResetStereoSideAfterMidOnly

func (e *Encoder) ResetStereoSideAfterMidOnly()

ResetStereoSideAfterMidOnly mirrors libopus enc_API.c when stereo side coding resumes after one or more mid-only frames. It preserves the long-lived encoder instance while clearing the side-channel state that libopus resets on re-entry.

func (*Encoder) ResetStereoState

func (e *Encoder) ResetStereoState()

ResetStereoState resets the stereo encoder state. Call this when starting a new stream.

func (*Encoder) ResetTransitionPrefillState

func (e *Encoder) ResetTransitionPrefillState()

ResetTransitionPrefillState clears the low-level fields that libopus reinitializes during the CELT->SILK/HYBRID prefill reset path, while leaving packet-level controls owned by the Opus wrapper intact.

func (*Encoder) SampleRate

func (e *Encoder) SampleRate() int

SampleRate returns the sample rate for current bandwidth.

func (*Encoder) SetBitrate

func (e *Encoder) SetBitrate(bitrate int)

SetBitrate sets the target bitrate in bps. In stereo packets this is the total stream rate (matching libopus silk_EncControlStruct.bitRate); the stereo split into mid/side rates happens inside silk_stereo_LR_to_MS via stereoAllocationTargetRate, so callers must not pre-divide by channels.

func (*Encoder) SetBitsExceeded

func (e *Encoder) SetBitsExceeded(bits int)

SetBitsExceeded sets packet-level bit reservoir excess state.

func (*Encoder) SetComplexity

func (e *Encoder) SetComplexity(complexity int)

SetComplexity sets the SILK encoder complexity (0-10) and related pitch parameters.

func (*Encoder) SetFEC

func (e *Encoder) SetFEC(enabled bool)

SetFEC enables or disables in-band Forward Error Correction (LBRR). When enabled, each packet includes redundant data for the previous frame at a lower quality, allowing the decoder to recover from packet loss.

Reference: libopus silk/control_codec.c silk_setup_LBRR

func (*Encoder) SetInterpolationState

func (e *Encoder) SetInterpolationState(predPrevQ13 [2]int16, widthPrevQ14 int16)

SetInterpolationState sets the interpolation state for the encoder. This is useful for testing or when restoring encoder state.

func (*Encoder) SetLPState

func (e *Encoder) SetLPState(state LPState)

SetLPState restores the LP variable cutoff filter state.

func (*Encoder) SetMaxBits

func (e *Encoder) SetMaxBits(maxBits int)

SetMaxBits sets the maximum number of bits allowed for the current frame.

func (*Encoder) SetPacketLoss

func (e *Encoder) SetPacketLoss(lossPercent int)

SetPacketLoss sets the expected packet loss percentage (0-100). This affects the LBRR gain increase - higher loss means more aggressive redundancy encoding with higher gains.

Reference: libopus silk/control_codec.c silk_setup_LBRR

func (*Encoder) SetPreAdjustedTargetRateBps

func (e *Encoder) SetPreAdjustedTargetRateBps(bitrate int)

SetPreAdjustedTargetRateBps provides a one-shot frame target that already includes packet-level reservoir/bits-balance adjustments. Shared stereo packet control uses this to avoid applying the same packet correction once per channel.

func (*Encoder) SetPrevLSFQ15

func (e *Encoder) SetPrevLSFQ15(lsf []int16)

SetPrevLSFQ15 copies LSF coefficients for interpolation with next frame.

func (*Encoder) SetPrevStereoWeights

func (e *Encoder) SetPrevStereoWeights(weights [2]int16)

SetPrevStereoWeights sets the stereo weights for the next frame.

func (*Encoder) SetPreviousFrameVoiced

func (e *Encoder) SetPreviousFrameVoiced(voiced bool)

SetPreviousFrameVoiced sets the voiced state for the previous frame.

func (*Encoder) SetPreviousLogGain

func (e *Encoder) SetPreviousLogGain(gain int32)

SetPreviousLogGain sets the log gain for delta coding.

func (*Encoder) SetRangeEncoder

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

SetRangeEncoder sets the range encoder for the current frame.

func (*Encoder) SetReducedDependency

func (e *Encoder) SetReducedDependency(enabled bool)

SetReducedDependency enables/disables reduced dependency coding. This mirrors libopus OPUS_SET_PREDICTION_DISABLED SILK behavior.

func (*Encoder) SetVADState

func (e *Encoder) SetVADState(speechActivityQ8 int32, inputTiltQ15 int32, inputQualityBandsQ15 [4]int32)

SetVADState sets speech activity and spectral tilt from VAD analysis. These values influence pitch thresholding and noise shaping.

func (*Encoder) SetVBR

func (e *Encoder) SetVBR(vbr bool)

SetVBR enables or disables variable bitrate mode.

func (*Encoder) StereoEncodeLRToMSWithInterp

func (e *Encoder) StereoEncodeLRToMSWithInterp(left, right []float32, frameLength, fsKHz int, widthQ14 int16) (midOut, sideOut []float32, predQ13 [2]int32)

StereoEncodeLRToMSWithInterp converts L/R to M/S and applies 8ms predictor interpolation. This is the full libopus-compatible stereo encoding function that: 1. Converts L/R to M/S with proper buffering 2. Computes LP/HP predictors 3. Applies 8ms smooth interpolation from previous to current predictors 4. Updates state for next frame continuity

The side channel output has the prediction subtracted, matching libopus behavior. The interpolation ensures smooth transitions at frame boundaries.

Parameters:

  • left, right: input stereo signals (length frameLength+2 for look-ahead)
  • frameLength: number of samples in the frame
  • fsKHz: sample rate in kHz (8, 12, or 16)
  • widthQ14: stereo width parameter in Q14 (16384 = full stereo)

Returns:

  • midOut: mid channel output (length frameLength)
  • sideOut: side channel with prediction subtracted (length frameLength)
  • predQ13: computed prediction coefficients [LP, HP]

func (*Encoder) StereoEncodeLRToMSWithInterpQuantized

func (e *Encoder) StereoEncodeLRToMSWithInterpQuantized(left, right []float32, frameLength, fsKHz int, widthQ14 int16) (midOut, sideOut []float32, predQ13 [2]int32, ix StereoQuantIndices)

StereoEncodeLRToMSWithInterpQuantized is the libopus-aligned variant that: 1) computes LP/HP predictors, 2) quantizes predictors to 80 levels, 3) applies 8ms interpolation using the quantized predictors, and 4) updates encoder stereo state based on quantized predictors.

This ensures the side residual is computed with the same predictors the decoder will use.

Returns mid/side outputs (length frameLength), the quantized predictors, and the quant indices.

func (*Encoder) StereoLRToMSWithRates

func (e *Encoder) StereoLRToMSWithRates(
	left, right []float32,
	frameLength, fsKHz int,
	totalRateBps int,
	prevSpeechActQ8 int32,
	toMono bool,
) (midOut, sideOut []float32, ix StereoQuantIndices, midOnly bool, midRate, sideRate int, widthQ14 int16)

StereoLRToMSWithRates is a libopus-aligned stereo front-end that computes mid/side signals, predictor indices, mid-only decision, and per-channel rates.

This approximates silk_stereo_LR_to_MS using float-domain analysis while preserving the key rate/width decision logic.

func (*Encoder) UpdatePacketBitsExceeded

func (e *Encoder) UpdatePacketBitsExceeded(nBytesOut, payloadSizeMs, bitRateBps int)

UpdatePacketBitsExceeded applies libopus packet-level nBitsExceeded update. This must be called once per packet when shared range coding is used.

func (*Encoder) UpdateVariableHPCutoff

func (e *Encoder) UpdateVariableHPCutoff()

UpdateVariableHPCutoff ports silk_HP_variable_cutoff (silk/HP_variable_cutoff.c). It adapts variable_HP_smth1_Q15 from the previous frame's pitch lag and quality. Call once per packet, before the Opus-level hp_cutoff() of the next packet, matching enc_API.c (silk_HP_variable_cutoff is invoked per packet on state_Fxx[0]).

func (*Encoder) VariableHPSmth1Q15

func (e *Encoder) VariableHPSmth1Q15() int32

VariableHPSmth1Q15 returns the current smoothed log-domain cutoff estimate (Q15) so the Opus-level encoder can drive hp_cutoff().

type EncoderState

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

EncoderState holds encoder state for streaming encoding.

func NewEncoderState

func NewEncoderState(bandwidth Bandwidth) *EncoderState

NewEncoderState creates a new streaming encoder.

func (*EncoderState) EncodeFrame

func (es *EncoderState) EncodeFrame(pcm []float32, vadFlag bool) ([]byte, error)

EncodeFrame encodes a frame maintaining state across calls.

type FrameDuration

type FrameDuration int

FrameDuration represents SILK frame duration in milliseconds.

const (
	// Frame10ms is a 10ms SILK frame (2 subframes).
	Frame10ms FrameDuration = 10
	// Frame20ms is a 20ms SILK frame (4 subframes).
	Frame20ms FrameDuration = 20
	// Frame40ms is a 40ms SILK frame (8 subframes, 2 x 20ms sub-blocks).
	Frame40ms FrameDuration = 40
	// Frame60ms is a 60ms SILK frame (12 subframes, 3 x 20ms sub-blocks).
	Frame60ms FrameDuration = 60
)

func FrameDurationFromSamples

func FrameDurationFromSamples(samples, sampleRate int) FrameDuration

FrameDurationFromSamples returns the SILK frame duration corresponding to a frame of samples at sampleRate, falling back to Frame20ms for any size that is not a valid SILK frame (10/20/40/60 ms) or for a non-positive rate.

func FrameDurationFromTOC

func FrameDurationFromTOC(tocFrameSize int) FrameDuration

FrameDurationFromTOC extracts frame duration from TOC frame size value. TOC frame sizes at 48kHz: 480=10ms, 960=20ms, 1920=40ms, 2880=60ms

type FrameParams

type FrameParams struct {
	// Frame classification
	SignalType  int // 0=inactive, 1=unvoiced, 2=voiced
	QuantOffset int // 0=low, 1=high quantization

	// Subframe parameters (4 subframes for 20ms, 2 for 10ms)
	NumSubframes int
	Gains        []int32 // Q16 format, one per subframe

	// LPC parameters
	LPCOrder  int
	LPCCoeffs []int16 // Q12 format

	// Pitch parameters (voiced only)
	PitchLags      []int32  // One per subframe
	LTPCoeffs      [][]int8 // Q7 format, [subframe][5 taps]
	LTPPeriodicity int      // 0, 1, or 2 (selects LTP codebook)
	LTPScaleIndex  int      // LTP scale index for gain adjustment

	// Excitation (filled by excitation decoder)
	Excitation []int32
}

FrameParams holds the decoded side-information parameters for a single SILK frame in a convenience, allocation-friendly form (the bit-exact decode path uses the internal decoderControl/indices structs instead). It collects the frame classification, per-subframe gains, LPC coefficients and, for voiced frames, the pitch and LTP parameters needed for synthesis filtering. The fields correspond to the indices decoded by libopus silk/decode_indices.c.

type LPState

type LPState struct {
	InLPState         [2]int32 // Biquad filter state
	TransitionFrameNo int32    // Counter mapped to cutoff frequency
	Mode              int      // Operating mode: <0=switch down, >0=switch up, 0=do nothing
	SavedFsKHz        int32    // Last sampling rate before bandwidth switching reset
}

LPState holds the LP variable cutoff filter state.

func (*LPState) LPVariableCutoff

func (lp *LPState) LPVariableCutoff(frame []int16, frameLength int)

LPVariableCutoff applies the LP variable cutoff filter to a frame. Matches libopus silk_LP_variable_cutoff.

type LTPCoeffsArray

type LTPCoeffsArray [4][5]int8

LTPCoeffsArray is a fixed-size type for LTP coefficients to avoid allocations. Maximum 4 subframes, 5 taps each.

type LatestDecoderControl

type LatestDecoderControl struct {
	PredCoefQ12 [2][maxLPCOrder]int16
	LTPCoefQ14  [ltpOrder * maxNbSubfr]int16
	GainsQ16    [maxNbSubfr]int32
	PitchL      [maxNbSubfr]int32
	LPCOrder    int32
	NbSubfr     int32
	SignalType  int32
	FsKHz       int32
	NumBits     int32
}

LatestDecoderControl is the public view of the most recent `silk_decoder_control` decoded for a channel. It mirrors the libopus `silk_decoder_control` fields the OSCE LACE / NoLACE feature extractor reads (`osce_features.c::osce_calculate_features`): per-subframe LPC prediction coefficients (Q12), LTP filter coefficients (Q14), subframe gains (Q16), pitch lags, and the SILK signal type for the frame. Field names mirror the libopus C struct so future cross- referencing stays mechanical.

type LibopusResampler

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

LibopusResampler implements the exact SILK resampler from libopus. It follows libopus' copy, direct 2x, IIR/FIR upsampling, and downsampling paths.

func NewLibopusResampler

func NewLibopusResampler(fsIn, fsOut int) *LibopusResampler

NewLibopusResampler creates a new resampler matching libopus behavior.

This is the decoder-side constructor (forEnc=0 in silk_resampler_init): the input delay comes from delay_matrix_dec and downsampling uses the decoder down_FIR. For the encoder input resampler (API_fs_Hz -> fs_kHz) use NewLibopusResamplerEnc, which selects delay_matrix_enc and the encoder down_FIR.

func NewLibopusResamplerEnc

func NewLibopusResamplerEnc(fsIn, fsOut int) *LibopusResampler

NewLibopusResamplerEnc creates the encoder-side SILK input resampler, matching silk_resampler_init(..., forEnc=1): API sample rate fsIn (8/12/16/24/48/96 kHz) to internal rate fsOut (8/12/16 kHz), using delay_matrix_enc and the encoder down_FIR. It supports the copy (Fs_in==Fs_out), direct 2x (Fs_out==2*Fs_in), IIR/FIR (other upsample) and down_FIR (downsample) paths.

func (*LibopusResampler) CopyFrom

func (r *LibopusResampler) CopyFrom(src *LibopusResampler)

CopyFrom copies state from another resampler. This is used to sync stereo resampler state when switching from mono.

func (*LibopusResampler) Process

func (r *LibopusResampler) Process(samples []float32) []float32

Process resamples float32 samples from input rate to output rate. This implements the exact libopus silk_resampler() flow with delay buffer.

func (*LibopusResampler) ProcessInt16Into

func (r *LibopusResampler) ProcessInt16Into(samples []int16, out []float32) int

ProcessInt16Into resamples int16 input samples into float32 output. This avoids float32->int16 conversion when the caller already has native int16 samples.

func (*LibopusResampler) ProcessInt16IntoBoth

func (r *LibopusResampler) ProcessInt16IntoBoth(samples []int16, outF32 []float32, outI16 []int16) int

ProcessInt16IntoBoth resamples int16 input samples, writing the resampler's int16 output to outF32 (as float32, identical to ProcessInt16Into) and also copying the native int16 resampler output to outI16. The int16 output is the pre-INT16TORES value libopus' FIXED_POINT silk_Decode emits before the `INT16TORES(x) = x << RES_SHIFT` opus_res conversion, so callers driving the integer hybrid path can recover the exact opus_res SILK lowband without a second resampler pass (which would corrupt the stateful delay buffers). Returns the number of samples written.

func (*LibopusResampler) ProcessInto

func (r *LibopusResampler) ProcessInto(samples []float32, out []float32) int

ProcessInto resamples float32 samples from input rate to output rate into a caller-provided buffer. This is the zero-allocation version of Process(). Returns the number of samples written to the output buffer.

func (*LibopusResampler) ProcessIntoBoth

func (r *LibopusResampler) ProcessIntoBoth(samples []float32, outF32 []float32, outI16 []int16) int

ProcessIntoBoth resamples float32 input, writing the resampler output to outF32 (identical to ProcessInto) and copying the native int16 resampler output to outI16. See ProcessInt16IntoBoth for why the int16 output is needed by the FIXED_POINT integer hybrid path.

func (*LibopusResampler) Reset

func (r *LibopusResampler) Reset()

Reset clears the resampler state.

func (*LibopusResampler) SetState

func (r *LibopusResampler) SetState(s ResamplerState)

SetState restores the resampler state from a snapshot.

func (*LibopusResampler) State

func (r *LibopusResampler) State() ResamplerState

State returns a snapshot of the current resampler state.

type NSQParams

type NSQParams struct {
	// Signal type: 0=inactive, 1=unvoiced, 2=voiced
	SignalType int

	// Quantization offset type: 0=low, 1=high
	QuantOffsetType int

	// LPC prediction coefficients (Q12)
	PredCoefQ12 []int16

	// NLSF interpolation coefficient (Q2). 4 means no interpolation.
	NLSFInterpCoefQ2 int

	// LTP coefficients (Q14), 5 per subframe
	LTPCoefQ14 []int16

	// Noise shaping AR coefficients (Q13)
	ARShpQ13 []int16

	// Harmonic shaping gain (Q14)
	HarmShapeGainQ14 []int32

	// Spectral tilt (Q14)
	TiltQ14 []int32

	// Low-frequency shaping (Q14)
	LFShpQ14 []int32

	// Quantization gains (Q16) per subframe
	GainsQ16 []int32

	// Pitch lags per subframe
	PitchL []int32

	// Rate/distortion tradeoff (Lambda, Q10)
	LambdaQ10 int32

	// LTP scale (Q14) for first subframe
	LTPScaleQ14 int32

	// Frame configuration
	FrameLength            int
	SubfrLength            int
	NbSubfr                int
	LTPMemLength           int
	PredLPCOrder           int
	ShapeLPCOrder          int
	WarpingQ16             int
	NStatesDelayedDecision int

	// LCG seed for dithering
	Seed int
}

NSQParams holds parameters for noise shaping quantization.

type NSQState

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

NSQState holds the noise shaping quantizer state. Mirrors libopus silk_nsq_state structure.

func NewNSQState

func NewNSQState() *NSQState

NewNSQState creates a new NSQ state with proper initialization.

func (*NSQState) Clone

func (s *NSQState) Clone() *NSQState

Clone creates a deep copy of the NSQ state.

func (*NSQState) Reset

func (s *NSQState) Reset()

Reset clears the NSQ state for a new stream.

func (*NSQState) RestoreFrom

func (s *NSQState) RestoreFrom(other *NSQState)

RestoreFrom copies state from another NSQState.

type NoiseShapeParams

type NoiseShapeParams struct {
	// Per-subframe parameters
	HarmShapeGainQ14 []int32 // Harmonic shaping gain (Q14, opus_int-width)
	TiltQ14          []int32 // Spectral tilt (Q14, opus_int-width)
	LFShpQ14         []int32 // Low-frequency shaping (packed MA/AR, Q14)
	ARShpQ13         []int16 // Noise shaping AR coefficients (Q13, per subframe)

	// Frame-level parameters
	LambdaQ10     int32   // Rate-distortion tradeoff (Q10, opus_int-width)
	CodingQuality float32 // Coding quality [0, 1]
	InputQuality  float32 // Input quality [0, 1]
}

NoiseShapeParams holds the computed noise shaping parameters for a frame.

type NoiseShapeState

type NoiseShapeState struct {
	// Smoothed harmonic shaping gain (float)
	HarmShapeGainSmth float32

	// Smoothed tilt (float)
	TiltSmth float32

	// Last gain index for conditional coding
	LastGainIndex int8
	// contains filtered or unexported fields
}

NoiseShapeState holds the noise shaping state that persists across frames. This mirrors libopus silk_shape_state_FLP structure.

func NewNoiseShapeState

func NewNoiseShapeState() *NoiseShapeState

NewNoiseShapeState creates a new noise shaping state.

func (*NoiseShapeState) ComputeNoiseShapeParams

func (s *NoiseShapeState) ComputeNoiseShapeParams(
	signalType int,
	speechActivityQ8 int,
	ltpCorr float32,
	pitchLags []int32,
	originalSNR float32,
	quantOffsetType int,
	inputQualityBandsQ15 [4]int32,
	numSubframes int,
	fsKHz int,
	nStatesDelayedDecision int,
) *NoiseShapeParams

ComputeNoiseShapeParams computes adaptive noise shaping parameters. This ports libopus silk/float/noise_shape_analysis_FLP.c logic.

Parameters:

  • signalType: TYPE_VOICED (2), TYPE_UNVOICED (1), or TYPE_INACTIVE (0)
  • speechActivityQ8: Speech activity level [0, 255]
  • ltpCorr: LTP correlation [0.0, 1.0] - higher means more periodic
  • pitchLags: Pitch lags per subframe (for LF shaping)
  • snrDBQ7: Target SNR in dB (Q7 format, e.g., 25 dB = 25 * 128)
  • numSubframes: Number of subframes
  • fsKHz: Sample rate in kHz (8, 12, or 16)

func (*NoiseShapeState) Reset

func (s *NoiseShapeState) Reset()

Reset clears noise-shaping state while retaining the caller-owned state object.

type PitchAnalysisState

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

PitchAnalysisState holds state for pitch analysis across frames

type RawMonoFrameHook

type RawMonoFrameHook func(samples []int16)

RawMonoFrameHook fires on raw mono/mid 10 ms chunks before CNG/glue mutates the decoded frame buffer. The slice aliases decoder scratch memory and must be consumed synchronously.

type ResamplerState

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

ResamplerState holds the internal state of the resampler. For downsampling configurations the work happens in the delegated down_FIR resampler, so the snapshot carries that state too.

type StereoEncStateInterp

type StereoEncStateInterp struct {
	PrevPredQ13  [2]int32 // Previous frame's predictors in Q13
	PrevWidthQ14 int16    // Previous frame's stereo width in Q14
	SMid         [2]int16 // Mid signal history buffer
	SSide        [2]int16 // Side signal history buffer
}

StereoEncStateInterp holds state for encoder-side 8ms predictor interpolation. This is a simplified float-based state for easier integration.

func (*StereoEncStateInterp) ApplyInterpolation

func (s *StereoEncStateInterp) ApplyInterpolation(currPredQ13 [2]int32, currWidthQ14 int16,
	mid, side []float32, frameLength, fsKHz int) []float32

ApplyInterpolation applies 8ms predictor interpolation to transform the side channel. This updates the state with current predictor values for the next frame.

Parameters:

  • currPredQ13: current frame's predictors [LP, HP] in Q13
  • currWidthQ14: current frame's stereo width in Q14 (16384 = full width)
  • mid, side: mid/side channels with 2 history samples prepended
  • frameLength: number of output samples
  • fsKHz: sample rate in kHz

Returns:

  • sideOut: transformed side channel (length frameLength)

func (*StereoEncStateInterp) Reset

func (s *StereoEncStateInterp) Reset()

Reset clears the interpolation state for a new stream.

type StereoQuantIndices

type StereoQuantIndices struct {
	// ix[n][0]: 0-2 (index within triplet)
	// ix[n][1]: 0-4 (sub-step index)
	// ix[n][2]: 0-4 (triplet index, derived from main index / 3)
	Ix [2][3]int8
}

StereoQuantIndices holds the three quantization indices per predictor as used by libopus stereo_quant_pred.c

func QuantizeStereoWeights

func QuantizeStereoWeights(predQ13 [2]int32) (quantized [2]int32, ix StereoQuantIndices)

QuantizeStereoWeights quantizes stereo prediction weights and returns the indices. This is the public interface for external callers who need the indices.

type VADFrameAnalyzer

type VADFrameAnalyzer func(frame []float32, frameSamples, fsKHz int) (VADFrameState, bool)

VADFrameAnalyzer computes libopus-style per-frame VAD state for a SILK block. It is used by the Opus-level stereo packet wrapper to run VAD after mid/side conversion on the actual coded signals.

type VADFrameState

type VADFrameState struct {
	SpeechActivityQ8     int32
	InputTiltQ15         int32
	InputQualityBandsQ15 [4]int32
	Valid                bool
}

VADFrameState carries per-frame SILK VAD-derived controls. It mirrors the state produced by silk_encode_do_VAD_Fxx in libopus.

Jump to

Keyboard shortcuts

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