♪Music, Built

Act IX · Electric Sound

Part 50 of 68

Dynamics, Distortion and Pitch

Foundationsstarts at this level35 min of film13 chaptersprerequisites: Part 4, Part 8, Part 40, Part 48, Part 49

What do effects that are not linear, or that change with the signal, do to sound, and how are they built?

Two accidents made two genres: a damaged amplifier on Rocket 88 (1951), and Auto-Tune set to act instantly on Believe (1998); an ear question hears Part 8's voice sung 28 cents off and hard-tuned to 0.6. Shapers make harmonics (odd only, for odd shapers: a hard clip's third at -11 dB, fifth at -18.5), Chebyshev polynomials deliver any harmonics exactly at full size (third -6.02 dB, fifth -12.04) and differently when quiet; two tones intermodulate (a fifth's products fall on multiples of 110 Hz, a third's on 55: the power chord); a clipped sweep aliases (an ear question), and the alias energy falls from -26.8 dB to -32.5 by antiderivative antialiasing and -47.3 by 8x oversampling. A compressor after Giannoulis, Massberg and Reiss draws its static curves, attacks in 12 ms, halves a groove's loudness spread (an ear question) while its attack keeps the punch (crest factor up); limiters, gates and a kick-keyed sidechain follow. Resampling ties pitch to time; PSOLA and the phase vocoder untie them; YIN and a corrector at three speeds tune a voice; a 16-band vocoder and ring modulation close it.

What you need. Part 4 for difference tones; Part 8 for the voice's source and filter; Part 40 for the guitar; Part 48 for aliasing; Part 49 for filters. Polynomials, Fourier series, autocorrelation, the short-time Fourier transform.

Ideas, mathematics and history
waveshaping and Chebyshev polynomials, intermodulation and the power chord, compressors, the phase vocoder, PSOLA, Auto-Tune, the vocoder
What we build, compute and hear
our compressor, fuzz and pitch corrector; the voice of Part 8, tuned

What you will be able to do

Foundations

  • Hear hard-tuned from natural, three shapers on one note, and a power chord against a major chord distorted.
  • Hear aliasing in a clipped sweep, a compressed groove at matched loudness, pumping, and a sidechain duck.
  • Hear pitch shifted by resampling and by PSOLA, a stretch by overlap-add and by the phase vocoder, and a vocoder.

Full course

  • Design a Chebyshev shaper by its harmonics; measure intermodulation and aliasing, with ADAA and oversampling.
  • Build a feedforward compressor with a soft knee, attack and release; measure its curves and a groove's spread.
  • Track pitch by YIN, correct it with PSOLA at a chosen speed, stretch by the phase vocoder, and vocode.

Research

  • Find the smallest neural amplifier model indistinguishable at every knob setting and free of aliasing.

Practice

  • Choose fifths under distortion, compressor timing for punch, sidechains for space, and correction speed for style.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Foundations 20 min · Full course 33 min · Research 35 min · Practice 33 min.

  1. 0Two accidents, two genresFoundations2 min
  2. 1Nonlinearity makes new frequenciesFoundations3 min
  3. 2Chebyshev's exact harmonicsFoundations2 min
  4. 3Intermodulation and the power chordFoundations2 min
  5. 4Aliasing in nonlinear effectsFoundations2 min
  6. 5CompressorsPractice4 min
  7. 6Limiters, gates and sidechainsPractice2 min
  8. 7Time and pitchFoundations3 min
  9. 8Overlap-add and the phase vocoderFoundations3 min
  10. 9Pitch correctionPractice3 min
  11. 10Vocoders and ring modulationPractice3 min
  12. 11Frontier: neural models of analog gearResearch2 min
  13. Variation 50, recap and problemsAll tracks2 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Two accidents, two genresFoundations2 min

In 1951 a guitar amplifier damaged on the way to a Memphis session gave a record its torn tone. That story comes later; listen first. The Tune's first phrase, sung twice by the same computed voice. One version was passed through a pitch corrector set to act instantly. Which one?

The second. Here are the two pitch tracks, measured frame by frame, against the notes of the scale. As sung, every note sits a little off, by a median of cents. Corrected, each note snaps onto the line, to within cents, and jumps between notes without gliding. That instant snap is the sound of a genre.

Two celebrated production stories illustrate how artifacts became musical resources. In 1951 Rocket 88 was recorded at Sam Phillips's Memphis Recording Service, before the Sun label was founded through a guitar amplifier damaged on the way to the session. Its fuzzy, torn tone was kept, and distortion became the sound of rock. In 1997 Andy Hildebrand, a geophysicist who had used autocorrelation to find oil, released Auto-Tune, to fix singers' pitch discreetly. In 1998 Cher's Believe set its speed to instant: the voice snapped between notes, and a style was born. Both are nonlinear or time-varying: effects the last part's linear rules cannot describe.

Here is the plan. Nonlinearity, harmonics, and Chebyshev's exact shaper. Intermodulation, the power chord, and aliasing. Compressors, limiters, gates and sidechains. Time and pitch: resampling, overlap-add and the phase vocoder. Pitch detection, PSOLA and pitch correction. And vocoders and ring modulation.

1Nonlinearity makes new frequenciesFoundations3 min

Where does distortion's sound come from?

Part 49's fixed LTI filters change existing spectral components; its modulated effects are time-varying and can create sidebands even while remaining linear. A nonlinear system creates new frequencies. The simplest is a waveshaper: each output sample a fixed function of the input sample, with no memory. If that function bends, a pure tone comes out with harmonics: the bend is in the waveform, the harmonics in the spectrum. Amplifiers driven too hard, saturated tape, valves and pedals all bend.

Three shapers. The dashed line is no shaping at all. A hard clip follows it until a limit, then flattens abruptly: the transistor or the digital ceiling. The hyperbolic tangent bends smoothly, like a valve. A cubic soft clip bends early and gently, and flattens at the top.

Drive a one-kilohertz sine three times past the bend and measure the harmonics. The hard clip: the third at decibels, the fifth at , the seventh at . The tanh: , and . The cubic: , and , its upper harmonics falling slowest of the three. And all three add only odd harmonics: the second, fourth and sixth are missing entirely.

