কম্পিউটার বিজ্ঞান · বই 2 · শ্রেণি 10–12

High School Computer Science

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

High School Computer Science · শ্রেণি 10–12

6Digital Images, Sound and Compression

Noor takes a photograph of the town square with her phone. The file on the phone weighs about 44 MB. She sends the picture to a friend in a message, and the copy that arrives weighs about 300300 KB, more than ten times less; on the friend’s screen it looks the same. Something was thrown away on the way, and something else was packed more tightly.

An illustration: taking a photograph of the market square, light becomes millions of numbers in a fraction of a second.
An illustration: taking a photograph of the market square, light becomes millions of numbers in a fraction of a second.

This chapter follows a picture and a sound from the world into numbers: how a sensor measures light, how a microphone signal becomes a list of samples, how big the raw numbers are, and the two ways of making them smaller, one that loses nothing and one that loses what the eye or the ear will not miss.

You already know

An image on a screen is a grid of pixels, each with a red, a green and a blue value from 00 to 255255 (Book 1, grade 5); a grid image can be stored as a plain-text file of numbers (Book 1, grade 9). The resolution of an image is its number of pixels across and down, and file sizes are counted in bytes, kilobytes and megabytes (Book 1, grade 4). The physics book describes sound as a vibration of the air and a signal as a quantity that varies with time (grade 10).

6.1 From a scene to pixels

A camera’s sensor is a grid of millions of tiny light detectors.

The image sensor of a consumer digital camera, on its flexible circuit: the light falls on the rectangle in the middle. Photograph: C-M, CC BY-SA 3.0.
The image sensor of a consumer digital camera, on its flexible circuit: the light falls on the rectangle in the middle. Photograph: C-M, CC BY-SA 3.0.

Definition 6.1 (Photosite)

A photosite is one light-sensitive cell of a camera’s sensor. During the exposure it measures how much light falls on it, as a number. A photosite measures brightness only; to see colour, each one sits under a small red, green or blue filter and measures that colour alone.

The filters form a repeating mosaic, usually with two green filters for one red and one blue in each 2×22 \times 2 block, because the eye is most sensitive to green. A photosite therefore knows one of the three colours of its pixel; the camera’s processor guesses the other two from the neighbours. This step is called demosaicing.

A colour filter mosaic over 4 × 4 photosites, and the 3 × 3 neighbourhood used to give the blue photosite at row 1, column 1 its missing red and green.
A colour filter mosaic over 4×44 \times 4 photosites, and the 3×33 \times 3 neighbourhood used to give the blue photosite at row 11, column 11 its missing red and green.
# Each photosite measured one colour: R, G or B, in the pattern RG / GB.
MOSAIC = [[200, 120, 190, 118],
          [110, 60, 115, 64],
          [180, 125, 170, 130],
          [105, 58, 100, 62]]


def colour_of(r, c):
    if r % 2 == 0:
        return "R" if c % 2 == 0 else "G"
    return "G" if c % 2 == 0 else "B"


def average(values):
    return round(sum(values) / len(values))


def rgb_at(r, c):
    """(R, G, B) of photosite (r, c): its own value, its neighbours' averages."""
    found = {"R": [], "G": [], "B": []}
    for dr in (-1, 0, 1):
        for dc in (-1, 0, 1):
            rr, cc = r + dr, c + dc
            if 0 <= rr < 4 and 0 <= cc < 4 and (dr, dc) != (0, 0):
                found[colour_of(rr, cc)].append(MOSAIC[rr][cc])
    found[colour_of(r, c)] = [MOSAIC[r][c]]
    return tuple(average(found[k]) for k in "RGB")


for r in range(4):
    print("  ".join(f"{colour_of(r, c)}{MOSAIC[r][c]:>3}" for c in range(4)))
print("pixel (1, 1):", rgb_at(1, 1))
print("pixel (2, 2):", rgb_at(2, 2))
Listing 6.1. Demosaicing by averaging the neighbours. code/grade-10/06-images-sound-compression/listings/demosaic.py
$ python demosaic.py
R200  G120  R190  G118
G110  B 60  G115  B 64
R180  G125  R170  G130
G105  B 58  G100  B 62
pixel (1, 1): (185, 118, 60)
pixel (2, 2): (170, 118, 61)
Output 6.1. The mosaic, each value with the colour it measured, and two pixels rebuilt.

