rangecoding

package
v0.2.10 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: BSD-3-Clause Imports: 1 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package rangecoding implements the Opus range coder in RFC 6716 Section 4.1. It ports libopus 1.6.1's `celt/entenc.c`, `celt/entdec.c`, and `celt/entcode.c`.

Range-coded symbols are written forward from the start of the packet buffer. Raw bits use a second stream packed backward from the end. Encoder.Done finalizes both streams; Decoder.DecodeRawBits reads the raw-bit stream. Encoder.Tell and Decoder.Tell report the combined bit position, while Encoder.TellFrac and Decoder.TellFrac report it in eighth-bit units.

Initialize an Encoder with a caller-owned output buffer and a Decoder with the packet bytes. The coder retains those slices for the duration of use, so callers must not mutate or reuse them while encoding or decoding. Each coder also retains mutable range and carry state; use one per active packet and serialize access.

Integer widths, wraparound, renormalization, carry propagation, and symbol reconstruction determine the encoded bytes and final range. Exact guarantees are scoped to the matched reference configurations listed in `reports/validation.md#coverage`.

Index

Constants

View Source
const (
	// EC_SYM_BITS is the number of bits to output/input at a time (one symbol).
	EC_SYM_BITS = 8
	// EC_CODE_BITS is the total number of bits in each of the rng/val state registers.
	EC_CODE_BITS = 32
	// EC_SYM_MAX is the maximum symbol value (0xFF); equals (1<<EC_SYM_BITS)-1.
	EC_SYM_MAX = (1 << EC_SYM_BITS) - 1
	// EC_CODE_TOP is the carry bit of the high-order range symbol (0x80000000).
	EC_CODE_TOP = 1 << (EC_CODE_BITS - 1)
	// EC_CODE_BOT is the low-order bit of the high-order range symbol
	// (0x00800000); renormalization keeps rng strictly above this value.
	EC_CODE_BOT = EC_CODE_TOP >> EC_SYM_BITS
	// EC_CODE_SHIFT is the shift to move a symbol into the high-order position (23).
	EC_CODE_SHIFT = EC_CODE_BITS - EC_SYM_BITS - 1
	// EC_CODE_EXTRA is the number of bits available for the last, partial symbol
	// in the code field (7).
	EC_CODE_EXTRA = (EC_CODE_BITS-2)%EC_SYM_BITS + 1
	// EC_UINT_BITS is the number of bits used for the range-coded part of
	// unsigned integers (ec_enc_uint/ec_dec_uint); the remainder are raw bits.
	EC_UINT_BITS = 8
	// EC_WINDOW_SIZE is the number of bits in the raw-bit end window
	// (sizeof(ec_window)*CHAR_BIT in libopus, with ec_window = opus_uint32).
	EC_WINDOW_SIZE = 32
)

Range coder constants from RFC 6716 Section 4.1 and libopus celt/mfrngcod.h / celt/entcode.h. The doc strings mirror the reference header comments; the numeric expressions are written exactly as in libopus so the derived values are provably identical.

Variables

This section is empty.

Functions

This section is empty.

Types

type Decoder

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

Decoder implements the Opus range decoder (RFC 6716 Section 4.1), a bit-exact port of the libopus ec_dec context and the functions in celt/entdec.c. It is the exact symmetric inverse of Encoder: initializing a Decoder with the output of Encoder.Done and issuing the matching decode calls reproduces the original symbol sequence, with ec_tell staying in lockstep.

Decoding a range-coded symbol is two steps, matching libopus: call Decoder.Decode (or DecodeBin) to read the cumulative frequency, locate the symbol in the model, then call Decoder.Update with that symbol's [fl, fh) interval. The DecodeICDF*, DecodeBit, and DecodeUniform helpers fuse both steps for the common cases. Raw bits are read from the end of the buffer with Decoder.DecodeRawBits.

