Sound Byte Libs 0.5.1-340-gab5b79a
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
gain.hpp
Go to the documentation of this file.
1/**
2 * @file gain.hpp
3 * @brief Gain in decibels, and the level taper for an amplifier's Level control
4 *
5 * Stateless. level_gain() is the taper the Vca applies to its Level port:
6 * exponential over a range in dB, as a VCA's exponential control input is,
7 * with a true zero at 0 and unity at 1. Exponential control for loudness
8 * follows Moog 1965 pp. 203-204 and the SSI2164's -33 mV/dB input.
9 */
10
11#ifndef SBL_DSP_MATH_GAIN_HPP_
12#define SBL_DSP_MATH_GAIN_HPP_
13
14#include <cmath>
15
16namespace sbl::dsp::math {
17
18inline constexpr float DB_PER_DOUBLING = 6.0206f; /**< 20 log10(2), in dB */
19
20/**
21 * @brief Amplitude gain for a level in dB: 10^(db / 20).
22 *
23 * @param db Level in dB
24 * @return Linear amplitude gain
25 */
26inline float db_to_gain(float db) { return std::exp2f(db / DB_PER_DOUBLING); }
27
28/**
29 * @brief Level in dB for an amplitude gain.
30 *
31 * @param gain Linear amplitude gain
32 * @return 20 log10(gain) in dB; -inf for a gain of 0 or less
33 */
34inline float gain_to_db(float gain) { return gain > 0.0f ? 20.0f * std::log10(gain) : -INFINITY; }
35
36/**
37 * @brief The level taper: a level in [0, 1] to a gain.
38 *
39 * Exponential over range_db, shifted so 0 is silence and 1 is unity:
40 * @code
41 * g(l) = (10^(-r (1 - l) / 20) - 10^(-r / 20)) / (1 - 10^(-r / 20)), r = range_db
42 * @endcode
43 * Halfway is close to -r/2 dB. A range of 0 or less is the linear taper.
44 *
45 * @param level Level in [0, 1], clamped; a non-finite level counts as 0
46 * @param range_db Range of the taper in dB; 0 or less selects the linear taper
47 * @return Linear amplitude gain in [0, 1]
48 */
49inline float level_gain(float level, float range_db) {
50 const float l = std::isfinite(level) ? (level < 0.0f ? 0.0f : (level > 1.0f ? 1.0f : level)) : 0.0f;
51 if (!(range_db > 0.0f)) {
52 return l;
53 }
54 const float floor = db_to_gain(-range_db);
55 return (db_to_gain(-range_db * (1.0f - l)) - floor) / (1.0f - floor);
56}
57
58} // namespace sbl::dsp::math
59
60#endif // SBL_DSP_MATH_GAIN_HPP_
Math for the audio stack.
Definition crossfade.hpp:18
constexpr float DB_PER_DOUBLING
Definition gain.hpp:18
float level_gain(float level, float range_db)
The level taper: a level in [0, 1] to a gain.
Definition gain.hpp:49
float gain_to_db(float gain)
Level in dB for an amplitude gain.
Definition gain.hpp:34
float db_to_gain(float db)
Amplitude gain for a level in dB: 10^(db / 20).
Definition gain.hpp:26