Real cameras use cleverer guesses than a plain average, but the principle is the same: two thirds of the colour values of a photograph were computed, not measured.

Definition 6.2 (Colour depth)

The colour depth of an image is the number of bits used for the colour of one pixel. With one byte for each of red, green and blue, it is 2424 bits, which gives 224=16,777,2162^{24} = 16{,}777{,}216 colours.

The raw size of an image follows: width times height times bytes per pixel.

def raw_size(width, height, bytes_per_pixel=3):
    """Bytes of an uncompressed image: one value per colour per pixel."""
    return width * height * bytes_per_pixel


for width, height in ((640, 480), (1920, 1080), (4000, 3000)):
    size = raw_size(width, height)
    print(f"{width} x {height}: {width * height:>10,} pixels, {size:>10,} bytes"
          f" = {size / 2**20:.1f} MiB")
Listing 6.2. Raw sizes of three images. code/grade-10/06-images-sound-compression/listings/raw_size.py
$ python raw_size.py
640 x 480:    307,200 pixels,    921,600 bytes = 0.9 MiB
1920 x 1080:  2,073,600 pixels,  6,220,800 bytes = 5.9 MiB
4000 x 3000: 12,000,000 pixels, 36,000,000 bytes = 34.3 MiB
Output 6.2. A 1212-megapixel photograph takes 3636 million bytes before any compression.

So Noor’s 44 MB file is already about nine times smaller than the raw 3636 MB of the image it holds.

6.2 Sound as numbers

A microphone turns the vibration of the air into an electric signal that varies continuously with time. A computer keeps only some values of it.

Definition 6.3 (Sampling rate, bit depth)

To sample a signal is to measure it at regular instants. The sampling rate is the number of measurements, or samples, per second, in hertz (Hz). Each sample is then rounded to one of a fixed number of levels, a step called quantisation; the bit depth is the number of bits used for one sample, so that there are 2bit depth2^{\text{bit depth}} levels.

A 440 Hz tone sampled 8000 times per second and quantised on 3 bits, that is 8 levels. Each dot is a stored sample; between two samples nothing is kept. With 16 bits the steps would be more than 9000 times finer.
A 440440 Hz tone sampled 80008000 times per second and quantised on 33 bits, that is 88 levels. Each dot is a stored sample; between two samples nothing is kept. With 1616 bits the steps would be more than 90009000 times finer.

The audio compact disc samples 44,10044{,}100 times per second with 1616 bits per sample. A stereo recording keeps two channels, one for each ear, so a second of it holds 44,100×2×2=176,40044{,}100 \times 2 \times 2 = 176{,}400 bytes. The listing writes one second of a tone at a smaller rate and depth, with Python’s wave module.

import math
import wave
from pathlib import Path

RATE = 8000        # samples per second
FREQUENCY = 440    # hertz
samples = bytes(round(127.5 + 127 * math.sin(2 * math.pi * FREQUENCY * k / RATE))
                for k in range(RATE))

with wave.open("tone.wav", "wb") as w:
    w.setnchannels(1)
    w.setsampwidth(1)  # one byte per sample: 8 bits
    w.setframerate(RATE)
    w.writeframes(samples)

print("first samples:", list(samples[:10]))
size = Path("tone.wav").stat().st_size
print("file size:", size, "bytes for", len(samples), "samples")
Listing 6.3. One second of a 440440 Hz tone, 88 kHz, 88 bits. code/grade-10/06-images-sound-compression/listings/make_wav.py
$ python make_wav.py
first samples: [128, 171, 208, 237, 252, 253, 239, 211, 174, 131]
file size: 8044 bytes for 8000 samples
Output 6.3. 80008000 samples of one byte, and 4444 bytes more for the file’s header.

The values go up and down around 128128, the middle of a byte, once every 8000/440≈188000 / 440 \approx 18 samples. A higher sampling rate follows faster vibrations, which the ear hears as higher notes; the physics book explains why a rate of twice the highest frequency is needed.

6.3 Compression without loss

Definition 6.4 (Compression, lossless, lossy)

Compression encodes data in fewer bytes. It is lossless when decompression gives back exactly the original bytes, and lossy when it gives back only an approximation, chosen so that the difference is hard to notice.