Hear the three bends on one guitar note, each driven five times past its knee, raw, with no loudspeaker to soften them.

The hard clip buzzes; the tanh is rounder; the cubic is the softest. Raw, all three are harsh: real amplifiers filter before and after the bend.

Hear it on a guitar: a riff, clean, then through a hard-driven shaper and a loudspeaker's band limit.

Why only odd harmonics? A shaper that treats positive and negative alike, an odd function, makes only odd harmonics, because an odd function of a cosine is a sum of odd cosines. Make it lopsided, as a single valve or a biased transistor is, and even harmonics appear. The second harmonic is an octave, so even distortion is often called warm, and odd distortion edgy. The shape of the bend is the timbre of the distortion.

Each device has its own bend. Some valve stages produce soft asymmetric distortion, but topology, bias and operating level determine the result. Transistor and op-amp circuits can clip hard or softly depending on feedback, bias and surrounding components. Tape saturates gently and compresses as it goes, losing a little of its top. Fuzz pedals clip almost to a square wave; overdrives clip softly, often after a filter that shapes which frequencies distort. Each has a shape, and the shape is the sound.

2Chebyshev's exact harmonicsFoundations2 min

Can we choose exactly which harmonics a shaper adds?

There is a way to choose a shaper's harmonics exactly. Pafnuty Chebyshev's polynomials start one, x, and each next one is two x times the last, minus the one before. Two x squared minus one; four x cubed minus three x; and so on. Their defining property: T n of cosine theta is cosine of n theta. So a full-size cosine passed through T n comes out as exactly its n-th harmonic, and passed through a weighted sum of them, as exactly those harmonics, at those weights. A shaper designed by its spectrum.

Ask for the fundamental, half of it at the third harmonic, a quarter at the fifth, nothing else. The shaper is T one plus half T three plus a quarter T five. Feed it a full-scale cosine and measure: the third at decibels, which is a half, the fifth at , a quarter, and the even harmonics below two hundred decibels down, nothing but rounding.

Hear the catch. A shaper designed for harmonics one, three, five and seven at full size, fed a tone at a quarter of full size, at 0.6, and at full size. At full size it delivers the design: the seventh at decibels. At a quarter, the seventh falls to and the fifth to : the upper harmonics fade fast. But the third rises to , almost level with the fundamental, because the polynomials' low terms cancel part of the fundamental. The timbre changes with level, and not always gently.

Marc Le Brun and Daniel Arfib turned this into a way to synthesize sound in 1979: waveshaping, a cheap way to make rich spectra. The catch is that the harmonics are exact only at full amplitude. Turn the input down and the spectrum changes with it, so a shaper's timbre follows loudness, as an acoustic instrument's does: a feature, if it is designed for. Part 51 builds synthesizers, and waveshaping is one of their tools.

3Intermodulation and the power chordFoundations2 min

Why do rock guitarists play fifths?

Now feed a shaper two tones at once. It makes the harmonics of each, and also tones at their sums and differences, and the sums and differences of their harmonics: intermodulation. If the two tones are in a simple ratio, every new tone is a multiple of their common divisor. A fifth, three to two, makes a harmonic series an octave below the lower note: the result is simply a bigger chord. A major third, five to four, makes a series two octaves down, crowded with tones that clash.

Measure it. A fifth, two hundred and twenty and three hundred and thirty hertz, through the tanh shaper: every new line falls on a multiple of a hundred and ten, an octave below the lower note, a clean harmonic series. A major third, two hundred and twenty and two hundred and seventy-five: the new lines fall on multiples of fifty-five, including some that clash with the chord itself.

Hear it on the guitar, through heavy distortion: a power chord, root, fifth and octave, then a full major chord. This power chord is clearer under the chosen distortion. Register, tuning and circuit matter, and distorted guitar also uses thirds and full chords.

The strongest new tone is often the difference between the two. For a fifth on low E and B, eighty-two and a hundred and twenty-three hertz, it is forty-one: an E an octave below the root. So a distorted power chord sounds deeper and bigger than its notes. The ear makes a faint difference tone of its own, Tartini's tone, from its own nonlinearity, as Part 4 described. And intermodulation is why distorting a whole mix sounds harsh: every pair of notes makes new ones.

4Aliasing in nonlinear effectsFoundations2 min

What happens to harmonics above the Nyquist frequency?

Nonlinearity has a digital trap. A digital shaper makes its harmonics inside the computer, after the anti-aliasing filter has done its work. A four-kilohertz tone's fifth harmonic is twenty kilohertz, but its seventh, twenty-eight, is above the Nyquist frequency, and it folds back down, as Part 48 showed: at forty-eight kilohertz sampling, twenty-eight is heard at twenty. Folded harmonics are not harmonics: they fall between the notes, and they move the wrong way. The harder the drive and the higher the note, the worse it gets.

Listen. A sine sweeping up from five hundred hertz to six kilohertz through a hard clip, twice. One was computed at forty-eight kilohertz, the other eight times faster and filtered back down. In which do you hear tones moving the wrong way?

The first. The sweep's high harmonics hit the Nyquist frequency, fold, and come back down as the sweep goes up: faint tones moving the wrong way, and a grainy whine. Computed eight times faster, the harmonics have room above hearing, and filtering before decimation removes many high components; finite oversampling does not eliminate every alias from an unlimited-bandwidth shaper.

How bad is it, and what cures it? Measure the energy of a driven tone that does not fall on a harmonic. Computed plainly at forty-eight kilohertz: decibels below the total. With antiderivative antialiasing, which applies the shaper to the straight line between samples and averages it, : a little better, almost for free. Computed eight times faster and filtered down: . Oversampling costs eight times the work, and buys the most.

Aliasing hides everywhere. Every nonlinear digital process can alias: shapers, compressors with fast attacks, ring modulators. A compressor whose gain jumps within a cycle is multiplying by a fast signal, and that makes new frequencies. A naive square-wave oscillator aliases too, since its corners are infinitely sharp. The general cure is the same: work at a higher rate, or make the new frequencies band-limited from the start. Part 51 builds oscillators that never alias.

