This is an excellent set of questions that hits at the fundamental differences and similarities between video and audio encoding. You've got a solid grasp of video codecs, so let's use that as a foundation to build upon for audio.
While both video and audio codecs aim for perceptually optimal lossy compression, their underlying data structures, redundancy patterns, and perceptual models lead to very different engineering trade-offs and design philosophies.
Core Principles of Audio Encoding (AAC/Opus)
Most modern perceptual audio codecs follow a similar high-level pipeline:
- Time-to-Frequency Domain Transformation: The raw PCM (Pulse Code Modulation) audio, which is a time-series of amplitude samples, is transformed into a frequency domain representation. This is crucial because our ears perceive sound on a logarithmic frequency scale, and psychoacoustic masking effects are predominantly frequency-dependent.
- Dominant Transform: The Modified Discrete Cosine Transform (MDCT) is almost universally used in modern perceptual audio codecs (AAC, MP3, Vorbis, AC-3, Opus's CELT mode).
- Why MDCT?
- Critical Bands: It compacts energy efficiently into frequency bins, which can then be grouped into "critical bands" that approximate the ear's frequency resolution.
- Overlap-Add: It uses overlapping windows, which is key to avoiding audible artifacts at block boundaries. This is directly related to your pre/post-echo question.
- Real Coefficients: Unlike the Discrete Fourier Transform (DFT), the MDCT yields only real coefficients, simplifying later processing.
- Perceptual Model / Psychoacoustic Analysis: This is the heart of a perceptual audio codec. It analyzes the frequency-domain data to determine what information is perceptually important and what can be discarded or highly quantized without being noticed by the listener.
- It calculates a masking threshold for each frequency band. Sounds below this threshold are inaudible (absolute threshold of hearing) or are masked by louder sounds nearby in frequency (simultaneous masking) or time (temporal masking).
- This model dictates the bit allocation: how many bits (and thus how much precision) should be allocated to quantize the coefficients in each frequency band.
- Quantization: The frequency coefficients are quantized (i.e., reduced in precision) based on the bit allocation determined by the psychoacoustic model. Coefficients in masked bands can be heavily quantized or even set to zero. This is where the loss occurs.
- Stereo Coding: To save bits for stereo signals, techniques like Mid/Side (M/S) stereo or Intensity Stereo Coding are used.
- Prediction (Long-Term Prediction - LTP): For periodic signals like pitched speech or singing, past frames can be used to predict the current frame, similar to how video codecs use motion compensation for temporal redundancy.
- Bandwidth Extension: For very low bitrates, only a limited frequency range is encoded explicitly. Higher frequencies can be synthesized from the lower ones, guided by the original signal's characteristics. (e.g., AAC's SBR, Opus's CELT).
- Entropy Coding: The quantized coefficients, side information (e.g., window shape, stereo mode), and prediction residuals are compressed using Huffman coding or arithmetic coding. This is lossless compression.
Addressing Your Specific Questions:
1. Why One-Pass Encoding (and ABR/VBR modes)?
You are correct that audio encoders are predominantly one-pass, even for high-quality music streaming. The reasons are multifaceted and stem from the nature of audio data and its redundancy:
- Temporal Dependency is Different:
- Video: Frames are highly correlated globally across time (backgrounds, static objects). Motion compensation exploits this over many frames. A global rate control strategy over a GOP (Group of Pictures) or entire scene is highly beneficial for smooth quality.
- Audio: While there's local temporal correlation (samples within a few milliseconds, or pitched sounds over tens of milliseconds), there's much less global temporal correlation over seconds or minutes. A section of music 10 seconds in is generally not highly predictive of a section 20 seconds later in the same way that frame N+1 is predictive of frame N in video.
- Local Redundancy is Key: Audio redundancy is mostly local (within a few milliseconds) and frequency-dependent (psychoacoustic masking). The encoder's primary task is to manage noise within each short time window based on the local masking properties.
- Psychoacoustic Model Operates Locally: The masking threshold calculation for a given audio frame (typically 20-40ms long) is primarily dependent on the spectral content within that frame. While temporal masking (pre- and post-masking) links adjacent frames, it's over a very short time scale (tens of milliseconds). There's no equivalent of a "B-frame" or "P-frame" that needs to look far forward/backward to optimize a global quality metric.
- Real-Time Requirements: A vast majority of audio encoding (streaming, VoIP, live broadcast) is real-time. Even offline encoding benefits from being fast. A full two-pass system, while theoretically offering some global optimization, would significantly increase encoding time for what are often marginal quality gains.
- Computational Complexity vs. Benefit: The gains from a truly global two-pass approach for audio are generally considered too small to justify the increased complexity and time, given how well the psychoacoustic model works on a frame-by-frame basis. A very short "lookahead" (e.g., a few frames) is common in modern encoders to detect transients for window switching, but it's not a multi-second lookahead for global rate control.
- ABR/VBR for Practicality:
- VBR (Variable Bit Rate): This is generally the preferred mode for quality, as it allows the encoder to use more bits for complex segments (dense music, transients) and fewer bits for simpler segments (silence, sustained tones), optimizing perceptual quality for a given average bitrate. Most music streaming uses VBR under the hood, targeting a specific quality level (e.g., "Quality 5" or "Target Bitrate 256kbps VBR").
2. Psychoacoustic Models: Formal and RD-Optimal?
This is where audio truly shines and differentiates itself. Yes, psychoacoustic models are formal, well-founded, and integrated in a highly effective way that is a form of RD-optimization, even if not explicitly called "RD-optimal" in the same way as video.
3. One-Pass Encoding and Echo Artifacts (Post-echo vs. Pre-echo)
You're spot on with this observation!
- The Problem: When an audio signal has a sharp transient (e.g., a cymbal crash, a sudden drum hit), quantizing the frequency domain representation can spread the quantization error across the entire time window of the transform.
- If the window is long (e.g., 20ms in AAC's long window), a sudden sound at the end of the window can cause a faint "echo" before the sound itself (pre-echo) and after it (post-echo).
- Why Post-echo is Preferred/Safer:
- Temporal Masking: The human ear is much more susceptible to pre-echo than post-echo. A loud sound effectively "masks" (makes inaudible) quieter sounds that immediately follow it (post-masking/backward masking). It's much less effective at masking sounds that precede it (pre-masking/forward masking is much shorter in duration and less potent).
- Therefore, an audible pre-echo is far more annoying and noticeable than an equally loud post-echo.
- How Pre-echo is Mitigated (and Post-echo managed):
- Adaptive Window Switching: This is the primary solution. Modern codecs don't use a fixed window size.
- When a transient is detected, the encoder switches to a shorter window (e.g., 2.5ms or 5ms in AAC). This effectively localizes the quantization noise to a much shorter time duration, minimizing the pre-echo.
- After the transient, it switches back to a longer window for better frequency resolution and coding gain.
- Overlapping Windows (MDCT): The overlap-add property of MDCT helps smooth the transitions between windows, reducing block boundary artifacts.
- Careful Quantization & Noise Shaping: The psychoacoustic model helps here too, by ensuring that even any residual pre-echo is pushed below the masking threshold if possible.
- The Trade-off: Shorter windows reduce pre-echo but offer poorer frequency resolution (less frequency bins for the same time duration), which reduces coding gain and can be less efficient for stationary sounds. This is why window switching is adaptive.
4. "Inter-prediction" in Audio
You're right that audio is much less reliant on "inter-prediction" in the video sense, but there are analogous concepts:
- Video Inter-prediction (Motion Compensation): Exploits macro-level temporal redundancy. Pixels are tracked and predicted from previous/future frames, and only the motion vectors and residuals are encoded. This is massive data reduction.
- Audio's Closest Equivalent: Long-Term Prediction (LTP):
- This is primarily used for pitched speech and music (e.g., vowels, sustained notes).
- It identifies a repeating pattern (the pitch period) in the audio signal.
- Instead of encoding the whole current frame, it predicts the current frame based on a past, delayed version of itself (the "long-term" part, typically tens of milliseconds, corresponding to vocal cord vibration or instrument sustain).
- Only the prediction coefficients and the residual (the difference between predicted and actual) are encoded.
- AAC includes LTP. Opus's SILK layer (for speech) heavily relies on LTP.
- Why less impactful than video's inter-prediction? Audio's pitch periods are much shorter and more variable than global motion in video. While effective for pitched sounds, it doesn't offer the same order-of-magnitude compression as video's inter-prediction for general audio, which is why the MDCT and psychoacoustic masking are the primary drivers of audio compression. Non-pitched sounds (percussion, noise) don't benefit from LTP.
- Other Forms of Redundancy Exploitation:
- Joint Stereo (Mid/Side & Intensity Stereo): This exploits redundancy between channels rather than across time.
- Mid/Side (M/S): For signals where the L and R channels are highly correlated (mono content), encoding the sum (M = L+R) and difference (S = L-R) channels can be more efficient. The S channel often has less energy and can be quantized more aggressively.
- Intensity Stereo: For high frequencies where the ear is less sensitive to phase differences and more to intensity, only the mid-channel's spectral envelope is encoded for a frequency band, and side channel information is transmitted as a gain factor for that band. This saves many bits.
- Perceptual Noise Substitution (PNS) / Noise Filling: For very quiet, unpitched noise (like the subtle hiss of a recording or ambient room tone), instead of trying to encode the noisy coefficients themselves, the encoder can just encode a flag that says "add noise here" and reconstruct similar noise at the decoder. This saves bits for perceptually unimportant details. AAC, Vorbis, and Opus (CELT layer) use variations of this.
Summary
Audio encoding, particularly modern codecs like AAC and Opus, is a triumph of signal processing deeply intertwined with psychoacoustics.
- One-pass is preferred because audio's temporal dependencies are mostly localized and the powerful psychoacoustic model can make optimal (perceptual) bit allocation decisions on a frame-by-frame basis, making two-pass encoding offer diminishing returns for the added complexity and latency.
- Psychoacoustics is fundamental and highly formalized. It dictates what bits are truly necessary to preserve perceived quality, driving the quantization and noise shaping, effectively acting as the "RD-optimization" for audio.
- Pre-echo is actively avoided by adaptive window switching and careful noise shaping, leveraging the ear's greater tolerance for post-echo due to temporal masking.
- "Inter-prediction" exists but is different. Long-Term Prediction (LTP) is used for pitched sounds, but the primary compression gains come from the MDCT and the psychoacoustic model's ability to discard inaudible information.
The magic of modern audio codecs lies in their ability to precisely sculpt the quantization noise, pushing it below the ear's masking threshold, achieving incredible compression without noticeable degradation for most listeners.