Documentation
¶
Overview ¶
Package multistream implements the Opus multistream engine: encoding and decoding of packets that carry several elementary Opus streams (each a normal SILK / CELT / Hybrid stream) which are decoded independently and routed to output channels via a channel-mapping table. It is the engine behind surround sound (5.1, 7.1, ...), discrete multichannel, and ambisonics/projection audio.
Most applications should reach for the top-level gopus multistream wrappers (gopus.NewMultistreamEncoder / gopus.NewMultistreamDecoder and the …Default constructors), which forward to this package. Import this package directly for the lower-level Encoder / Decoder types and for projection / ambisonics, whose constructors live only here.
Channel mapping families (RFC 7845 Section 5) RFC 7845 Section 5)" aria-label="Go to Channel mapping families (RFC 7845 Section 5)">¶
A multistream layout is described by three integers plus a mapping table:
- streams (N): total number of elementary Opus streams.
- coupledStreams (M): number of those streams that are coupled (stereo); the first M streams decode to 2 channels each, the remaining N-M decode to 1 channel. The total decoded-channel count is therefore N+M, and the invariant N+M <= 255 always holds.
- mapping: one byte per OUTPUT channel selecting its source decoded channel (see below). len(mapping) == output channels.
Each mapping byte is interpreted as:
- 0 .. 2*M-1: a channel of a coupled (stereo) stream; even = left, odd = right of stereo pair index value/2.
- 2*M .. N+M-1: a mono (uncoupled) stream.
- 255: a silent output channel (decoded as zeros).
RFC 7845 channel mapping families this package supports:
- Family 0 (mono/stereo): the degenerate 1- or 2-channel case (1 stream).
- Family 1 (Vorbis/surround): 1..8 channels in Vorbis channel order; see DefaultMapping / NewEncoderDefault / NewDecoderDefault.
- Family 2 (ambisonics, mono streams): ACN/SN3D ambisonics carried as mono streams plus an optional non-diegetic stereo pair; see ValidateAmbisonics, AmbisonicsMapping, and NewEncoderAmbisonics(.., 2).
- Family 3 (ambisonics projection): ACN/SN3D ambisonics carried as maximally coupled stereo streams with a mixing/demixing matrix; see the Projection types below.
- Family 255 (discrete): an explicit, arbitrary mapping with no defined channel semantics; constructed directly via NewEncoder / NewDecoder.
Surround semantics ¶
Surround encoding (family 1, 3..8 channels) splits the requested total bitrate across the elementary streams using libopus' surround masking / rate-allocation model, applies per-stream LFE and trim decisions, then concatenates the per-stream packets with RFC 6716 Appendix B self-delimiting framing (the first N-1 streams are self-delimited; the last uses standard framing). Decoding reverses this: split, decode each stream, then scatter decoded channels to the output via the mapping table.
Projection semantics (family 3) ¶
Projection encoding mixes the input ambisonics channels through a fixed mixing matrix into the coupled/mono elementary streams, so inter-channel energy is redistributed for better coding efficiency. The decoder reverses this with a demixing matrix obtained from the encoder. gopus does not expose separate projection encoder/decoder types as libopus does; instead use NewProjectionEncoder / Encoder.GetDemixingMatrix on the encode side and NewProjectionDecoder (or NewDecoder + Decoder.SetProjectionDemixingMatrix) on the decode side. Projection decoders always use the trivial identity mapping [0, 1, ..., channels-1]; the demixing matrix carries the routing. libopus 1.6.1 (and gopus) provide pre-computed matrices for ambisonics orders 1..5 only.
Buffer ownership ¶
Constructors copy the caller's mapping (and demixing matrix) defensively, so the caller may reuse or mutate those slices afterwards. Encode and the Decode* methods allocate and return a fresh output slice on every call that the caller fully owns; input slices are read-only and never retained past the call.
Error conditions ¶
Constructor and CTL errors (ErrInvalidChannels, ErrInvalidStreams, ErrInvalidCoupledStreams, ErrTooManyChannels, ErrInvalidMapping, ErrInvalidProjectionMatrix, ErrInvalidGain, ErrInvalidComplexity, ...) report out-of-range layout or control parameters. Decode-path errors (ErrPacketTooShort, ErrInvalidPacket, ErrDurationMismatch, ErrBufferTooSmall, ErrInvalidStreamCount) report malformed or inconsistent input packets; the decode path is hardened so that no malformed input causes a panic or out-of-bounds access — every defect surfaces as one of these errors.
Build tags ¶
DRED is available only in builds using -tags gopus_dred. OSCE helper surfaces remain extra-controls-gated and absent from the default build.
Reference: RFC 7845 Section 5 (Channel Mapping), RFC 6716 Appendix B (self-delimiting framing), libopus opus_multistream_* and opus_projection_*.
Index ¶
- Variables
- func AmbisonicsChannelCount(order int, withNondiegetic bool) int
- func AmbisonicsMapping(channels int) ([]byte, error)
- func AmbisonicsMappingFamily3(channels int) ([]byte, error)
- func DefaultMapping(channels int) (streams, coupledStreams int, mapping []byte, err error)
- func GetAmbisonicsOrder(channels int) (order, nondiegetic int, err error)
- func IsValidAmbisonicsChannelCount(channels int) bool
- func PacketDuration(data []byte, numStreams int) (int, error)
- func PacketDurationAtRate(data []byte, numStreams, sampleRate int) (int, error)
- func ProjectionDemixingMatrixSize(channels, streams, coupled int) int
- func ValidateAmbisonics(channels int) (streams, coupledStreams int, err error)
- func ValidateAmbisonicsFamily3(channels int) (streams, coupledStreams int, err error)
- type Decoder
- func (d *Decoder) Bandwidth() types.Bandwidth
- func (d *Decoder) Channels() int
- func (d *Decoder) Complexity() int
- func (d *Decoder) CoupledStreams() int
- func (d *Decoder) DNNBlobLoaded() bool
- func (d *Decoder) Decode(data []byte, frameSize int) ([]float32, error)
- func (d *Decoder) DecodeToFloat32(data []byte, frameSize int) ([]float32, error)
- func (d *Decoder) DecodeToInt16(data []byte, frameSize int) ([]int16, error)
- func (d *Decoder) FARGANModelLoaded() bool
- func (d *Decoder) FinalRange() uint32
- func (d *Decoder) Gain() int
- func (d *Decoder) GetFinalRange() uint32
- func (d *Decoder) IgnoreExtensions() bool
- func (d *Decoder) LastPacketDuration() int
- func (d *Decoder) PLCModelLoaded() bool
- func (d *Decoder) PhaseInversionDisabled() bool
- func (d *Decoder) PitchDNNLoaded() bool
- func (d *Decoder) Reset()
- func (d *Decoder) SampleRate() int
- func (d *Decoder) SetComplexity(complexity int) error
- func (d *Decoder) SetDNNBlob(blob *dnnblob.Blob)
- func (d *Decoder) SetGain(gainQ8 int) error
- func (d *Decoder) SetIgnoreExtensions(ignore bool)
- func (d *Decoder) SetPhaseInversionDisabled(disabled bool)
- func (d *Decoder) SetProjectionDemixingMatrix(matrix []byte) error
- func (d *Decoder) Streams() int
- type Encoder
- func NewEncoder(sampleRate, channels, streams, coupledStreams int, mapping []byte) (*Encoder, error)
- func NewEncoderAmbisonics(sampleRate, channels, mappingFamily int) (*Encoder, error)
- func NewEncoderDefault(sampleRate, channels int) (*Encoder, error)
- func NewProjectionEncoder(sampleRate, channels int) (*Encoder, error)
- func (e *Encoder) Bandwidth() types.Bandwidth
- func (e *Encoder) Bitrate() int
- func (e *Encoder) BitrateMode() encoder.BitrateMode
- func (e *Encoder) Channels() int
- func (e *Encoder) Complexity() int
- func (e *Encoder) CoupledStreams() int
- func (e *Encoder) DNNBlobLoaded() bool
- func (e *Encoder) DTXEnabled() bool
- func (e *Encoder) DemixingMatrixGain() int
- func (e *Encoder) DemixingMatrixSize() int
- func (e *Encoder) Encode(pcm []float32, frameSize int) ([]byte, error)
- func (e *Encoder) EncodeFloat32(pcm []float32, frameSize int) ([]byte, error)
- func (e *Encoder) EncodeFloat32WithAnalysis(pcm []float32, frameSize int, analysisPCM []float32) ([]byte, error)
- func (e *Encoder) EncodeFloat32WithAnalysisMaxBytes(pcm []float32, frameSize int, analysisPCM []float32, maxDataBytes int) ([]byte, error)
- func (e *Encoder) EncodeWithAnalysis(pcm []float32, frameSize int, analysisPCM []float32) ([]byte, error)
- func (e *Encoder) FECEnabled() bool
- func (e *Encoder) ForceChannels() int
- func (e *Encoder) GetDemixingMatrix() []byte
- func (e *Encoder) GetFinalRange() uint32
- func (e *Encoder) InBandFEC() int
- func (e *Encoder) LSBDepth() int
- func (e *Encoder) Lookahead() int
- func (e *Encoder) LowDelay() bool
- func (e *Encoder) MappingFamily() int
- func (e *Encoder) MaxBandwidth() types.Bandwidth
- func (e *Encoder) Mode() encoder.Mode
- func (e *Encoder) PacketLoss() int
- func (e *Encoder) PhaseInversionDisabled() bool
- func (e *Encoder) PredictionDisabled() bool
- func (e *Encoder) Reset()
- func (e *Encoder) SampleRate() int
- func (e *Encoder) SetBandwidth(bw types.Bandwidth)
- func (e *Encoder) SetBandwidthAuto()
- func (e *Encoder) SetBitrate(totalBitrate int)
- func (e *Encoder) SetBitrateMode(mode encoder.BitrateMode)
- func (e *Encoder) SetComplexity(complexity int)
- func (e *Encoder) SetDNNBlob(blob *dnnblob.Blob)
- func (e *Encoder) SetDTX(enabled bool)
- func (e *Encoder) SetFEC(enabled bool)
- func (e *Encoder) SetForceChannels(channels int)
- func (e *Encoder) SetInBandFEC(config int) error
- func (e *Encoder) SetLSBDepth(depth int) error
- func (e *Encoder) SetLowDelay(enabled bool)
- func (e *Encoder) SetMaxBandwidth(bw types.Bandwidth)
- func (e *Encoder) SetMode(mode encoder.Mode)
- func (e *Encoder) SetPacketLoss(lossPercent int)
- func (e *Encoder) SetPhaseInversionDisabled(disabled bool)
- func (e *Encoder) SetPredictionDisabled(disabled bool)
- func (e *Encoder) SetRestrictedSilkApplication(enabled bool)
- func (e *Encoder) SetSignal(signal types.Signal)
- func (e *Encoder) SetVBR(enabled bool)
- func (e *Encoder) SetVBRConstraint(constrained bool)
- func (e *Encoder) SetVoIPApplication(enabled bool)
- func (e *Encoder) Signal() types.Signal
- func (e *Encoder) Streams() int
- func (e *Encoder) VBR() bool
- func (e *Encoder) VBRConstraint() bool
- func (e *Encoder) VoIPApplication() bool
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidAmbisonicsChannels indicates an invalid channel count for ambisonics. // Valid counts are (order+1)^2 or (order+1)^2 + 2 for orders 0-14. ErrInvalidAmbisonicsChannels = errors.New("multistream: invalid ambisonics channel count") // ErrAmbisonicsChannelsTooHigh indicates too many channels for ambisonics (max 227). ErrAmbisonicsChannelsTooHigh = errors.New("multistream: ambisonics channel count exceeds maximum (227)") // ErrInvalidMappingFamily indicates an invalid mapping family. ErrInvalidMappingFamily = errors.New("multistream: invalid mapping family for ambisonics (must be 2 or 3)") // ErrProjectionOrderUnsupported indicates the ambisonics order is outside the range // supported by mapping family 3 (projection). libopus 1.6.1 provides pre-computed // mixing and demixing matrices for orders 1..5 (orderPlusOne 2..6) only. // // Valid channel counts for projection (family 3): // Order 1 (FOA): 4 or 6 channels // Order 2 (SOA): 9 or 11 channels // Order 3 (TOA): 16 or 18 channels // Order 4 (4thOA): 25 or 27 channels // Order 5 (5thOA): 36 or 38 channels // // Higher orders (6-14, channels 49-227) are valid ambisonics but are not supported // by projection encoding; use mapping family 2 for those orders. // // Reference: libopus src/mapping_matrix.c (mapping_matrix_*_mixing/_demixing tables), // src/opus_projection_encoder.c:opus_projection_ambisonics_encoder_get_size ErrProjectionOrderUnsupported = errors.New("multistream: ambisonics order not supported by projection (family 3); valid orders are 1-5") )
Errors for ambisonics validation.
var ( // ErrInvalidChannels indicates channels is not in the valid range (1-255). ErrInvalidChannels = errors.New("multistream: invalid channel count (must be 1-255)") // ErrInvalidStreams indicates streams is not in the valid range (1-255). ErrInvalidStreams = errors.New("multistream: invalid stream count (must be 1-255)") // ErrInvalidCoupledStreams indicates coupledStreams is invalid (must be 0 to streams). ErrInvalidCoupledStreams = errors.New("multistream: invalid coupled streams (must be 0 to streams)") // ErrTooManyChannels indicates the total channel count exceeds the maximum. ErrTooManyChannels = errors.New("multistream: too many channels (streams + coupled_streams must be <= 255)") // ErrInvalidMapping indicates the mapping table is malformed. ErrInvalidMapping = errors.New("multistream: invalid mapping table") // ErrInvalidProjectionMatrix indicates malformed projection demixing metadata. ErrInvalidProjectionMatrix = errors.New("multistream: invalid projection demixing matrix") // ErrInvalidStreamIndex indicates an out-of-range per-stream state lookup. ErrInvalidStreamIndex = errors.New("multistream: invalid stream index") // ErrInvalidGain indicates an invalid decoder gain value. ErrInvalidGain = errors.New("multistream: invalid gain (must be -32768 to 32767)") // ErrInvalidComplexity indicates an invalid decoder complexity value. ErrInvalidComplexity = errors.New("multistream: invalid complexity (must be 0-10)") // ErrBufferTooSmall indicates the requested decode frame is smaller than the packet duration. ErrBufferTooSmall = errors.New("multistream: output buffer too small") )
Errors for multistream decoder creation and operation.
var ( // ErrPacketTooShort indicates insufficient data in the multistream packet. ErrPacketTooShort = errors.New("multistream: packet too short") // ErrInvalidPacket indicates malformed Opus packet framing. ErrInvalidPacket = errors.New("multistream: invalid packet framing") // ErrDurationMismatch indicates streams have different frame durations. ErrDurationMismatch = errors.New("multistream: streams have different frame durations") // ErrInvalidStreamCount indicates an invalid stream count (must be >= 1). ErrInvalidStreamCount = errors.New("multistream: invalid stream count (must be >= 1)") )
Errors for multistream packet parsing.
var ErrInvalidDefaultMappingChannels = errors.New("multistream: invalid default mapping channel count (must be 1-8)")
ErrInvalidDefaultMappingChannels indicates a channel count outside the default mapping range.
var ErrInvalidInput = errors.New("multistream: invalid input length")
ErrInvalidInput indicates the input samples have incorrect length.
var ErrInvalidLSBDepth = errors.New("multistream: invalid LSB depth (must be 8-24)")
ErrInvalidLSBDepth indicates the LSB depth is outside the valid range (8-24).
var ErrInvalidLayout = errors.New("multistream: invalid layout - coupled stream missing left or right channel")
ErrInvalidLayout indicates the channel mapping has an invalid layout. For coupled streams, both left and right channels must be mapped.
Functions ¶
func AmbisonicsChannelCount ¶
AmbisonicsChannelCount returns the number of channels for a given ambisonics order with optional non-diegetic stereo pair.
Parameters:
- order: ambisonics order (0-14)
- withNondiegetic: true to include 2 non-diegetic channels
Returns the channel count, or 0 if order is out of range.
func AmbisonicsMapping ¶
AmbisonicsMapping generates the ACN-style channel mapping for ambisonics family 2 encoding.
The mapping layout for family 2:
- First (streams - coupled_streams) entries map to mono streams
- Remaining entries map to coupled (stereo) streams
For pure ambisonics (no non-diegetic):
- All streams are mono
- mapping[i] = i + 0 (since coupled_streams * 2 = 0)
For ambisonics with non-diegetic:
- First (acn_channels) entries map to mono streams
- Last 2 entries map to the stereo non-diegetic stream
Reference: libopus opus_multistream_encoder.c:opus_multistream_surround_encoder_init
func AmbisonicsMappingFamily3 ¶
AmbisonicsMappingFamily3 generates the channel mapping for ambisonics family 3 encoding. Family 3 uses projection-based encoding where channels are paired into stereo streams.
The mapping is a simple sequential ordering where:
- Even channels (0, 2, 4...) are left channels of coupled streams
- Odd channels (1, 3, 5...) are right channels of coupled streams
For odd channel counts, the last channel is in a mono stream.
func DefaultMapping ¶
DefaultMapping returns the default Vorbis-style (mapping family 1) configuration for a given channel count.
Returns:
- streams: total number of elementary Opus streams (N)
- coupledStreams: number of coupled (stereo) streams (M), where first M streams are stereo
- mapping: channel mapping table where mapping[i] indicates the source for output channel i
- err: error if channel count is invalid for the default mapping (must be 1-8)
The mapping table encodes which decoded channel feeds each output channel:
- Values 0 to 2*M-1: from coupled streams (even=left, odd=right of stereo pair)
- Values 2*M to N+M-1: from uncoupled (mono) streams
- Value 255: silent channel
Reference: RFC 7845 Section 5.1.1
func GetAmbisonicsOrder ¶
GetAmbisonicsOrder returns the ambisonics order and non-diegetic channel count from a given channel count.
The order is derived from: channels = (order+1)^2 + nondiegetic where nondiegetic is 0 or 2.
Returns:
- order: the ambisonics order (0 for mono, 1 for FOA, 2 for SOA, etc.)
- nondiegetic: number of non-diegetic channels (0 or 2)
- err: error if channel count is invalid
Reference: libopus opus_projection_encoder.c:get_order_plus_one_from_channels
func IsValidAmbisonicsChannelCount ¶
IsValidAmbisonicsChannelCount returns true if the channel count is valid for ambisonics encoding.
Valid counts are (order+1)^2 or (order+1)^2 + 2 for orders 0-14: 1, 4, 6, 9, 11, 16, 18, 25, 27, 36, 38, 49, 51, 64, 66, 81, 83, 100, 102, 121, 123, 144, 146, 169, 171, 196, 198, 225, 227
func PacketDuration ¶
PacketDuration returns the common packet duration for a multistream packet in 48 kHz samples per channel.
func PacketDurationAtRate ¶
PacketDurationAtRate returns the common packet duration in samples per channel at sampleRate, matching opus_packet_get_nb_samples().
func ProjectionDemixingMatrixSize ¶
ProjectionDemixingMatrixSize returns the byte size of the demixing matrix for a family-3 projection encoder with the given dimensions.
This mirrors OPUS_PROJECTION_GET_DEMIXING_MATRIX_SIZE:
size = channels * (streams + coupled_streams) * sizeof(opus_int16)
Reference: libopus src/opus_projection_encoder.c:opus_projection_encoder_ctl
func ValidateAmbisonics ¶
ValidateAmbisonics validates that the channel count is valid for ambisonics encoding (mapping family 2) and returns the expected number of streams and coupled streams.
Valid ambisonics channel counts are:
- (order+1)^2 for pure ambisonics (e.g., 1, 4, 9, 16, 25...)
- (order+1)^2 + 2 for ambisonics with non-diegetic stereo (e.g., 6, 11, 18, 27...)
For family 2:
- streams = acn_channels + (nondiegetic > 0 ? 1 : 0)
- coupled = (nondiegetic > 0 ? 1 : 0)
The maximum supported channel count is 227 (order 14 + 2 non-diegetic).
Reference: libopus opus_multistream_encoder.c:validate_ambisonics
func ValidateAmbisonicsFamily3 ¶
ValidateAmbisonicsFamily3 validates channel count for ambisonics family 3 (projection-based ambisonics) and returns streams/coupled configuration.
Family 3 uses maximum stereo coupling:
- streams = (channels + 1) / 2
- coupled = channels / 2
libopus 1.6.1 projection encoding supports only orders 1..5 (orderPlusOne 2..6), with optional non-diegetic stereo channels. Pre-computed mixing and demixing matrices exist for FOA/SOA/TOA/4thOA/5thOA only. Higher orders (6-14) are valid ambisonics channel counts but are not supported by family 3; use mapping family 2 (ValidateAmbisonics) for orders 6-14.
Valid channel counts:
Order 1 (FOA): 4 or 6 channels Order 2 (SOA): 9 or 11 channels Order 3 (TOA): 16 or 18 channels Order 4 (4thOA): 25 or 27 channels Order 5 (5thOA): 36 or 38 channels
Reference: libopus src/opus_projection_encoder.c:get_streams_from_channels, src/mapping_matrix.c (mapping_matrix_foa…fifthoa mixing/demixing tables)
Types ¶
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
Decoder decodes Opus multistream packets containing multiple elementary streams. Each stream is decoded independently and routed to output channels via a mapping table.
Multistream packets are used for surround sound configurations (5.1, 7.1, etc.) where multiple coupled (stereo) and uncoupled (mono) streams are combined.
Reference: RFC 7845 Section 5.1.1
func NewDecoder ¶
func NewDecoder(sampleRate, channels, streams, coupledStreams int, mapping []byte) (*Decoder, error)
NewDecoder creates a new multistream decoder.
Parameters:
- sampleRate: output sample rate (8000, 12000, 16000, 24000, or 48000 Hz)
- channels: total output channels (1-255)
- streams: total elementary streams (N, 1-255)
- coupledStreams: number of coupled stereo streams (M, 0 to streams)
- mapping: channel mapping table (length must equal channels)
The mapping table determines how decoded audio is routed to output channels:
- Values 0 to 2*M-1: from coupled streams (even=left, odd=right of stereo pair)
- Values 2*M to N+M-1: from uncoupled (mono) streams
- Value 255: silent channel (output zeros)
Example for 5.1 surround (6 channels, 4 streams, 2 coupled):
mapping = [0, 4, 1, 2, 3, 5] Channel 0 (FL): mapping[0]=0 -> coupled stream 0, left Channel 1 (C): mapping[1]=4 -> uncoupled stream 2 (2*2+0) Channel 2 (FR): mapping[2]=1 -> coupled stream 0, right Channel 3 (RL): mapping[3]=2 -> coupled stream 1, left Channel 4 (RR): mapping[4]=3 -> coupled stream 1, right Channel 5 (LFE): mapping[5]=5 -> uncoupled stream 3 (2*2+1)
func NewDecoderDefault ¶
NewDecoderDefault creates a multistream decoder with default Vorbis-style mapping for standard channel configurations (1-8 channels).
This is a convenience function that calls DefaultMapping() to get the appropriate streams, coupledStreams, and mapping for the given channel count.
Supported channel counts:
- 1: mono (1 stream, 0 coupled)
- 2: stereo (1 stream, 1 coupled)
- 3: 3.0 (2 streams, 1 coupled)
- 4: quad (2 streams, 2 coupled)
- 5: 5.0 (3 streams, 2 coupled)
- 6: 5.1 surround (4 streams, 2 coupled)
- 7: 6.1 surround (4 streams, 3 coupled)
- 8: 7.1 surround (5 streams, 3 coupled)
func NewProjectionDecoder ¶
func NewProjectionDecoder(sampleRate, channels, streams, coupledStreams int, demixingMatrix []byte) (*Decoder, error)
NewProjectionDecoder creates a family-3 projection ambisonics decoder initialized with a demixing matrix obtained from a projection encoder.
The demixingMatrix parameter must match the output of Encoder.GetDemixingMatrix() (S16LE-encoded, as returned by OPUS_PROJECTION_GET_DEMIXING_MATRIX). Passing nil creates a plain multistream decoder without projection demixing.
streams and coupledStreams must match the values from the corresponding encoder (enc.Streams(), enc.CoupledStreams()). The mapping is always the trivial identity [0, 1, 2, ..., channels-1] for projection decoders.
Reference: libopus src/opus_projection_decoder.c:opus_projection_decoder_create
func (*Decoder) Bandwidth ¶
Bandwidth returns the audio bandwidth of the last decoded packet, taken from the first stream (OPUS_GET_BANDWIDTH). Defaults to fullband before any decode.
func (*Decoder) Complexity ¶
Complexity returns the decoder complexity setting (OPUS_GET_COMPLEXITY).
func (*Decoder) CoupledStreams ¶
CoupledStreams returns the number of coupled (stereo) streams.
func (*Decoder) DNNBlobLoaded ¶
DNNBlobLoaded reports whether a validated model blob is retained.
func (*Decoder) Decode ¶
Decode decodes a multistream Opus packet and returns PCM samples.
If data is nil, performs Packet Loss Concealment (PLC) by generating concealment audio based on the previous frames' state.
Parameters:
- data: raw multistream packet data, or nil for PLC
- frameSize: frame size in samples at the decoder sample rate
Returns sample-interleaved float32 samples: [ch0_s0, ch1_s0, ..., chN_s0, ch0_s1, ch1_s1, ...] where N is the number of output channels.
All elementary streams within the packet must have the same frame duration. If durations differ, ErrDurationMismatch is returned.
func (*Decoder) DecodeToFloat32 ¶
DecodeToFloat32 decodes a multistream packet and returns float32 PCM. This is a convenience wrapper for audio APIs expecting float32.
Parameters:
- data: raw multistream packet data, or nil for PLC
- frameSize: frame size in samples at the decoder sample rate
Returns sample-interleaved float32 samples in approximate range [-1, 1]. The output format is: [ch0_s0, ch1_s0, ..., chN_s0, ch0_s1, ch1_s1, ...]
func (*Decoder) DecodeToInt16 ¶
DecodeToInt16 decodes a multistream packet and converts to int16 PCM. This is a convenience wrapper for common audio output formats.
Parameters:
- data: raw multistream packet data, or nil for PLC
- frameSize: frame size in samples at the decoder sample rate
Returns sample-interleaved int16 samples in range [-32768, 32767]. The output format is: [ch0_s0, ch1_s0, ..., chN_s0, ch0_s1, ch1_s1, ...]
func (*Decoder) FARGANModelLoaded ¶
FARGANModelLoaded reports whether the retained blob contains the FARGAN model family.
func (*Decoder) FinalRange ¶
FinalRange returns the combined range-coder final state for the last decoded packet. It is an alias for GetFinalRange.
func (*Decoder) GetFinalRange ¶
GetFinalRange returns the XOR of every elementary stream's range-coder final state, mirroring libopus opus_multistream_decoder_ctl(OPUS_GET_FINAL_RANGE). It is used to verify bit-exact decode against another implementation.
func (*Decoder) IgnoreExtensions ¶
IgnoreExtensions reports whether opaque packet-extension handling is disabled.
func (*Decoder) LastPacketDuration ¶
LastPacketDuration returns the duration in samples (at the decoder sample rate) of the last decoded packet, taken from the first stream (OPUS_GET_LAST_PACKET_DURATION).
func (*Decoder) PLCModelLoaded ¶
PLCModelLoaded reports whether the retained blob contains the PLC model family.
func (*Decoder) PhaseInversionDisabled ¶
PhaseInversionDisabled reports whether stereo phase inversion is disabled.
func (*Decoder) PitchDNNLoaded ¶
PitchDNNLoaded reports whether the retained blob contains libopus's shared decoder pitch model family.
func (*Decoder) Reset ¶
func (d *Decoder) Reset()
Reset clears all decoder state for a new stream. Call this when starting to decode a new audio stream.
func (*Decoder) SampleRate ¶
SampleRate returns the output sample rate in Hz.
func (*Decoder) SetComplexity ¶
SetComplexity sets the decoder complexity (0-10) for every elementary stream, mirroring OPUS_SET_COMPLEXITY. Out-of-range values return ErrInvalidComplexity.
func (*Decoder) SetDNNBlob ¶
SetDNNBlob retains a validated USE_WEIGHTS_FILE blob for future optional extension paths. A nil blob clears the retained main-decoder model state. The blob is also fanned out to every child stream decoder so each stream can bind its own OSCE LACE/NoLACE and OSCE BWE runtime models (libopus keeps an independent `silk_OSCE_struct` per `silk_channel_state` and one `silk_OSCE_BWE_struct` per `silk_channel_state`; the multistream decoder mirrors that by giving every per-stream `streamState` its own copy of the runtime state).
func (*Decoder) SetGain ¶
SetGain sets the decoder output gain in Q8 dB units, applied uniformly to every elementary stream (libopus OPUS_SET_GAIN semantics). Valid range is [-32768, 32767]; out-of-range values return ErrInvalidGain.
func (*Decoder) SetIgnoreExtensions ¶
SetIgnoreExtensions toggles libopus-style opaque packet-extension handling for every elementary stream. When true, opaque in-band extensions (including any DRED side payloads) carried in packet padding are ignored rather than parsed.
func (*Decoder) SetPhaseInversionDisabled ¶
SetPhaseInversionDisabled disables (or re-enables) stereo phase inversion for every coupled stream, mirroring OPUS_SET_PHASE_INVERSION_DISABLED. Disabling it trades stereo quality for better mono downmix behaviour.
func (*Decoder) SetProjectionDemixingMatrix ¶
SetProjectionDemixingMatrix sets optional projection demixing coefficients. Matrix data is S16LE, column-major, with dimensions:
rows = output channels cols = streams + coupledStreams
This method is intended for mapping-family-3 projection flows where decoded stream channels are routed with trivial mapping and then demixed to output channels.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder encodes multi-channel audio into Opus multistream packets. Each elementary stream is encoded independently using a Phase 8 unified Encoder, then combined with self-delimiting framing per RFC 6716 Appendix B.
Multistream packets are used for surround sound configurations (5.1, 7.1, etc.) where multiple coupled (stereo) and uncoupled (mono) streams are combined.
Reference: RFC 7845 Section 5.1.1
func NewEncoder ¶
func NewEncoder(sampleRate, channels, streams, coupledStreams int, mapping []byte) (*Encoder, error)
NewEncoder creates a new multistream encoder.
Parameters:
- sampleRate: input sample rate (8000, 12000, 16000, 24000, or 48000 Hz)
- channels: total input channels (1-255)
- streams: total elementary streams (N, 1-255)
- coupledStreams: number of coupled stereo streams (M, 0 to streams)
- mapping: channel mapping table (length must equal channels)
The mapping table determines how input audio is routed to stream encoders:
- Values 0 to 2*M-1: to coupled streams (even=left, odd=right of stereo pair)
- Values 2*M to N+M-1: to uncoupled (mono) streams
- Value 255: silent channel (input ignored)
Example for 5.1 surround (6 channels, 4 streams, 2 coupled):
mapping = [0, 4, 1, 2, 3, 5] Input 0 (FL): mapping[0]=0 -> coupled stream 0, left Input 1 (C): mapping[1]=4 -> uncoupled stream 2 (2*2+0) Input 2 (FR): mapping[2]=1 -> coupled stream 0, right Input 3 (RL): mapping[3]=2 -> coupled stream 1, left Input 4 (RR): mapping[4]=3 -> coupled stream 1, right Input 5 (LFE): mapping[5]=5 -> uncoupled stream 3 (2*2+1)
func NewEncoderAmbisonics ¶
NewEncoderAmbisonics creates a new multistream encoder for ambisonics audio.
Parameters:
- sampleRate: input sample rate (8000, 12000, 16000, 24000, or 48000 Hz)
- channels: total input channels (valid ambisonics count: 1, 4, 6, 9, 11, 16, 18, 25, 27...)
- mappingFamily: 2 for ACN/SN3D (mostly mono), 3 for projection (paired stereo)
Valid ambisonics channel counts are (order+1)^2 or (order+1)^2 + 2:
- Order 0: 1 channel (or 3 with non-diegetic)
- Order 1 (FOA): 4 channels (or 6 with non-diegetic)
- Order 2 (SOA): 9 channels (or 11 with non-diegetic)
- Order 3 (TOA): 16 channels (or 18 with non-diegetic)
For mapping family 2:
- ACN channel ordering with SN3D normalization
- All ambisonics channels are mono streams
- Optional non-diegetic stereo pair as one coupled stream
For mapping family 3:
- Projection-based encoding
- Channels are paired into stereo coupled streams
- streams = (channels+1)/2, coupled = channels/2
- libopus parity support is limited to orders 1..5 (valid channels: 4, 6, 9, 11, 16, 18, 25, 27, 36, 38)
Reference: RFC 7845 Section 5.1.1.2, libopus opus_multistream_encoder.c
func NewEncoderDefault ¶
NewEncoderDefault creates a multistream encoder with default Vorbis-style mapping for standard channel configurations (1-8 channels).
This is a convenience function that calls DefaultMapping() to get the appropriate streams, coupledStreams, and mapping for the given channel count.
Supported channel counts:
- 1: mono (1 stream, 0 coupled)
- 2: stereo (1 stream, 1 coupled)
- 3: 3.0 (2 streams, 1 coupled)
- 4: quad (2 streams, 2 coupled)
- 5: 5.0 (3 streams, 2 coupled)
- 6: 5.1 surround (4 streams, 2 coupled)
- 7: 6.1 surround (4 streams, 3 coupled)
- 8: 7.1 surround (5 streams, 3 coupled)
func NewProjectionEncoder ¶
NewProjectionEncoder creates a family-3 projection ambisonics encoder.
This is a convenience alias for NewEncoderAmbisonics(sampleRate, channels, 3). Supported channel counts are: 4, 6, 9, 11, 16, 18, 25, 27, 36, 38 (ambisonics orders 1-5, with or without non-diegetic stereo channels).
Returns ErrProjectionOrderUnsupported for valid ambisonics channel counts outside the range supported by family 3 (orders 6-14 / channels 49-227).
Reference: libopus src/opus_projection_encoder.c:opus_projection_ambisonics_encoder_create
func (*Encoder) BitrateMode ¶
func (e *Encoder) BitrateMode() encoder.BitrateMode
BitrateMode returns the current bitrate mode (from first stream encoder).
func (*Encoder) Complexity ¶
Complexity returns the complexity setting of the first encoder. All stream encoders use the same complexity.
func (*Encoder) CoupledStreams ¶
CoupledStreams returns the number of coupled (stereo) streams.
func (*Encoder) DNNBlobLoaded ¶
DNNBlobLoaded reports whether a validated model blob is retained.
func (*Encoder) DTXEnabled ¶
DTXEnabled returns whether DTX is enabled (from first encoder).
func (*Encoder) DemixingMatrixGain ¶
DemixingMatrixGain returns the gain field of the internal demixing matrix, matching OPUS_PROJECTION_GET_DEMIXING_MATRIX_GAIN_REQUEST.
Returns 0 if this encoder is not mapping family 3.
Reference: libopus src/opus_projection_encoder.c:opus_projection_encoder_ctl OPUS_PROJECTION_GET_DEMIXING_MATRIX_GAIN_REQUEST
func (*Encoder) DemixingMatrixSize ¶
DemixingMatrixSize returns the byte size of the demixing matrix, matching OPUS_PROJECTION_GET_DEMIXING_MATRIX_SIZE_REQUEST.
Returns 0 if this encoder is not mapping family 3.
Reference: libopus src/opus_projection_encoder.c:opus_projection_encoder_ctl OPUS_PROJECTION_GET_DEMIXING_MATRIX_SIZE_REQUEST
func (*Encoder) Encode ¶
Encode encodes multi-channel PCM samples to an Opus multistream packet.
Parameters:
- pcm: input samples as float32, sample-interleaved [ch0_s0, ch1_s0, ..., chN_s0, ch0_s1, ...]
- frameSize: number of samples per channel (must be valid for Opus: 120, 240, 480, 960, 1920, 2880)
Returns:
- The encoded multistream packet
- nil, nil if DTX is active for all streams (all returned 1-byte TOC-only packets)
- error if encoding fails
The encoding process:
- Routes input channels to stream buffers via mapping table
- Encodes each stream independently using the unified encoder
- Assembles packets with self-delimiting framing per RFC 6716 Appendix B
Reference: RFC 6716 Appendix B, RFC 7845 Section 5.1.1
func (*Encoder) EncodeFloat32 ¶
EncodeFloat32 encodes libopus float-build PCM samples to an Opus multistream packet.
func (*Encoder) EncodeFloat32WithAnalysis ¶
func (e *Encoder) EncodeFloat32WithAnalysis(pcm []float32, frameSize int, analysisPCM []float32) ([]byte, error)
EncodeFloat32WithAnalysis encodes the selected frame while letting child encoders analyze the full caller frame selected by expert-frame-duration controls. PCM routing and projection mixing stay in the libopus float domain.
The top-level packet budget defaults to the libopus per-stream maximum (maxOpusFrameBytes per stream), matching the recommended 4000-byte-per-stream caller buffer. Use EncodeFloat32WithAnalysisMaxBytes to pass an explicit caller buffer size, which libopus threads into the per-stream curr_max budgeting (opus_multistream_encoder.c opus_multistream_encode_native()).
func (*Encoder) EncodeFloat32WithAnalysisMaxBytes ¶
func (e *Encoder) EncodeFloat32WithAnalysisMaxBytes(pcm []float32, frameSize int, analysisPCM []float32, maxDataBytes int) ([]byte, error)
EncodeFloat32WithAnalysisMaxBytes encodes one frame with an explicit caller packet budget. maxDataBytes is the total output buffer size; libopus uses it as the top-level max_data_bytes and derives each stream's curr_max from it (opus_multistream_encoder.c opus_multistream_encode_native(), lines 1016-1024).
func (*Encoder) EncodeWithAnalysis ¶
func (e *Encoder) EncodeWithAnalysis(pcm []float32, frameSize int, analysisPCM []float32) ([]byte, error)
EncodeWithAnalysis encodes the selected frame while letting child encoders analyze the full caller frame selected by expert-frame-duration controls.
func (*Encoder) FECEnabled ¶
FECEnabled returns whether FEC is enabled (from first encoder).
func (*Encoder) ForceChannels ¶
ForceChannels returns forced channel count from the first stream encoder.
func (*Encoder) GetDemixingMatrix ¶
GetDemixingMatrix returns the serialized demixing matrix for this projection encoder, matching the output of OPUS_PROJECTION_GET_DEMIXING_MATRIX_REQUEST.
The returned bytes are S16LE-encoded, row-major over:
- rows = streams + coupled_streams (nb_input_streams)
- cols = channels (nb_output_streams)
Returns nil if this encoder is not mapping family 3, or if no defaults are available for the configured channel count.
Reference: libopus src/opus_projection_encoder.c:opus_projection_encoder_ctl OPUS_PROJECTION_GET_DEMIXING_MATRIX_REQUEST
func (*Encoder) GetFinalRange ¶
GetFinalRange returns the final range coder state for all streams. The values from all streams are XOR combined to produce a single verification value. This matches libopus OPUS_GET_FINAL_RANGE for multistream encoders. Must be called after Encode() to get a meaningful value.
func (*Encoder) LSBDepth ¶
LSBDepth returns the current LSB depth setting (from first encoder). All stream encoders share the same LSB depth setting.
func (*Encoder) Lookahead ¶
Lookahead returns the encoder's algorithmic delay in samples at 48kHz. This includes both CELT delay compensation and mode-specific delay. For multistream, all stream encoders have the same lookahead. Reference: libopus OPUS_GET_LOOKAHEAD
func (*Encoder) LowDelay ¶
LowDelay reports low-delay application behavior from the first stream encoder.
func (*Encoder) MappingFamily ¶
MappingFamily returns the channel mapping family used by this encoder.
Mapping families:
- 0: RTP mapping (mono or stereo only)
- 1: Vorbis-style mapping (1-8 channels)
- 2: Ambisonics ACN/SN3D (mostly mono streams)
- 3: Ambisonics with projection (paired stereo streams)
- 255: Discrete channels (no predefined mapping)
func (*Encoder) MaxBandwidth ¶
MaxBandwidth returns the maximum bandwidth limit (from first encoder). All stream encoders share the same max bandwidth setting.
func (*Encoder) PacketLoss ¶
PacketLoss returns the expected packet loss percentage (from first encoder).
func (*Encoder) PhaseInversionDisabled ¶
PhaseInversionDisabled reports whether stereo phase inversion is disabled.
func (*Encoder) PredictionDisabled ¶
PredictionDisabled reports whether inter-frame prediction is disabled.
func (*Encoder) Reset ¶
func (e *Encoder) Reset()
Reset clears all encoder state for a new stream. Call this when starting to encode a new audio stream.
func (*Encoder) SampleRate ¶
SampleRate returns the input sample rate in Hz.
func (*Encoder) SetBandwidth ¶
SetBandwidth sets the target bandwidth for all stream encoders.
func (*Encoder) SetBandwidthAuto ¶
func (e *Encoder) SetBandwidthAuto()
SetBandwidthAuto restores automatic bandwidth selection on all stream encoders.
func (*Encoder) SetBitrate ¶
SetBitrate sets the total bitrate in bits per second. The bitrate is distributed across streams with coupled streams getting proportionally more bits than mono streams.
Distribution formula:
- Coupled streams: 3 units (e.g., 96 kbps at typical settings)
- Mono streams: 2 units (e.g., 64 kbps at typical settings)
func (*Encoder) SetBitrateMode ¶
func (e *Encoder) SetBitrateMode(mode encoder.BitrateMode)
SetBitrateMode sets the bitrate mode for all stream encoders.
func (*Encoder) SetComplexity ¶
SetComplexity sets encoder complexity (0-10) for all stream encoders. Higher values use more CPU for better quality. Default is 10 (maximum quality).
func (*Encoder) SetDNNBlob ¶
SetDNNBlob retains a validated USE_WEIGHTS_FILE blob and propagates it to all child stream encoders. A nil blob clears the retained model.
func (*Encoder) SetDTX ¶
SetDTX enables or disables Discontinuous Transmission for all streams. When enabled, packets are suppressed during silence.
func (*Encoder) SetFEC ¶
SetFEC enables or disables in-band Forward Error Correction for all streams. When enabled, encoders include LBRR data for loss recovery.
func (*Encoder) SetForceChannels ¶
SetForceChannels sets forced channel count on all stream encoders.
func (*Encoder) SetInBandFEC ¶
SetInBandFEC sets the in-band FEC configuration for all streams.
func (*Encoder) SetLSBDepth ¶
SetLSBDepth sets the input signal's LSB depth for all stream encoders. Valid range is 8-24 bits. This affects DTX sensitivity.
func (*Encoder) SetLowDelay ¶
SetLowDelay toggles low-delay application behavior for all stream encoders.
func (*Encoder) SetMaxBandwidth ¶
SetMaxBandwidth sets the maximum bandwidth limit for all stream encoders. The actual bandwidth will be clamped to this limit.
func (*Encoder) SetPacketLoss ¶
SetPacketLoss sets the expected packet loss percentage (0-100) for all streams. This affects FEC behavior and bitrate allocation.
func (*Encoder) SetPhaseInversionDisabled ¶
SetPhaseInversionDisabled toggles stereo phase inversion on all stream encoders.
func (*Encoder) SetPredictionDisabled ¶
SetPredictionDisabled toggles inter-frame prediction for all stream encoders.
func (*Encoder) SetRestrictedSilkApplication ¶
SetRestrictedSilkApplication toggles restricted-SILK application behavior.
func (*Encoder) SetSignal ¶
SetSignal sets the signal type hint for all stream encoders. SignalVoice biases toward SILK mode, SignalMusic toward CELT mode.
func (*Encoder) SetVBRConstraint ¶
SetVBRConstraint enables or disables constrained VBR mode.
func (*Encoder) SetVoIPApplication ¶
SetVoIPApplication toggles VoIP application bias for all stream encoders.
func (*Encoder) Signal ¶
Signal returns the current signal type hint (from first encoder). All stream encoders share the same signal type setting.
func (*Encoder) VBRConstraint ¶
VBRConstraint reports whether constrained VBR is enabled.
func (*Encoder) VoIPApplication ¶
VoIPApplication reports VoIP application bias from the first stream encoder.
Source Files
¶
- ambisonics.go
- decode_hybrid.go
- decode_transition.go
- decoder.go
- decoder_dnn_helpers.go
- decoder_dred_fields_default.go
- decoder_dred_helpers_default.go
- decoder_fixedpoint_fields_default.go
- decoder_osce_apply_default.go
- decoder_osce_fields_default.go
- decoder_osce_helpers_default.go
- decoder_osce_state_default.go
- decoder_qext_hook_default.go
- decoder_qext_payloads_default.go
- doc.go
- encoder.go
- encoder_helpers.go
- extensions.go
- framing.go
- mapping.go
- multistream.go
- projection.go
- projection_demixing_defaults.go
- projection_demixing_defaults_data.go
- projection_helpers.go
- projection_matrix.go
- projection_mixing_defaults.go
- projection_mixing_defaults_data.go
- stream.go