5CompressorsPractice4 min

How do you make the quiet parts louder without the loud ones clipping?

The second family of effects controls level. A compressor turns the level down when it is high, and leaves it alone when it is low. Above a threshold, every four decibels more going in gives only one decibel more coming out: a ratio of four to one. Then the whole signal can be turned up, with make-up gain. The result is denser and louder on average, with smaller swings. And it is nonlinear and time-varying: its gain depends on the signal itself.

Draw level out against level in, in decibels. Below the threshold, minus twenty here, the line is the diagonal: nothing happens. Above it, the slope is one over the ratio: two to one gently, four to one firmly, ten to one almost flat. A soft knee bends from one slope to the other over six decibels instead of at a corner. This is the gain computer of Dimitrios Giannoulis, Michael Massberg and Joshua Reiss's 2012 design, which our compressor follows.

A compressor must also decide how fast to act. Feed it a tone that jumps twenty-four decibels for four-tenths of a second. The gain reduction rises to decibels in about milliseconds: the attack. When the tone falls back, it lets go more slowly, over about milliseconds: the release. A fast attack catches every peak; a slow release avoids pumping the level up and down with every beat.

Hear what the release does. The groove compressed hard, first with a twenty-five millisecond release, then with four hundred. Listen to the bass and the hi-hat between the kicks.

With the fast release, the level leaps back up after every hit, and the quiet parts surge and fall: pumping, and even a little distortion on the bass, as the gain follows its waveform. With the slow release the gain hardly moves between hits, and the groove is held down evenly.

Your turn. A groove, twice, at the same average loudness. One is compressed. Which?

The second. Its level, measured in windows of twenty milliseconds, wanders over about decibels against for the plain groove: the bass and the tail of each drum come up to meet the hits. It sounds thicker and more even, even at the same average loudness.

One measurement goes the other way. The compressed groove's crest factor, its peak over its average, rose, from to decibels. The three-millisecond attack lets the first instant of every hit through before the gain comes down, so the clicks stay sharp while the body is turned down: engineers call it punch. A faster attack would flatten the hits too; a slower one would leave more of each through. A compressor's sound lies in its timing as much as in its ratio.

What level does a compressor see? The peak, instant by instant, or the RMS, an average over tens of milliseconds. Peak detection follows amplitude peaks subject to its timing; RMS estimates energy over a window and is only a rough proxy for perceived loudness. Feedforward compressors measure their input; feedback ones measure their own output, as many classic units did. Optical compressors used a lamp and a photocell, whose slow, level-dependent response gave them their character. Every one of these choices changes the sound, which is why engineers own several.

6Limiters, gates and sidechainsPractice2 min

What else can a gain that follows a signal do?

The compressor has relatives. An ideal static limiter has infinite ratio above its threshold; practical limiters use finite timing and often lookahead, with separate sample-peak and true-peak specifications. It often looks ahead: the signal is delayed a few milliseconds, so the gain can come down before the peak arrives. A gate is the reverse: below a threshold the level is cut, silencing hiss and spill between notes. An expander is a gentle gate, widening the dynamics instead of narrowing them. Part 57 meets the limiter again, in mastering's loudness war.

A compressor's detector can listen to a different signal from the one it turns down: a sidechain. Here the kick drum drives a compressor on a sustained pad. Every kick pushes the pad down, and it swells back between them: the pumping sound of dance music, and the way engineers keep a bass out of the kick's way. Hear the pad plain, then ducked.

Hear a gate. Six snare hits over a steady hiss, as if from a noisy old recording. Plain, the hiss fills every gap. Gated, the level is cut whenever it falls below the threshold, and the gaps go silent.

The idea spreads. De-essing is a compressor keyed by the sibilant band, taming a singer's s sounds. Ducking makes music dip when a presenter speaks. Multiband compression splits the sound and compresses the lows, mids and highs separately. Broadcast processors chain several, so that every station sounds equally loud. All of them are one idea: a gain that follows a level.

How does a limiter keep its promise? It must never let a sample through above its ceiling, while limiting audible artifacts; any signal-dependent gain can create distortion. With no warning, the only way is to clip, and clipping is distortion. So the signal is delayed a few milliseconds while the detector reads ahead, and the gain starts falling before the peak arrives, smoothly, reaching just low enough as it does. The cost is latency: fine for mastering, a problem on stage.

7Time and pitchFoundations3 min

Can a sound be made higher without being made faster?

The last family changes time and pitch. Play a recording faster, and every frequency rises in proportion: pitch and tempo move together. A tape at double speed is an octave higher and twice as quick, and the voice's formants, from Part 8, rise too: the singer shrinks into a chipmunk. Changing pitch alone, or time alone, needs the sound taken apart and put back together. There are two ways: by grains of the waveform, and by its spectrum.

Hear the difference. The voice; then a fifth higher by playing it faster; then a fifth higher by PSOLA.

PSOLA works on the waveform. Eric Moulines and Francis Charpentier described it in 1990. Mark every period of the voice, and cut a grain two periods long around each mark. Lay the grains back down closer together to raise the pitch, or further apart to lower it. Each grain keeps its own shape, so the formants, and the vowel, stay where they were. Repeat or skip grains to keep the length. Pitch and time are untied, for voices and other sounds with a clear period.

Studios have long played with the link. Varispeed ran tape a little fast to brighten a track, or slow to deepen it. The Chipmunks, in 1958, were voices recorded at half speed and played back at full. Samplers transpose by resampling, so a sampled piano needs a recording every few notes, or its timbre shifts. Eventide's H910 Harmonizer, in 1975, was one of the first boxes to change pitch alone, in real time. The grains of PSOLA and the spectra of the phase vocoder are its descendants.