Definition 6.5 (Compression ratio)

The compression ratio is the original size divided by the compressed size. A ratio of 44 means the compressed data is four times smaller; a ratio below 11 means it grew.

The simplest lossless method works on data with long stretches of the same value, such as a map with a plain background.

Definition 6.6 (Run-length coding)

Run-length coding replaces each run, a maximal stretch of equal consecutive values, by the pair (length of the run, value).

One row of 55 pixels of a map, white and black, and its five runs. Ten numbers describe 55 pixels.
One row of 5555 pixels of a map, white and black, and its five runs. Ten numbers describe 5555 pixels.
import random


def rle_encode(s):
    """Return the list of (count, character) runs of the string s."""
    runs = []
    for ch in s:
        if runs and runs[-1][1] == ch:
            runs[-1] = (runs[-1][0] + 1, ch)
        else:
            runs.append((1, ch))
    return runs


def rle_decode(runs):
    return "".join(ch * count for count, ch in runs)


row = "WWWWWWWWWWBBBWWWWWWWWWWWWWWWWBBBBBBBBWWWWWWWWWWWWWWWWWW"
runs = rle_encode(row)
print(runs)
print(rle_decode(runs) == row, len(row), "characters,", len(runs), "runs")

rng = random.Random(7)
noise = "".join(rng.choice("WB") for _ in range(len(row)))
print(noise)
print(len(rle_encode(noise)), "runs for", len(noise), "characters")
Listing 6.4. Run-length coding, on a map row and on noise. code/grade-10/06-images-sound-compression/listings/rle.py
$ python rle.py
[(10, 'W'), (3, 'B'), (16, 'W'), (8, 'B'), (18, 'W')]
True 55 characters, 5 runs
BWBWWWBWWWWBBWWWBWWWWBWWWWBBWWBWWWBWWWWBBBBBBBWWWWBBBBB
21 runs for 55 characters
Output 6.4. Five runs for the map row; 2121 for a random row of the same length.

On noise the runs are short, and storing each one as a pair can take more room than the pixels themselves. How much a method compresses depends on the data, not only on the method.

The general-purpose compressors used for files, such as the DEFLATE method behind zip files and Python’s zlib module (described in 1996), go further: they replace a repeated sequence by a reference to its earlier occurrence, a dictionary method, and write frequent values with fewer bits than rare ones.

import random
import zlib

samples = {
    "repeated text": b"the cat sat on the mat. " * 400,
    "zeros": bytes(10_000),
    "random bytes": random.Random(1).randbytes(10_000),
}
for name, data in samples.items():
    packed = zlib.compress(data, 9)
    same = zlib.decompress(packed) == data
    print(f"{name:14} {len(data):6} -> {len(packed):6} bytes"
          f"  ratio {len(data) / len(packed):7.1f}  same back: {same}")
Listing 6.5. zlib on three kinds of data. code/grade-10/06-images-sound-compression/listings/zlib_sizes.py
$ python zlib_sizes.py
repeated text    9600 ->     73 bytes  ratio   131.5  same back: True
zeros           10000 ->     33 bytes  ratio   303.0  same back: True
random bytes    10000 ->  10011 bytes  ratio     1.0  same back: True
Output 6.5. Repetitive data shrinks a hundredfold; random bytes grow a little.

Proposition 6.7 (No lossless method shrinks everything)

For every lossless compression method and every nn, some file of nn bytes is not made shorter.

The proof is Exercise 6.12: it counts files. The random bytes of the listing are such files, and so, very nearly, are recordings of music, as the weekend problem shows.

6.4 Compression with loss

A photograph or a song does not have to come back bit for bit: it has to look or sound the same. Lossy methods throw away what matters least: fine detail that the eye cannot see at the viewing size, sounds hidden by louder ones, and small differences of colour or loudness. The simplest of these steps uses fewer levels.

def quantise(value, levels):
    """Round a grey value 0..255 to the nearest of `levels` evenly spaced values."""
    step = 255 / (levels - 1)
    return round(round(value / step) * step)


greys = list(range(256))
for levels in (256, 16, 8, 2):
    errors = [abs(g - quantise(g, levels)) for g in greys]
    step = 255 / (levels - 1)
    print(f"{levels:3} levels: step {step:6.2f}  largest error {max(errors)}")
