Dr. Dobb's Journal October 1998
Compensating for Poor Hardware Clipping
Analog-to-digital converters map a voltage linearly into a binary number. For example, they may map -1 volt to -32768 and +1 volt to 32767; see Figure 1. For signals within the (+1/-1 volt range, this works great. What happens if the signal exceeds +1 volt, as in Figure 2? Nothing good, I assure you. This situation is called "clipping," and there are several ways to handle it. For digital audio recording, limiting the signal to a maximum or minimum value is best, as in Figure 3. The signal is slightly distorted, but otherwise fine. Unfortunately, some Macs and Windows sound cards do the unexpected -- they modify the signal as in Figure 4, inverting and then limiting the signal at peak amplitudes. This distorts the signal severely, making for unpleasant playback.
Figure 1: Signals within the digitizer's range are converted to digital form. |
Figure 2: What value should be given to samples outside the expressible range? |
Figure 3: Limiting the signal to maximum and minimum values is a reasonable approach. |
Figure 4: Some sound cards invert and limit the signal, which introduces strong distortions. |
Detecting Distortion
To compensate for this, I have developed an algorithm (available electronically) that detects the distortion of Figure 4 and transforms it into the gentler signal of Figure 3. Basically you examine the difference between a sample and its predecessor. If the magnitude of the difference exceeds a certain threshold (indicating that the signal has been inverted), you negate all subsequent samples until you detect another inversion.
Because it has to examine every sample, the first implementation of the algorithm is unacceptably slow. However, by splitting the main processing loop into two cases (inverting and not inverting) and simplifying the test for possible signal inversion to the sign of the result of an exclusive-or operation (also available electronically), a dramatic speedup (over 10 times) can be achieved. Optimizations like this are typical in real-time code.
-- R.C.
Copyright © 1998, Dr. Dobb's Journal