multistream

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2026 License: BSD-3-Clause Imports: 13 Imported by: 1 module, 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 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

Constants

This section is empty.

Variables

View Source
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.

View Source
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.

View Source
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.

View Source
var ErrInvalidDefaultMappingChannels = errors.New("multistream: invalid default mapping channel count (must be 1-8)")

ErrInvalidDefaultMappingChannels indicates a channel count outside the default mapping range.

View Source
var ErrInvalidInput = errors.New("multistream: invalid input length")

ErrInvalidInput indicates the input samples have incorrect length.

View Source
var ErrInvalidLSBDepth = errors.New("multistream: invalid LSB depth (must be 8-24)")

ErrInvalidLSBDepth indicates the LSB depth is outside the valid range (8-24).

View Source
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

func AmbisonicsChannelCount(order int, withNondiegetic bool) int

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

func AmbisonicsMapping(channels int) ([]byte, error)

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

func AmbisonicsMappingFamily3(channels int) ([]byte, error)

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

func DefaultMapping(channels int) (streams, coupledStreams int, mapping []byte, err error)

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

func GetAmbisonicsOrder(channels int) (order, nondiegetic int, err error)

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

func IsValidAmbisonicsChannelCount(channels int) bool

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

func PacketDuration(data []byte, numStreams int) (int, error)

PacketDuration returns the common packet duration for a multistream packet in 48 kHz samples per channel.

func PacketDurationAtRate

func PacketDurationAtRate(data []byte, numStreams, sampleRate int) (int, error)

PacketDurationAtRate returns the common packet duration in samples per channel at sampleRate, matching opus_packet_get_nb_samples().

func ProjectionDemixingMatrixSize

func ProjectionDemixingMatrixSize(channels, streams, coupled int) int

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

func ValidateAmbisonics(channels int) (streams, coupledStreams int, err error)

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

func ValidateAmbisonicsFamily3(channels int) (streams, coupledStreams int, err error)

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

func NewDecoderDefault(sampleRate, channels int) (*Decoder, error)

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

func (d *Decoder) Bandwidth() types.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) Channels

func (d *Decoder) Channels() int

Channels returns the total number of output channels.

func (*Decoder) Complexity

func (d *Decoder) Complexity() int

Complexity returns the decoder complexity setting (OPUS_GET_COMPLEXITY).

func (*Decoder) CoupledStreams

func (d *Decoder) CoupledStreams() int

CoupledStreams returns the number of coupled (stereo) streams.

func (*Decoder) DNNBlobLoaded

func (d *Decoder) DNNBlobLoaded() bool

DNNBlobLoaded reports whether a validated model blob is retained.

func (*Decoder) Decode

func (d *Decoder) Decode(data []byte, frameSize int) ([]float32, error)

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

func (d *Decoder) DecodeToFloat32(data []byte, frameSize int) ([]float32, error)

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

func (d *Decoder) DecodeToInt16(data []byte, frameSize int) ([]int16, error)

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

func (d *Decoder) FARGANModelLoaded() bool

FARGANModelLoaded reports whether the retained blob contains the FARGAN model family.

func (*Decoder) FinalRange

func (d *Decoder) FinalRange() uint32

FinalRange returns the combined range-coder final state for the last decoded packet. It is an alias for GetFinalRange.

func (*Decoder) Gain

func (d *Decoder) Gain() int

Gain returns the decoder output gain in Q8 dB units (OPUS_GET_GAIN).

func (*Decoder) GetFinalRange

func (d *Decoder) GetFinalRange() uint32

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

func (d *Decoder) IgnoreExtensions() bool

IgnoreExtensions reports whether opaque packet-extension handling is disabled.

func (*Decoder) LastPacketDuration

func (d *Decoder) LastPacketDuration() int

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

func (d *Decoder) PLCModelLoaded() bool

PLCModelLoaded reports whether the retained blob contains the PLC model family.

func (*Decoder) PhaseInversionDisabled

func (d *Decoder) PhaseInversionDisabled() bool

PhaseInversionDisabled reports whether stereo phase inversion is disabled.

func (*Decoder) PitchDNNLoaded

func (d *Decoder) PitchDNNLoaded() bool

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

func (d *Decoder) SampleRate() int

SampleRate returns the output sample rate in Hz.

func (*Decoder) SetComplexity