print([quantise(g, 8) for g in (0, 20, 100, 128, 200, 255)])
Listing 6.6. Fewer grey levels. code/grade-10/06-images-sound-compression/listings/quantise.py
$ python quantise.py
256 levels: step   1.00  largest error 0
 16 levels: step  17.00  largest error 8
  8 levels: step  36.43  largest error 18
  2 levels: step 255.00  largest error 127
[0, 36, 109, 146, 182, 255]
Output 6.6. With 88 levels instead of 256256, each grey needs 33 bits instead of 88, and is off by at most 1818.
How a photograph file is made: a lossy step chooses what to forget, then a lossless step packs what is left. Sending a picture in a message usually repeats the lossy step more strongly.
How a photograph file is made: a lossy step chooses what to forget, then a lossless step packs what is left. Sending a picture in a message usually repeats the lossy step more strongly.

Method 6.8 (Choosing a kind of compression)

  1. Programs, text, tables and anything that must come back exactly: lossless only.
  2. Photographs, music and video meant for eyes and ears: lossy, at a quality chosen for the use (a message, a print, an archive).
  3. Never compress a lossy file again and again with loss: each round loses a little more.

6.5 Metadata

Definition 6.9 (Metadata)

The metadata of a file is data about the data it holds: for an image, its width, height and colour depth; for a sound, its sampling rate, bit depth and number of channels; often also the date, the device and the place where it was made.

Every image or sound file starts with a header that holds the metadata a program needs to read the rest.

The simple PPM image format writes its header as text: the letters P6, the width, the height and the largest value. A WAV file, a format of 1991, starts with the four letters RIFF, then WAVE and a block named fmt that gives the channels, the sampling rate and the bit depth.

import wave
from pathlib import Path

pixels = bytes([255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255])  # 2 x 2, RGB
Path("tiny.ppm").write_bytes(b"P6\n2 2\n255\n" + pixels)
data = Path("tiny.ppm").read_bytes()
magic, width, height, maxval = data.split(maxsplit=4)[:4]
print("PPM:", magic, int(width), int(height), int(maxval), len(data), "bytes")

with wave.open("click.wav", "wb") as w:
    w.setnchannels(2)
    w.setsampwidth(2)
    w.setframerate(44100)
    w.writeframes(bytes(4 * 441))
with wave.open("click.wav", "rb") as r:
    print("WAV:", r.getnchannels(), "channels,", 8 * r.getsampwidth(), "bits,",
          r.getframerate(), "Hz,", r.getnframes(), "frames")
print(Path("click.wav").read_bytes()[:16])
Listing 6.7. Writing two tiny files and reading their headers. code/grade-10/06-images-sound-compression/listings/read_header.py
$ python read_header.py
PPM: b'P6' 2 2 255 23 bytes
WAV: 2 channels, 16 bits, 44100 Hz, 441 frames
b'RIFF\x08\x07\x00\x00WAVEfmt '
Output 6.7. 2×22 \times 2 pixels take 1212 bytes and the PPM header 1111; the WAV file begins with its format’s name.

Safe use

A photograph taken with a phone usually carries, in its metadata, the date, the model of the phone and often the exact position where it was taken. Before sharing a picture of a place that should stay private, such as your home, check what the file says about itself, or use a program or setting that removes the metadata.

6.6 Exercises

Exercise 6.1 ★

What is the raw size, in bytes and in MiB, of a 4000×30004000 \times 3000 image with 33 bytes per pixel? And of the same image in grey levels with one byte per pixel?

Solution

Solution of Exercise 6.1.

4000×3000×3=36,000,0004000 \times 3000 \times 3 = 36{,}000{,}000 bytes, that is 36,000,000/220≈34.336{,}000{,}000 / 2^{20} \approx 34.3 MiB, as the listing printed. In grey levels, one byte per pixel: 12,000,00012{,}000{,}000 bytes, about 11.411.4 MiB.

Exercise 6.2 ★

How many bytes does one second of stereo sound take at 48,00048{,}000 samples per second and 1616 bits per sample? And one hour?

Solution

Solution of Exercise 6.2.

