# resolving clipping audio issues

I have implemented a pre-emphasis filter by the following (pseudo) code:

a = 0.5;
s1[0] = s[0];

for (n = 1; n < N; n++) {
s1[n] = (s[n-1] * a) + s[n]
}


The problem I am finding is that due to summing, there is clipping happening. I thought the solution would be to find the difference between the max value in s1[n] and 1.0 and then subtract s1[n] by that amount...

However, that results in my audio turning into complete garbage, which I am confused as to why........ Subtracting a constant amount from an entire signal should simply lower it's amplitude by that amount, correct?

Subtracting a constant value from all of your samples will just cause all the clipping to happen at -1, and will give you some nasty distortion. The proper way to remove clipping is to normalize the samples.

Keep track of the max value of s1 in your loop, then in a second loop divide all of of your points by the max value, i.e.

a = 0.5;
s1[0] = s[0];
max_s1 = 0;
mean = 0;

for (n = 1; n < N; n++) {
s1[n] = (s[n-1] * a) + s[n]
if (abs(s1[n]) > max_s1) {
max_s1 = abs(s1[n]);
}
mean += s1[n];
}
mean /= N;
max_s1 -= mean;
for (n = 0; n < N; n++) {
s1[n] = (s1[n] - mean) / max_s1;
}


EDIT: For bonus points your can also subtract the mean from your filtered signal prior to doing the normalization. This will ensure you get maximum level without distortion from clipping.

• so prior to that second loop you would do something like: s1[n] = s1[n] - (sum(s1[0]..s1[N]) / N) ? Can you explain to me how that helps the signal exactly? – patrick Nov 25 '14 at 5:22
• In most systems, audio data is assumed to be in the range -1 to 1--samples outside that range are 'clipped' to 1 or -1. Normalization is a way to ensure that every sample falls within that range, with the maximum sample value being exactly 1 or -1. Now, you can imagine that if your original signal wasn't 'centered'--i.e. it's in the range 1 to 2, normalizing will give you values in the range .5 to 1. By subtracting the mean before normalizing to center your data, you ensure that you get the max possible dynamic range. Will edit code in answer to include mean subtraction.. – matt Nov 25 '14 at 5:37