Act X · The Studio and the Stage
Part 58 of 68Compression for the Ear
How can a file a tenth the size of a recording sound the same, and how would anyone prove it does?
Brandenburg tuned the first MP3 coder on Suzanne Vega's voice alone; an ear question hears the Tune sung alone as recorded and through Monochord's own perceptual coder at 64 kbit/s (a twelfth the size, its noise 16 dB under the mask) and 16 (18 dB over). Two kinds of compression. Entropy, prediction (the voice from 13 to 3.5 bits a sample), Rice codes, and a lossless coder that rebuilds every bit (voice 23 per cent, mix 55). Masking: Schroeder's spreading, Johnston's tonality offsets, the threshold in quiet; one frame's mask; an ear question hears white and mask-shaped noise at the same power (the shaped noise only 10 dB under the music, hidden). The MDCT, one frame's aliases and their cancellation to 1e-13, heard by dropping alternate frames. A perceptual coder: step sizes from the mask, a margin found by bisection, Rice-coded bands; the voice and the mix at five rates (the mix 19 dB under the mask at 128 kbit/s, 18 over at 16), heard. Pre-echo: at equal noise-to-mask, long blocks leave 5.5 dB more noise before each hit and short ones cost three times the bits (an ear question); window switching. Mid-side coding about 4 dB better at the same bits, heard. MP3, AAC, Vorbis, HE-AAC and Opus; the business. Listening tests: an ABX trial, binomial thresholds (12 of 16), the power (a 70 per cent listener passes 16 trials 45 per cent of the time), BS.1116 and MUSHRA. Five generations of transcoding (SNR 8.5 to about 2 dB), heard. Residual vector quantization in stages (5 dB each), heard; neural codecs; learned metrics. The Tune at five rates, and the residue alone.
What you need. Part 4 for masking, critical bands and the threshold in quiet; Part 48 for sampling and quantization; Part 49 for filters and the FFT; Part 55 for stereo cues; Part 57 for true peaks and level-matched comparison. Entropy, the binomial distribution, linear algebra of a transform, k-means.
- Ideas, mathematics and history
- lossless coding, masking thresholds, the MDCT and its cancelling aliases, MP3 to Opus, listening tests, neural codecs
- What we build, compute and hear
- a lossless coder and a perceptual codec; the sound the codec throws away
What you will be able to do
Foundations
- Hear a lone voice at 64 and 16 kbit/s against the original, and the voice at five rates.
- Hear white and mask-shaped noise of equal power, pre-echo with long and short blocks, and an ABX trial.
- Hear left-right against mid-side coding, five generations of transcoding, and vector quantization in stages.
Full course
- Compute entropy and code prediction residuals with Rice codes, and decode them bit for bit.
- Prove the MDCT's alias cancellation and build a masking model with spreading, tonality and quiet.
- Allocate bits by step sizes under rate control, and compute an ABX test's threshold and power.
Research
- Find whether a learned metric can predict ratings for a kind of codec it never saw in training.
Practice
- Choose codecs and rates for delivery, keep lossless masters, avoid transcoding, and run fair listening tests.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Foundations 21 min · Full course 35 min · Research 37 min · Practice 35 min.
- 0A voice that sounded dreadfulFoundations3 min
- 1Entropy and lossless codingPractice4 min
- 2What the ear cannot hearFoundations3 min
- 3The MDCTPractice3 min
- 4A perceptual coderPractice3 min
- 5Window switching and pre-echoFoundations2 min
- 6Stereo codingFoundations2 min
- 7MP3, AAC and OpusFoundations4 min
- 8Listening testsFoundations2 min
- 9GenerationsFoundations2 min
- 10Vectors and residualsPractice3 min
- 11Frontier: neural codecs and learned metricsResearch2 min
- Variation 58, recap and problemsAll tracks3 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.
A voice that sounded dreadfulFoundations3 min
In the 1980s Karlheinz Brandenburg, at Erlangen in Germany, was coding music for digital telephone lines. Begin with a voice. The Tune's first phrase, sung alone, three times: once as recorded, and twice through a codec that throws most of the data away. Which was the original?
The second. The original is sixteen-bit samples at forty-eight kilohertz: seven hundred and sixty-eight kilobits a second. The third was our codec at sixteen kilobits, an estimated coding budget one forty-eighth of the PCM rate, and you could hear it: its noise rises above what the voice can hide. But the first was the same codec targeting sixty-four; its estimated rate here is about kilobits a second. If you could not tell it from the original, that is the whole idea of this part: substantial data reduction can be perceptually subtle under suitable conditions; this demonstration does not prove transparency. Our perceptual coder estimates coded lengths rather than serializing a complete bitstream.
The question has a famous history. In the 1980s, at Erlangen in Germany, Karlheinz Brandenburg was working on coding music for digital telephone lines. His codec coped with orchestras and rock, and failed on one recording: Suzanne Vega's Tom's Diner, a voice alone. A voice alone has nothing to hide the coding noise behind, and he has said he listened to it over and over while tuning the coder. The result became MPEG-1 Audio Layer Three, standardized between 1991 and 1993, and from 1995 its files ended in dot m p three. In 1999 came Napster: small files and peer-to-peer distribution disrupted the record industry alongside other economic and technological changes.
There are two kinds of compression. Lossless coding removes redundancy: what can be predicted need not be sent, and music usually halves. Perceptual coding removes irrelevance: what cannot be heard need not be sent, and music shrinks to a tenth or less. The second needs a model of hearing, Part 4's masking, applied band by band and frame by frame, and a transform in which to spend the bits where they will be heard.
Here is the plan. Entropy, prediction, and a lossless coder that rebuilds every bit. Masking thresholds, computed frame by frame. The modified discrete cosine transform, and why its aliases cancel. A perceptual coder of our own: bit allocation, rate control, pre-echo and stereo. MP3, AAC and Opus, and listening tests with their statistics. And transcoding, vector quantization, and the neural codecs at the frontier.
1Entropy and lossless codingPractice4 min
How small can a recording get without losing a single bit?
Start with the limit. Claude Shannon proved in 1948 that for uniquely decodable lossless codes under the stated source model, expected length is bounded by entropy; sample correlations require entropy-rate reasoning: minus the sum of p log p. A fair coin has one bit of entropy; a coin that lands heads nine times in ten, under half a bit. Sixteen-bit samples spend sixteen bits each, but their empirical sample-value entropy can be lower, because common values can be given short codes. And it falls much further once we stop coding the samples, and code only what we could not predict.
Audio is predictable from one sample to the next. Here are four hundred samples of our voice. Predict each one by continuing the straight line through the two before it, two x n minus one minus x n minus two, and keep only the error: the residual, on the same scale, is tiny. Send the first samples and the residual, and the decoder makes the same predictions and adds the errors back, exactly.
How much does prediction save? Here is the entropy of the residual for predictors of order nought to four, Tony Robinson's fixed predictors from his coder Shorten of 1994: nought is the samples themselves, one the previous sample, two a straight line, three a parabola, four a cubic. Our smooth synthetic voice falls from thirteen bits a sample to three and a half; the busy mix, full of drums and noise, only to nine and a half, at order two. Predictability is a property of the music.
Then the residual must be written in as few bits as possible. It is small and symmetric about zero, so first fold it onto the counting numbers: nought, minus one, one, minus two, and so on. A Rice code with parameter k writes a number's top bits in unary, as a run of zeros and a one, and its low k bits as they are. Thirteen, with k equal to two, is three fours and one: three zeros and a one, then nought one. Choose k for each block to fit the residual's size, and the code comes close to the entropy for the two-sided exponential shape that residuals have. Solomon Golomb found the family in 1966 and Robert Rice its simple case in 1979; FLAC, since 2001, does exactly this with better predictors.
Monochord's lossless coder puts it together: blocks of four thousand and ninety-six samples, the best of the five predictors for each block, Rice codes for the residual. The voice shrinks to per cent of its size, the mix to , and the decoder rebuilds every sample, bit for bit. Half the size is about what lossless coding does for real music. To go further, we have to stop sending what cannot be heard.
Real lossless coders go a little further. FLAC and MPEG-4 ALS fit a predictor to each block: linear prediction of orders limited by the format; FLAC supports up to thirty-two, while ALS supports substantially higher orders, by the Levinson-Durbin recursion. The coefficients are quantized and sent with the block, and the decoder runs the same filter in integer arithmetic, so the result is still exact. For stereo they predict one channel from the other, or code the difference. The best reach forty to sixty per cent of the original on music; and independent uniformly distributed full-resolution noise offers little lossless compression; colored or otherwise structured noise can be predictable.
2What the ear cannot hearFoundations3 min
How much noise can a piece of music hide?
A perceptual coder rests on Part 4. A sound raises the threshold for other sounds in its critical band, and a little beyond. So in every band of every frame there is a level of noise this simplified model predicts may be masked: the masking threshold. A coder may put its errors anywhere below that level, and nowhere above it. The model needs four ingredients: critical bands, how masking spreads across them, whether the masker is a tone or noise, and the threshold in quiet.
How far does masking reach? On the Bark scale, where each unit is one critical band, Manfred Schroeder fitted this curve in 1979: steep below the masker, about twenty-five decibels a band, shallow above it, about ten, so low sounds mask high ones much more than the reverse. James Johnston's model of 1988 then lowers it by an offset: a tone hides noise poorly, so the threshold sits fourteen and a half plus the band number decibels below a tone, but only five and a half below noise. Our coder judges how tonal each frame is from its spectral flatness, and blends the two. And no threshold goes below the threshold in quiet, Part 4's curve.
Here is the model at work on twenty-one milliseconds of our mix. In grey, the frame's spectrum. In gold, the noise allowed in each critical band: the band energies spread, lowered by the tonality offset. In blue, the threshold in quiet, which takes over at the top. Everything between the grey and the gold is room for noise this simplified model predicts may be masked; and this model may allocate very few bits there; real audibility still depends on model accuracy, temporal structure and listening conditions.
Your turn. Our mix twice, with exactly the same amount of noise added each time: once plain white noise, once noise shaped band by band to the masking threshold. In which can you hear the noise?
The first, the white noise, hisses over everything. The shaped noise has the same power, only decibels below the music, and yet it is very hard to hear, because every band of it hides behind the music in that band. A perceptual coder's errors are noise of the second kind.
Masking reaches across time as well. A loud sound hides quieter ones after it for up to about a hundred milliseconds. And, oddly, before it, but only for a few milliseconds. A coder's frames last tens of milliseconds, so quantization error spread through a frame can land before an attack, where nothing hides it. That is pre-echo, the subject of Chapter 5.
3The MDCTPractice3 min
How can a transform overlap its frames and still send no extra numbers?
A perceptual coder works on the spectrum, because masking is decided band by band. Its frames must overlap and be windowed, or the edges between them will click once the coefficients are made coarse. But overlapping by half normally doubles the numbers: a Fourier transform of two N samples every N samples gives two N values for every N new ones. John Princen and Alan Bradley found in 1986 a transform of two N samples to only N coefficients, overlapped by half, that still rebuilds the signal exactly.
Here it is. The modified discrete cosine transform takes a frame of two N samples, windowed, and returns N coefficients, one for each of these windowed cosines: successive half-integer frequency bins, shifted by a quarter frame. The window is a sine, chosen so that the squares of its two halves add to one. The transform appears in MP3 and AAC and in Opus's CELT path; Opus's SILK path uses predictive coding.
But N numbers cannot hold two N samples. Take one frame, windowed, in grey, and send it through the transform and back on its own, in orange. It is not the frame: each half has come back with its own mirror image added to it, the first half reflected with one sign, the second with the other. This error is called time-domain aliasing.
Now overlap the frames by half, window them again, and add. In each overlap, one frame's second half and the next frame's first half carry the same alias with opposite signs, and the window's squares add to one. So the sum is the signal itself. Here, in gold over grey, a signal rebuilt from its MDCT frames: the largest error is times ten to the minus fifteen, and on our whole mix about ten to the minus thirteen: the limit of the computer's arithmetic. Time-domain aliasing cancellation, TDAC: N new coefficients for N new samples, and nothing lost.
Hear the aliases: our mix rebuilt from all its frames, then from every other frame alone, so that no alias has a partner to cancel it.
The first is the mix exactly. The second flutters and smears, every note followed by a reversed ghost: the aliases a coder relies on its neighbours to cancel. A coarse coder leaves a little of this behind.
Seen another way, the MDCT is a filter bank. With a thousand and twenty-four coefficients at forty-eight kilohertz it is a bank of a thousand and twenty-four filters, each twenty-three hertz wide, refreshed every twenty-one milliseconds. Critical bands are a hundred hertz wide in the bass and several kilohertz in the treble, so the coder groups bins into bands to match the ear. The sine window's filters leak into their neighbours; AAC also offers a Kaiser-derived window, sharper, for tonal music. And the same transform run on shorter frames trades that frequency resolution for time, which is the next chapter's subject.
4A perceptual coderPractice3 min
How do you spend a fixed number of bits where the ear will notice?
Here is the coder this part builds, the shape of every perceptual codec. The signal is cut into MDCT frames of two thousand and forty-eight samples, a new frame every twenty-one milliseconds. The masking model looks at each frame and says how much noise each band can hide. Each band is quantized with a step size from that allowance, and Rice-code lengths are estimated with a fixed per-band overhead. And a rate control turns one knob for the whole signal until the estimated bits fit the budget.
The bit allocation is hidden in the step sizes. Under a high-resolution, approximately uniform error model, a quantizer of step delta has error variance delta squared over twelve; coarse, signal-dependent quantization can depart from this. So choose each band's step to put its noise exactly at the band's allowance, and then lower it by a margin, m decibels, the same for every band. A positive margin puts the noise below the mask; a negative one above it, where it can be heard. Our rate estimate charges six bits per scale factor plus Rice-code costs; the teaching implementation does not serialize or quantize these scale factors into a complete interoperable bitstream; bands where everything quantizes to zero cost almost nothing, and that is where most of the saving comes from.
Then the rate control. Find the one margin that makes the whole signal fit the bit rate, by bisection. With plenty of bits the margin is positive, and the noise sits under the mask everywhere: the model predicts low audibility; transparency requires controlled listening tests. With too few, the margin goes negative, and the noise rises above the mask in band after band. Real coders also cut off the top of the spectrum at low rates, spending nothing above nine to sixteen kilohertz, and keep a reservoir of bits so that hard frames can borrow from easy ones.
Here is our coder on the voice alone and on the mix, at five bit rates. At a hundred and twenty-eight kilobits both are far under the mask. At sixty-four the voice still has sixteen decibels to spare, the busy mix only three. At thirty-two the mix's noise is above the mask in most of its bands, and at sixteen seventeen decibels above. The voice alone is the easier signal for this coder, because its spectrum is sparse and its bits go a long way; but where a coder does fail on a lone voice, nothing else is playing to hide the failure, which is what made Tom's Diner such a good test.
Hear the voice alone at the five rates, from a hundred and twenty-eight kilobits down to sixteen.
The first two may sound close to the original; we have not established indistinguishability in a listener study; at thirty-two a faint roughness appears; at twenty-four and sixteen the voice turns watery and metallic, the sound of a coder starved of bits.
5Window switching and pre-echoFoundations2 min
Why does a codec smear a castanet?
Every transform trades time for frequency. A long block, forty-three milliseconds here, resolves the spectrum finely, so the coder can follow the mask band by narrow band. But its quantization error can spread across the transform window, including before an attack. Put a castanet hit in the middle of a block, and its coding noise arrives up to twenty milliseconds before the hit, in silence. Pre-masking hides only a few milliseconds of that; the rest is heard as a swish before each attack: pre-echo.
Here is the coding error around one castanet hit, magnified eight times, with the hit in grey behind. With long blocks the error starts long before the hit: decibels below the hit, in the fifteen milliseconds before it. With short blocks of five milliseconds it starts just before, decibels down. But both put their noise right at the mask, and the short blocks need three times the bits to do it, because each one carries its own scale factors and resolves the spectrum coarsely.
Your turn. Castanet-like hits through our coder twice, once with long blocks and once with short ones. Which had a swish before each hit?
The first, with long blocks: each hit is preceded by a soft smear, as if the castanet were being rubbed before it is struck. Listen for it on headphones; it is subtle on loudspeakers.
The cure is to switch. Use long blocks for steady sound, and eight short blocks the moment an attack is detected. The window's shape must change smoothly, through start and stop windows, so that the aliases still cancel. Common AAC-LC modes use two-thousand-and-forty-eight-sample long windows and two-hundred-and-fifty-six-sample short windows; other frame configurations exist; MP3 between five hundred and seventy-six and a hundred and ninety-two, inside a filter bank; Opus uses frames of two and a half to twenty milliseconds. AAC adds temporal noise shaping, a prediction across frequency that shapes the noise in time within a long block. And the bit reservoir pays for the expensive short blocks from the cheap frames around them.
6Stereo codingFoundations2 min
Why code two channels when most of the music is in both?
Stereo doubles the data, but not the information. Left and right share most of a mix: the voice, bass and drums sit in the centre, in both. So code their sum and difference instead, the mid and the side. In our mix the side carries decibels less energy than the mid. The quiet side needs far fewer bits, and the mid gets the rest. It is Blumlein's mid-side of 1931, from Part 56, put to work saving bits.
Here is our stereo mix at sixty-four kilobits in all. Coded as two channels of thirty-two, each comes back with a signal-to-noise ratio near decibels. Coded as a mid of kilobits and a side of , each channel comes back about four decibels better, from the same number of bits.
Hear both, with headphones: left and right coded apart, then mid and side. The first is rough, and the noise in its two channels is unrelated, so it spreads around the head away from the music. The second is cleaner, its noise sitting in the centre with the voice that masks it.
Coders go further. They switch per band and per frame: mid-side where the channels agree, left-right where they do not. Intensity stereo sends a single channel above a few kilohertz, with a level ratio per band, since the ear locates high sounds by level. And parametric stereo, in HE-AAC version two of 2006, sends one channel plus a few kilobits of cues: level and time differences and how alike the channels are. They are Part 55's two cues, sent as numbers instead of as sound.
7MP3, AAC and OpusFoundations4 min
What did each generation of codec add?
Real codecs are elaborations of ours. MP3, standardized in 1993, splits the signal into thirty-two bands and then applies a short MDCT within each. AAC, from 1997, uses the MDCT alone, with long and short blocks. Vorbis, from 2002, did the same, free of patents. HE-AAC, from 2003, added spectral band replication. And Opus, from 2012, joins a speech coder to an MDCT coder with a minimum algorithmic delay around five milliseconds in suitable modes, before transport, buffering and hardware delays. Later codecs often improve quality at a given rate; no rate guarantees transparency for every encoder, excerpt or listener: roughly a hundred and ninety-two kilobits for MP3 in stereo, a hundred and twenty-eight for AAC, less again for Opus, though the figures depend on the music and on the encoder.
MP3 shows its history. It keeps the thirty-two-band polyphase filter bank of Layers One and Two, and adds an MDCT inside each band: a hybrid. Its psychoacoustic model runs on its own Fourier transform, beside the coding path. It uses Huffman codes, a bit reservoir and joint stereo. Its filter bank leaks between bands, patched by little butterflies of arithmetic: the price of compatibility. And only the decoder is standardized, not the encoder, so MP3 kept improving long after 1993: the open-source LAME encoder, from 1998, made it far better than its first encoders.
AAC started over. A clean MDCT of a thousand and twenty-four coefficients, with window switching and two window shapes. Temporal noise shaping for attacks, and prediction and noise substitution in later profiles. Spectral band replication, in HE-AAC: send only the lower half of the spectrum, and a few bits telling the decoder how to rebuild the top half from it, which works because high harmonics resemble low ones. AAC became the codec of the iTunes Store in 2003, of YouTube, digital radio and most phones.
Opus came from the internet. Standardized by the IETF in 2012, open and royalty-free, from six to five hundred and ten kilobits. It contains SILK, a speech coder by linear prediction from Skype, and CELT, a low-delay MDCT coder from Xiph, and uses either or both. CELT codes each band's energy explicitly and the band's shape as a point on a sphere, so even at low rates the energy in every band is right, and the ear forgives the detail. With as little as five milliseconds of delay, musicians can play together over a network, which Part 59 will want.
And the business. In 1999 Napster let millions of people trade MP3s for nothing, and the record industry's revenue began a fall that lasted fifteen years. In 2001 the iPod put a thousand songs in a pocket; in 2003 the iTunes Store sold them at ninety-nine cents each, in AAC. From 2008, streaming, Spotify in Ogg Vorbis and later others in Opus and AAC at several rates. A codec decided what music cost to copy, and so what it cost to buy, as Part 60 will follow.
8Listening testsFoundations2 min
How do you prove that nobody can hear a difference?
An ABX trial, for you. A is the Tune as sung. B is the same through our coder at thirty-two kilobits. X is one of the two. Is X A, or B?
X was B. But one right answer proves nothing: someone guessing gets it right half the time. The proof is in counting.
So repeat the trial, and count. If the listener hears no difference, each answer is a coin toss, and the number right follows the binomial distribution. Call the result significant when a guesser would do as well less than one time in twenty. In eight trials that needs seven right; in sixteen, twelve; in a hundred, fifty-nine. These thresholds assume a preplanned, one-sided test with independent fair guesses; repeated or adaptive testing needs adjustment, which Part 67 will take further.
The other side of the test is its power: the chance it detects a listener who really can hear the difference. A listener right nine times in ten passes almost any test. But a listener right seven times in ten, who certainly hears something, passes a sixteen-trial test only per cent of the time, and needs fifty trials to be found reliably. So a failed short test does not show that a difference is inaudible; it means this test did not establish discrimination; sample size, listener ability, excerpt and test conditions all matter.
Codecs are judged by formal tests. The ITU's BS.1116, from 1994, is for small impairments: a hidden reference, a five-point scale, trained listeners and a quiet room. MUSHRA, BS.1534 from 2001, compares several systems at once against a hidden reference and a low-passed anchor, on a scale of nought to a hundred. Listeners are screened: exclusion criteria are specified by the test protocol and applied with care; a low reference rating alone is not a universal rule. The results are reported with confidence intervals across listeners and pieces of music, never as one number. Every codec of the last chapter was tuned by tests like these; objective measures came later, and learned ones later still.
9GenerationsFoundations2 min
What happens when a compressed file is compressed again?
Files are often compressed more than once: downloaded, edited, uploaded, streamed. A decoded file is not the original; it carries the first coder's noise, shaped to the first coder's masks. A second coder computes its own masks from that signal, and adds its own noise on top. Worse, the first noise is now part of the music, to be coded as faithfully as the music itself, with bits the music needed. And frames that do not line up put new errors where the old ones were hidden.
Here is our mix through our coder at kilobits, decoded and re-encoded five times. The signal-to-noise ratio against the original falls from decibels after one generation to about two by the fourth and fifth: the noise is now nearly as strong as the music, and much of it is no longer under any mask.
Hear one generation, then five. The fifth generation is hollow and gurgling, the cymbals turned to swirling noise: errors coded as if they were music.
The practice follows. Keep a lossless or high-resolution master, and make every lossy file from it, once. Never edit a lossy file and re-encode it if the master exists. Streaming services ask for twenty-four-bit masters and encode them themselves, at each rate they offer. And leave Part 57's true-peak margin, because decoded peaks can change across encodings; overshoot is not guaranteed to increase monotonically.
10Vectors and residualsPractice3 min
What if the codec learned its own alphabet?
There is another way to spend bits. Scalar quantization rounds each number on its own. Vector quantization codes several numbers at once, as the index of the nearest entry in a codebook. The codebook is learned from examples by k-means, Stuart Lloyd's algorithm of 1957, as Linde, Buzo and Gray applied it to coding in 1980. Here: eight neighbouring MDCT coefficients at a time, divided by their band's level, and a codebook of two hundred and fifty-six entries, so eight bits for eight numbers. But one codebook of two hundred and fifty-six cannot be fine, and a codebook of two to the fortieth is impractical to search exhaustively in this simple implementation.
Residual vector quantization solves both problems. Code the vector with the nearest of two hundred and fifty-six entries. Then code what that missed, the residual, with a second codebook trained on residuals, and what that missed with a third. Each stage adds eight bits and refines the last, and the decoder can stop after any stage: a bit rate chosen by how many stages are sent.
Here it is on our mix, with codebooks trained on two other phrases of the Tune. Each stage cuts the error in the coded vectors by about five decibels, from minus six after one stage to minus thirty-seven after eight. The mix's signal-to-noise ratio rises from seven decibels to about twenty-two, where it levels off, because this little coder never sends anything above fifteen kilohertz.
Hear one stage, three and eight. With one stage the band levels are right but every detail is a guess from the codebook; with eight, the mix is back, a little dull at the top.
This is where the field has gone. Neural codecs replace the MDCT with a learned encoder, and its inverse with a learned decoder. Between them sits residual vector quantization of the learned features, as in Google's SoundStream of 2021 and Meta's EnCodec of 2022. They are trained end to end, with a second network as critic, judging whether the decoded audio sounds real. They code speech in three kilobits a second, and music in six to twenty-four, with promising low-rate quality in reported tests; comparisons depend on content, models, latency and evaluation conditions. And their codes are tokens: the alphabet in which the generative audio of Part 66 writes.
11Frontier: neural codecs and learned metricsResearch2 min
Can a machine judge what a listener will hear?
Neural codecs change what a codec error is. Neural codec errors can include noise, altered detail and plausible reconstruction artifacts; when it lacks bits it invents plausible detail. Invented detail can pass a listening test, because it sounds real, though it is not what was played. These codecs fail differently on music unlike what they were trained on: unusual instruments, tunings and voices. They cost far more computation than an MDCT coder, though less every year. Fidelity and plausibility have come apart, and reference-based tests assess fidelity as well as quality, while plausibility without a reference is a different task.
And the measures. Listening tests are slow and costly, so coders are tuned by objective measures between them. PEAQ, the ITU's BS.1387 of 1998, runs an ear model over the coded signal and the reference and predicts the test score. ViSQOL and others compare spectro-temporal patterns, fitted to listening data. Learned metrics are networks trained on thousands of ratings: excellent on errors like those they saw, unreliable on new kinds. And optimizing a metric can exploit its blind spots, so independent evaluation is needed.
A research problem to end on. Collect MUSHRA ratings for classical and neural codecs on varied music, including music unlike any training set. Train metrics on some codecs, and test them on codecs they have never seen. Measure how well each predicts the listeners, with confidence intervals, codec by codec. The question: can a learned metric predict listeners' ratings for a kind of codec that did not exist when it was trained? An answer would decide whether codecs can safely be trained against metrics.
Variation 58, recap and problemsAll tracks3 min
Every part ends by doing something to the Tune with what it built. Here our session plays it through our coder at five bit rates, from a hundred and twenty-eight kilobits down to sixteen; and then you hear what the thirty-two kilobit version threw away, alone.
Row fifty-eight of the ledger. From a hundred and twenty-eight kilobits, where the noise sits decibels under the mask, to sixteen, where it is decibels over it. And the residue, heard alone, is a ghostly copy of the music: everything the coder decided you would not miss.
What did we find? Entropy bounds lossless coding, and prediction with Rice codes reaches about half the size. A masking model gives each band of each frame the noise it can hide. The MDCT overlaps its frames by half yet sends N numbers for N samples, because its aliases cancel. Step sizes come from the mask, one margin from the bit rate; short blocks fight pre-echo, and mid-side saves bits. ABX tests count right answers, and need many trials to find a subtle difference. Generations compound errors, and vector quantization leads to the neural codecs.
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 live sound, with low-delay codecs on stage and online. In the business of music, changed by these files. In finding music, with fingerprints that survive a codec. In generative audio, which writes in codec tokens. And in research, with listening tests and their statistics.
And in practice. Keep lossless masters, and make every lossy file from them, once. Deliver music in AAC or Opus at a hundred and twenty-eight kilobits or more, with a true-peak margin. Judge codecs blind, level-matched, with enough trials and a hidden reference. And test them on a lone voice or castanets, useful stress material alongside varied music and listening conditions.
The books and papers this part follows. The full list, with notes, is in the README.
Where it goes next. Low-delay codecs on stage in Part 59; the files that changed the business in Part 60; fingerprints that survive a codec in Part 63; codec tokens as generative audio's alphabet in Part 66; listening tests and their statistics in Part 67.
Key results
The part's results in one place, for revision.
Try it
Lab 58 · Compression for the ear, computed
Compress a sound losslessly and get every bit back, check that the MDCT's aliases cancel, compute a masking threshold, code a sound at several bit rates with a perceptual coder, and work out how many ABX trials it takes to find a subtle difference.
python -m videos.music.labs 58
needs numpy, scipy, matplotlib · download lab58.py ·
source on GitHublossless: size against 16-bit PCM, exact? 73 %, True
MDCT, N = 1024: largest error after overlap-add 1.1e-13
one frame: tonality (0 noise, 1 tone), bands 0.29, 24
coded at 96 kbit/s: rate reached, margin to the mask, SNR 94.7, +6.9 dB, 13.2 dB
coded at 48 kbit/s: rate reached, margin to the mask, SNR 39.8, -8.8 dB, 2.1 dB
coded at 24 kbit/s: rate reached, margin to the mask, SNR 23.3, -10.3 dB, 1.0 dB
coded at 12 kbit/s: rate reached, margin to the mask, SNR 11.9, -13.0 dB, 0.3 dB
ABX: right answers needed in 16; power for a listener right 70 % 12, 45 %
ear problem: after the original, the four coded versions: their bit rates? (listen first) 24, 96, 48, 12
Lossless coding removes what can be predicted; perceptual coding removes what cannot be heard, by putting its noise under a masking threshold computed band by band; the MDCT makes that possible without sending extra numbers; and a listening test needs enough trials to see a small difference.
The code (78 lines; it asserts its own result)
"""Lab 58: compression for the ear, computed: a lossless round trip, the MDCT's alias cancellation, a masking
threshold, a perceptual coder at several bit rates, and the power of an ABX test."""
import numpy as np
from videos.coursekit import labs
from explainer.music.monochord import SR, Clip, concat
from explainer.music.monochord import codec as K
TITLE = "Compression for the ear, computed"
GOAL = ("Compress a sound losslessly and get every bit back, check that the MDCT's aliases cancel, compute a masking "
"threshold, code a sound at several bit rates with a perceptual coder, and work out how many ABX trials it takes "
"to find a subtle difference.")
TASKS = [
"Change RATES. Where does the margin to the mask go negative, and what do you hear when it does?",
"Change N (the MDCT size). Do the aliases still cancel? What happens to the masking threshold's detail?",
"Change P_TRUE and TRIALS. How many trials does a listener who is right 65% of the time need to be found 80% of the time?",
]
RATES = [96, 48, 24, 12]
N = 1024
P_TRUE, TRIALS = 0.7, 16
def tone_mix(seconds=2.5, seed=0):
rng = np.random.default_rng(seed)
t = np.arange(int(seconds * SR)) / SR
x = sum(np.sin(2 * np.pi * f * t) / (i + 1) for i, f in enumerate((220, 330, 440, 660, 880))) * 0.12
x += 0.02 * rng.standard_normal(len(t)) * (1 + np.sin(2 * np.pi * 2 * t))
return x * np.clip(t / 0.02, 0, 1)
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
x = tone_mix(seed=seed)
s = np.round(x * 32767).astype(np.int64)
e = K.lossless_encode(s)
ok = np.array_equal(K.lossless_decode(e["data"]), s)
lab.row("lossless: size against 16-bit PCM, exact?", f"{100 * e['bits'] / (16 * len(s)):.0f} %, {ok}")
assert ok
y = K.frames_imdct(K.frames_mdct(x, N), N, len(x))
lab.row(f"MDCT, N = {N}: largest error after overlap-add", f"{np.max(np.abs(y - x)):.1e}")
assert np.max(np.abs(y - x)) < 1e-9
m = K.mask(K.frames_mdct(x, N)[10], N)
lab.row("one frame: tonality (0 noise, 1 tone), bands", f"{m['alpha']:.2f}, {len(m['bands'])}")
coded = {}
for kb in RATES:
r = K.encode(x, kb, N=N)
coded[kb] = r["y"]
snr = 10 * np.log10(np.sum(x ** 2) / np.sum((x - r["y"]) ** 2))
lab.row(f"coded at {kb} kbit/s: rate reached, margin to the mask, SNR", f"{r['kbps']:.1f}, {r['margin_db']:+.1f} dB, {snr:.1f} dB")
lab.row(f"ABX: right answers needed in {TRIALS}; power for a listener right {100 * P_TRUE:.0f} %",
f"{K.abx_threshold(TRIALS)}, {100 * K.abx_power(TRIALS, P_TRUE):.0f} %")
order = list(rng.permutation(len(RATES)))
lab.audio = concat([Clip(x, SR)] + [Clip(coded[RATES[i]], SR) for i in order], gap=0.6)
lab.row("ear problem: after the original, the four coded versions: their bit rates? (listen first)", ", ".join(f"{RATES[i]}" for i in order))
fig, (ax1, ax2) = labs.figure(2)
f = (np.arange(N) + 0.5) * SR / (2 * N)
X = K.frames_mdct(x, N)[10]
ax1.semilogx(f, 10 * np.log10(X ** 2 + 1e-12), color="0.6", lw=0.6, label="frame")
allowed = np.zeros(N)
for (a, b), nb in zip(m["bands"], m["allowed"]):
allowed[a:b] = nb / (b - a)
ax1.semilogx(f, 10 * np.log10(allowed + 1e-12), color=labs.GOLD, label="allowed noise")
ax1.set_xlabel("Hz")
ax1.set_ylabel("dB")
ax1.legend(fontsize=7)
ns = np.arange(8, 101)
ax2.plot(ns, [K.abx_power(int(n), P_TRUE) for n in ns], color="C0")
ax2.set_xlabel("ABX trials")
ax2.set_ylabel("power")
lab.fig = fig
lab.note = ("Lossless coding removes what can be predicted; perceptual coding removes what cannot be heard, by "
"putting its noise under a masking threshold computed band by band; the MDCT makes that possible without "
"sending extra numbers; and a listening test needs enough trials to see a small difference.")
return lab
Now change it
- Change RATES. Where does the margin to the mask go negative, and what do you hear when it does?
- Change N (the MDCT size). Do the aliases still cancel? What happens to the masking threshold's detail?
- Change P_TRUE and TRIALS. How many trials does a listener who is right 65% of the time need to be found 80% of the time?
Problems, with solutions
Try each problem before opening its solution.
-
Compute. A band allows noise of power 10⁻⁴ per coefficient. What step size puts the noise exactly there, and 6 dB under?
Solution
A uniform quantizer's noise is Δ²/12, so Δ = √(12 × 10⁻⁴) = 0.0346; 6 dB under halves the step (power down by 4): Δ = 0.0173.
-
Prove. Show that the MDCT's window must satisfy w²ₙ + w²ₙ₊ₙ = 1 for the aliases to cancel.
Solution
In the overlap between frame i's second half and frame i + 1's first half, windowing twice and adding gives the signal times wₙ₊ₙ² + wₙ², plus two aliases (time-reversed copies of the overlap) with opposite signs, each multiplied by a product of window values; for a window symmetric about its centre (w at n equal to w at 2N − 1 − n) the two products are equal and the aliases cancel. What remains is the signal times wₙ² + wₙ₊ₙ², so it is recovered exactly if and only if wₙ² + wₙ₊ₙ² = 1: the Princen–Bradley condition, which the sine window meets because sin² + cos² = 1.
-
Ear. The lab codes a sound at random rates and plays them after the original; order them by bit rate.
Solution
The lab prints the order. Listen for the top of the spectrum first (low rates low-pass it), then for a watery roughness on the sustained notes.
-
Build. Add window switching to the coder: short blocks when an attack is detected, with start and stop windows.
Where to look. Detect attacks from the energy of short sub-blocks (a jump of 10 dB or more); in those frames use eight MDCTs of N/8 with their own scale factors; between long and short frames use asymmetric start and stop windows whose halves still satisfy the Princen–Bradley condition with their neighbours; check reconstruction first, then pre-echo.
-
★ Can a learned metric predict listeners' ratings for a kind of codec that did not exist when it was trained?
Where the frontier is. Collect MUSHRA ratings for classical and neural codecs on varied music; train metrics on some codecs and test on unseen ones; measure prediction codec by codec, with confidence intervals.
Notes and sources
Sources
- M. Bosi and R. E. Goldberg, Introduction to Digital Audio Coding and Standards (2003); J. Sterne, MP3: The Meaning of a Format (2012); K. Brandenburg, "MP3 and AAC explained", AES Conference (1999); T. Painter and A. Spanias, "Perceptual coding of digital audio", Proc. IEEE (2000).
- C. E. Shannon, "A mathematical theory of communication" (1948); S. W. Golomb, "Run-length encodings" (1966); R. F. Rice, "Some practical universal noiseless coding techniques" (JPL, 1979); T. Robinson, "SHORTEN" (Cambridge, 1994).
- M. R. Schroeder, B. S. Atal and J. L. Hall, "Optimizing digital speech coders by exploiting masking properties of the human ear", JASA (1979); J. D. Johnston, "Transform coding of audio signals using perceptual noise criteria", IEEE JSAC (1988); E. Terhardt, "Calculating virtual pitch" (1979).
- J. P. Princen and A. B. Bradley, "Analysis/synthesis filter bank design based on time domain aliasing cancellation", IEEE Trans. ASSP (1986).
- J.-M. Valin, G. Maxwell, T. B. Terriberry and K. Vos, "High-quality, low-delay music coding in the Opus codec", AES Convention (2013).
- ITU-R BS.1116 (1994), BS.1534 (MUSHRA, 2001), BS.1387 (PEAQ, 1998); D. Clark, "High-resolution subjective testing using a double-blind comparator", JAES (1982).
- S. P. Lloyd, "Least squares quantization in PCM" (1957; 1982); Y. Linde, A. Buzo and R. M. Gray, "An algorithm for vector quantizer design", IEEE Trans. Comm. (1980); N. Zeghidour et al., "SoundStream: an end-to-end neural audio codec" (2021); A. Défossez et al., "High fidelity neural audio compression" (EnCodec, 2022).
About this partfrom its README
Part 58 of a sixty-eight-part course in music (see the series plan and
the syllabus), the fifth part of Act X, The Studio and the Stage. The engineer tuning the first MP3
encoder tested it on an unaccompanied voice, Suzanne Vega's "Tom's Diner", because on that voice it sounded dreadful.
Years of research into what the ear cannot hear produced a file a tenth the size, and a few years later those files helped disrupt
the record industry. This part builds the two kinds of compression: a lossless coder that rebuilds every bit,
and a perceptual coder on Part 4's masking, with the MDCT, rate control, window sizes and mid-side stereo; then it asks how
controlled tests can establish limits on codec discrimination. The tools are Monochord's (explainer/music/monochord/codec.py); every
codec heard here is Monochord's own, not MP3, AAC or Opus.
- A voice that sounded dreadful. An ear question (the Tune sung alone, through our coder at 64 kbit/s, as recorded, and at 16 kbit/s: which was the original? the second; the first targets 64 kbit/s and estimates about 60 kbit/s on this signal); Tom's Diner and the MP3; two kinds of compression; the plan.
- 1. Entropy and lossless coding. Entropy; prediction; how much prediction saves (the voice from 13.0 to 3.5 bits a sample at order 4, the mix to 9.5 at order 2); Rice codes; a lossless coder, round trip (voice 23 %, mix 55 %, every sample exact); better predictors.
- 2. What the ear cannot hear. A masking model; how far masking reaches (Schroeder's spreading, Johnston's offsets); one frame's mask; an ear question (white noise and mask-shaped noise of the same power, 10 dB under the music: in which can you hear the noise? the white); masking in time.
- 3. The MDCT. Why a special transform; the modified discrete cosine transform; one frame's aliases; the aliases cancel (to 7 × 10⁻¹⁵, and 2 × 10⁻¹³ on the mix); aliases heard, from every other frame; a bank of filters.
- 4. A perceptual coder. Monochord's coder; bit allocation by step size; rate control; the voice and the mix at five rates (the mix 19 dB under the mask at 128 kbit/s, 3 at 64, 17 over at 16); five rates heard.
- 5. Window switching and pre-echo. Time against frequency; 30 ms before a hit (at equal noise-to-mask, long blocks leave 5.5 dB more noise before each hit, and short blocks cost three times the bits); an ear question (which had a swish before each hit? the long blocks); window switching.
- 6. Stereo coding. Mid and side (the side 11 dB under the mid); the same 64 kbit/s spent two ways (about 4 dB better per channel as mid-side); heard; intensity and parametric stereo.
- 7. MP3, AAC and Opus. Five codecs; MP3's hybrid filter bank; AAC; Opus; the file that broke a business.
- 8. Listening tests. An ABX trial (X was B); counting right answers (12 of 16, 59 of 100); the power of an ABX test (a listener right 70 % of the time passes 16 trials 45 % of the time); BS.1116 and MUSHRA.
- 9. Generations. Transcoding; five generations (SNR from 8.5 dB to about 2); heard; in practice.
- 10. Vectors and residuals. Vector quantization; residual vector quantization; stage by stage (5 dB less error per stage); heard; neural codecs.
- 11. Frontier: neural codecs and learned metrics. What neural codecs change; learned metrics; ★ research problem: can a learned metric predict listeners' ratings for a kind of codec that did not exist when it was trained?
- Variation 58, recap and problems. The Tune by our session at 128, 64, 32, 24 and 16 kbit/s, then what the 32 kbit/s version discarded, alone; the ledger; what we found; five problems; where it comes back; in practice; references; Part 59.
What is computed and built
python -m videos.music.music58.compute (about five minutes; the vector quantizer's training takes the longest) fills
.cache/music58/.
| Item | What it computes | Checked against |
|---|---|---|
hook, rates, tune58 |
the perceptual coder at several rates on the voice and the mix | the bit rate met; margins ordered (tests) |
lossless |
entropy by predictor order; a Rice-coded lossless coder | bit-exact decoding (tests) |
masking |
one frame's mask; white and mask-shaped noise | a tone's mask (tests) |
mdct |
basis, aliases, overlap-add | reconstruction to 1e-11 (tests) |
preecho |
long and short blocks at equal noise-to-mask | the pre-echo ordering (tests) |
stereo |
left/right against mid/side at one rate | SNR (tests) |
abx |
thresholds and power of ABX tests; one trial | the binomial (tests) |
transcode, rvq |
five generations; residual vector quantization | errors fall stage by stage (tests) |
Monochord's tools are held in tests/music/test_codec.py; this part's claims and clips in tests/music/test_music58.py.
Sounds. Part 8's voice singing the Tune alone, Part 56's session (mono and stereo), Part 40's clave as castanets, all through Monochord's coders.
What the models are, and are not. The perceptual coder is mono, with one block size per run, no bit reservoir, no Huffman tables (Rice codes per band instead), a nominal six-bit scale-factor cost and a low-pass by target rate. Scale factors are not actually quantized and serialized, so these are estimated model rates, not measured complete files. It is a teaching coder, and its rates are not comparable one for one with MP3's or AAC's. The masking model is Johnston's (1988) in outline: Bark bands, Schroeder's spreading, a tonality offset from the spectral flatness, and Terhardt's threshold in quiet (capped at 60 dB SPL), with a full-scale sine taken to play at 96 dB SPL. The lossless coder uses Shorten's fixed predictors, not FLAC's fitted ones. The vector quantizer codes normalized MDCT vectors, not learned features.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: an ear question (which was the original?); sizes and margins; Tom's Diner and the MP3; two kinds of compression; the plan.
- Entropy and lossless coding: entropy; prediction; how much it saves; Rice codes; a bit-exact round trip; better predictors.
- What the ear cannot hear: a masking model; spreading; one frame's mask; an ear question (white or shaped noise?); masking in time.
- The MDCT: why; the transform; one frame's aliases; the aliases cancel; aliases heard; a bank of filters.
- A perceptual coder: the coder; bit allocation by step size; rate control; five rates; five rates heard.
- Window switching and pre-echo: time against frequency; 30 ms before a hit; an ear question (which had a swish?); switching.
- Stereo coding: mid and side; the same bits two ways; heard; intensity and parametric stereo.
- MP3, AAC and Opus: five codecs; MP3; AAC; Opus; the file that broke a business.
- Listening tests: an ABX trial (an ear question); counting right answers; the power of a test; BS.1116 and MUSHRA.
- Generations: transcoding; five generations; heard; in practice.
- Vectors and residuals: vector quantization; residual stages; stage by stage; heard; neural codecs.
- Frontier: what neural codecs change; learned metrics; the research problem.
- Variation 58: the Tune at five bit rates, and the residue alone. Outro: problems, payoffs.
Covers: entropy and lossless coding by prediction; masking thresholds; the MDCT and why its aliases cancel;
window switching and pre-echo; bit allocation; stereo coding; MP3, AAC and Opus; listening tests and their
statistics; transcoding; neural codecs and residual vector quantization.
Built and computed: monochord/codec.py: a lossless coder (fixed predictors, Rice codes) with a bit-exact round
trip (voice 23 %, mix 55 %); the MDCT with its cancellation verified to 1e-13; a masking model (Bark bands,
Schroeder's spreading, Johnston's tonality, the threshold in quiet) and a perceptual coder with rate control (the mix
19 dB under the mask at 128 kbit/s, 18 over at 16); pre-echo at equal noise-to-mask; mid-side coding; the power of an
ABX test (12 of 16; a 70 % listener passes 45 % of the time); five generations; residual vector quantization.
Variation 58: the Tune at five bitrates, and the residue the codec discards, played alone.
Frontier: neural codecs; learned perceptual metrics (open: can a learned metric judge a kind of codec it never saw?).
Reading: Bosi & Goldberg; Brandenburg (1999); Valin et al. on Opus; Sterne, MP3: The Meaning of a Format.
Build the film
python -m videos.music.music58.compute # the part's numbers, into .cache/music58
python tools/build.py music58 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py music58 Hook # one chapter, silent, with a contact sheet
Scenes: videos/music/music58. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.music.music58.compute # numbers and sounds (about five minutes)
EXPLAINER_TTS=silent python tools/build.py music58 -q l --fps 15 # a silent-narration preview, with the sounds
python tools/qa_sound.py music58 --sync # the sound gates
python tools/dead_air.py renders/music58_480p.mp4 --sound music58 # no empty screen; no sound over a still one
python tools/lecture_length.py music58 # 30 to 60 minutes, listening included
python tools/build.py music58 # 1080p30, narrated
python -m pytest -q tests/music # Monochord against its references; this part's claims and clips
python -m videos.music.labs 58 # the lab (writes a figure and a short WAV)