Why does PSOLA keep the vowel? A voice is a source and a filter, as Part 8 showed: the vocal folds set the pitch, and the vocal tract sets the formants. Resampling moves both; PSOLA approximately preserves the spectral envelope over suitable voiced signals because it reuses short waveform grains; large shifts and tracking errors can alter formants and introduce artifacts. Spectral shifters separate the envelope by linear prediction or the cepstrum, shift the rest, and put the envelope back. Shift the formants alone, and the same singer sounds larger or smaller, older or younger. Part 8's model made this a matter of two numbers; here it is done to a recording.

8Overlap-add and the phase vocoderFoundations3 min

How do you stretch a sound without changing its pitch?

The simplest way to stretch is overlap-add. Cut the sound into overlapping windows and lay them down further apart. Each window keeps its pitch, and the whole lasts longer. But the pieces of a steady tone no longer line up, and where they overlap they partly cancel. The result warbles, with a regular flutter at the window rate. The cure is to fix each frequency's phase as the windows are laid down.

That is the phase vocoder. James Flanagan and Roger Golden built it at Bell Labs in 1966. Transform each window, as Part 3's short-time Fourier transform does, and keep every bin's magnitude. From how far each bin's phase moved between windows, work out its true frequency. Then rebuild the phase so that frequency advances smoothly across the new, wider spacing. Jean Laroche and Mark Dolson improved it in 1999 by locking the bins around each spectral peak together, so that each partial stays whole.

Hear it: the sung phrase, then twice as long by overlap-add, then twice as long by the phase vocoder.

Overlap-add flutters, as the out-of-step windows beat against each other. The phase vocoder is smooth, though a little reverberant: its known weakness, the smearing of attacks.

The phase vocoder has limits. It smears transients: a drum hit spread over a window sounds soft and phasey. Modern stretchers detect attacks and leave them alone, stretching only what lies between. To shift pitch by spectrum, stretch in time and then resample back to the original length; but that moves the formants too, so voices need their spectral envelope separated and kept. Every audio workstation's warp, and every karaoke key change, rests on these two ideas.

Stretch far enough and a sound becomes a texture: eight times, eighty, eight hundred. Paul Nasca's Paulstretch, from 2006, randomises each bin's phase, giving up the attack for a smooth wash. An extremely stretched pop recording became an ambient piece that spread online in 2010. Variation 50 stretches one second of the Tune to eight. At that scale the phase vocoder is less an effect than a microscope.

Stretching is everywhere at work. DJ software matches the tempo of two tracks without changing their key. Film editors fit a cue to a cut a few per cent longer or shorter, the hit points of Part 44. Language learners and transcribers slow speech and music down, keeping the pitch. Producers move a sampled loop to a new tempo, or a new key, independently. Each is a careful use of the same machinery: analyse, move, rebuild.

9Pitch correctionPractice3 min

How does a machine know what note you meant?

A pitch corrector must first find the pitch. A voice's waveform repeats once a period. Autocorrelation compares the signal with a shifted copy of itself, and it matches best when the shift is one period. Hildebrand had used the same tool to find echoes from oil-bearing rock. The trap is that it also matches at two periods, and three, so octave errors lurk. YIN, by Alain de Cheveigné and Hideki Kawahara in 2002, is built to avoid them.

YIN goes in four steps. Compute the difference between the signal and its shifted self, squared and summed: zero at a perfect period. Normalise it by its running mean, so that tiny shifts do not win by default. Take the first dip below a threshold, not the deepest: this reduces octave errors but does not guarantee the correct period. Refine the answer between samples by fitting a parabola. Done frame by frame, every few milliseconds, it tracks the voice's pitch as it moves.

Then choose the nearest scale note as this program's target; that heuristic cannot determine a singer's intended note in every context. Here is the out-of-tune voice's pitch, as YIN measured it. A slow corrector glides towards the target over a quarter of a second: the singer's own scoops and vibrato survive, and the result sounds natural. A faster one arrives in sixty milliseconds. At speed zero, the target jumps straight to the scale note and every glide between notes vanishes: the pitch moves in steps. That is the setting Believe used. PSOLA then moves the voice to whichever target was chosen.

Hear the three speeds on the out-of-tune voice: a slow glide, a faster one, and instant.

The slow glide still sounds like a singer, a little more in tune. The fast one tightens it. The instant one snaps from note to note: no singer moves like that, which is exactly why it became a sound of its own.

The story of pitch correction is the story of fuzz again. Auto-Tune was sold to fix flat notes invisibly, and it became routine in pop production. Cher's Believe, in 1998, made the artefact the point. T-Pain built a style on it, and in hip-hop and Afrobeats it became an instrument. Gentle settings can be transparent on suitable material, while fast correction often produces an audible effect. A tool's mistakes became an art's materials, as fuzz did.

Correction need not be automatic. Celemony's Melodyne, from 2001, draws every note of a recording as a blob on a piano roll. Drag a blob and the note moves, by the same detection and shifting, done offline and with care. Its Direct Note Access, in 2009, separated the notes of a chord, so that a single string of a guitar could be retuned. The singer's vibrato and scoops can be kept, flattened or redrawn. Part 61 builds the transcription underneath: pitches and onsets from audio.

10Vocoders and ring modulationPractice3 min

How do you make an instrument talk?

The vocoder began as telephone engineering. Homer Dudley at Bell Labs built it in 1939, to send speech in less bandwidth: split speech into bands, and send only how loud each band is, a few times a second. At the far end, impose those band levels on a buzz or a hiss, and out comes intelligible, robotic speech. Vocoder analysis formed part of SIGSALY's secure wartime speech system; the encryption involved additional machinery, and musicians took it up from the 1970s. The voice is the modulator; a synthesizer chord is the carrier.

Here is what our sixteen-band vocoder extracts from a sung phrase whose vowels change on every note: each band's level, low frequencies at the bottom, through time. The vowels show as moving patterns of formants. Fine spectral structure is discarded, though band envelopes can retain periodicity cues; the transmitted representation here is this pattern, which is then stamped onto the carrier.

Hear the voice, the carrier chord, the chord vocoded by the voice, and last, the voice ring-modulated.