48,000×2×2=192,00048{,}000 \times 2 \times 2 = 192{,}000 bytes per second. One hour: 3600×192,000=691,200,0003600 \times 192{,}000 = 691{,}200{,}000 bytes, about 659659 MiB.

Exercise 6.3 ★

What does rle_encode("AAABCCCCD") return? How many numbers and characters does the result hold, against the 99 characters of the string?

Solution

Solution of Exercise 6.3.

[(3, "A"), (1, "B"), (4, "C"), (1, "D")] (Python prints the letters with single quotes): 44 numbers and 44 characters, 88 values against 99. Runs of length 11 cost more than they save.

Exercise 6.4 ★

Put these in order of compressed size with zlib, without running: 10,00010{,}000 copies of the letter a; a book chapter of 10,00010{,}000 characters; 10,00010{,}000 random bytes. Explain.

Solution

Solution of Exercise 6.4.

The 10,00010{,}000 letters a come out smallest, a few dozen bytes: the whole input is one repetition. The chapter’s text comes next, a few thousand bytes: words and spaces repeat, and some letters are much more frequent than others. The random bytes come out largest, a little more than 10,00010{,}000 bytes: there is nothing to exploit, and the format adds a few bytes of its own, as the listing showed.

Exercise 6.5 ★

Write rle_decode(runs) without looking at the listing, and check that decoding an encoding gives back the string.

Solution

Solution of Exercise 6.5.

return "".join(ch * count for count, ch in runs): each pair gives its character repeated count times, and the pieces are joined in order. The listing checks rle_decode(rle_encode(row)) == row; the chapter’s tests check it on 300300 random strings.

Exercise 6.6 ★★

An encoder walks through the string with an index, counts equal neighbours, and appends a run each time the character changes. On "WWB" it returns [(2, "W")]. Find the bug and correct it; which strings does the buggy version handle correctly?

Solution

Solution of Exercise 6.6.

A run is appended only when the character changes, and the last run is followed by no change: it is never appended. After the loop, add the last run (exercises/rle_bugs.py):

if s: runs.append((count, s[-1]))

The test on the empty string keeps an empty list. The buggy version is right only on the empty string: every other string has a last run.

Exercise 6.7 ★★

Suppose a run is stored in 22 bytes, one for the length and one for the value. Which row of nn pixels of one byte each makes the encoding as long as possible, and how long? When does run-length coding pay?

Solution

Solution of Exercise 6.7.

The worst row has no two equal neighbours, such as WBWBWB: nn runs of length 11, so 2n2n bytes, twice the row. The encoding is shorter exactly when there are fewer than n/2n/2 runs, that is, when runs are on average longer than 22 pixels: plain areas, drawings and maps, not photographs.

Exercise 6.8 ★★

A plain PGM image is a text file: P2, the width, the height, the largest grey value, then the grey values. Write histogram(text), which returns the list of the numbers of pixels of each grey level.

Solution

Solution of Exercise 6.8.

Split the text into words; check that the first is P2; read the width, height and largest value; take the next width * height words as whole numbers; count them in a list of maxval + 1 zeros (exercises/pgm_histogram.py). For the image P2 3 2 4 with values 0 1 1 4 4 4 it returns [1, 2, 0, 0, 3].

Exercise 6.9 ★★

Some screens store a colour in 1616 bits: 55 for red, 66 for green and 55 for blue. How many colours is that? How many levels does each colour have, and why might green get the extra bit?

Solution

Solution of Exercise 6.9.

216=65,5362^{16} = 65{,}536 colours. Red and blue have 25=322^5 = 32 levels each, green 26=642^6 = 64. The eye tells shades of green apart best, as the colour filter mosaic also reflects with its two green photosites in four, so the extra bit is best spent there.

Exercise 6.10 ★★

A student changes the condition of the demosaicing listing to 0 <= rr <= 4 and 0 <= cc <= 4. Which pixels does this break, and how?

Solution

Solution of Exercise 6.10.

With <= 4, the index 44 is accepted, but the rows and columns are numbered 00 to 33. For every pixel in the last row or the last column, a neighbour at index 44 is read, and MOSAIC[4] or MOSAIC[r][4] raises an IndexError: the program stops. The other pixels are unchanged. The condition must be < 4, or better < len(MOSAIC).

Exercise 6.11 ★★