The decoder is robust to truncated or malformed input: reads past the end of the buffer return zero bytes (per the RFC), so no method panics or indexes out of bounds on arbitrary input. Out-of-range coded values set the error flag reported by Decoder.Error. The field widths match libopus ec_ctx exactly.

func (*Decoder) BytesUsed

func (d *Decoder) BytesUsed() int

BytesUsed returns the number of bytes consumed from the buffer.

func (*Decoder) Decode

func (d *Decoder) Decode(ft uint32) uint32

Decode returns the cumulative frequency fs (in [0, ft)) of the current symbol without advancing the decoder, the bit-exact port of libopus ec_decode. The caller maps fs to a symbol whose model interval [fl, fh) satisfies fl <= fs < fh, then must call Decoder.Update with that interval to consume the symbol. Decode caches the scale factor used by the paired Update.

func (*Decoder) DecodeBin

func (d *Decoder) DecodeBin(bits uint) uint32

DecodeBin returns the cumulative frequency of the current symbol when the total frequency is the power of two 1<<bits, the bit-exact port of libopus ec_decode_bin. Like Decoder.Decode it does not advance the decoder; pair it with Decoder.Update using ft = 1<<bits. Using a power-of-two total lets the scale factor be a shift instead of a division.

func (*Decoder) DecodeBit

func (d *Decoder) DecodeBit(logp uint) int

DecodeBit decodes a single bit with the given log probability. logp is the number of bits of probability for a 0 (1 to 15). P(0) = 1 - 1/(2^logp), P(1) = 1/(2^logp) Returns 0 or 1.

Per libopus entdec.c, the probability regions are: - [0, s): bit = 1, probability = 1 / 2^logp (rare, bottom region) - [s, rng): bit = 0, probability = (2^logp - 1) / 2^logp

For silence flag (logp=15): P(silence=1) = 1/32768, which is very rare.

func (*Decoder) DecodeICDF

func (d *Decoder) DecodeICDF(icdf []uint8, ftb uint) int

DecodeICDF decodes a symbol using an inverse cumulative distribution function table. The icdf table contains values in decreasing order from 256 down to 0. ftb is the number of bits of precision in the table (typically 8). Returns the decoded symbol index.

func (*Decoder) DecodeICDF2

func (d *Decoder) DecodeICDF2(icdf0 uint8, ftb uint) int

DecodeICDF2 decodes a 2-symbol ICDF with entries [icdf0, 0]. This avoids generic loop/slice overhead in hot binary-symbol call sites.

func (*Decoder) DecodeICDF2_8

func (d *Decoder) DecodeICDF2_8(icdf0 uint8) int

DecodeICDF2_8 decodes a 2-symbol 8-bit ICDF with entries [icdf0, 0].

func (*Decoder) DecodeICDF2_8SignBlock16

func (d *Decoder) DecodeICDF2_8SignBlock16(icdf0 uint8, block *[16]int16)

DecodeICDF2_8SignBlock16 decodes the sign of every positive entry of one 16-sample SILK shell block, in order, with the binary 8-bit iCDF {icdf0, 0}. Symbol 0 negates the entry and symbol 1 keeps it, which is libopus silk/decode_pulses.c silk_decode_signs: q[j] *= silk_dec_map(ec_dec_icdf(dec, icdf, 8)).

Every entry must be non-negative, as the decoded pulse magnitudes are. The loop visits only the positive entries, found from a bit mask built four entries at a time, and updates the range state with masks instead of branching on each sign, whose outcome is unpredictable.

func (*Decoder) DecodeICDF3_8

func (d *Decoder) DecodeICDF3_8(icdf0, icdf1 uint8) int

DecodeICDF3_8 decodes a 3-symbol 8-bit ICDF with entries [icdf0, icdf1, 0].

func (*Decoder) DecodeICDF4_8

func (d *Decoder) DecodeICDF4_8(icdf0, icdf1, icdf2 uint8) int

DecodeICDF4_8 decodes a 4-symbol 8-bit ICDF with entries [icdf0, icdf1, icdf2, 0].

func (*Decoder) DecodeICDF5_8

func (d *Decoder) DecodeICDF5_8(icdf0, icdf1, icdf2, icdf3 uint8) int

DecodeICDF5_8 decodes a 5-symbol 8-bit ICDF with entries [icdf0, icdf1, icdf2, icdf3, 0].

func (*Decoder) DecodeICDF7_8Slice

func (d *Decoder) DecodeICDF7_8Slice(icdf []uint8) int

DecodeICDF7_8Slice decodes a 7-symbol 8-bit ICDF.

func (*Decoder) DecodeICDF8

func (d *Decoder) DecodeICDF8(icdf []uint8) int

DecodeICDF8 decodes a symbol using an 8-bit ICDF table. This is the hot SILK/CELT entropy path and matches DecodeICDF(icdf, 8).

func (*Decoder) DecodeICDF8Linear

func (d *Decoder) DecodeICDF8Linear(icdf []uint8) int

DecodeICDF8Linear decodes a non-empty 8-bit ICDF table with the generic linear walk directly. It is for known large tables, where DecodeICDF8Unchecked would first pay the small-table switch before reaching this same loop.

func (*Decoder) DecodeICDF8Unchecked

func (d *Decoder) DecodeICDF8Unchecked(icdf []uint8) int

DecodeICDF8Unchecked decodes using a non-empty 8-bit ICDF table. Codec hot paths pass static tables. Callers must not pass an empty slice.

func (*Decoder) DecodeICDF8UncheckedN

func (d *Decoder) DecodeICDF8UncheckedN(icdf []uint8, n int) int

DecodeICDF8UncheckedN decodes using the first n entries of a non-empty 8-bit ICDF table. It is useful for packed zero-terminated table rows where the backing slice continues with subsequent rows.

func (*Decoder) DecodeICDF8UncheckedNOffset

func (d *Decoder) DecodeICDF8UncheckedNOffset(icdf []uint8, off, n int) int

DecodeICDF8UncheckedNOffset decodes using n entries starting at off in a non-empty 8-bit ICDF table. This avoids materializing row slices in hot paths backed by packed static table storage.

func (*Decoder) DecodeICDF9_8Slice

func (d *Decoder) DecodeICDF9_8Slice(icdf []uint8) int

DecodeICDF9_8Slice decodes a 9-symbol 8-bit ICDF.

func (*Decoder) DecodeICDF16

func (d *Decoder) DecodeICDF16(icdf []uint16, ftb uint) int

DecodeICDF16 decodes a symbol using a uint16 ICDF table. This variant is needed because SILK ICDF tables use values 0-256, and 256 doesn't fit in uint8. The icdf table contains values in decreasing order from 256 down to 0. ftb is the number of bits of precision in the table (typically 8). Returns the decoded symbol index.

func (*Decoder) DecodeICDF16_8

func (d *Decoder) DecodeICDF16_8(icdf []uint16) int

DecodeICDF16_8 decodes a symbol using a uint16 ICDF table with 8-bit precision.

func (*Decoder) DecodeICDF16_8Unchecked

func (d *Decoder) DecodeICDF16_8Unchecked(icdf []uint16) int

DecodeICDF16_8Unchecked decodes using a non-empty uint16 ICDF table with 8-bit precision. Callers must not pass an empty slice.

func (*Decoder) DecodeRawBit

func (d *Decoder) DecodeRawBit() uint32

DecodeRawBit reads a single raw bit from the end of the buffer.

func (*Decoder) DecodeRawBits

func (d *Decoder) DecodeRawBits(bits uint) uint32

DecodeRawBits reads `bits` raw bits from the raw-bit stream at the end of the buffer and returns them, the bit-exact port of libopus ec_dec_bits and the inverse of Encoder.EncodeRawBits. These bits bypass the range coder; reads past the start of the available raw region yield zero. Used for fine energy bits, PVQ sign bits, and similar fields.

func (*Decoder) DecodeSymbol

func (d *Decoder) DecodeSymbol(fl, fh, ft uint32)

DecodeSymbol decodes a symbol given cumulative frequencies and updates state. fl: cumulative frequency of symbols before this one fh: cumulative frequency up to and including this symbol ft: total frequency (sum of all symbol frequencies)

This implements the range decoder update: rng = s * fh, val = val - s * fl where s = rng / ft (the scale factor).

Reference: libopus celt/entdec.c ec_dec_update()

func (*Decoder) DecodeUniform

func (d *Decoder) DecodeUniform(ft uint32) uint32

DecodeUniform decodes a uniformly distributed integer in [0, ft), the bit-exact port of libopus ec_dec_uint and the inverse of Encoder.EncodeUniform. For ft larger than 1<<EC_UINT_BITS the high EC_UINT_BITS bits come from the range coder and the low bits from the raw-bit stream. If the reconstructed value exceeds ft-1 (only possible on malformed input) the error flag is set and ft-1 is returned. Used for fine energy bits, PVQ indices, and similar fields.

func (*Decoder) DecodeUniformSmall

func (d *Decoder) DecodeUniformSmall(ft uint32) uint32

DecodeUniformSmall decodes a uniform value for totals that fit entirely in the range coder path. Callers must only use this for ft <= 1<<EC_UINT_BITS.

func (*Decoder) Error

func (d *Decoder) Error() int

Error returns the decoder error flag (libopus ec_ctx.error). A non-zero value means malformed input was detected, currently an out-of-range value reported by Decoder.DecodeUniform. Note that, per the RFC, reading past the end of a truncated buffer is not an error: it yields zero bytes.

func (*Decoder) Init

func (d *Decoder) Init(buf []byte)

Init initializes the decoder to read from buf, the bit-exact port of libopus ec_dec_init. It reads the first byte, seeds the range and value registers, and renormalizes so the decoder is ready for the first symbol. buf is treated as read-only and may be any length, including empty; reads past its end yield zero bytes per RFC 6716 Section 4.1.

func (*Decoder) Offs

func (d *Decoder) Offs() uint32

Offs returns the current read offset.

func (*Decoder) Range

func (d *Decoder) Range() uint32

Range returns the current range value.

func (*Decoder) ShrinkStorage

func (d *Decoder) ShrinkStorage(bytes int)

ShrinkStorage reduces the effective input size by the given number of bytes. This is used to exclude trailing redundancy bytes from the range decoder while preserving the current decoding state. The raw-bits window may have read ahead past what was consumed, so whole unconsumed bytes are first returned to the pool — making the observable state identical to a reader that refills one byte at a time — before the end offset is rebased onto the shrunk buffer.

func (*Decoder) SkipToTell added in v0.2.0

func (d *Decoder) SkipToTell(targetBits int)

SkipToTell advances the decoder's bit accounting so Tell() reports exactly targetBits, without consuming further input. It mirrors the CELT silence handling in celt_decode_with_ec: dec->nbits_total += tell - ec_tell(dec).

func (*Decoder) State

func (d *Decoder) State() (uint32, uint32)

State returns the internal range decoder state (rng, val). Useful for bit-exact comparisons against libopus in tests.

func (*Decoder) StorageBits

func (d *Decoder) StorageBits() int

StorageBits returns the total number of bits in the input buffer.

func (*Decoder) Tell

func (d *Decoder) Tell() int

Tell returns the number of bits consumed from the combined stream so far, rounded up to the nearest whole bit. This is the libopus ec_tell macro (nbits_total - EC_ILOG(rng)) and counts both range-coded symbols and raw bits. It stays in lockstep with Encoder.Tell on the encoding side.

func (*Decoder) TellFrac

func (d *Decoder) TellFrac() int

TellFrac returns the number of bits consumed from the combined stream so far in 1/8th-bit (BITRES) precision; divide by 8 to compare with Decoder.Tell. It is the bit-exact port of libopus ec_tell_frac and matches Encoder.TellFrac.

func (*Decoder) Update

