Digital Representation of Audio and Image Signals
In questa pagina 7
A microphone produces a voltage that varies continuously in time; a photographic sensor measures light at every point of the plane. To store or send these signals through a network they must be turned into sequences of bits. This note explains how it is done, what is lost and what is not, and how to go back. It is the basis of the following notes: how many bits per second a signal produces decides how much compression is needed (Source Coding and Compression - Entropy, Huffman and the Quality-Bitrate Trade-offThe information of an event of probability p is log2(1/p) bits and the entropy H = sum p log2(1/p) is the average information of a source; lossless source coding maps source words to variable-length prefix codewords (shorter for likelier words), the Kraft-McMillan inequality constrains the lengths, Shannon's theorem gives H/log2(My) <= L <= H/log2(My) + 1, Huffman coding is optimal among prefix codes; lossy compression gives up exactness to reach a lower rate, and rate, quality, complexity, delay and robustness are conflicting parameters.Source Coding and Compression - Entropy, Huffman and the Quality-Bitrate Trade-off →, Image Coding - DCT and JPEGQuantizing pixels directly is inefficient because they are not sparse, so JPEG applies an orthogonal linear transform on 8x8 blocks (the 2-D DCT, Y = A X A^T) that concentrates energy in few coefficients, quantizes them with a table of steps scaled by a quality factor Q, scans them in zig-zag order, codes the DC coefficient differentially and the AC coefficients as (run, category) pairs with Huffman codes; one worked block shrinks from 512 bits to 49 bits (0.766 bit/pixel) and higher Q gives more bits and higher PSNR.Image Coding - DCT and JPEG →), and the effect of quantization is quantified in Quantization Noise and SNRA uniform mid-riser quantizer with L = 2^b levels over [-Vsat, Vsat] has step Delta = 2 Vsat / L; the error e = aq - a is granular (at most Delta/2, roughly uniform, power Delta^2/12) or saturation (outside the range), and with negligible saturation the SNR is [SNR]dB = 6.02 b + 4.77 + 20 log10(sigma / Vsat), so every extra bit gives 6 dB; Vsat follows from the saturation probability and b from the required SNR rounded up; with bit errors on the channel the PCM SNR becomes SNR_q / (1 + 4 P_bit (4^b - 1)).Quantization Noise and SNR →.
1. Signal types and the transmission chain
Three kinds of signal are distinguished, according to whether the domain (the "when") and the codomain (the "how much") are continuous or discrete.
| Type | Domain | Codomain | Model |
|---|---|---|---|
| analog | continuous time | continuous amplitude | |
| sampled | discrete time | continuous amplitude | |
| digital | discrete time | discrete amplitude (finite alphabet) |
The definitions extend to several variables. A grey-scale analog image is ; a digital one is ; in colour every pixel has three components, . A video adds the frame index. A computer represents and processes exactly only digital signals.
The analog-to-digital conversion (ADC) has three steps:
- sampling: the independent variable becomes discrete;
- quantization: the amplitude becomes discrete;
- coding (binarization): the quantized amplitude is written with bits.
The complete chain. .
- ADC: sampling and quantization.
- COD (source encoder): turns the sequence into bits and can compress, even introducing distortion.
- NET: the network carries the bits to the destination (it may introduce errors and losses).
- DEC: decodes the bit stream into the quantized samples.
- DAC (digital-to-analog conversion): rebuilds a signal usable by a person.
Quality can degrade in every block: filter and sampler (if badly chosen), quantization, lossy coding, network, non-ideal DAC. The converter itself consists of four blocks: an anti-aliasing filter (a low-pass filter), the sampler, the quantizer and the inverse bit mapper followed by a parallel-to-serial converter that puts the words in a single binary stream. At the receiver the opposite path is followed: serial-to-parallel conversion, bit mapping back to levels, and an interpolator that rebuilds the continuous signal.
2. Sampling
Definition (sampling). The signal is read at regular intervals of duration (sampling period): , . The sampling frequency is .
Does sampling lose information? Between one sample and the next the signal could do anything. The answer of Shannon's theorem is surprising: no, if the signal does not vary too fast with respect to . "Too fast" is made precise with the spectrum (see Sampling and the Sampling TheoremSampling multiplies a continuous-time signal by a pulse train, which replicates its spectrum every omega_s; if the signal is band-limited with maximum angular frequency omega_M and omega_s exceeds 2 omega_M, an ideal low-pass filter recovers it exactly (Shannon theorem and sinc interpolation formula).Sampling and the Sampling Theorem → for the proof).
A signal is band-limited if its spectrum is zero beyond a maximum frequency . Band-limited signals are "all and only" those that can be perfectly rebuilt from their samples.
Sampling theorem (Shannon). A band-limited signal with maximum frequency can be rebuilt with zero error from the samples if and only if the sampling frequency is at least twice the maximum frequency: When it holds, the ideal interpolation formula returns the signal:
Reading: a is placed at each sampling instant , stretched horizontally so that its zeros fall at distance , and scaled in height by the sample value. At the instant all the sinc functions are zero except the one centred at , which equals .
Why : spectrum replicas. Sampling in time is equivalent to periodically replicating the spectrum with period : the spectrum of the sampled signal is the sum of the copies , . The original spectrum occupies , the copy occupies . They do not overlap if , i.e. exactly . In that case a low-pass filter selecting the copy centred at zero gives back the original spectrum (ideal interpolation is exactly this filter). The quantity is the Nyquist frequency. If the copies overlap and cannot be separated.
2.1 Aliasing
Definition (aliasing). Aliasing is the frequency shift of a signal rebuilt from samples taken with an that does not respect the Nyquist criterion: high-frequency components appear, after reconstruction, as lower-frequency components.
A pure tone at frequency sampled at is rebuilt as a tone at the frequency
the distance of from the nearest multiple of . Intuition: to see a signal oscillate at least two samples per period are needed; if there are fewer, the samples are also compatible with a slower oscillation.
Example. kHz. A 3 kHz tone ( kHz) is rebuilt correctly. A 5 kHz tone becomes kHz: it is confused with the 3 kHz one. A 7 kHz tone becomes kHz; a 9 kHz tone becomes kHz. Another way to see it: a 6 kHz tone sampled at 8 kHz has samples , identical to those of a 2 kHz tone. For a signal of bandwidth kHz, among , and kHz the only valid choice is kHz ( kHz).
2.2 In practice: the anti-aliasing filter
No real signal is strictly band-limited: a signal of finite duration has, strictly, unlimited bandwidth. But all interesting signals concentrate most of their information in a limited band, so high frequencies can be removed with a low-pass filter without significant distortion. For this reason every A/D converter has, before the sampler, a low-pass filter with cut-off (see Aliasing and Anti-Aliasing FiltersAliasing is the overlap of spectral replicas that occurs when the band-limited or Nyquist assumptions of the sampling theorem fail; an anti-aliasing low-pass filter with cut-off omega_s/2 applied before sampling removes it at the price of losing the high frequencies; two worked exercises.Aliasing and Anti-Aliasing Filters →): it enforces the Nyquist criterion by removing frequencies above . Without the filter, high components would create aliasing inside the useful band and could no longer be removed: once sampled, an alias cannot be told apart from a true signal. The error committed by the filter is the energy of the discarded part of the spectrum, . The same rule holds for subsampling an already digital signal: filter, then decimate.
If the anti-aliasing filter has cut-off and the sampler works at , aliasing is avoided if . With kHz: kHz.
The practical choice of starts from the band of the signal and takes a value slightly above : 8 kHz for speech (band 200-3400 Hz, filtered at 4 kHz), 44.1 kHz for music (useful band up to 20 kHz). The margin is needed because a real filter does not have a vertical cut.
2.3 Interpolation at the receiver
The ideal interpolation uses sinc functions, which have infinite support and cannot be built (the ideal filter has a sinc impulse response, of infinite duration and non-causal). In practice other kernels are used with the formula
The kernel is scaled (dividing the variable by ) and shifted (). Constraints: finite support, to be realisable; and , for the other integers , so that interpolation preserves the values at the samples.
| Kernel | Expression | Quality | Cost | Typical use |
|---|---|---|---|---|
| order 0, sample and hold | lowest; stepped signal, spurious high frequencies | very low | acceptable if is very high | |
| order 1, linear | (triangle) | intermediate | low | when something better than S&H is needed |
| order 3, cubic (spline) | degree-3 polynomials | excellent for images | medium-high | image resampling |
| truncated | highest | highest | sound cards, near the Nyquist limit |
The zero-order holder has frequency response : the sinc is rounded (not flat) and distorts the frequencies near . It is compensated by oversampling: sampling at well above , so that in the band the filter is almost flat (with one loses 24% at , with only 2.6%). If is high enough the simple interpolators (S&H, linear) suffice; if is near the Nyquist frequency the truncated sinc is needed.
3. Quantization and binarization
After sampling the values are still real numbers. Quantization maps them onto a discrete set, the set of quantization levels. If there are levels, every sample is represented with bits: more levels mean more precision but more bits.
The most common type is the uniform quantizer: the interval of possible values is divided into equal intervals of width
Two variants exist: mid-tread, , in which zero is a level (useful when the signal has many values near zero), and mid-rise (mid-riser), , in which zero is a threshold between two levels and the levels are the centres of the intervals. The maximum error inside the covered interval is . The detailed error statistics are in Quantization Noise and SNRA uniform mid-riser quantizer with L = 2^b levels over [-Vsat, Vsat] has step Delta = 2 Vsat / L; the error e = aq - a is granular (at most Delta/2, roughly uniform, power Delta^2/12) or saturation (outside the range), and with negligible saturation the SNR is [SNR]dB = 6.02 b + 4.77 + 20 log10(sigma / Vsat), so every extra bit gives 6 dB; Vsat follows from the saturation probability and b from the required SNR rounded up; with bit errors on the channel the PCM SNR becomes SNR_q / (1 + 4 P_bit (4^b - 1)).Quantization Noise and SNR →.
Quantization is irreversible: unlike sampling (which under Nyquist loses nothing), it always loses information, since a whole interval of values ends up in the same level. For this reason the quantization of the ADC is very fine, so that the loss is not perceptible. Typical experimentally found values:
- music: 16 bits per sample ( levels) for perfect perception; for speech 8 bits are enough;
- grey-scale images: 8 bits (256 grey levels);
- colour images: 8 bits for each of the three RGB channels, i.e. 24 bits per pixel ( million colours).
Two quantizations in a real system. (1) The one inside the ADC, very fine with negligible distortion. (2) The one inside the source encoder, i.e. of the compression algorithm: this one introduces the evident distortion. It should be called requantization, because it acts on already quantized data.
Binarization. The inverse bit mapper transforms each level into the corresponding string of bits (usually the binary representation of the index of the interval); a parallel-to-serial converter serialises the bits into a single stream. Example (5 levels, 3 bits): the levels have codes ; the quantized signal gives the stream The index is transmitted, not the value; the bit mapper at the receiver gives back the values.
Bit-rate. One sample every seconds and bits per sample give one bit every seconds, i.e.
( is times the bit time, not equal to it.) This is the nominal bit-rate, without source coding. For any uncompressed signal:
Do not compute the bit-rate with in place of .
4. Audio
4.1 How we perceive sound
The human auditory system performs a frequency analysis of the incoming sounds: it can be modelled as a bank of filters , each analysing a band. Two phenomena matter for compression.
- Hearing threshold. There is a minimum power below which a pure tone of frequency is not heard; it varies from person to person and with age. Taking the 1 kHz tone as reference, the threshold as a function of frequency is very high at the extremes of the audible spectrum and lower in the 1-5 kHz region (bowl-shaped). Sounds under the curve are useless to encode.
- Frequency masking. A strong tone raises the threshold for nearby frequencies: a weak tone next to a strong one is not heard. The threshold-raising function decreases with frequency distance but is not symmetric: it falls more slowly for higher frequencies. A tone masks higher frequencies more than lower ones.
- Temporal masking. A strong tone also masks in time: a little before (pre-masking, 2-5 ms) and much after (post-masking, 100-200 ms).
Perceptual coding. The signal can be quantized so that the generated quantization noise falls below the masking threshold and is therefore not heard. This is done by shaping the noise spectrum, or with a time-frequency analysis that coarsely quantizes the masked components. It is the principle of MP3 and AAC.
4.2 Speech: PCM at 64 kbit/s
The power of the voice signal is concentrated in the band Hz. Speech is acquired with a low-pass filter at kHz and sampling at kHz. The number of levels was found experimentally. Two common choices: 128 levels, i.e. 7 bits per sample (Asia and America): kbit/s; 256 levels, i.e. 8 bits (rest of the world): . This scheme is called PCM (pulse code modulation), although strictly it is a digitization scheme and not a modulation.
Packetisation. A packet typically corresponds to 20 ms of voice: samples, i.e. bytes with 8 bits ( bytes with 7 bits). The rate is therefore 50 packets per second.
4.3 Music: the audio CD
For music the parameters that make distortion imperceptible are: useful band Hz; two channels (stereo); kHz with anti-aliasing filter (slightly more than kHz); 16 bits per sample, i.e. levels.
A single channel (mono) needs kbit/s.
Example (capacity of a CD). The stream written on the disc contains 87% useful data and 13% is error protection code. The disc holds MB of useful data. Total bit-rate: Mbit/s (useful data are 87% of the total, so total = useful / 0.87). Maximum duration: s minutes (the data rate of the useful data only is used, since the 730 MB are useful).
| Signal | levels | bits/sample | channels | data rate | |
|---|---|---|---|---|---|
| Speech | 8 kHz | 256 | 8 | 1 | 64 kbit/s |
| Music | 44.1 kHz | 65 536 | 16 | 2 | 1.411 Mbit/s |
File size: . Example: 128 kbit/s for 10 minutes: kbit MB. Bits per sample with levels: (2048 levels 11 bits). A signal of band 20 kHz sampled at the minimum frequency ( kHz) and quantized on 2048 levels produces kbit/s.
5. Images
5.1 Acquisition and quantization
Light from the scene crosses the optics and hits the sensor on the image plane. Each pixel of the sensor measures the light hitting its surface: a filtering and a two-dimensional spatial sampling are performed. Quality grows with the number of pixels (the first digital cameras had about 1 Mpixel; today over 100 Mpixel).
Grey-scale images use 1 byte per pixel: 256 grey levels, practically indistinguishable from a non-quantized version. But 256 brightness levels may not be enough if the image contains areas much darker (underexposed) or brighter (overexposed) than the rest: the "true" values of those areas end at 0 or 255 and detail is lost. The solution is more bits per pixel: HDR (high dynamic range) formats use 10 or 12 bits per sample.
5.2 Colour: RGB
The eye perceives colour thanks to the cones of the retina: there are three types, each with a different response as a function of wavelength. A colour can be obtained by combining three primary colours: red, green, blue. The RGB space represents the colour of a pixel with three intensities. Each channel has bits; with there are colours (24 bits/pixel); with HDR at 10 or 12 bits, 36 bits/pixel.
Uncompressed sizes. An RGB image at 8 bits/channel takes bytes. HD: Mbit MB. pixels RGB: Mbit.
5.3 YCbCr and chroma subsampling
The three RGB channels are strongly correlated: the three images R, G, B are almost equal. The YCbCr space is obtained by rotating the axes so that the diagonal of the colour cube (the grey line ) becomes one axis, followed by an offset keeping values in : is the luminance, and are the chrominances. In one of the versions in use (the one of JPEG files):
A grey () has . Example. The pixel gives , , .
The eye is much less sensitive to chrominance than to luminance, so three chrominance samples out of four can be discarded without visible degradation. Sampling schemes: 4:4:4 (all components at full resolution), 4:2:2 ( and halved horizontally), 4:2:0 ( and halved both horizontally and vertically: one chroma sample every pixels). In 4:2:0 a frame has samples: half of the RGB (). Example: a 10 Mpixel image takes MB in RGB and MB in YCbCr 4:2:0. At the receiver the missing chroma samples are recreated by zero-order interpolation (replicating the value) before converting back to RGB.
5.4 Video
A video is a sequence of images, the frames, typically at 24, 30, 50, 60 fps. For uncompressed 4:2:0 video at bits per sample:
| Format | Resolution | fps | Rate (8 bit, 4:2:0) |
|---|---|---|---|
| CIF | 30 | 36 Mbit/s | |
| HDTV 720p | 50 | 553 Mbit/s | |
| HDTV 1080p | 50 | 1244 Mbit/s | |
| 4K | 50 | 5308 Mbit/s |
Check of one row: 1080p at 50 fps: bit/s. These rates are far too high for network and memory: compression is needed. For example a 4K video (, 30 fps, 4:2:0, 8 bit) is Gbit/s; to send it on a 10 Mbit/s link a compression ratio of at least is needed. This shows how traffic depends on the coding parameters: resolution, frame rate, bits per sample and chroma format all multiply in the bit-rate.
6. Measuring quality: MSE and PSNR
Measuring the quality of a signal with respect to the original is measuring the distortion between the two. With the error signal , the mean squared error is
which, up to , is the squared Euclidean distance between the sample vectors. The PSNR (peak signal-to-noise ratio) expresses the same number in decibels:
The numerator is the peak power of the signal; the denominator is the noise power. MSE is a measure of distortion (smaller is better), PSNR of quality (larger is better). For 8-bit grey-scale images .
| PSNR | quality |
|---|---|
| dB | excellent, indistinguishable from the original |
| dB | very good, barely visible differences |
| dB | good, visible differences |
| dB | sufficient, clear differences |
| dB | poor |
Example (requantizing an image from 8 to 4 bits). From 256 to 16 levels: the step becomes grey levels. The quantization error has power . Then dB: "good-sufficient" quality, with visible differences. At 2 bits (, MSE ) PSNR drops to about 22.8 dB.
Limit of PSNR: it does not always reflect the quality perceived by a human observer (too simple a model: it ignores contrast sensitivity, colour perception, masking). It remains widely used for simplicity and ease of interpretation. The perceptual listening and viewing experiments that the program mentions (effect of sampling frequency, number of quantization bits and filtering on perceived quality) are not described by any certified source, so they are not written here; the sources only say that taking bits away, even a few, worsens quality quickly (audio at 16, 8, 4, 2 bits per sample, images at 256, 16, 4 levels), so enough bits are kept at acquisition.
Typical mistakes
- Writing (it is ); believing that exactly always suffices (it requires the ideal filter: in practice one samples a little above).
- Saying that quantization is invertible.
- Using for the interval (it is ).
- Forgetting the filter before subsampling.
- Confusing index and quantized value; confusing and ().
- Reading PSNR as a "percentage" (it is in dB).
Versione ripasso
Chain. ADC COD bits NET DEC DAC . ADC = sampling + quantization (+ binarization). COD may compress (even with loss), NET may add errors and losses, DAC is not ideal: quality can degrade at every block. Analog = continuous time and amplitude; sampled = discrete time, continuous amplitude; digital = both discrete. Digital image: (colour: three components).
Sampling. , .
- Shannon's theorema band-limited signal with maximum frequency is rebuilt without error from its samples if and only if (Nyquist criterion); ideal reconstruction (Sampling and the Sampling TheoremSampling multiplies a continuous-time signal by a pulse train, which replicates its spectrum every omega_s; if the signal is band-limited with maximum angular frequency omega_M and omega_s exceeds 2 omega_M, an ideal low-pass filter recovers it exactly (Shannon theorem and sinc interpolation formula).Sampling and the Sampling Theorem →).
- Why : sampling replicates the spectrum with period ; copies at and do not touch if .
- Aliasing: if the copies overlap. A tone appears at : with kHz, 3 kHz stays 3, 5 kHz 3 kHz, 7 kHz 1 kHz, 9 kHz 1 kHz; 6 kHz gives the same samples as 2 kHz (Aliasing and Anti-Aliasing FiltersAliasing is the overlap of spectral replicas that occurs when the band-limited or Nyquist assumptions of the sampling theorem fail; an anti-aliasing low-pass filter with cut-off omega_s/2 applied before sampling removes it at the price of losing the high frequencies; two worked exercises.Aliasing and Anti-Aliasing Filters →).
- Anti-aliasing filter: low-pass with cut-off before the sampler (cut-off needs ). Same rule to subsample: filter, then decimate. Practical slightly above : 8 kHz speech, 44.1 kHz music.
- Interpolation : finite support, , . Sample and hold (lowest quality, near-zero cost, high ); linear triangle; cubic spline (images); truncated sinc (best, sound cards). Holder , compensated by oversampling.
Quantization. levels. on . Mid-tread (zero is a level) or mid-rise . Maximum error . Irreversible: ADC quantization is fine (16 bits audio, 8 bits speech, 8 bits per RGB channel = 24 bits/pixel); the encoder adds a second one (requantization), the evident distortion. Binarization: index bits; . Speech kbit/s; .
Audio. Speech: band 200-3400 Hz, kHz, 8 bits, 64 kbit/s (7 bits: 56 kbit/s); packet of 20 ms = 160 samples = 160 bytes. CD: 44.1 kHz, 16 bits, 2 channels: 1.411 Mbit/s; 730 MB gives 69 minutes (useful rate). File size . Band 20 kHz on 2048 levels: 440 kbit/s. Perception: hearing threshold, frequency masking (a tone masks higher frequencies more), temporal masking (pre 2-5 ms, post 100-200 ms); perceptual coding puts the noise under the masking threshold (MP3, AAC).
Images and video. Grey 8 bits; RGB 24 bits/pixel. YCbCr: , and centred on 128; grey ; . The eye is less sensitive to chroma: 4:2:0 keeps 1 chroma sample per pixels, samples (half of RGB); chroma restored by zero-order interpolation. Video rate : 1080p at 50 fps Mbit/s; 4K 30 fps 8 bit Gbit/s, compression at least 300 for a 10 Mbit/s link.
Quality. ; ; 8 bits: . Table: excellent, 40-45 very good, 35-40 good, 30-35 sufficient, below 30 poor. Example: 8 to 4 bits: , MSE , PSNR dB; 2 bits: 22.8 dB. PSNR ignores contrast, colour and masking. Perceptual experiments have no certified source and are not written.
Typical mistakes: ; assumed enough; invertible quantization; ; no filter before subsampling; PSNR as a percentage; instead of in the bit-rate.
More reminders.
- Converter blocks: anti-aliasing filter, sampler, quantizer, inverse bit mapper, P/S; receiver: S/P, bit mapper, interpolator. The ideal interpolator has a sinc response: infinite and non-causal, hence not realisable.
- Replicas: the spectrum of the sampled signal is ; the filter error is the energy of the discarded part, .
- Holder: ; at it loses 24% with and 2.6% with : oversample.
- Binarization example: levels with codes ; the signal becomes . The index is sent, not the value.
- Speech packet: 20 ms samples bytes (140 bytes at 7 bits), 50 packets/s.
- CD capacity: useful data 87%, 730 MB: total rate Mbit/s, duration s min.
- Sizes: HD RGB MB; RGB Mbit; 10 Mpixel: RGB 30 MB, 4:2:0 15 MB. 4:4:4 = all components, 4:2:2 = chroma halved horizontally, 4:2:0 = halved both ways.
- Video rows: CIF 30 fps 36 Mbit/s; 720p 50 fps 553 Mbit/s; 1080p 50 fps 1244 Mbit/s; 4K 50 fps 5308 Mbit/s; the rate is the product .
- Quantization levels in practice: music 16 bits, speech 8 bits, grey image 8 bits, RGB 24 bits/pixel; two quantizations (ADC fine, encoder requantization).
- Mid-rise vs mid-tread: mid-rise has zero as a threshold, mid-tread has zero as a level.
- Interpolation choice: high means S&H or linear is enough; near Nyquist the truncated sinc is needed; with a larger support the interpolation is better but complexity and delay grow.
- Subsampling a digital signal: filter first, then keep one sample out of ().
- Speech parameters: filtered at 4 kHz, sampled at 8 kHz; 128 levels (7 bits) in Asia and America, 256 levels (8 bits) elsewhere.
- HDR: 10 or 12 bits per sample when 256 levels lose detail in very dark or very bright areas; 36 bits/pixel in RGB.