Write wav_duration(path), which returns the duration of a WAV file in seconds from the number of frames and the sampling rate in its header. What is the duration of the tone of the listing?

Solution

Solution of Exercise 6.11.

Open the file with wave.open(path, "rb") and return w.getnframes() / w.getframerate() (exercises/wav_duration.py): a frame holds one sample per channel, so the number of frames per second is the sampling rate. The tone of the listing has 80008000 frames at 80008000 Hz: 1.01.0 s.

Exercise 6.12 ★★★

Prove the proposition that no lossless method shrinks every file: count the files of exactly nn bytes, and the files of fewer than nn bytes, and use the fact that two different files must not be compressed to the same result.

Solution

Solution of Exercise 6.12.

There are 256n256^n files of exactly nn bytes, and 1+256+2562+⋯+256n−11 + 256 + 256^2 + \dots + 256^{n-1} files of fewer than nn bytes. Multiplying this sum by 256−1256 - 1 gives 256n−1256^n - 1, since all the other terms cancel; so the sum is (256n−1)/255(256^n - 1)/255, less than 256n256^n. A lossless method must send two different files to two different results, otherwise decompression could not tell which one to give back. If it made every file of nn bytes shorter, it would send 256n256^n different files into fewer than 256n256^n shorter files: two of them would share a result. So some file of nn bytes is not made shorter.

Exercise 6.13 ★★★

Write bitmap_ratio(rows) for a black-and-white bitmap given as a list of strings of W and B: it returns the number of pixels, the number of runs over all rows, and the ratio when each run costs as much as two pixels. Try it on a bitmap of your own with large plain areas, and on a chessboard.

Solution

Solution of Exercise 6.13.

bitmap_ratio adds the lengths of the rows and the numbers of runs of each row, and returns the pixels divided by twice the runs (exercises/rle_bitmap.py). On a map with large plain areas the ratio is well above 11. On an 8×88 \times 8 chessboard every pixel is a run: 6464 pixels, 6464 runs, a ratio of 0.50.5, the worst case of Exercise 6.7.

Exercise 6.14 ★★★

Prove that rounding a grey value to the nearest of evenly spaced levels with step ss makes an error of at most s/2s/2. Check it against the output of the quantisation listing for 1616 and 88 levels.

Solution

Solution of Exercise 6.14.

The levels are 0,s,2s,…0, s, 2s, \dots. A grey value vv lies between two neighbouring levels ksks and (k+1)s(k + 1)s, so its distances to them add up to ss; the smaller of the two is at most s/2s/2, and rounding picks the nearer level. In the listing the levels are also rounded to whole numbers, which can add up to 12\tfrac12. For 1616 levels, s=17s = 17 and the largest error printed is 8≤8.58 \le 8.5; for 88 levels, s≈36.43s \approx 36.43 and the largest error is 18≤18.218 \le 18.2.

Exercise 6.15 ★★★

A tone of 70007000 Hz is sampled 80008000 times per second. Count, in the samples, how many times per second the signal goes from negative to non-negative. What frequency does the recording seem to have? Explain with the positions of the samples on the wave (this effect is called aliasing).

Solution

Solution of Exercise 6.15.

The count gives 10001000 crossings per second (exercises/aliasing.py): the recording seems to be a 10001000 Hz tone. Between two samples the 70007000 Hz wave makes 7000/8000=787000/8000 = \tfrac78 of a turn, which lands at the same place as going back 18\tfrac18 of a turn. The samples therefore trace a wave that goes back one eighth of a turn per sample, one turn every 88 samples: 8000/8=10008000 / 8 = 1000 turns per second. The samples cannot tell the two waves apart, which is why the sampling rate must be more than twice the highest frequency kept.

6.7 Problem: A Minute of Music

Problem 6.1

Weekend problem — why music files hardly shrink with a general-purpose compressor

A disc-quality recording uses the compact disc’s sampling rate and bit depth, in stereo. The program exercises/minute_of_music.py computes its size and compresses one second of synthetic music, made of three tones and a little noise, and one second of silence.

Part I — The format.

  1. Give the sampling rate and the bit depth of the compact disc.
  2. How many levels can one sample take?
  3. How many samples does one second of stereo hold?
  4. How long is the gap between two samples of one channel, in microseconds?