func (d *Decoder) Update(fl, fh, ft uint32)

Update consumes the symbol whose model interval is [fl, fh) out of total ft, advancing the decoder and renormalizing. It must be called after Decoder.Decode (or DecodeBin) with the interval selected from the returned cumulative frequency, and it reuses the scale factor cached by that call. This is the bit-exact port of libopus ec_dec_update and the inverse of Encoder.Encode.

func (*Decoder) Val

func (d *Decoder) Val() uint32

Val returns the current val.

type Encoder

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

Encoder implements the Opus range encoder (RFC 6716 Section 4.1), a bit-exact port of the libopus ec_enc context and the functions in celt/entenc.c. It is the exact symmetric inverse of Decoder.

Lifecycle: call Encoder.Init with a destination buffer, emit symbols with the Encode/EncodeBin/EncodeBit/EncodeICDF* methods and raw bits with Encoder.EncodeRawBits, then call Encoder.Done to flush and obtain the packet. Range-coded symbols are written forward from the start of the buffer while raw bits are written backward from the end; Encoder.Done merges them.

The field widths match libopus ec_ctx exactly because the integer wrap/truncation behavior is part of the bit-exact contract (see the package doc and the state-type parity test). In particular rem uses -1 as the "no buffered byte yet" sentinel, so it is signed.

func (*Encoder) AdvanceTell added in v0.2.0

func (e *Encoder) AdvanceTell(bits int)

AdvanceTell counts the bits up to bits as written (zeros), so Tell reports bits: celt_encode_with_ec's "pretend we've filled all the remaining bits with zeros" for a silent frame (enc->nbits_total += tell - ec_tell(enc)).

func (*Encoder) Buffer

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

Buffer returns the underlying output buffer. Callers must treat the returned slice as read-only.

func (*Encoder) Done

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

Done finalizes the stream and returns the encoded packet. It emits the minimum number of bits needed to unambiguously identify the final range interval, flushes any buffered carry byte and pending raw bits, and merges the forward range-coded bytes with the backward raw-bit bytes into one packet.

This is the bit-exact port of libopus ec_enc_done. The returned slice aliases the buffer passed to Encoder.Init; copy it if it must outlive the next use of the buffer. After Done the encoder must be re-initialized before reuse. Check Encoder.Error for buffer overflow during encoding.

func (*Encoder) Encode

func (e *Encoder) Encode(fl, fh, ft uint32)

Encode encodes a symbol that occupies the cumulative-frequency interval [fl, fh) out of a total frequency ft, the core range-coder primitive of RFC 6716 Section 4.1.2. It is the bit-exact port of libopus ec_encode and the inverse of Decoder.Decode followed by Decoder.Update.

fl is the sum of the frequencies of all symbols preceding this one, fh is fl plus this symbol's frequency, and ft is the sum of all symbol frequencies. Callers must ensure 0 <= fl < fh <= ft. The range is subdivided by the scale factor r = rng/ft, after which the encoder renormalizes.

func (*Encoder) EncodeBin

func (e *Encoder) EncodeBin(fl, fh uint32, bits uint)

EncodeBin encodes a symbol whose model interval is [fl, fh) when the total frequency is the power of two 1<<bits, the bit-exact port of libopus ec_encode_bin and the inverse of [Decoder.DecodeBin]+[Decoder.Update]. Using a power-of-two total lets the scale factor be a shift instead of a division.

func (*Encoder) EncodeBit

func (e *Encoder) EncodeBit(val int, logp uint)

EncodeBit encodes a single bit with the given log probability. val is the bit to encode (0 or 1). logp is the log probability: P(0) = 1 - 1/(2^logp), P(1) = 1/(2^logp).

Per RFC 6716 Section 4.1, the probability regions are: - [0, rng-r): bit = 0, probability = (2^logp - 1) / 2^logp - [rng-r, rng): bit = 1, probability = 1 / 2^logp

For silence flag (logp=15): P(silence=1) = 1/32768, which is very rare.

