Skip to content

Commit a6cb6ff

Browse files
committed
Add helper function to convert dB to linear
1 parent 64cf70b commit a6cb6ff

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

src/source/amplify.rs

+52
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ where
1212
Amplify { input, factor }
1313
}
1414

15+
/// converts decibels to linear
16+
pub fn to_linear(decibels: f32) -> f32 {
17+
f32::powf(10f32, decibels * 0.05)
18+
}
19+
1520
/// Filter that modifies each sample by a given value.
1621
#[derive(Clone, Debug)]
1722
pub struct Amplify<I> {
@@ -93,3 +98,50 @@ where
9398
self.input.try_seek(pos)
9499
}
95100
}
101+
102+
#[cfg(test)]
103+
mod test {
104+
use super::*;
105+
106+
const EPSILON: f32 = 0.3;
107+
/// Based on [Wikipedia's Decibel article].
108+
///
109+
/// [Wikipedia's Decibel article]: https://web.archive.org/web/20230810185300/https://en.wikipedia.org/wiki/Decibel
110+
const DECIBELS_LINEAR_TABLE: [(f32, f32); 27] = [
111+
(100., 100000.),
112+
(90., 31623.),
113+
(80., 10000.),
114+
(70., 3162.),
115+
(60., 1000.),
116+
(50., 316.2),
117+
(40., 100.),
118+
(30., 31.62),
119+
(20., 10.),
120+
(10., 3.162),
121+
(5.998, 1.995),
122+
(3.003, 1.413),
123+
(1.002, 1.122),
124+
(0., 1.),
125+
(-1.002, 0.891),
126+
(-3.003, 0.708),
127+
(-5.998, 0.501),
128+
(-10., 0.3162),
129+
(-20., 0.1),
130+
(-30., 0.03162),
131+
(-40., 0.01),
132+
(-50., 0.003162),
133+
(-60., 0.001),
134+
(-70., 0.0003162),
135+
(-80., 0.0001),
136+
(-90., 0.00003162),
137+
(-100., 0.00001),
138+
];
139+
140+
#[test]
141+
fn convert_decibels_to_linear() {
142+
for (db, linear) in DECIBELS_LINEAR_TABLE {
143+
dbg!(db, linear, f32::abs(to_linear(db) - linear));
144+
assert!(f32::abs(to_linear(db) - linear) < EPSILON,)
145+
}
146+
}
147+
}

src/source/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use crate::Sample;
88
use dasp_sample::FromSample;
99

1010
pub use self::agc::AutomaticGainControl;
11-
pub use self::amplify::Amplify;
11+
pub use self::amplify::{to_linear, Amplify};
1212
pub use self::blt::BltFilter;
1313
pub use self::buffered::Buffered;
1414
pub use self::channel_volume::ChannelVolume;

0 commit comments

Comments
 (0)