12 #ifndef hifi_AudioHelpers_h
13 #define hifi_AudioHelpers_h
17 #include <NumericalConstants.h>
20 const int IEEE754_MANT_BITS = 23;
21 const int IEEE754_EXPN_BIAS = 127;
30 static inline float fastLog2f(
float x) {
32 union {
float f; int32_t i; } mant, bits = { x };
35 mant.i = (bits.i & ((1 << IEEE754_MANT_BITS) - 1)) | (IEEE754_EXPN_BIAS << IEEE754_MANT_BITS);
36 int32_t expn = (bits.i >> IEEE754_MANT_BITS) - IEEE754_EXPN_BIAS;
41 x = (((-0.0821307180f * mant.f + 0.321188984f) * mant.f - 0.677784014f) * mant.f + 1.43872575f) * mant.f;
53 static inline float fastExp2f(
float x) {
55 union {
float f; int32_t i; } xi;
58 x += IEEE754_EXPN_BIAS;
65 xi.i &= ~(xi.i >> 31);
66 xi.i <<= IEEE754_MANT_BITS;
69 x = (((0.0135557472f * x + 0.0520323690f) * x + 0.241379763f) * x + 0.693032121f) * x + 1.0f;
77 #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__x86_64__)
79 #include <xmmintrin.h>
81 static inline float fastSqrtf(
float x) {
82 return _mm_cvtss_f32(_mm_sqrt_ss(_mm_set_ss(x)));
87 static inline float fastSqrtf(
float x) {
99 static inline float fastAcosf(
float x) {
101 union {
float f; int32_t i; } xi = { x };
103 int32_t sign = xi.i & 0x80000000;
107 float r = fastSqrtf(1.0f - xi.f);
110 xi.f = ((-0.0198439236f * xi.f + 0.0762021306f) * xi.f + -0.212940971f) * xi.f + 1.57079633f;
113 return (sign ? PI - xi.f : xi.f);
123 const float GAIN_CONVERSION_RATIO = 2.0f * 6.02059991f;
124 const float GAIN_CONVERSION_OFFSET = 255 - 60.0f;
126 static inline uint8_t packFloatGainToByte(
float gain) {
127 float f = fastLog2f(gain) * GAIN_CONVERSION_RATIO + GAIN_CONVERSION_OFFSET;
128 int32_t i = std::lround(f);
130 uint8_t
byte = std::clamp(i, 0, 255);
134 static inline float unpackFloatGainFromByte(uint8_t
byte) {
136 float gain = (
byte == 0) ? 0.0f : fastExp2f((
byte - GAIN_CONVERSION_OFFSET) * (1.0f/GAIN_CONVERSION_RATIO));