func (d *Decoder) SetComplexity(complexity int) error

SetComplexity sets the decoder complexity (0-10) for every elementary stream, mirroring OPUS_SET_COMPLEXITY. Out-of-range values return ErrInvalidComplexity.

func (*Decoder) SetDNNBlob

func (d *Decoder) SetDNNBlob(blob *dnnblob.Blob)

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

func (d *Decoder) SetGain(gainQ8 int) error

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

func (d *Decoder) SetIgnoreExtensions(ignore bool)

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

func (d *Decoder) SetPhaseInversionDisabled(disabled bool)

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

func (d *Decoder) SetProjectionDemixingMatrix(matrix []byte) error

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.

func (*Decoder) Streams

func (d *Decoder) Streams() int

Streams returns the total number of elementary streams.

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

func NewEncoderAmbisonics(sampleRate, channels, mappingFamily int) (*Encoder, error)

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

func NewEncoderDefault(sampleRate, channels int) (*Encoder, error)

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

func NewProjectionEncoder(sampleRate, channels int) (*Encoder, error)

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) Bandwidth

func (e *Encoder) Bandwidth() types.Bandwidth

Bandwidth returns the target bandwidth from the first stream encoder.

func (*Encoder) Bitrate

func (e *Encoder) Bitrate() int

Bitrate returns the total bitrate in bits per second.

func (*Encoder) BitrateMode

func (e *Encoder) BitrateMode() encoder.BitrateMode

BitrateMode returns the current bitrate mode (from first stream encoder).

func (*Encoder) Channels

func (e *Encoder) Channels() int

Channels returns the total number of input channels.

func (*Encoder) Complexity

func (e *Encoder) Complexity() int

Complexity returns the complexity setting of the first encoder. All stream encoders use the same complexity.

func (*Encoder) CoupledStreams

func (e *Encoder) CoupledStreams() int

CoupledStreams returns the number of coupled (stereo) streams.

func (*Encoder) DNNBlobLoaded

func (e *Encoder) DNNBlobLoaded() bool

DNNBlobLoaded reports whether a validated model blob is retained.

func (*Encoder) DTXEnabled

func (e *Encoder) DTXEnabled() bool

DTXEnabled returns whether DTX is enabled (from first encoder).

func (*Encoder) DemixingMatrixGain

func (e *Encoder) DemixingMatrixGain() int

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

func (e *Encoder) DemixingMatrixSize() int

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

func (e *Encoder) Encode(pcm []float32, frameSize int) ([]byte, error)

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:

  1. Routes input channels to stream buffers via mapping table
  2. Encodes each stream independently using the unified encoder
  3. 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

func (e *Encoder) EncodeFloat32(pcm []float32, frameSize int) ([]byte, error)

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

func (e *Encoder) FECEnabled() bool

FECEnabled returns whether FEC is enabled (from first encoder).

func (*Encoder) ForceChannels

func (e *Encoder) ForceChannels() int

ForceChannels returns forced channel count from the first stream encoder.

func (*Encoder) GetDemixingMatrix

func (e *Encoder) GetDemixingMatrix() []byte

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

func (e *Encoder) GetFinalRange() uint32

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) InBandFEC

func (e *Encoder) InBandFEC() int

InBandFEC returns the in-band FEC configuration from the first stream.

func (*Encoder) LSBDepth

func (e *Encoder) LSBDepth() int

LSBDepth returns the current LSB depth setting (from first encoder). All stream encoders share the same LSB depth setting.

func (*Encoder) Lookahead

func (e *Encoder) Lookahead() int

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

func (e *Encoder) LowDelay() bool

LowDelay reports low-delay application behavior from the first stream encoder.

func (*Encoder) MappingFamily

func (e *Encoder) MappingFamily() int

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

func (e *Encoder) MaxBandwidth() types.Bandwidth

MaxBandwidth returns the maximum bandwidth limit (from first encoder). All stream encoders share the same max bandwidth setting.

func (*Encoder) Mode

func (e *Encoder) Mode() encoder.Mode

Mode returns the base mode from the first stream encoder.

func (*Encoder) PacketLoss

func (e *Encoder) PacketLoss() int

PacketLoss returns the expected packet loss percentage (from first encoder).

func (*Encoder) PhaseInversionDisabled