Ring modulation is simpler and stranger. Multiply the sound by a sine. Since the product of two sines is half the difference of two cosines, every component splits in two, at its frequency minus the sine's and plus it. For ideal balanced multiplication there are no unshifted carrier terms, although shifted components can coincide with original frequencies; harmonicity depends on frequency ratios: a metallic, bell-like voice. The Daleks' voices on the BBC were made this way, and Stockhausen used it in concert works. Part 52 meets frequency modulation, its more musical cousin.

The vocoder has a mechanical cousin. In a talk box, a tube carries an instrument's sound into the player's mouth; the mouth shapes it as it would a vowel, and a microphone picks it up. It is a vocoder made of flesh, whose filter bank is the mouth's formants. Peter Frampton and Roger Troutman made it famous in the 1970s and 80s. The vocoder, the talk box and pitch correction all make an instrument out of a voice, or a voice out of an instrument.

Musicians kept the vocoder alive. Wendy Carlos used one to make synthesizers sing in A Clockwork Orange, in 1971. Kraftwerk made it the voice of machines on Autobahn, in 1974, and after. Herbie Hancock, Laurie Anderson and Daft Punk each found a different character in it. The more bands, the clearer the words; and the brighter the carrier, the more of them survive. A 1930s telephone experiment, kept alive by musicians.

11Frontier: neural models of analog gearResearch2 min

Can a network learn an amplifier?

The frontier is learning the gear itself. Record a guitar amplifier's input and output, and train a recurrent network to map one to the other. Alec Wright, Eero-Pekka Damskägg and Vesa Välimäki showed in 2019 and 2020 that small networks can model amplifiers in real time, and listeners struggled to tell them from the real ones in blind tests. Commercial capture pedals now do this for any amplifier you own. The open problem is a model that stays right across every setting of every knob.

Aliasing stays a live problem. Oversampling works, but costs its factor in computation. Antiderivative antialiasing, from Julian Parker, Vadim Zavalishin and Efflam Le Bivic in 2016, shapes the straight line between samples instead of the samples alone. Higher orders, and versions for shapers with memory, followed, from Stefan Bilbao and colleagues. And a network trained at one rate can alias when run at another, so the two problems meet. Part 51 needs the same care for oscillators.

There is a middle way. White-box models simulate a circuit from its parts, the virtual analogue of Part 49. Black-box models, like those networks, learn only from input and output. Grey-box models keep the structure, a filter, a shaper and another filter, and learn its parameters. Differentiable shapers and compressors make that learning a gradient descent. It is the best of both: few parameters, each one meaningful, fitted to the real device.

A research problem to end on. Take one amplifier and many settings of its knobs, and record input and output at each. Train one network conditioned on the knobs. Test it blind at settings it never saw, and measure its aliasing at forty-eight kilohertz. The question: how small can a model be that is indistinguishable at every setting, and free of aliasing? An answer would say how much of an amplifier the ear can hear.

Variation 50, recap and problemsAll tracks2 min

Every part ends by doing something to the Tune with what it built. Here, its first phrase sung a little out of tune; hard-tuned; vocoded onto a chord; and its first second stretched eightfold by the phase vocoder.

Row fifty of the ledger. As sung, the median pitch error is cents; after correction, . And one second became .

What did we find? A nonlinear shaper makes harmonics, and its symmetry decides which. Chebyshev sums produce selected harmonics for a unit-amplitude cosine, subject to digital bandwidth limits. Two tones make intermodulation whose perceived clarity depends on tuning, register and the shaper. Digital distortion aliases, and oversampling cures it best. Compressors, limiters, gates and sidechains are gains that follow levels. And PSOLA and the phase vocoder untie pitch from time, while correction snaps pitch to a scale.

Five problems. One to compute, one to prove, one for your ears, one to build, and a research problem, marked with a star. Solutions are in this part's notes. Pause here.

Where does this come back? In synthesis, with waveshaping and oscillators that do not alias. In physical models of nonlinear strings and reeds. In recording and mixing, where compressors go to work. In mastering, with limiters and the loudness war. And in pitch and transcription, finding pitch in recordings.

And in practice. Guitarists choose fifths under heavy distortion and full chords when clean. Mix engineers compress for density and set the attack for punch. Producers key a compressor from the kick, so the bass makes room. And vocal editors correct pitch gently, unless the snap is the point.

The books and papers this part follows. The full list, with notes, is in the README.

Where it goes next. Waveshaping and alias-free oscillators in Part 51; nonlinear physical models in Part 52; compressors in a mix in Part 56; limiters in Part 57; pitch tracking in Part 61.

Key results

The part's results in one place, for revision.

Chebyshev\(\displaystyle T_n(\cos\theta) = \cos n\theta\)
Intermodulation\(\displaystyle m f_1 \pm n f_2\)
Static curve\(\displaystyle y = T + (x - T)/R \quad\allowbreak (x > T + W/2)\)
Ring modulation\(\displaystyle \sin a \sin b = \tfrac12[\cos(a-b) - \cos(a+b)]\)
Phase vocoder\(\displaystyle \omega_k + \Delta\phi_k / H_a \Rightarrow \phi \mathrel{+}= \hat\omega_k H_s\)

Try it

Lab 50 · Dynamics, distortion and pitch, computed

Design a shaper by its harmonics, compress a groove and measure what changed, and correct an out-of-tune voice.

Figure produced by Lab 50: Dynamics, distortion and pitch, computed
Produced by the lab below, seed 0, in 3.9 s.
python -m videos.music.labs 50 needs numpy, scipy, matplotlib · download lab50.py · source on GitHub
Chebyshev shaper, full input: harmonics (dB re the fundamental)       0.0, -182.8, -6.0, -188.0, -12.0
the same shaper at half input                                         0.0, -189.0, -9.9, -204.5, -26.8
groove: loudness spread plain / compressed (dB, 20 ms windows)        9.3 / 4.9
crest factor plain / compressed (dB)                                  16.3 / 21.2
voice: median pitch error before correction (cents)                   18.7
ear problem: the last three are natural or hard-tuned (listen first)  natural, natural, hard-tuned

