Optimize dBFS/amplitude conversion functions (#7535)

* Optimize dBFS <-> amplitude functions
This commit is contained in:
Lost Robot
2024-10-15 07:29:47 -05:00
committed by GitHub
parent 97b61bbd9a
commit b8b1dae407

View File

@@ -164,37 +164,22 @@ inline float linearToLogScale(float min, float max, float value)
return std::isnan( result ) ? 0 : result;
}
//! @brief Converts linear amplitude (0-1.0) to dBFS scale. Handles zeroes as -inf.
//! @param amp Linear amplitude, where 1.0 = 0dBFS.
//! @return Amplitude in dBFS. -inf for 0 amplitude.
inline float safeAmpToDbfs(float amp)
inline float fastPow10f(float x)
{
return amp == 0.0f
? -INFINITY
: log10f( amp ) * 20.0f;
return std::exp(2.302585092994046f * x);
}
//! @brief Converts dBFS-scale to linear amplitude with 0dBFS = 1.0. Handles infinity as zero.
//! @param dbfs The dBFS value to convert: all infinites are treated as -inf and result in 0
//! @return Linear amplitude
inline float safeDbfsToAmp(float dbfs)
inline float fastLog10f(float x)
{
return std::isinf( dbfs )
? 0.0f
: std::pow(10.f, dbfs * 0.05f );
return std::log(x) * 0.4342944819032518f;
}
//! @brief Converts linear amplitude (>0-1.0) to dBFS scale.
//! @param amp Linear amplitude, where 1.0 = 0dBFS. ** Must be larger than zero! **
//! @return Amplitude in dBFS.
inline float ampToDbfs(float amp)
{
return log10f(amp) * 20.0f;
return fastLog10f(amp) * 20.0f;
}
@@ -203,10 +188,29 @@ inline float ampToDbfs(float amp)
//! @return Linear amplitude
inline float dbfsToAmp(float dbfs)
{
return std::pow(10.f, dbfs * 0.05f);
return fastPow10f(dbfs * 0.05f);
}
//! @brief Converts linear amplitude (0-1.0) to dBFS scale. Handles zeroes as -inf.
//! @param amp Linear amplitude, where 1.0 = 0dBFS.
//! @return Amplitude in dBFS. -inf for 0 amplitude.
inline float safeAmpToDbfs(float amp)
{
return amp == 0.0f ? -INFINITY : ampToDbfs(amp);
}
//! @brief Converts dBFS-scale to linear amplitude with 0dBFS = 1.0. Handles infinity as zero.
//! @param dbfs The dBFS value to convert: all infinites are treated as -inf and result in 0
//! @return Linear amplitude
inline float safeDbfsToAmp(float dbfs)
{
return std::isinf(dbfs) ? 0.0f : dbfsToAmp(dbfs);
}
//! Returns the linear interpolation of the two values
template<class T, class F>
constexpr T lerp(T a, T b, F t)