Beware the uninitialized variable

fairlight

The new AKSampler class in AudioKit 4.2 makes use of several lower-level C++ classes, one of which is a simple low-pass filter with resonance. This filter includes some four “state” variables called x1, x2, y1, and y2, to keep track of the last two input (x) samples and also the last two output (y) samples. They are all supposed to be initialized to zero, which in C or C++ is written
x1 = x2 = y1 = y2 = 0.0f

When I first typed this, however, what I actually wrote was
x1 = x2 = y1 = y1 = 0.0f

I typed “y1” twice. The result was that y2 was not initialized at all. In programming circles, this is known as a “bad thing”, and I learned just how bad this week. An uninitialized floating-point variable could have any value, based on whatever random configuration of bits was in the memory it occupies — quite possibly much larger than the small values (usually between -1 and +1) used for audio samples.

A digital filter computes each output sample by combining the current input sample with the handful of older ones it “remembers” in its state variables. Each of the samples is multiplied by some constant value and the results are summed. (The constant multipliers, or “coefficients”, collectively determine the filter’s cutoff frequency and resonance.) So in this case, the first output sample could be affected by whatever “junk” value was in the uninitialized y2 variable. Most of the time, the effect is minor (because the coefficients are all very small), so you don’t hear anything different, and y2 immediately gets overwritten with a real sample value, and all is well. Every so often, though, y2 starts off with a really huge junk value, and the result is a nasty noise spike, which goes straight to your computer’s D/A converters, straight out to your speakers, and straight into your ears! In my case, a bunch of these spikes blew out one channel of my USB audio interface — ouch!

The good news is, the problem is now fixed, and as I write, the fix is about to be released as part of a new 4.2.2 update of AudioKit. If you’re working with 4.2.0 or 4.2.1, and you’re trying out AKSampler, make sure to get this update before turning on the filter!

The lesson to be learned is, beware the uninitialized variable, especially in audio development where numbers turn into sound, and really big numbers turn into really loud sound!

Authorized Fairlight CMI photo, courtesy of Peter Wielk, horizontalproductions.com.au

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.