Wacky Knobs

← Lab / Understanding audio DSP code, sorry it’s only math :)

· 10 min read

Overdrive in code: waveshaping, asymmetry and aliasing

← Tremolo in code

In an analog pedal, distortion happens when some part of the circuit can no longer follow the signal. Diodes cut off everything above their threshold, a transistor or a tube goes into saturation, and an op-amp hits its supply voltage. The Fuzz Face clips with transistors alone, the RAT and the Tube Screamer with diodes, and an amp with tubes. The details are in the clipping and gain stage articles. All of these parts do the same thing: they let a quiet signal through almost unchanged and stop a loud one from passing a certain limit. That can be drawn as a curve. Code has no diodes or transistors, but it can write that curve down directly: it turns every input number into an output number. The process is called waveshaping, and almost every digital overdrive, distortion and fuzz is built on it. The curve itself is one line of code. The real problem lies elsewhere: aliasing, a flaw an analog pedal does not have.

A curve instead of a circuit

Picture a table: the input is a number from -1 to 1, and the output is whatever the curve says. If the curve is a straight line, the output equals the input and nothing happens. If the curve bends and flattens near the top, the loud parts of the wave cannot pass the ceiling. The peaks flatten, the wave gets squarer, and new harmonics appear. That is distortion.

DRIVE is just a multiplier in front of the curve: shape(g × x). A small g keeps the signal in the straight part of the curve, where the sound is almost clean. A big g pushes even the quiet parts into the bend, so almost everything gets clipped. That is why DRIVE on a pedal is the same as gain: it does not change the curve, only how deep into it you go.

Hard and soft

The two most common curves are also the two classic sounds:

CurveIn codeAs in a pedalSound
Hardclamp(v, -1, 1)diodes to ground: DS-1, RAT, Distortion+sharp, “buzzy”, lots of high harmonics
Softtanh(v)diodes in the feedback loop: Tube Screamerrounder, a smoother move from clean to dirty
Tubeexponential, asymmetrictubes, an asymmetric circuitwarm, lots of even harmonics

The hard curve is perfectly straight up to 1 and then suddenly flat. The wave gets sharp corners, and a sharp corner holds a lot of high harmonics. The tanh curve bends gradually: a quiet signal passes almost clean, and the louder it is, the more it gets squashed. That is why a soft overdrive follows your dynamics better: play softly and it is clean, dig in and it “bites”.

The hard and soft curves are symmetric: the top and bottom peaks are cut the same way. A symmetric curve makes only odd harmonics (3rd, 5th, 7th…). You will see that in the picture in the simulator below.

The third curve is a simple tube model from the book DAFX: Digital Audio Effects (Udo Zölzer), which almost everyone who writes audio effects learns from:

f(x) = Q / (1 − ed·Q) + (x − Q) / (1 − e−d·(x − Q)), with Q = −0.2 and d = 8

It looks scary but does a simple thing. The negative side of the wave flattens softly at about −0.25, and the positive side goes almost straight up until the ceiling at 1 stops it. One side is cut early and softly, the other late and hard. That is very asymmetric, so this curve makes lots of even harmonics even without BIAS. Because of the same asymmetry, the average of the wave after it moves far from zero (up to 0.8 in the simulator), so the DC blocker after the curve matters even more here.

One trap in the code: when x is exactly Q, the second term is 0 / 0. The true value at that point is 1 / d, and that is exactly how it should be written. If that case is caught too broadly, for example by skipping the second term for every x below Q, the curve gets a jump of 0.125. A jump in the curve sounds just like hard clipping: harsh, and with aliasing.

Asymmetry: even harmonics and DC

Tubes, germanium transistors and asymmetric diodes do not cut the top and bottom peaks equally. In code that takes one number. BIAS shifts the signal before the curve, so one side of the wave hits the ceiling earlier than the other:

v = shape(g × x + BIAS) − shape(BIAS)

An asymmetric curve also makes even harmonics, above all the second, which is an octave above the fundamental. An octave fits with any note, so the sound gets warmer and “fuller”. That is why tubes are said to sound warm.

Asymmetry has a side effect. When one side is cut more than the other, the average of the wave is no longer zero. The wave sits slightly up or down, and that is a direct current (DC) component. You cannot hear it, but it eats headroom and makes a click when the effect switches on. That is why a DC blocker follows the curve, a high-pass filter at a few hertz. In a pedal that job is done by the output capacitor, the one that passes sound but blocks DC voltage. The − shape(BIAS) part makes sure silence stays silence.

What to try in the simulator

  • From clean to dirty. On “Riff”, slowly turn DRIVE from 0 to 48 dB. In the picture, watch the dot move deeper into the bend of the curve and the harmonic bars grow.
  • Soft versus hard. Same DRIVE, then flip CURVE. The hard curve has more high harmonics and sounds “buzzy”.
  • BIAS and the tube. On the soft curve, raise BIAS: blue bars appear, the even harmonics. Set BIAS back to 0 and they disappear. The “Tube” curve has them even without BIAS; try the “Tube (DAFX)” preset.
  • TIGHT. Compare “Distortion (hard)” and “No TIGHT (mud)” on the riff. The only difference is the bass before the curve, and the riff turns muddy and “flabby”.
  • Chords. Play “Chords” on “Distortion (hard)”. A full major chord turns to mud, and the fifth (power chord) at the end sounds solid. Why is explained below.
  • Aliasing. “Aliasing: hear it” plays the riff with high solo notes, with no oversampling. The high notes get a rough, “grainy” edge that is not part of the note. Switch OVERSAMPLE to 4× and the sound cleans up.