func (e *Encoder) PhaseInversionDisabled() bool

PhaseInversionDisabled reports whether stereo phase inversion is disabled.

func (*Encoder) PredictionDisabled

func (e *Encoder) PredictionDisabled() bool

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

func (e *Encoder) SampleRate() int

SampleRate returns the input sample rate in Hz.

func (*Encoder) SetBandwidth

func (e *Encoder) SetBandwidth(bw types.Bandwidth)

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

func (e *Encoder) SetBitrate(totalBitrate int)

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

func (e *Encoder) SetComplexity(complexity int)

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

func (e *Encoder) SetDNNBlob(blob *dnnblob.Blob)

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

func (e *Encoder) SetDTX(enabled bool)

SetDTX enables or disables Discontinuous Transmission for all streams. When enabled, packets are suppressed during silence.

func (*Encoder) SetFEC

func (e *Encoder) SetFEC(enabled bool)

SetFEC enables or disables in-band Forward Error Correction for all streams. When enabled, encoders include LBRR data for loss recovery.

func (*Encoder) SetForceChannels

func (e *Encoder) SetForceChannels(channels int)

SetForceChannels sets forced channel count on all stream encoders.

func (*Encoder) SetInBandFEC

func (e *Encoder) SetInBandFEC(config int) error

SetInBandFEC sets the in-band FEC configuration for all streams.

func (*Encoder) SetLSBDepth

func (e *Encoder) SetLSBDepth(depth int) error

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

func (e *Encoder) SetLowDelay(enabled bool)

SetLowDelay toggles low-delay application behavior for all stream encoders.

func (*Encoder) SetMaxBandwidth

func (e *Encoder) SetMaxBandwidth(bw types.Bandwidth)

SetMaxBandwidth sets the maximum bandwidth limit for all stream encoders. The actual bandwidth will be clamped to this limit.

func (*Encoder) SetMode

func (e *Encoder) SetMode(mode encoder.Mode)

SetMode sets the base mode for all stream encoders.

func (*Encoder) SetPacketLoss

func (e *Encoder) SetPacketLoss(lossPercent int)

SetPacketLoss sets the expected packet loss percentage (0-100) for all streams. This affects FEC behavior and bitrate allocation.

func (*Encoder) SetPhaseInversionDisabled

func (e *Encoder) SetPhaseInversionDisabled(disabled bool)

SetPhaseInversionDisabled toggles stereo phase inversion on all stream encoders.

func (*Encoder) SetPredictionDisabled

func (e *Encoder) SetPredictionDisabled(disabled bool)

SetPredictionDisabled toggles inter-frame prediction for all stream encoders.

func (*Encoder) SetRestrictedSilkApplication

func (e *Encoder) SetRestrictedSilkApplication(enabled bool)

SetRestrictedSilkApplication toggles restricted-SILK application behavior.

func (*Encoder) SetSignal

func (e *Encoder) SetSignal(signal types.Signal)

SetSignal sets the signal type hint for all stream encoders. SignalVoice biases toward SILK mode, SignalMusic toward CELT mode.

func (*Encoder) SetVBR

func (e *Encoder) SetVBR(enabled bool)

SetVBR enables or disables VBR mode for all stream encoders.

func (*Encoder) SetVBRConstraint

func (e *Encoder) SetVBRConstraint(constrained bool)

SetVBRConstraint enables or disables constrained VBR mode.

func (*Encoder) SetVoIPApplication

func (e *Encoder) SetVoIPApplication(enabled bool)

SetVoIPApplication toggles VoIP application bias for all stream encoders.

func (*Encoder) Signal

func (e *Encoder) Signal() types.Signal

Signal returns the current signal type hint (from first encoder). All stream encoders share the same signal type setting.

func (*Encoder) Streams

func (e *Encoder) Streams() int

Streams returns the total number of elementary streams.

func (*Encoder) VBR

func (e *Encoder) VBR() bool

VBR reports whether VBR mode is enabled.

func (*Encoder) VBRConstraint

func (e *Encoder) VBRConstraint() bool

VBRConstraint reports whether constrained VBR is enabled.

func (*Encoder) VoIPApplication

func (e *Encoder) VoIPApplication() bool

VoIPApplication reports VoIP application bias from the first stream encoder.

Jump to

Keyboard shortcuts

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