A shaper's harmonics depend on the input level; a compressor narrows the loudness spread while its attack can keep the transients; pitch correction is detection, a target, and a shift that keeps the formants.
The code (70 lines; it asserts its own result)
"""Lab 50: dynamics, distortion and pitch, computed: shapers and their harmonics, a compressor, and a pitch corrector."""

import numpy as np

from videos.coursekit import labs
from explainer.music.monochord import SR, Clip, concat
from explainer.music.monochord import dynamics as D
from videos.music.music50 import compute as C

TITLE = "Dynamics, distortion and pitch, computed"
GOAL = ("Design a shaper by its harmonics, compress a groove and measure what changed, and correct an out-of-tune voice.")
TASKS = [
    "Edit AMPS (harmonic amplitudes). Check the measured harmonics, then halve the input level and explain what moved.",
    "Change THRESHOLD, RATIO, ATTACK and RELEASE. Which setting most reduces the loudness spread? Which keeps the punch?",
    "Change DETUNE and SPEED_MS. At what speed does the corrected voice stop sounding like a singer?",
]
AMPS = [1.0, 0.0, 0.5, 0.0, 0.25]
THRESHOLD, RATIO, ATTACK, RELEASE = -24.0, 6.0, 3.0, 80.0
DETUNE, SPEED_MS = 0.45, 0.0


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    t = np.arange(SR) / SR
    x = np.cos(2 * np.pi * 220 * t)
    h = D.harmonics(D.cheb_shaper(AMPS, x), 220, SR, len(AMPS))
    lab.row("Chebyshev shaper, full input: harmonics (dB re the fundamental)", ", ".join(f"{v:.1f}" for v in h))
    h2 = D.harmonics(D.cheb_shaper(AMPS, 0.5 * x), 220, SR, len(AMPS))
    lab.row("the same shaper at half input", ", ".join(f"{v:.1f}" for v in h2))
    g = C.groove()
    r = D.compressor(g, SR, THRESHOLD, RATIO, 6, ATTACK, RELEASE)
    y = C.norm_rms(r["y"])
    lab.row("groove: loudness spread plain / compressed (dB, 20 ms windows)", f"{C.spread(C.norm_rms(g)):.1f} / {C.spread(y):.1f}")
    lab.row("crest factor plain / compressed (dB)", f"{D.crest_db(C.norm_rms(g)):.1f} / {D.crest_db(y):.1f}")
    v = C.sung(C.tune_notes(detune=DETUNE, seed=int(rng.integers(1000))))
    z, tt, f0, tg = C.correct_voice(v, SPEED_MS)
    ok = (f0 > 0) & (tg > 0)
    lab.row("voice: median pitch error before correction (cents)", f"{np.median(np.abs(1200 * np.log2(f0[ok] / tg[ok]))):.1f}")
    assert len(z) == len(v)

    # sound: compressed groove and corrected voice; ear problem: hard-tuned or natural, at random
    clips = [Clip(0.9 * y / np.max(np.abs(y)), SR), Clip(z, SR)]
    answers = []
    for i in range(3):
        vv = C.sung(C.tune_notes(detune=DETUNE, seed=int(rng.integers(1000))))
        if rng.random() < 0.5:
            clips.append(Clip(vv, SR))
            answers.append("natural")
        else:
            clips.append(Clip(C.correct_voice(vv, 0.0)[0], SR))
            answers.append("hard-tuned")
    lab.audio = concat(clips, gap=0.8)
    lab.row("ear problem: the last three are natural or hard-tuned (listen first)", ", ".join(answers))

    fig, (ax1, ax2) = labs.figure(2)
    ax1.bar(range(1, len(h) + 1), np.maximum(h, -80), color=labs.GOLD, label="full")
    ax1.bar(np.arange(1, len(h2) + 1) + 0.3, np.maximum(h2, -80), width=0.3, color="C0", label="half")
    ax1.set_xlabel("harmonic")
    ax1.set_ylabel("dB")
    ax1.legend(fontsize=7)
    ax2.plot(tt, np.where(f0 > 0, f0, np.nan), color="C7", label="sung")
    ax2.plot(tt, np.where(tg > 0, tg, np.nan), color="C3", label="target")
    ax2.set_xlabel("s")
    ax2.set_ylabel("Hz")
    ax2.legend(fontsize=7)
    lab.fig = fig
    lab.note = ("A shaper's harmonics depend on the input level; a compressor narrows the loudness spread while its attack "
                "can keep the transients; pitch correction is detection, a target, and a shift that keeps the formants.")
    return lab

Now change it

  1. Edit AMPS (harmonic amplitudes). Check the measured harmonics, then halve the input level and explain what moved.
  2. Change THRESHOLD, RATIO, ATTACK and RELEASE. Which setting most reduces the loudness spread? Which keeps the punch?
  3. Change DETUNE and SPEED_MS. At what speed does the corrected voice stop sounding like a singer?

Problems, with solutions

Try each problem before opening its solution.

  1. Compute. A compressor has threshold −20 dB, ratio 4 and no knee. What comes out for −8 dB in?

    Solution

    −8 is 12 dB over the threshold; at 4 : 1 that becomes 3 dB over: −20 + 12/4 = −17 dB out, a gain reduction of 9 dB.

  2. Prove. Prove that an odd shaper, f(−x) = −f(x), fed a pure tone, makes only odd harmonics.

    Solution

    Let x(t) = cos ωt and y(t) = f(x(t)). Shifting time by half a period, t → t + π/ω, turns cos ωt into −cos ωt, so y(t + π/ω) = f(−x(t)) = −y(t): the output is half-wave antisymmetric. Its Fourier coefficient at harmonic n picks up a factor e^{−inπ} = (−1)ⁿ under the shift, while the antisymmetry multiplies it by −1. So (−1)ⁿ = −1 for every non-zero coefficient: n is odd.

  3. Ear. The lab plays the Tune hard-tuned or natural, in random order; say which is which.

    Solution

    The lab prints them. The hard-tuned voice holds each note dead steady and jumps between notes with no scoop; the natural one drifts slightly within notes and glides between them.

  4. Build. Add a look-ahead to the compressor, so that no sample exceeds the threshold.

    Where to look. Delay the audio by L samples (a few milliseconds) and run the detector on the undelayed signal; take the maximum gain reduction needed over the next L samples (a sliding maximum) and smooth it with an attack no longer than L. With an infinite ratio, check that the delayed output never exceeds the threshold.

  5. ★ How small can a neural amplifier model be, indistinguishable at every setting and alias-free?

    Where the frontier is. Record one amplifier across a grid of knob settings; train networks of decreasing size, conditioned on the knobs; test them blind at unseen settings, and measure their aliasing at 48 kHz against oversampled and ADAA versions.