Part II — Bytes per second and per minute.

  1. Compute the number of bytes per second.
  2. Compute the number of bytes per minute.
  3. Convert it to MiB (11 MiB =220= 2^{20} bytes) and to MB (10610^6 bytes).
  4. What is the bit rate, in bits per second?

Part III — A song and an album.

  1. What is the raw size of a song of 33 minutes 3030 seconds?
  2. How many such songs fit in 11 GB (10910^9 bytes)?
  3. A WAV file adds a header of 4444 bytes. By what fraction does it change the size of the song?
  4. A music service sends the same song at 160,000160{,}000 bits per second. What is its compression ratio against the raw recording?
  5. Is that compression lossy or lossless? Use the proposition of this chapter and Part IV to argue.

Part IV — Compressing samples.

  1. Run the program. How many runs does one second of music have, against how many bytes? What would run-length coding do to it?
  2. What ratio does zlib reach on the music, and on the silence?
  3. Why are the bytes of music so different from one to the next, even for a smooth tone? Think of what a 1616-bit sample’s low byte holds.
  4. Why does the silence compress so well?
  5. A recording has a long silence at the end. Explain why lossless compression of the whole file still gains a little.
  6. State the result: the size of one minute of disc-quality stereo, in bytes and in MiB, and the ratio that zlib reaches on music against silence.
Solution

Solution of Problem 6.1.

1. 44,10044{,}100 samples per second, 1616 bits per sample.

2. 216=65,5362^{16} = 65{,}536 levels.

3. 2×44,100=88,2002 \times 44{,}100 = 88{,}200 samples.

4. 1/44,1001/44{,}100 s ≈22.7\approx 22.7 µs.

5. 88,200×2=176,40088{,}200 \times 2 = 176{,}400 bytes per second, as the program prints.

6. 60×176,400=10,584,00060 \times 176{,}400 = 10{,}584{,}000 bytes.

7. 10,584,000/220≈10.0910{,}584{,}000 / 2^{20} \approx 10.09 MiB, and 10.58410.584 MB.

8. 8×176,400=1,411,2008 \times 176{,}400 = 1{,}411{,}200 bits per second.

9. 210×176,400=37,044,000210 \times 176{,}400 = 37{,}044{,}000 bytes, about 35.335.3 MiB.

10. 109/37,044,000≈26.9910^9 / 37{,}044{,}000 \approx 26.99: 2626 whole songs.

11. 44/37,044,000≈1.2×10−644 / 37{,}044{,}000 \approx 1.2 \times 10^{-6}, about a millionth: nothing.

12. 1,411,200/160,000=8.821{,}411{,}200 / 160{,}000 = 8.82.

13. Lossy. Part IV measures a lossless ratio of about 1.091.09 on this music with zlib, nowhere near 8.828.82. Methods built for sound do better by predicting each sample from the ones before, but still nowhere near 8.828.82; and the proposition says that no lossless method shrinks every file. The service throws away what the ear hardly notices.

14. 175,662175{,}662 runs for 176,400176{,}400 bytes: almost every byte is a run of its own. Run-length coding with two bytes per run would nearly double the size, to about 351,000351{,}000 bytes.

15. About 1.091.09 on music (161,664161{,}664 bytes) and about 909909 on silence (194194 bytes).

16. A sample is stored in two bytes, the low byte first. The low byte holds the finest 1256\tfrac{1}{256} of the amplitude: even a smooth tone moves by hundreds of levels from one sample to the next, and the small noise changes it at random. The bytes of the two channels and of the two halves of each sample also alternate. Seen as a sequence of bytes, the music looks almost random.

17. Every byte is 00: one run of 176,400176{,}400 bytes, which a dictionary method describes in a few references to what it has just written.

18. The silent part compresses as well as the silence of Part IV, so the file shrinks by roughly the length of that silence; the music before it hardly shrinks at all.

19. One minute of disc-quality stereo is 44,100×2×2×60=10,584,00044{,}100 \times 2 \times 2 \times 60 = 10{,}584{,}000 bytes, about 10.110.1 MiB. A general-purpose lossless compressor, zlib, reaches a ratio of only about 1.091.09 on this music, against about 909909 on silence: seen as bytes, the samples look nearly random. Compressors made for sound predict each sample and do better, but not by a factor of eight: that is why music files are made small with lossy methods.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো