Documentation
¶
Overview ¶
Package opusmath holds the gopus floating-point math kernels shared by the CELT, SILK and Opus glue layers. Every function here is a deliberate, narrow mirror of a specific libopus 1.6.1 routine or macro from the default (non-FIXED_POINT) build, kept in one place so call sites stay bit-exact with the reference decoder/encoder.
Width discipline is the whole point of the package:
- The CELT FLOAT_APPROX approximations (celt_log2, celt_exp2) are reproduced as float32 polynomial evaluations with the exact libopus coefficients and the same bit-twiddling on the IEEE-754 exponent. Doing the arithmetic in float64 would change the rounding and break parity, so these stay in float32 and route their fused multiply-add through fma32 (see fma32_*.go).
- The thin SILK/Opus FLP wrappers (in silk.go) wrap libm functions that C evaluates in double and narrows once on assignment to a float. They keep the computation in float64 and convert the single final result, matching that one rounding step. Operands that libopus deliberately keeps in C double use the CReal alias.
- The PCM quantizers (in pcm.go) reproduce libopus' float-to-int rounding and saturation exactly, including round-half-to-even and the rail clamps.
The package is import-safe from both the default and the gopus_fixed_point builds. Per-target helpers preserve contraction at the matching C rounding boundaries.
Index ¶
- Constants
- func AbsF32(v float32) float32
- func AcosF32(x float32) float32
- func CELTCosNormF32(x float32) float32
- func CeltExp2(x float32) float32
- func CeltLog2(x float32) float32
- func CeltSinNormArg(x float32) float32
- func CosF32(x float32) float32
- func Exp2DivIntF32(x float32, denom int) float32
- func Exp2F32(x float32) float32
- func ExpF32(x float32) float32
- func FMA32(a, b, c float32) float32
- func Float32ToInt16(x float32) int16
- func Float32ToInt16OSCEOutputScale(x float32) int16
- func Float32ToInt16Raw(y float32) int16
- func Float32ToInt24(x float32) int32
- func FloorCRealToInt32(x CReal) int32
- func FloorF32ToInt32(x float32) int32
- func FloorHalfPlusF32ToInt32(x float32) int32
- func ISqrt32(x uint32) uint32
- func Log2F32(x float32) float32
- func Log10F32(x float32) float32
- func LogF32(x float32) float32
- func MaxF32(a, b float32) float32
- func MinF32(a, b float32) float32
- func PCMSoftClip(x []float32, n, channels int, declipMem []float32)
- func Pow10F32(x float32) float32
- func RoundClampedFloat32ToInt32Even(y float32) int32
- func RoundF32HalfAwayFromZeroToInt32(x float32) int32
- func RoundToEvenF32ToInt32(x float32) int32
- func SelectF32(c bool, a, b float32) float32
- func SilkLog2F32(x float32) float32
- func SinF32(x float32) float32
- func SqrtF32(x float32) float32
- type CReal
Constants ¶
const ( // CeltExp2CoeffA0..A5 are exported for the vector celt_exp2 kernels. CeltExp2CoeffA0 float32 = 9.999999403953552246093750000000e-01 CeltExp2CoeffA1 float32 = 6.931530833244323730468750000000e-01 CeltExp2CoeffA2 float32 = 2.401536107063293457031250000000e-01 CeltExp2CoeffA3 float32 = 5.582631751894950866699218750000e-02 CeltExp2CoeffA4 float32 = 8.989339694380760192871093750000e-03 CeltExp2CoeffA5 float32 = 1.877576694823801517486572265625e-03 )
celtLog2Coeff* and CeltExp2Coeff* are the FLOAT_APPROX polynomial coefficients from celt/mathops.h, written out to their full float32 decimal expansion so the compiled constants are the same bit patterns libopus uses. They must stay float32 (not untyped/float64) constants: rounding each coefficient to single precision is part of reproducing the reference output.
Variables ¶
This section is empty.
Functions ¶
func CELTCosNormF32 ¶
CELTCosNormF32 matches libopus celt/mathops.h celt_cos_norm() in the floating-point build: (float)cos((.5f*PI)*x). CELT exp_rotation() in celt/vq.c relies on that C double cos() before narrowing back to float, so the half-pi product is formed and evaluated in double here too.
func CeltExp2 ¶
CeltExp2 mirrors libopus celt_exp2() on the FLOAT_APPROX path (celt/mathops.h). It splits x into integer and fractional parts, evaluates a degree-5 polynomial in the fraction via fma32 (so the fused multiply-adds match the reference), then adds the integer part straight into the IEEE-754 exponent field and masks off the sign bit. Inputs below -50 underflow to 0, exactly as libopus short-circuits. The float32 width and the fma32 fusion are load-bearing for bit-exactness.
func CeltLog2 ¶
CeltLog2 mirrors libopus celt_log2() on the FLOAT_APPROX path (celt/mathops.h). It decomposes x into an IEEE-754 exponent and mantissa, selects one of eight piecewise ranges from the mantissa's top bits, applies a degree-4 minimax polynomial to the range-normalised mantissa, and recombines with the per-range offset. All arithmetic is float32 with the exact libopus coefficients; widening to float64 would change the rounding and lose parity.
func CeltSinNormArg ¶
CeltSinNormArg reproduces the argument reduction inside libopus celt_sin() (celt/mathops.h): it forms (pi/2)*x - 1 with the half-pi product evaluated in double (as the C code does) before narrowing to float, so the reduced argument fed to the sine polynomial is bit-exact.
func Exp2DivIntF32 ¶
Exp2DivIntF32 returns (2**x)/denom as a float, matching the libopus FLP expression exp2(x)/N. The division is carried out in double (denom widened to float64) before the single narrowing to float, so the quotient rounds exactly as the C code does.
func Exp2F32 ¶
Exp2F32 mirrors C exp2() narrowed to float (2**x), rounded to float exactly once, as in libopus.
func ExpF32 ¶
ExpF32 mirrors the C exp() used in the SILK FLP paths (e**x). libopus computes it in double and narrows once on assignment to a float; doing the math in float64 and converting the single final result reproduces that rounding.
func FMA32 ¶ added in v0.2.0
FMA32 is a correctly rounded float32 fused multiply-add: a*b+c with a single rounding to float32, the result of the FMADDS / VFMADD*PS instructions the libopus CELT AVX2 and arm64 NEON kernels use.
The float32 product is exact in float64 (48 significant bits). The float64 sum of the product and c can round once, so it is re-rounded to odd (TwoSum recovers the exact error; an inexact even result moves one float64 ulp toward the exact sum). Rounding a round-to-odd float64 to float32 then yields the correctly rounded float32 result, which float32(math.FMA(a, b, c)) does not guarantee: the double rounding of the float64 FMA result can land on a float32 tie (0x3fcca800*0x3f979800 + 0xa20c2545 is 0x3ff26137, not 0x3ff26138). The float64 values are transient and never stored as codec state or scratch.
func Float32ToInt16 ¶
Float32ToInt16 converts a normalised float sample in roughly [-1, 1) to signed 16-bit PCM, matching libopus FLOAT2INT16() (celt/float_cast.h): scale by 32768 then round-half-to-even and saturate to the int16 rails. The scale is applied in float32 first (as the C macro does) before the rounding/clamp in Float32ToInt16Raw, so the result is bit-exact with the reference.
func Float32ToInt16OSCEOutputScale ¶
Float32ToInt16OSCEOutputScale mirrors libopus OSCE SCALE_OUTPUT quantization. Unlike the generic PCM helper it clamps the negative rail to -32767 (a symmetric +/-32767 range), matching the OSCE output scaling in the DNN post-filters; the scale-by-32768 and round-half-to-even are otherwise the same as Float32ToInt16.
func Float32ToInt16Raw ¶
Float32ToInt16Raw rounds and saturates an already-scaled value (i.e. one in 16-bit code units, not normalised [-1, 1)) to int16. It matches silk_float2short_array in silk/float/SigProc_FLP.h: float2int to int32, followed by SAT16. The full negative rail (-32768) is allowed here, unlike the OSCE variant. The usual finite range uses an early saturation path; NaN and int32 overflow preserve the target float-to-int conversion before SAT16.
func Float32ToInt24 ¶
Float32ToInt24 converts a float32 PCM sample to a 24-bit-scale integer stored in int32, matching libopus RES2INT24 for float builds:
RES2INT24(a) = float2int(32768.f * 256.f * (a)) (celt/arch.h)
Full scale is ±8388608 (= 2^23). The result is not saturated to the signed 24-bit range; samples at or above full scale can exceed that range. Libopus does not soft-clip before this conversion in the 24-bit path.
func FloorCRealToInt32 ¶
FloorCRealToInt32 truncates a C-double value toward negative infinity to int32.
func FloorF32ToInt32 ¶
FloorF32ToInt32 truncates toward negative infinity, the C (opus_int32)floor(x) idiom used across the SILK FLP code. The floor is taken in double before narrowing so the result is bit-exact with libopus.
func FloorHalfPlusF32ToInt32 ¶
FloorHalfPlusF32ToInt32 returns floor(x + 0.5) as int32, the plain round-half-up form (toward +inf) libopus uses where ties on negatives are not special-cased; contrast with RoundF32HalfAwayFromZeroToInt32. The bias and floor are taken in double before narrowing.
func ISqrt32 ¶
ISqrt32 returns floor(sqrt(x)), matching libopus isqrt32() (celt/mathops.c). It seeds the result from a double sqrt and then corrects up or down with exact 64-bit integer multiplies so the floor is exact even where the double sqrt rounds the wrong side of an integer boundary. The 64-bit (uint64) products avoid overflow for x near 2**32, which the correction loops require.
func MaxF32 ¶ added in v0.2.0
MaxF32 is C's MAX16(a, b) in float builds, a > b ? a : b: b wins a tie and an unordered comparison.
func MinF32 ¶ added in v0.2.0
MinF32 is C's MIN16(a, b) in float builds, a < b ? a : b: b wins a tie and an unordered comparison.
func PCMSoftClip ¶
PCMSoftClip applies libopus opus_pcm_soft_clip() (src/opus.c) in place to n interleaved frames of the given channel count. It expects samples in roughly [-1, 1] and smoothly attenuates excursions past +/-1 (hard-limiting only beyond +/-2) instead of clipping, carrying the per-channel adaptation coefficient across calls in declipMem (one entry per channel, the C float declip_mem[]).
The whole routine runs in float32 to match the reference: the quadratic soft-knee (v + a*v*v), the peak search, and the coefficient update a = (maxval-1)/(maxval*maxval) plus the 2.4e-7 nudge are all single precision, as is the boundary-continuity ramp. If every sample is already within [-1, 1] and all declipMem entries are zero, it returns without modifying x and resets the state to positive zero, matching libopus's no-clipping result.
func Pow10F32 ¶
Pow10F32 mirrors C pow(10, x) narrowed to float, the 10**x form libopus uses for decibel conversions in the FLP gain code.
func RoundClampedFloat32ToInt32Even ¶ added in v0.2.0
RoundClampedFloat32ToInt32Even is the branchless round-to-nearest-even used on already-clamped 16-bit-scale values (|y| <= 32768). It is bit-exact with [roundFloat32ToInt32Even] for |y| < 2^22 but avoids that helper's data-dependent branches, which mispredict on roughly every other audio sample.
func RoundF32HalfAwayFromZeroToInt32 ¶
RoundF32HalfAwayFromZeroToInt32 rounds x to the nearest integer with ties going away from zero. It matches libopus silk_float2int() (silk/float/SigProc_FLP.h), i.e. (opus_int32)floor(x + 0.5) for non-negative x and the symmetric ceil(x - 0.5) for negatives. The +/-0.5 bias and the floor/ceil run in double so the rounding boundary is exact before the int32 truncation.
func RoundToEvenF32ToInt32 ¶
RoundToEvenF32ToInt32 rounds to the nearest integer with ties to even (banker's rounding), matching the C rint()/nearbyint() default rounding mode libopus assumes where round-to-nearest-even is intended.
func SelectF32 ¶ added in v0.2.0
SelectF32 returns a when c holds and b otherwise. Both operands move to integer registers first so the compiler lowers the choice to a conditional move instead of a branch on targets without scalar FP conditional select.
func SilkLog2F32 ¶
SilkLog2F32 matches silk/float/SigProc_FLP.h silk_log2(): log2(x) computed as 3.32192809488736 * log10(x). libopus uses exactly this log10-based identity (not a native log2), and the constant 1/log10(2) is the literal from the header, so reproducing the same expression is required for bit-exactness.
Types ¶
type CReal ¶
type CReal = float64
CReal is the C double type as used by the libopus floating-point (FLP) build. It is an alias (not a defined type) so values flow to and from float64 helpers without conversions, exactly as C double does.
libopus' FLP code is mostly single precision, but a handful of accumulators are intentionally declared double even there to keep enough precision for bit-exactness against the reference. Marking those operands CReal documents that the double width is deliberate and stops them from being narrowed to float32. Examples include silk_energy_FLP(), silk_inner_product_FLP_c(), silk_burg_modified_FLP(), silk_schur_FLP(), warped_autocorrelation_FLP() and corrMatrix_FLP() (all in silk/float/).
func ExpCReal ¶
ExpCReal is the double-precision e**x for the FLP helpers that keep their accumulator in C double (see CReal); no narrowing to float occurs.
func Log10CReal ¶
Log10CReal is the double-precision log10 for the C-double FLP helpers.