Aliasing: a flaw an analog pedal does not have

At a sampleRate of 48 kHz the highest frequency that can be stored is half of that, 24 kHz (the Nyquist limit). But the curve knows nothing about that limit. A hard-clipped tone has harmonics far above it: a 3 kHz tone has its 9th harmonic at 27 kHz, its 11th at 33 kHz and so on.

A frequency above the limit does not disappear; it “bounces” back, as off a mirror. 27 kHz is 3 kHz above the limit, so it shows up 3 kHz below it, at 21 kHz. 33 kHz ends up at 15 kHz. Those bounced tones are no longer harmonics of the note but random frequencies that fit with nothing. When the note goes up, they go down. On low notes they are quiet and hidden, but on high solo notes and bends the sound gets “grainy” and cold. It is one of the main reasons old digital distortions sounded bad.

The fix is oversampling. Before the curve, the signal is made four times denser (192 kHz), the curve runs on that, and then a lowpass filter removes everything above the old Nyquist. Only then is every fourth sample kept. Harmonics up to 96 kHz now have room, and the filter removes them before they could bounce. In the simulator 4× pushes the bounced tones down by about 45 dB. The price is four times the work for the curve, plus the filter. That is why almost every serious digital overdrive and amp simulator oversamples, and cheap ones sometimes do not.

There is a cheaper trick too: cut everything above a quarter of the sampleRate (12 kHz) before the curve, so not even the second harmonic passes the limit. That is enough for a curve that makes at most a second harmonic, such as x². But tanh, clamp and the tube curve make many higher harmonics, and those still fold back. On the same tones that trick left 25 to 35 dB more aliasing here than oversampling, for about the same amount of work.

Why chords turn to mud

When two notes go through the curve at once, you get not only their harmonics but also the sums and differences of their frequencies. That is called intermodulation. In a fifth (power chord) the frequencies are almost exactly in a 3 : 2 ratio, so the sums and differences land on notes that fit the chord, for example an octave below the root. In a third the ratio should be 5 : 4, but in equal temperament, the tuning a guitar uses, the third is off by about 14 cents, and the fifth by only about 2. So the new tones from a third do not land exactly on the chord’s notes but just next to them, and they beat against each other. A full chord has many such pairs, and the result is mud. That is why heavy distortion goes with power chords and a full major chord sounds muddy. It is not a flaw of the code: every analog pedal does the same.

TIGHT: cut the bass before the curve

The same goes for a single note. Low frequencies are the strongest part of a guitar signal, so they hit the ceiling first. Once the bass is in the curve, intermodulation with it muddies everything else and the tone gets “flabby”. That is why a high-pass filter before the curve removes the bass below about 150 Hz. Almost every pedal does this: the Tube Screamer’s clipping stage has a filter (4.7 kΩ and 47 nF) that only amplifies above about 720 Hz, so the bass is barely clipped, and that is also where its “mid hump” comes from. For metal tones a whole TS is often put in front of the distortion as a boost, just to cut the bass.

It is a first-order filter: h = (2 × (x − xPrev) + (2 − hw) × hPrev) / (2 + hw). The bass is not lost for good. The guitar still sounds full, because after the distortion the bass comes from the amp and the cabinet, and the curve brings part of it back as differences between harmonics.

Why tone comes after clipping

The curve makes harmonics at high frequencies too, and up there they sound harsh, like a buzzing insect. That is why almost every distortion pedal has a tone control after the clipping. Here it is a second-order lowpass filter. It cuts 12 dB per octave, twice as steep as the simple filter from the tremolo, so the “fizz” above 5 kHz almost disappears while the mids stay untouched. How such a filter is built and why it has exactly five numbers is the topic of the next article, on filters. More on what tone does to the sound is in tone controls.

The code, line by line

  1. From dB to a multiplier. g and lvl are DRIVE and LEVEL converted from decibels. 20 dB is ×10, 40 dB is ×100.
  2. TIGHT. A first-order high-pass removes the bass before the curve. hw depends on TIGHT_HZ.
  3. The curve. shape(g × h + BIAS) − shape(BIAS): amplify, shift, pass through the curve and put silence back at zero.
  4. DC blocker. dc is the difference of two samples in a row plus 0.9995 of the previous output. That is a high-pass at about 4 Hz, so everything stays except the DC.
  5. TONE. A second-order lowpass; lw depends on TONE_HZ.
  6. LEVEL and the limiter. After clipping the signal is always near the ceiling, so LEVEL brings it back to a sensible volume. The limiter at the end makes sure the output never goes past ±1.
  7. Oversampling (when on): the curve line runs four times, for four points between the previous and the current sample. A 48-tap lowpass cleans the result, and every fourth value is kept.

And in a real pedal?

Digital pedals and plugins rarely compute tanh directly, because it is expensive. Instead the curve is read from a table of a few thousand values, or replaced with a polynomial close enough to it. Amp simulators stack several such stages in a row with filters in between, like the tubes in an amp (see gain stage). Some go further and simulate the circuit itself, diodes and capacitors, solving equations for every sample. That sounds the most faithful but takes much more power, so it runs on the stronger chips from the earlier overview.

That is why some pedals that combine several effects still do their distortion the analog way, with diodes, and use the digital part for delay and reverb. Distortion is the one effect that is cheap and easy in the analog world and needs care in the digital one, because of aliasing.

If you want to see a complete overdrive written for a real STM32, from the input filter to the curve, I recommend the Phil's Lab video and its code.

Next step: filters, the biquad and five numbers behind every EQ, tone control and wah →

More in Understanding audio DSP code, sorry it’s only math :)

← Lab