Documentation
¶
Overview ¶
Package multistream encodes and decodes Opus packets with multiple elementary streams, as used for surround sound and ambisonics.
Encoder and Decoder map channels to mono or coupled stereo streams. The default constructors use Vorbis channel order for layouts with up to eight channels; explicit constructors accept a mapping table. Ambisonics helpers provide ACN/SN3D layouts, including projection encoding and decoding.
PCM is interleaved by sample, and frame sizes are measured in samples per channel. Constructors copy mapping tables and projection matrices. Stateful Encoder and Decoder instances are not safe for concurrent use.
Sample rates are 8, 12, 16, 24, or 48 kHz; 96 kHz and QEXT controls are available in builds tagged gopus_qext. DRED controls are available with gopus_dred or gopus_osce, while OSCE controls require gopus_osce.
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) DecodeIntoFloat32(data []byte, output []float32, frameSize int) (int, error)
- func (d *Decoder) DecodeToFloat32(data []byte, frameSize int) ([]float32, error)
- func (d *Decoder) DecodeToInt16(data []byte, frameSize int) ([]int16, error)
- func (d *Decoder) DecodeToInt24(data []byte, frameSize int) ([]int32, 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) PacketDurationAtRate(data []byte) (int, error)
- 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) AnyStreamHasCodedFrame() bool
- 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, out []byte) (int, error)
- func (e *Encoder) EncodeInt16(pcm []int16, frameSize int, out []byte) (int, error)
- func (e *Encoder) EncodeInt16WithAnalysis(pcm []int16, frameSize int, analysisPCM []int16, out []byte) (int, error)
- func (e *Encoder) EncodeWithAnalysis(pcm []float32, frameSize int, analysisPCM []float32, out []byte) (int, 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) error
- 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 ( // ErrInvalidSampleRate indicates a rate outside the selected Opus API build. ErrInvalidSampleRate = errors.New("multistream: invalid sample rate") // 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 a stream count outside 1..255. ErrInvalidStreamCount = errors.New("multistream: invalid stream count (must be 1-255)") )
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 ErrInvalidForceChannels = errors.New("multistream: invalid force channels")
ErrInvalidForceChannels indicates that a forced channel count is invalid for the stream where the control is applied.
var ErrInvalidInput = errors.New("multistream: invalid input length")
ErrInvalidInput indicates an unsupported frame size or malformed PCM shape.
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 Vorbis mapping family configuration for 1–8 channels. In a decoder, mapping[i] selects the decoded stream channel for output channel i; in an encoder, it selects the destination stream channel for input channel i. The returned slice is newly allocated. Other channel counts return ErrInvalidDefaultMappingChannels.
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, 3, 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. numStreams must be in 1..255.
func PacketDurationAtRate ¶
PacketDurationAtRate returns the common packet duration in samples per channel at sampleRate, matching opus_packet_get_nb_samples(). numStreams must be in 1..255.
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 multistream Opus packets and maps decoded stream channels to interleaved output channels. It retains decoding state and is not safe for concurrent use.
func NewDecoder ¶
func NewDecoder(sampleRate, channels, streams, coupledStreams int, mapping []byte) (*Decoder, error)
NewDecoder returns a multistream decoder for channels of interleaved PCM. sampleRate must be 8, 12, 16, 24, or 48 kHz; 96 kHz is available with gopus_qext. channels and streams must be in 1..255, coupledStreams in 0..streams, and streams+coupledStreams at most 255. mapping has one entry per output channel: 0..2*coupledStreams-1 selects a coupled stream channel, 2*coupledStreams..streams+coupledStreams-1 selects a mono stream, and 255 produces silence. Entries may repeat or leave decoded channels unused. The mapping is copied.
func NewDecoderDefault ¶
NewDecoderDefault returns a decoder with the Vorbis mapping for 1–8 output channels. It returns an error for an unsupported sample rate or channel count.
func NewProjectionDecoder ¶
func NewProjectionDecoder(sampleRate, channels, streams, coupledStreams int, demixingMatrix []byte) (*Decoder, error)
NewProjectionDecoder returns a decoder with identity channel mapping and an optional projection demixing matrix. The matrix uses signed 16-bit little- endian coefficients in column-major order, with channels rows and streams+coupledStreams columns; its length must be 2*channels*(streams+ coupledStreams) bytes. Encoder.GetDemixingMatrix returns a compatible matrix. An empty matrix disables demixing. The matrix is copied. An invalid matrix returns ErrInvalidProjectionMatrix; invalid dimensions return the corresponding constructor error.
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 returns a newly allocated interleaved float32 PCM slice. frameSize is the maximum number of samples per channel at SampleRate; requests above 120 ms are capped. A packet returns its actual duration, which must not exceed frameSize. A nil or empty data slice requests PLC for the capped frameSize. All elementary streams in a packet must have the same duration.
func (*Decoder) DecodeIntoFloat32 ¶ added in v0.2.0
DecodeIntoFloat32 decodes into output and returns the number of samples per channel written. frameSize is the maximum number of samples per channel at SampleRate; requests above 120 ms are capped. Only the interleaved prefix for the decoded duration is written. It returns ErrBufferTooSmall when the packet exceeds frameSize or output is too short.
func (*Decoder) DecodeToFloat32 ¶
DecodeToFloat32 returns newly allocated interleaved float32 PCM with values approximately in [-1, 1]. frameSize is the maximum number of samples per channel at SampleRate; requests above 120 ms are capped. A packet returns its actual duration, and nil or empty data requests PLC for the capped frameSize.
func (*Decoder) DecodeToInt16 ¶
DecodeToInt16 returns newly allocated interleaved signed 16-bit PCM. frameSize is the maximum number of samples per channel at SampleRate; requests above 120 ms are capped. A packet returns its actual duration, and nil or empty data requests PLC for the capped frameSize.
func (*Decoder) DecodeToInt24 ¶ added in v0.2.0
DecodeToInt24 returns newly allocated interleaved signed 24-bit PCM stored right-justified in int32 values. frameSize is the maximum number of samples per channel at SampleRate; requests above 120 ms are capped. A packet returns its actual duration, and nil or empty data requests PLC for the capped frameSize.
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) PacketDurationAtRate ¶ added in v0.2.0
PacketDurationAtRate returns the packet duration using this decoder's reusable parser storage. The result is independent of later decoder calls.
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 codec, concealment, and extension-payload history for a new stream. It retains the channel layout, projection matrix, gain, and extension- handling setting.
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. It binds OSCE models to each child decoder and DRED models to the parent's per-stream recovery state. A nil blob clears the model bindings. The per-stream OSCE state corresponds to libopus's silk_OSCE_struct and silk_OSCE_BWE_struct in each silk_channel_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 the optional signed 16-bit little-endian projection matrix in column-major order. The matrix has outputChannels rows and streams+coupledStreams columns, so its byte length must be 2*outputChannels*(streams+coupledStreams). It requires identity channel mapping. The matrix is copied; an empty slice clears demixing. Invalid size or mapping returns ErrInvalidProjectionMatrix.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder encodes interleaved PCM as an Opus packet containing multiple streams. It routes input channels through its mapping table and is not safe for concurrent use.
func NewEncoder ¶
func NewEncoder(sampleRate, channels, streams, coupledStreams int, mapping []byte) (*Encoder, error)
NewEncoder returns a multistream encoder for channels of interleaved PCM. sampleRate must be 8, 12, 16, 24, or 48 kHz; 96 kHz is available with gopus_qext. channels and streams must be in 1..255, coupledStreams in 0..streams, and streams+coupledStreams at most 255. mapping has one entry per input channel: 0..2*coupledStreams-1 selects a coupled stream channel, 2*coupledStreams..streams+coupledStreams-1 selects a mono stream, and 255 leaves that input channel unused. Each coupled stream must map both channels, and each mono stream must be mapped at least once. The mapping is copied. The initial total bitrate is 256000 bits per second.
func NewEncoderAmbisonics ¶
NewEncoderAmbisonics returns a multistream encoder with ACN/SN3D mapping. Family 2 accepts valid ambisonics counts through 227 channels; family 3 projection supports 4, 6, 9, 11, 16, 18, 25, 27, 36, or 38 channels. Other families return ErrInvalidMappingFamily, and unsupported family 3 orders return ErrProjectionOrderUnsupported.
func NewEncoderDefault ¶
NewEncoderDefault returns an encoder with the Vorbis mapping for 1–8 input channels. It returns an error for an unsupported sample rate or channel count.
func NewProjectionEncoder ¶
NewProjectionEncoder returns a family 3 projection encoder for ambisonics orders 1–5. Supported channel counts are 4, 6, 9, 11, 16, 18, 25, 27, 36, and 38; unsupported projection orders return ErrProjectionOrderUnsupported.
func (*Encoder) AnyStreamHasCodedFrame ¶ added in v0.2.0
AnyStreamHasCodedFrame reports whether any child encoder has committed a frame since it was created or reset. libopus rejects an application change once the affected child encoder has committed a frame.
func (*Encoder) Bitrate ¶
Bitrate returns the configured aggregate target, retaining the automatic and maximum bitrate sentinels. Libopus OPUS_GET_BITRATE sums the current per-stream targets instead.
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 serialized demixing matrix size in bytes, or zero when this is not a family 3 encoder.
func (*Encoder) Encode ¶
Encode encodes frameSize samples per channel of interleaved float32 PCM into out and returns the packet length. len(out) is the maximum packet size in bytes. pcm must contain exactly frameSize*Channels() samples. A too-small output buffer returns ErrBufferTooSmall.
func (*Encoder) EncodeInt16 ¶ added in v0.2.0
EncodeInt16 encodes frameSize samples per channel of interleaved int16 PCM into out and returns the packet length. pcm must contain exactly frameSize*Channels() samples; len(out) is the maximum packet size in bytes.
func (*Encoder) EncodeInt16WithAnalysis ¶ added in v0.2.0
func (e *Encoder) EncodeInt16WithAnalysis(pcm []int16, frameSize int, analysisPCM []int16, out []byte) (int, error)
EncodeInt16WithAnalysis encodes pcm while analysisPCM supplies the interleaved samples used for tonality analysis. pcm must contain exactly frameSize*Channels() samples, and analysisPCM must contain at least that many whole samples.
func (*Encoder) EncodeWithAnalysis ¶
func (e *Encoder) EncodeWithAnalysis(pcm []float32, frameSize int, analysisPCM []float32, out []byte) (int, error)
EncodeWithAnalysis encodes frameSize samples per channel from pcm while analysisPCM supplies the samples used for tonality analysis. pcm must contain exactly frameSize*Channels() samples; analysisPCM must contain at least that many whole interleaved samples.
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 a copy of this projection encoder's demixing matrix as S16LE bytes in column-major order. Each column contains one input stream channel's coefficients for all output channels. It returns nil when this is not a family 3 encoder or no matrix is available.
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 SampleRate. 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 codec and surround-analysis history for a new stream. It keeps the encoder's sample rate, channel mapping, and projection matrix.
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 applies the forced channel count to stream encoders in order. A mono stream rejects a value of 2 after earlier coupled streams have already accepted it, matching opus_multistream_encoder_ctl.
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_fixed_output_float_default.go
- decoder_fixed_projection_default.go
- decoder_fixed_transition_default.go
- decoder_fixedpoint_fields_default.go
- decoder_osce_apply_default.go
- decoder_osce_fields_default.go
- decoder_osce_helpers_default.go
- decoder_osce_loss_hook_default.go
- decoder_osce_state_default.go
- decoder_qext_hook_default.go
- decoder_qext_payloads_default.go
- doc.go
- encoder.go
- encoder_helpers.go
- encoder_state.go
- extensions.go
- framing.go
- mapping.go
- multistream.go
- projection.go
- projection_demixing_defaults.go
- projection_demixing_defaults_data.go
- projection_helpers.go
- projection_int16_encode.go
- projection_int16_encode_default.go
- projection_int24.go
- projection_matrix.go
- projection_matrix_int24.go
- projection_mixing_defaults.go
- projection_mixing_defaults_data.go
- stream.go
- surround_analysis_default.go