Skip to content

Commit

Permalink
Optimize dBFS/amplitude conversion functions (#7535)
Browse files Browse the repository at this point in the history
* Optimize dBFS <-> amplitude functions
  • Loading branch information
LostRobotMusic authored Oct 15, 2024
1 parent 97b61bb commit b8b1dae
Showing 1 changed file with 25 additions and 21 deletions.
46 changes: 25 additions & 21 deletions include/lmms_math.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}


Expand All @@ -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)
Expand Down

0 comments on commit b8b1dae

Please sign in to comment.