Notes and sources

Sources

  • U. Zölzer (ed.), DAFX: Digital Audio Effects (2nd ed., 2011); J. O. Smith, Spectral Audio Signal Processing (2011).
  • M. Le Brun, "Digital waveshaping synthesis", JAES (1979); D. Arfib, "Digital synthesis of complex spectra by means of multiplication of nonlinear distorted sine waves", JAES (1979).
  • J. D. Parker, V. Zavalishin and E. Le Bivic, "Reducing the aliasing of nonlinear waveshaping using continuous-time convolution", DAFx (2016); S. Bilbao, F. Esqueda, J. D. Parker and V. Välimäki, "Antiderivative antialiasing for memoryless nonlinearities", IEEE Signal Processing Letters (2017).
  • D. Giannoulis, M. Massberg and J. D. Reiss, "Digital dynamic range compressor design: a tutorial and analysis", JAES (2012).
  • J. L. Flanagan and R. M. Golden, "Phase vocoder", Bell System Technical Journal (1966); J. Laroche and M. Dolson, "Improved phase vocoder time-scale modification of audio", IEEE Trans. Speech and Audio Processing (1999); E. Moulines and F. Charpentier, "Pitch-synchronous waveform processing techniques for text-to-speech synthesis using diphones", Speech Communication (1990).
  • A. de Cheveigné and H. Kawahara, "YIN, a fundamental frequency estimator for speech and music", JASA (2002); H. A. Hildebrand, "Pitch detection and intonation correction apparatus and method", US patent 5,973,252 (1999).
  • H. Dudley, "Remaking speech", JASA (1939).
  • A. Wright, E.-P. Damskägg and V. Välimäki, "Real-time black-box modelling with recurrent neural networks", DAFx (2019); A. Wright, E.-P. Damskägg, L. Juvela and V. Välimäki, "Real-time guitar amplifier emulation with deep learning", Applied Sciences (2020).
About this partfrom its README