Encoder interval assignment (symmetric with decoder): - bit=0: use interval [0, threshold), rng = threshold, val unchanged - bit=1: use interval [threshold, rng), val += threshold, rng = r

func (*Encoder) EncodeICDF

func (e *Encoder) EncodeICDF(s int, icdf []uint8, ftb uint)

EncodeICDF encodes a symbol using an inverse CDF table. s is the symbol to encode (0 to len(icdf)-1). icdf is the inverse cumulative distribution function table (decreasing values). ftb is the number of bits of precision (total = 1 << ftb).

This is a direct port of libopus ec_enc_icdf.

func (*Encoder) EncodeICDF8

func (e *Encoder) EncodeICDF8(s int, icdf []uint8, ftb uint)

EncodeICDF8 encodes a symbol using a uint8 ICDF table. s is the symbol to encode (0 to len(icdf)-1). icdf is the inverse cumulative distribution function table (decreasing values). ftb is the number of bits of precision (total = 1 << ftb).

This is the uint8 variant of EncodeICDF for SILK tables.

func (*Encoder) EncodeICDF16

func (e *Encoder) EncodeICDF16(s int, icdf []uint16, ftb uint)

EncodeICDF16 encodes a symbol using a uint16 ICDF table. Required because SILK tables use uint16 (256 doesn't fit in uint8). Per RFC 6716 Section 4.1.

This is the uint16 variant of EncodeICDF, matching libopus ec_enc_icdf.

func (*Encoder) EncodeRawBits

func (e *Encoder) EncodeRawBits(val uint32, bits uint)

EncodeRawBits writes the low `bits` bits of val directly to the raw-bit stream at the end of the buffer, bypassing the range coder. It is the bit-exact port of libopus ec_enc_bits and the inverse of Decoder.DecodeRawBits. Raw bits grow backward from the end of the packet while range-coded symbols grow forward from the start; Encoder.Done reconciles the two streams.

func (*Encoder) EncodeUniform

func (e *Encoder) EncodeUniform(val uint32, ft uint32)

EncodeUniform encodes a uniformly distributed integer val in the range [0, ft). It is the bit-exact port of libopus ec_enc_uint and the inverse of Decoder.DecodeUniform. For ft larger than 1<<EC_UINT_BITS the high EC_UINT_BITS bits are range-coded and the low bits are written as raw bits, so large uniform values consume part of each stream. Used for fine energy bits, PVQ indices, and similar uniformly distributed fields.

func (*Encoder) Error

func (e *Encoder) Error() int

Error returns the encoder error flag (libopus ec_ctx.error). A non-zero value means the output did not fit in the buffer passed to Encoder.Init (the forward range-coded and backward raw-bit streams collided), so the produced packet is truncated and not decodable.

func (*Encoder) Ext

func (e *Encoder) Ext() uint32

Ext returns the extension count.

func (*Encoder) Init

func (e *Encoder) Init(buf []byte)

Init initializes the encoder with the given output buffer. The buffer must be pre-allocated to the maximum expected output size.

func (*Encoder) Limit

func (e *Encoder) Limit(size uint32)

Limit reduces the storage size to the given number of bytes without forcing CBR-style output length. This is useful for VBR/CVBR paths that need a bit budget cap but still want Done() to return the actual number of bytes used. It mirrors ec_enc_shrink() without setting the "shrunk" flag.

func (*Encoder) Offs

func (e *Encoder) Offs() uint32

Offs returns the current write offset in bytes.

func (*Encoder) PatchInitialBits

func (e *Encoder) PatchInitialBits(val uint32, nbits uint)

PatchInitialBits overwrites the first few bits in the range coder stream. This mirrors libopus ec_enc_patch_initial_bits and is used for VAD/LBRR flag encoding in SILK packets where the flags must be written at the packet start but their values are only known after encoding the frame data.

func (*Encoder) Range

func (e *Encoder) Range() uint32

Range returns the current range value.

func (*Encoder) RangeBytes

func (e *Encoder) RangeBytes() int

RangeBytes returns the number of range-coded bytes written. This mirrors libopus ec_range_bytes.

func (*Encoder) Rem

func (e *Encoder) Rem() int

Rem returns the stored remainder byte.

func (*Encoder) RestoreState

func (e *Encoder) RestoreState(state *EncoderState)

RestoreState restores the encoder to a previously saved state.

func (*Encoder) RestoreStateShallow

func (e *Encoder) RestoreStateShallow(state *EncoderState)

RestoreStateShallow mirrors a libopus ec_ctx struct assignment such as celt/bands.c:*ec = ec_save: scalar fields are restored, while the shared packet buffer keeps bytes dirtied by speculative encoding.

func (*Encoder) SaveState

func (e *Encoder) SaveState() *EncoderState

SaveState captures the current encoder state for later restoration. This allows trying different encoding choices and restoring to try again.

func (*Encoder) SaveStateInto

func (e *Encoder) SaveStateInto(state *EncoderState)

SaveStateInto captures the current encoder state into a pre-allocated state struct. This is the allocation-free version of SaveState for hot paths.

func (*Encoder) SaveStateShallowInto added in v0.2.0

func (e *Encoder) SaveStateShallowInto(state *EncoderState)

SaveStateShallowInto captures only the scalar encoder state, like a libopus ec_ctx struct copy. The saved state is for RestoreStateShallow; it holds no packet bytes, so RestoreState must not be used with it.

func (*Encoder) SaveStateSinceInto added in v0.2.0

func (e *Encoder) SaveStateSinceInto(state, since *EncoderState)

SaveStateSinceInto captures the encoder state like SaveStateInto, but saves only the packet bytes from the front offset of the earlier state since to the end of storage: the span that coding after since can have changed. It is the libopus pattern of an ec_ctx copy plus a copy of the bytes from the saved ec_range_bytes() onward (celt/bands.c theta RDO, celt/quant_bands.c quant_coarse_energy()). RestoreState writes that span back.

func (*Encoder) Shrink

func (e *Encoder) Shrink(size uint32)

Shrink reduces the storage size to the given number of bytes. This is used in CBR mode to ensure the output packet is exactly the target size. The raw bits written from the end are moved to the new end position. This is a direct port of libopus celt/entenc.c ec_enc_shrink.

After calling Shrink, Done() will return exactly 'size' bytes (padded with zeros).

func (*Encoder) State

func (e *Encoder) State() (uint32, uint32)

State returns the internal range encoder state (rng, val). Useful for bit-exact comparisons against libopus in tests.

func (*Encoder) Storage

func (e *Encoder) Storage() int

Storage returns the storage capacity in bytes.

func (*Encoder) StorageBits

func (e *Encoder) StorageBits() int

StorageBits returns the total number of bits in the output buffer.

func (*Encoder) Tell

func (e *Encoder) Tell() int

Tell returns the number of bits written to the combined stream so far, rounded up to the nearest whole bit. This is the libopus ec_tell macro (nbits_total - EC_ILOG(rng)) and counts both range-coded symbols and raw bits.

func (*Encoder) TellFrac

func (e *Encoder) TellFrac() int

TellFrac returns the number of bits written to the combined stream so far in 1/8th-bit (BITRES) precision; divide by 8 to compare with Encoder.Tell. It is the bit-exact port of libopus ec_tell_frac, including the eight-entry correction table that refines the fractional bit count from the range.

func (*Encoder) Val

func (e *Encoder) Val() uint32

Val returns the current val, the low end of the range.

type EncoderState

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

EncoderState captures the encoder state for save/restore operations. This is used by theta RDO to try different quantization choices.

func (*EncoderState) ReserveBufferCapacity added in v0.2.0

func (state *EncoderState) ReserveBufferCapacity(capacity int)

ReserveBufferCapacity reserves reusable storage for a future encoder snapshot without changing the snapshot's logical length or scalar fields.

Jump to

Keyboard shortcuts

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