1 // A small program to try to even out the audio levels within a file
2 // (essentially a compressor with infinite lookahead).
9 // The frequency to filter on, in Hertz. Larger values makes the
10 // compressor react faster, but if it is too large, you'll
11 // ruin the waveforms themselves.
12 #define LPFILTER_FREQ 50.0
14 // The minimum estimated sound level at any given point.
15 // If you decrease this, you'll be able to amplify really silent signals
16 // by more, but you'll also increase the level of silent (ie. noise-only) segments,
17 // possibly caused misdetected pulses in these segments.
18 #define MIN_LEVEL 0.05
20 // A final scalar to get the audio within approximately the right range.
21 // Increase to _lower_ overall volume.
22 #define DAMPENING_FACTOR 5.0
25 #define FILTER_DEPTH 4
27 static float a1, a2, b0, b1, b2;
30 static void filter_init(float cutoff_radians)
32 float resonance = 1.0f / sqrt(2.0f);
33 float sn = sin(cutoff_radians), cs = cos(cutoff_radians);
34 float alpha = float(sn / (2 * resonance));
36 // coefficients for lowpass filter
50 // reset filter delays
54 static float filter_update(float in)
56 float out = b0*in + d0;
57 d0 = b1 * in - a1 * out + d1;
58 d1 = b2 * in - a2 * out;
62 std::vector<float> level_samples(const std::vector<float> &pcm, int sample_rate)
64 // filter forwards, then backwards (perfect phase filtering)
65 std::vector<float> filtered_samples, refiltered_samples, leveled_samples;
66 filtered_samples.resize(pcm.size());
67 refiltered_samples.resize(pcm.size());
68 leveled_samples.resize(pcm.size());
70 filter_init(M_PI * LPFILTER_FREQ / sample_rate);
71 for (unsigned i = 0; i < pcm.size(); ++i) {
72 filtered_samples[i] = filter_update(fabs(pcm[i]));
74 filter_init(M_PI * LPFILTER_FREQ / sample_rate);
75 for (unsigned i = pcm.size(); i --> 0; ) {
76 refiltered_samples[i] = filter_update(filtered_samples[i]);
79 for (int i = 1; i < FILTER_DEPTH; ++i) {
80 filter_init(M_PI * LPFILTER_FREQ / sample_rate);
81 for (unsigned i = 0; i < pcm.size(); ++i) {
82 filtered_samples[i] = filter_update(refiltered_samples[i]);
84 filter_init(M_PI * LPFILTER_FREQ / sample_rate);
85 for (unsigned i = pcm.size(); i --> 0; ) {
86 refiltered_samples[i] = filter_update(filtered_samples[i]);
90 for (unsigned i = 0; i < pcm.size(); ++i) {
91 float f = DAMPENING_FACTOR * std::max<float>(refiltered_samples[i], MIN_LEVEL);
92 leveled_samples[i] = pcm[i] / f;
95 return leveled_samples;