Part 50 of a sixty-eight-part course in music (see the series plan and the syllabus), the third part of Act IX, Electric Sound. Two celebrated production stories illustrate artifacts becoming musical resources. A damaged amplifier in 1951 gave rock its fuzz. In 1998 a pitch corrector, invented by a geophysicist who had used autocorrelation to find oil, was set to act instantly, and the sound of a voice snapping between notes became a style. This part builds the effects that are not linear, or that change with the signal: shapers and their harmonics, intermodulation and aliasing, compressors and their relatives, and the machinery that unties pitch from time. The tools are Monochord's (explainer/music/monochord/dynamics.py); the voice is Part 8's, the guitar and drums Part 40's.

  • Two accidents, two genres. An ear question (the Tune sung a little out of tune, then hard-tuned: which was corrected? A median 28 cents off, then 0.6); the pitch tracks; Rocket 88 and Believe; the plan.
  • 1. Nonlinearity makes new frequencies. New frequencies; three ways to bend (hard clip, tanh, cubic); what each bend adds (a 1 kHz sine driven three times past the bend: the hard clip's third at −11 dB, fifth −18.5, seventh −27.5); three bends heard on one guitar note; a riff clean and driven, heard; why only odd harmonics; valves, transistors and tape.
  • 2. Chebyshev's exact harmonics. Tₙ(cos θ) = cos nθ; a shaper built from its spectrum (asked for 1, ½, ¼ at harmonics 1, 3, 5: measured −6.02 and −12.04 dB, the even ones below −180); one shaper at three input levels, heard (at a quarter of full size the upper harmonics fade, while the third rises nearly to the fundamental); waveshaping synthesis.
  • 3. Intermodulation and the power chord. Two tones in, many out; a fifth and a third through tanh (products on multiples of 110 Hz and of 55); a power chord and a major chord distorted, heard; the difference tone.
  • 4. Aliasing in nonlinear effects. Harmonics that fold; an ear question (a sweep through a hard clip at 48 kHz and 8 times oversampled: which has tones moving the wrong way?); three ways to compute a shaper (alias energy −26.8 dB plain, −32.5 with antiderivative antialiasing, −47.3 oversampled); aliasing hides everywhere.
  • 5. Compressors. An automatic hand on the fader; the static curve (ratios 2, 4, 10, a 6 dB knee); attack and release (12 ms to 90 per cent; about 0.3 s to let go); release heard (pumping at 25 ms); an ear question (a groove plain and compressed at the same loudness: which?, the loudness spread 9.1 dB against 4.9); punch (the crest factor rises, 16.3 to 21.2 dB); what the compressor hears.
  • 6. Limiters, gates and sidechains. The family; a gate, heard; a sidechain ducking a pad, heard; more uses; looking ahead.
  • 7. Time and pitch. Pitch and time, tied; a fifth higher by resampling and by PSOLA, heard; PSOLA; speed and pitch in the studio; pitch and formants.
  • 8. Overlap-add and the phase vocoder. Overlap-add; the phase vocoder (Flanagan and Golden; Laroche and Dolson); the phrase stretched twice two ways, heard; limits and uses; extreme stretching; stretching at work.
  • 9. Pitch correction. Finding the pitch; YIN, step by step; the target at three speeds; three speeds heard; from repair to style; editing pitch by hand.
  • 10. Vocoders and ring modulation. Dudley's vocoder; what it sends (16 bands); the voice, the chord, vocoded and ring-modulated, heard; the talk box; the vocoder in music; ring modulation.
  • 11. Frontier: neural models of analog gear. Amplifiers learned; white, black and grey boxes; antialiasing nonlinearities; ★ research problem: how small can a neural amplifier model be, indistinguishable at every setting and alias-free?
  • Variation 50, recap and problems. The Tune sung, hard-tuned, vocoded and stretched eightfold; the ledger (28 cents sung, 0.6 corrected; one second stretched to 7.7); what we found; five problems; where it comes back; in practice; references; Part 51.
What is computed and built

python -m videos.music.music50.compute (under a minute) fills .cache/music50/.

Item What it computes Checked against
shapers, shapers3, cheblevels, fuzz harmonics of three shapers; Chebyshev's exact harmonics; a riff driven Tₙ(cos θ) = cos nθ (tests)
imd two-tone products for a fifth and a third common divisors 110 and 55 Hz (tests)
alias a clipped sweep; alias energy plain, by ADAA, 8× oversampled oversampling best (tests)
curves, comp, pump, gate, duck static curves; attack and release; loudness spread and crest; pumping; a gate; a sidechain the static gain (tests)
pitch, stretch resampling against PSOLA; overlap-add against the phase vocoder length and pitch kept (tests)
hook, correct, speeds YIN pitch tracks; correction targets at three speeds; PSOLA the scale notes (tests)
vocoder a 16-band channel vocoder and ring modulation —

Monochord's tools are held in tests/music/test_dynamics.py; this part's claims and clips in tests/music/test_music50.py.

Sounds. Part 8's voice (a source-filter model), Part 40's guitar, drums and pad, a plucked bass, sawtooth chords and sine tones, through this part's effects. The songs named (Rocket 88, Believe and others) are described, not played.

What the models are, and are not. The shapers are memoryless; real amplifiers filter before and after, and have memory. The compressor is one feedforward design with a peak detector; real units differ in detection and character. The pitch corrector is YIN, a nearest-note target and PSOLA; commercial correctors add formant handling, note-change detection and much else. The voice was sung out of tune on purpose, by random detuning of each note.

Notes

The Rocket 88 session predates Sun’s label; amplifier distortion depends on circuit, bias and level rather than device stereotypes. Modulated linear systems can create sidebands. Chebyshev harmonic control assumes a unit cosine and sufficient digital bandwidth. Intermodulation clarity is contextual, and finite oversampling reduces rather than guarantees elimination of aliasing. Compressor timing and RMS energy are not universal perceptual loudness models; limiter sample and true peaks differ. PSOLA only approximately preserves formants. Nearest-scale targeting is a heuristic, not intent recognition, and vocoder envelopes may retain pitch cues.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: an ear question (which was hard-tuned?); the pitch tracks; Rocket 88 and Believe; the plan.
  2. Nonlinearity: new frequencies; three bends; their harmonics; three bends heard; a riff driven; odd harmonics; devices.
  3. Chebyshev: the identity; a shaper built from its spectrum; three input levels heard; waveshaping synthesis.
  4. Intermodulation: two tones in; a fifth and a third measured; the power chord heard; the difference tone.
  5. Aliasing in nonlinear effects: harmonics that fold; an ear question (a clipped sweep); three ways to compute; everywhere.
  6. Compressors: the idea; static curves; attack and release; pumping heard; an ear question (which was compressed?); punch; detectors.
  7. Limiters, gates and sidechains: the family; a gate heard; a sidechain heard; uses; look-ahead.
  8. Time and pitch: tied; resampling and PSOLA heard; PSOLA; history; formants.
  9. Overlap-add and the phase vocoder: OLA; the phase vocoder; two stretches heard; limits; extreme stretching; uses.
  10. Pitch correction: detection; YIN; the target at three speeds; three speeds heard; repair to style; editing by hand.
  11. Vocoders and ring modulation: Dudley; the bands; four sounds heard; the talk box; in music; ring modulation.
  12. Frontier: neural amplifier models; grey boxes; antialiasing; the research problem.
  13. Variation 50: the Tune sung, hard-tuned, vocoded and stretched. Outro: problems, payoffs.

Covers: nonlinearity and new frequencies; Chebyshev waveshaping; intermodulation and the power chord; aliasing in nonlinear effects; compressors, limiters and gates; sidechains; time and pitch: resampling, overlap-add, the phase vocoder, PSOLA; formants; pitch correction; vocoders and ring modulation. Built and computed: monochord/dynamics.py: shapers and their harmonics; a Chebyshev shaper with exact harmonics (−6.02 and −12.04 dB as asked); intermodulation (products on 110 Hz for a fifth, 55 for a third); aliasing measured (−26.8 dB plain, −32.5 with ADAA, −47.3 oversampled); a feedforward compressor with measured curves (12 ms attack; a groove's loudness spread 9.1 to 4.9 dB); a gate and a sidechain; overlap-add and a phase vocoder with phase locking; YIN; PSOLA; a pitch corrector for Part 8's voice (28 cents to 0.6); a 16-band vocoder; ring modulation. Variation 50: the Tune sung, hard-tuned, vocoded and stretched eightfold (one second to 7.7). Frontier: neural models of analog gear; antialiasing nonlinearities (open: the smallest alias-free model that passes). Reading: Zölzer; Giannoulis, Massberg & Reiss (2012); Laroche & Dolson (1999).

Build the film

python -m videos.music.music50.compute        # the part's numbers, into .cache/music50
python tools/build.py music50                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py music50 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/music/music50. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.music.music50.compute                          # numbers and sounds (under a minute)
EXPLAINER_TTS=silent python tools/build.py music50 -q l --fps 15   # a silent-narration preview, with the sounds
python tools/qa_sound.py music50 --sync                         # the sound gates
python tools/dead_air.py renders/music50_480p.mp4 --sound music50  # no empty screen; no sound over a still one
python tools/lecture_length.py music50                          # 30 to 60 minutes, listening included
python tools/build.py music50                                   # 1080p30, narrated
python -m pytest -q tests/music                                 # Monochord against its references; this part's claims and clips
python -m videos.music.labs 50                                  # the lab (writes a figure and a short WAV)