home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk1.iso / answers / compression-faq / part2 < prev    next >
Internet Message Format  |  1993-12-16  |  58KB

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!spool.mu.edu!howland.reston.ans.net!pipex!uknet!EU.net!julienas!chorus!chorus.fr
  2. From: jloup@chorus.fr (Jean-loup Gailly)
  3. Newsgroups: comp.compression,comp.compression.research,news.answers,comp.answers
  4. Subject: comp.compression Frequently Asked Questions (part 2/3)
  5. Summary: *** READ THIS BEFORE POSTING ***
  6. Keywords: data compression, FAQ
  7. Message-ID: <compr2_16dec93@chorus.fr>
  8. Date: 16 Dec 93 14:38:38 GMT
  9. Expires: 30 Jan 94 16:17:20 GMT
  10. References: <compr1_16dec93@chorus.fr>
  11. Sender: news@chorus.chorus.fr
  12. Reply-To: jloup@chorus.fr
  13. Followup-To: comp.compression
  14. Lines: 1118
  15. Approved: news-answers-request@MIT.Edu
  16. Supersedes: <compr2_16nov93@chorus.fr>
  17. Xref: senator-bedfellow.mit.edu comp.compression:9723 comp.compression.research:1195 news.answers:15906 comp.answers:3056
  18.  
  19. Archive-name: compression-faq/part2
  20. Last-modified: Nov 16th, 1993
  21.  
  22. This file is part 2 of a set of Frequently Asked Questions for the
  23. groups comp.compression and comp.compression.research.
  24. If you did not get part 1 or 3, you can get them by ftp
  25. on rtfm.mit.edu in directory
  26.    /pub/usenet/news.answers/compression-faq
  27.  
  28. If you don't want to see this FAQ regularly, please add the subject
  29. line to your kill file. If you have corrections or suggestions for
  30. this FAQ, send them to Jean-loup Gailly <jloup@chorus.fr>.  Thank you.
  31.  
  32. Contents
  33. ========
  34.  
  35. Part 2: (Long) introductions to data compression techniques
  36.  
  37. [70] Introduction to data compression (long)
  38.        Huffman and Related Compression Techniques
  39.        Arithmetic Coding
  40.        Substitutional Compressors
  41.           The LZ78 family of compressors
  42.           The LZ77 family of compressors
  43.  
  44. [71] Introduction to MPEG (long)
  45.        What is MPEG?
  46.        Does it have anything to do with JPEG?
  47.        Then what's JBIG and MHEG?
  48.        What has MPEG accomplished?
  49.        So how does MPEG I work?
  50.        What about the audio compression?
  51.        So how much does it compress?
  52.        What's phase II?
  53.        When will all this be finished?
  54.        How do I join MPEG?
  55.        How do I get the documents, like the MPEG I draft?
  56.  
  57. [72] What is wavelet theory?
  58. [73] What is the theoretical compression limit?
  59. [74] Introduction to JBIG
  60. [75] Introduction to JPEG
  61.  
  62. Part 3: (Long) list of image compression hardware
  63.  
  64. [85] Image compression hardware
  65. [99] Acknowledgments
  66.  
  67.  
  68. Search for "Subject: [#]" to get to question number # quickly. Some news
  69. readers can also take advantage of the message digest format used here.
  70.  
  71. ------------------------------------------------------------------------------
  72.  
  73. Subject: [70] Introduction to data compression (long)
  74.  
  75.  
  76. Written by Peter Gutmann <pgut1@cs.aukuni.ac.nz>.
  77.  
  78.  Huffman and Related Compression Techniques
  79.  ------------------------------------------
  80.  
  81.   *Huffman compression* is a statistical data compression technique which 
  82. gives a reduction in the average code length used to represent the symbols of 
  83. a alphabet.  The Huffman code is an example of a code which is optimal in the 
  84. case where all symbols probabilities are integral powers of 1/2.  A Huffman 
  85. code can be built in the following manner:
  86.  
  87.   (1) Rank all symbols in order of probability of occurrence.
  88.     
  89.   (2) Successively combine the two symbols of the lowest probability to form
  90.       a new composite symbol; eventually we will build a binary tree where
  91.       each node is the probability of all nodes beneath it.
  92.  
  93.   (3) Trace a path to each leaf, noticing the direction at each node.
  94.  
  95.   For a given frequency distribution, there are many possible Huffman codes,
  96. but the total compressed length will be the same. It is possible to
  97. define a 'canonical' Huffman tree, that is, pick one of these alternative
  98. trees. Such a canonical tree can then be represented very compactly, by
  99. transmitting only the bit length of each code. This technique is used
  100. in most archivers (pkzip, lha, zoo, arj, ...).
  101.  
  102.  
  103.   A technique related to Huffman coding is *Shannon-Fano coding*, which
  104. works as follows:
  105.  
  106.   (1) Divide the set of symbols into two equal or almost equal subsets
  107.       based on the probability of occurrence of characters in each
  108.       subset.  The first subset is assigned a binary zero, the second
  109.       a binary one.
  110.  
  111.   (2) Repeat step (1) until all subsets have a single element.
  112.  
  113. The algorithm used to create the Huffman codes is bottom-up, and the
  114. one for the Shannon-Fano codes is top-down. Huffman encoding always
  115. generates optimal codes, Shannon-Fano sometimes uses a few more bits.
  116.  
  117.  
  118.  Arithmetic Coding
  119.  -----------------
  120.  
  121.   It would appear that Huffman or Shannon-Fano coding is the perfect
  122. means of compressing data.  However, this is *not* the case.  As
  123. mentioned above, these coding methods are optimal when and only when
  124. the symbol probabilities are integral powers of 1/2, which is usually
  125. not the case.
  126.  
  127.   The technique of *arithmetic coding* does not have this restriction:
  128. It achieves the same effect as treating the message as one single unit
  129. (a technique which would, for Huffman coding, require enumeration of
  130. every single possible message), and thus attains the theoretical
  131. entropy bound to compression efficiency for any source.
  132.  
  133.   Arithmetic coding works by representing a number by an interval of real 
  134. numbers between 0 and 1.  As the message becomes longer, the interval needed 
  135. to represent it becomes smaller and smaller, and the number of bits needed to 
  136. specify that interval increases.  Successive symbols in the message reduce 
  137. this interval in accordance with the probability of that symbol. The more
  138. likely symbols reduce the range by less, and thus add fewer bits to the   
  139. message.
  140.  
  141.      1                                             Codewords
  142.     +-----------+-----------+-----------+           /-----\
  143.     |           |8/9 YY     |  Detail   |<- 31/32    .11111
  144.     |           +-----------+-----------+<- 15/16    .1111
  145.     |    Y      |           | too small |<- 14/16    .1110
  146.     |2/3        |    YX     | for text  |<- 6/8      .110
  147.     +-----------+-----------+-----------+
  148.     |           |           |16/27 XYY  |<- 10/16    .1010
  149.     |           |           +-----------+
  150.     |           |    XY     |           |
  151.     |           |           |   XYX     |<- 4/8      .100
  152.     |           |4/9        |           |
  153.     |           +-----------+-----------+
  154.     |           |           |           |
  155.     |    X      |           |   XXY     |<- 3/8      .011
  156.     |           |           |8/27       |
  157.     |           |           +-----------+
  158.     |           |    XX     |           |
  159.     |           |           |           |<- 1/4      .01
  160.     |           |           |   XXX     |
  161.     |           |           |           |
  162.     |0          |           |           |
  163.     +-----------+-----------+-----------+
  164.  
  165.   As an example of arithmetic coding, lets consider the example of two
  166. symbols X and Y, of probabilities 0.66 and 0.33. To encode this message, we
  167. examine the first symbol: If it is a X, we choose the lower partition; if
  168. it is a Y, we choose the upper partition.  Continuing in this manner for
  169. three symbols, we get the codewords shown to the right of the diagram above
  170. - they can be found by simply taking an appropriate location in the
  171. interval for that particular set of symbols and turning it into a binary
  172. fraction. In practice, it is also necessary to add a special end-of-data
  173. symbol, which is not represented in this simpe example.
  174.         
  175.   In this case the arithmetic code is not completely efficient, which is due 
  176. to the shortness of the message - with longer messages the coding efficiency 
  177. does indeed approach 100%.
  178.  
  179.   Now that we have an efficient encoding technique, what can we do with it? 
  180. What we need is a technique for building a model of the data which we can 
  181. then use with the encoder.  The simplest model is a fixed one, for example a 
  182. table of standard letter frequencies for English text which we can then use 
  183. to get letter probabilities.  An improvement on this technique is to use an 
  184. *adaptive model*, in other words a model which adjusts itself to the data 
  185. which is being compressed as the data is compressed.  We can convert the 
  186. fixed model into an adaptive one by adjusting the symbol frequencies after 
  187. each new symbol is encoded, allowing the model to track the data being 
  188. transmitted.  However, we can do much better than that.
  189.  
  190. Using the symbol probabilities by themselves is not a particularly good
  191. estimate of the true entropy of the data: We can take into account
  192. intersymbol probabilities as well.  The best compressors available today
  193. take this approach: DMC (Dynamic Markov Coding) starts with a zero-order
  194. Markov model and gradually extends this initial model as compression
  195. progresses; PPM (Prediction by Partial Matching) looks for a match of the
  196. text to be compressed in an order-n context.  If no match is found, it
  197. drops to an order n-1 context, until it reaches order 0.  Both these
  198. techniques thus obtain a much better model of the data to be compressed,
  199. which, combined with the use of arithmetic coding, results in superior
  200. compression performance.
  201.  
  202.   So if arithmetic coding-based compressors are so powerful, why are they not 
  203. used universally?  Apart from the fact that they are relatively new and 
  204. haven't come into general use too much yet, there is also one major concern:  
  205. The fact that they consume rather large amounts of computing resources, both 
  206. in terms of CPU power and memory.  The building of sophisticated models for 
  207. the compression can chew through a fair amount of memory (especially in the 
  208. case of DMC, where the model can grow without bounds); and the arithmetic 
  209. coding itself involves a fair amount of number crunching.
  210. There is however an alternative approach, a class of compressors generally 
  211. referred to as *substitutional* or *dictionary-based compressors*.
  212.  
  213.  Substitutional Compressors
  214.  --------------------------
  215.  
  216.   The basic idea behind a substitutional compressor is to replace an 
  217. occurrence of a particular phrase or group of bytes in a piece of data with a 
  218. reference to a previous occurrence of that phrase.  There are two main 
  219. classes of schemes, named after Jakob Ziv and Abraham Lempel, who first 
  220. proposed them in 1977 and 1978.
  221.  
  222. <The LZ78 family of compressors>
  223.  
  224.   LZ78-based schemes work by entering phrases into a *dictionary* and then, 
  225. when a repeat occurrence of that particular phrase is found, outputting the 
  226. dictionary index instead of the phrase.  There exist several compression 
  227. algorithms based on this principle, differing mainly in the manner in which 
  228. they manage the dictionary.  The most well-known scheme (in fact the most 
  229. well-known of all the Lempel-Ziv compressors, the one which is generally (and 
  230. mistakenly) referred to as "Lempel-Ziv Compression"), is Terry Welch's LZW 
  231. scheme, which he designed in 1984 for implementation in hardware for high- 
  232. performance disk controllers.
  233.  
  234. Input string: /WED/WE/WEE/WEB
  235.  
  236. Character input:    Code output:    New code value and associated string:
  237.     /W                  /                   256 = /W
  238.     E                   W                   257 = WE
  239.     D                   E                   258 = ED
  240.     /                   D                   259 = D/
  241.     WE                  256                 260 = /WE
  242.     /                   E                   261 = E/
  243.     WEE                 260                 262 = /WEE
  244.     /W                  261                 263 = E/W
  245.     EB                  257                 264 = WEB
  246.     <END>               B
  247.     
  248.   LZW starts with a 4K dictionary, of which entries 0-255 refer to individual 
  249. bytes, and entries 256-4095 refer to substrings.  Each time a new code is 
  250. generated it means a new string has been parsed.  New strings are generated 
  251. by appending the current character K to the end of an existing string w.  The 
  252. algorithm for LZW compression is as follows:
  253.  
  254.   set w = NIL
  255.   loop
  256.       read a character K
  257.       if wK exists is in the dictionary
  258.           w = wK
  259.       else
  260.           output the code for w
  261.           add wK to the string table
  262.           w = K
  263.   endloop
  264.  
  265.   A sample run of LZW over a (highly redundant) input string can be seen in 
  266. the diagram above.  The strings are built up character-by-character starting 
  267. with a code value of 256.  LZW decompression takes the stream of codes and 
  268. uses it to exactly recreate the original input data.  Just like the 
  269. compression algorithm, the decompressor adds a new string to the dictionary 
  270. each time it reads in a new code.  All it needs to do in addition is to 
  271. translate each incoming code into a string and send it to the output.  A 
  272. sample run of the LZW decompressor is shown in below.
  273.  
  274. Input code: /WED<256>E<260><261><257>B
  275.  
  276. Input code:        Output string:     New code value and associated string:
  277.     /                  /            
  278.     W                  W                      256 = /W
  279.     E                  E                      257 = WE
  280.     D                  D                      258 = ED
  281.     256                /W                     259 = D/
  282.     E                  E                      260 = /WE
  283.     260                /WE                    261 = E/
  284.     261                E/                     262 = /WEE
  285.     257                WE                     263 = E/W
  286.     B                  B                      264 = WEB
  287.            
  288.   The most remarkable feature of this type of compression is that the entire 
  289. dictionary has been transmitted to the decoder without actually explicitly 
  290. transmitting the dictionary.  At the end of the run, the decoder will have a 
  291. dictionary identical to the one the encoder has, built up entirely as part of 
  292. the decoding process.
  293.     LZW is more commonly encountered today in a variant known as LZC, after 
  294. its use in the UNIX "compress" program.  In this variant, pointers do not 
  295. have a fixed length.  Rather, they start with a length of 9 bits, and then 
  296. slowly grow to their maximum possible length once all the pointers of a 
  297. particular size have been used up.  Furthermore, the dictionary is not frozen 
  298. once it is full as for LZW - the program continually monitors compression 
  299. performance, and once this starts decreasing the entire dictionary is 
  300. discarded and rebuilt from scratch.  More recent schemes use some sort of 
  301. least-recently-used algorithm to discard little-used phrases once the 
  302. dictionary becomes full rather than throwing away the entire dictionary.  
  303.  
  304. Finally, not all schemes build up the dictionary by adding a single new 
  305. character to the end of the current phrase. An alternative technique is to 
  306. concatenate the previous two phrases (LZMW), which results in a faster 
  307. buildup of longer phrases than the character-by-character buildup of the 
  308. other methods.  The disadvantage of this method is that a more sophisticated 
  309. data structure is needed to handle the dictionary.
  310.  
  311. [A good introduction to LZW, MW, AP and Y coding is given in the yabba
  312. package. For ftp information, see question 2 in part one, file type .Y]
  313.  
  314.  
  315. <The LZ77 family of compressors>
  316.  
  317.   LZ77-based schemes keep track of the last n bytes of data seen, and when a 
  318. phrase is encountered that has already been seen, they output a pair of 
  319. values corresponding to the position of the phrase in the previously-seen 
  320. buffer of data, and the length of the phrase.  In effect the compressor moves 
  321. a fixed-size *window* over the data (generally referred to as a *sliding 
  322. window*), with the position part of the (position, length) pair referring to 
  323. the position of the phrase within the window.  The most commonly used 
  324. algorithms are derived from the LZSS scheme described by James Storer and 
  325. Thomas Szymanski in 1982.  In this the compressor maintains a window of size 
  326. N bytes and a *lookahead buffer* the contents of which it tries to find a 
  327. match for in the window:
  328.  
  329.   while( lookAheadBuffer not empty )
  330.       {
  331.       get a pointer ( position, match ) to the longest match in the window
  332.           for the lookahead buffer;
  333.  
  334.       if( length > MINIMUM_MATCH_LENGTH )
  335.           {
  336.           output a ( position, length ) pair;
  337.           shift the window length characters along;
  338.           }
  339.       else
  340.           {
  341.           output the first character in the lookahead buffer;
  342.           shift the window 1 character along;
  343.           }
  344.       }
  345.         
  346.   Decompression is simple and fast:  Whenever a ( position, length ) pair is 
  347. encountered, go to that ( position ) in the window and copy ( length ) bytes 
  348. to the output.
  349.  
  350.   Sliding-window-based schemes can be simplified by numbering the input text
  351. characters mod N, in effect creating a circular buffer.  The sliding window
  352. approach automatically creates the LRU effect which must be done explicitly in
  353. LZ78 schemes.  Variants of this method apply additional compression to the
  354. output of the LZSS compressor, which include a simple variable-length code
  355. (LZB), dynamic Huffman coding (LZH), and Shannon-Fano coding (ZIP 1.x)), all
  356. of which result in a certain degree of improvement over the basic scheme,
  357. especially when the data are rather random and the LZSS compressor has little
  358. effect.
  359.   Recently an algorithm was developed which combines the ideas behind LZ77 and
  360. LZ78 to produce a hybrid called LZFG.  LZFG uses the standard sliding window,
  361. but stores the data in a modified trie data structure and produces as output
  362. the position of the text in the trie.  Since LZFG only inserts complete
  363. *phrases* into the dictionary, it should run faster than other LZ77-based
  364. compressors.
  365.  
  366. All popular archivers (arj, lha, zip, zoo) are variations on the LZ77 theme.
  367.  
  368. ------------------------------------------------------------------------------
  369.  
  370. Subject: [71] Introduction to MPEG (long)
  371.  
  372.  
  373. For MPEG players, see item 15 in part 1 of the FAQ.  Frank Gadegast
  374. <phade@cs.tu-berlin.de> also posts a FAQ specialized in MPEG, available in
  375. ftp.cs.tu-berlin.de:/pub/msdos/windows3/graphics/mpegfa*.zip.
  376. Chad Fogg <cfogg@ole.cdac.com> also has another FAQ in preparation.
  377. The site ftp.crs4.it dedicated to the MPEG compression standard,
  378. see the directory mpeg and subdirectories.
  379.  
  380.  
  381. Introduction to MPEG written by Mark Adler <madler@cco.caltech.edu> around  
  382. January 1992 (and hence wildly out of date in this fast moving  
  383. area--any volunteers to update this section are welcome):
  384.  
  385. Q. What is MPEG?
  386. A. MPEG is a group of people that meet under ISO (the International
  387.    Standards Organization) to generate standards for digital video
  388.    (sequences of images in time) and audio compression.  In particular,
  389.    they define a compressed bit stream, which implicitly defines a
  390.    decompressor.  However, the compression algorithms are up to the
  391.    individual manufacturers, and that is where proprietary advantage
  392.    is obtained within the scope of a publicly available international
  393.    standard.  MPEG meets roughly four times a year for roughly a week
  394.    each time.  In between meetings, a great deal of work is done by
  395.    the members, so it doesn't all happen at the meetings.  The work
  396.    is organized and planned at the meetings.
  397.  
  398. Q. So what does MPEG stand for?
  399. A. Moving Pictures Experts Group.
  400.  
  401. Q. Does it have anything to do with JPEG?
  402. A. Well, it sounds the same, and they are part of the same subcommittee
  403.    of ISO along with JBIG and MHEG, and they usually meet at the same
  404.    place at the same time.  However, they are different sets of people
  405.    with few or no common individual members, and they have different
  406.    charters and requirements.  JPEG is for still image compression.
  407.  
  408. Q. Then what's JBIG and MHEG?
  409. A. Sorry I mentioned them. Ok, I'll simply say that JBIG is for binary
  410.    image compression (like faxes), and MHEG is for multi-media data
  411.    standards (like integrating stills, video, audio, text, etc.).
  412.    For an introduction to JBIG, see question 74 below.
  413.  
  414. Q. Ok, I'll stick to MPEG.  What has MPEG accomplished?
  415. A. So far (as of January 1992), they have completed the "Committee
  416.    Draft" of MPEG phase I, colloquially called MPEG I.  It defines
  417.    a bit stream for compressed video and audio optimized to fit into
  418.    a bandwidth (data rate) of 1.5 Mbits/s.  This rate is special
  419.    because it is the data rate of (uncompressed) audio CD's and DAT's.
  420.    The draft is in three parts, video, audio, and systems, where the
  421.    last part gives the integration of the audio and video streams
  422.    with the proper timestamping to allow synchronization of the two.
  423.    They have also gotten well into MPEG phase II, whose task is to
  424.    define a bitstream for video and audio coded at around 3 to 10
  425.    Mbits/s.
  426.  
  427. Q. So how does MPEG I work?
  428. A. First off, it starts with a relatively low resolution video
  429.    sequence (possibly decimated from the original) of about 352 by
  430.    240 frames by 30 frames/s (US--different numbers for Europe),
  431.    but original high (CD) quality audio.  The images are in color,
  432.    but converted to YUV space, and the two chrominance channels
  433.    (U and V) are decimated further to 176 by 120 pixels.  It turns
  434.    out that you can get away with a lot less resolution in those
  435.    channels and not notice it, at least in "natural" (not computer
  436.    generated) images.
  437.  
  438.    The basic scheme is to predict motion from frame to frame in the
  439.    temporal direction, and then to use DCT's (discrete cosine
  440.    transforms) to organize the redundancy in the spatial directions.
  441.    The DCT's are done on 8x8 blocks, and the motion prediction is
  442.    done in the luminance (Y) channel on 16x16 blocks.  In other words,
  443.    given the 16x16 block in the current frame that you are trying to
  444.    code, you look for a close match to that block in a previous or
  445.    future frame (there are backward prediction modes where later
  446.    frames are sent first to allow interpolating between frames).
  447.    The DCT coefficients (of either the actual data, or the difference
  448.    between this block and the close match) are "quantized", which
  449.    means that you divide them by some value to drop bits off the
  450.    bottom end.  Hopefully, many of the coefficients will then end up
  451.    being zero.  The quantization can change for every "macroblock"
  452.    (a macroblock is 16x16 of Y and the corresponding 8x8's in both
  453.    U and V).  The results of all of this, which include the DCT
  454.    coefficients, the motion vectors, and the quantization parameters
  455.    (and other stuff) is Huffman coded using fixed tables.  The DCT
  456.    coefficients have a special Huffman table that is "two-dimensional"
  457.    in that one code specifies a run-length of zeros and the non-zero
  458.    value that ended the run.  Also, the motion vectors and the DC
  459.    DCT components are DPCM (subtracted from the last one) coded.
  460.  
  461. Q. So is each frame predicted from the last frame?
  462. A. No.  The scheme is a little more complicated than that.  There are
  463.    three types of coded frames.  There are "I" or intra frames.  They
  464.    are simply a frame coded as a still image, not using any past
  465.    history.  You have to start somewhere.  Then there are "P" or
  466.    predicted frames.  They are predicted from the most recently
  467.    reconstructed I or P frame.  (I'm describing this from the point
  468.    of view of the decompressor.)  Each macroblock in a P frame can
  469.    either come with a vector and difference DCT coefficients for a
  470.    close match in the last I or P, or it can just be "intra" coded
  471.    (like in the I frames) if there was no good match.
  472.  
  473.    Lastly, there are "B" or bidirectional frames.  They are predicted
  474.    from the closest two I or P frames, one in the past and one in the
  475.    future.  You search for matching blocks in those frames, and try
  476.    three different things to see which works best.  (Now I have the
  477.    point of view of the compressor, just to confuse you.)  You try using
  478.    the forward vector, the backward vector, and you try averaging the
  479.    two blocks from the future and past frames, and subtracting that from
  480.    the block being coded.  If none of those work well, you can intra-
  481.    code the block.
  482.  
  483.    The sequence of decoded frames usually goes like:
  484.  
  485.    IBBPBBPBBPBBIBBPBBPB...
  486.  
  487.    Where there are 12 frames from I to I (for US and Japan anyway.)
  488.    This is based on a random access requirement that you need a
  489.    starting point at least once every 0.4 seconds or so.  The ratio
  490.    of P's to B's is based on experience.
  491.  
  492.    Of course, for the decoder to work, you have to send that first
  493.    P *before* the first two B's, so the compressed data stream ends
  494.    up looking like:
  495.  
  496.    0xx312645...
  497.  
  498.    where those are frame numbers.  xx might be nothing (if this is
  499.    the true starting point), or it might be the B's of frames -2 and
  500.    -1 if we're in the middle of the stream somewhere.
  501.  
  502.    You have to decode the I, then decode the P, keep both of those
  503.    in memory, and then decode the two B's.  You probably display the
  504.    I while you're decoding the P, and display the B's as you're
  505.    decoding them, and then display the P as you're decoding the next
  506.    P, and so on.
  507.  
  508. Q. You've got to be kidding.
  509. A. No, really!
  510.  
  511. Q. Hmm.  Where did they get 352x240?
  512. A. That derives from the CCIR-601 digital television standard which
  513.    is used by professional digital video equipment.  It is (in the US)
  514.    720 by 243 by 60 fields (not frames) per second, where the fields
  515.    are interlaced when displayed.  (It is important to note though
  516.    that fields are actually acquired and displayed a 60th of a second
  517.    apart.)  The chrominance channels are 360 by 243 by 60 fields a
  518.    second, again interlaced.  This degree of chrominance decimation
  519.    (2:1 in the horizontal direction) is called 4:2:2.  The source
  520.    input format for MPEG I, called SIF, is CCIR-601 decimated by 2:1
  521.    in the horizontal direction, 2:1 in the time direction, and an
  522.    additional 2:1 in the chrominance vertical direction.  And some
  523.    lines are cut off to make sure things divide by 8 or 16 where
  524.    needed.
  525.  
  526. Q. What if I'm in Europe?
  527. A. For 50 Hz display standards (PAL, SECAM) change the number of lines
  528.    in a field from 243 or 240 to 288, and change the display rate to
  529.    50 fields/s or 25 frames/s.  Similarly, change the 120 lines in
  530.    the decimated chrominance channels to 144 lines.  Since 288*50 is
  531.    exactly equal to 240*60, the two formats have the same source data
  532.    rate.
  533.  
  534. Q. You didn't mention anything about the audio compression.
  535. A. Oh, right.  Well, I don't know as much about the audio compression.
  536.    Basically they use very carefully developed psychoacoustic models
  537.    derived from experiments with the best obtainable listeners to
  538.    pick out pieces of the sound that you can't hear.  There are what
  539.    are called "masking" effects where, for example, a large component
  540.    at one frequency will prevent you from hearing lower energy parts
  541.    at nearby frequencies, where the relative energy vs. frequency
  542.    that is masked is described by some empirical curve.  There are
  543.    similar temporal masking effects, as well as some more complicated
  544.    interactions where a temporal effect can unmask a frequency, and
  545.    vice-versa.
  546.  
  547.    The sound is broken up into spectral chunks with a hybrid scheme
  548.    that combines sine transforms with subband transforms, and the
  549.    psychoacoustic model written in terms of those chunks.  Whatever
  550.    can be removed or reduced in precision is, and the remainder is
  551.    sent.  It's a little more complicated than that, since the bits
  552.    have to be allocated across the bands.  And, of course, what is
  553.    sent is entropy coded.
  554.  
  555. Q. So how much does it compress?
  556. A. As I mentioned before, audio CD data rates are about 1.5 Mbits/s.
  557.    You can compress the same stereo program down to 256 Kbits/s with
  558.    no loss in discernable quality.  (So they say.  For the most part
  559.    it's true, but every once in a while a weird thing might happen
  560.    that you'll notice.  However the effect is very small, and it takes
  561.    a listener trained to notice these particular types of effects.)
  562.    That's about 6:1 compression.  So, a CD MPEG I stream would have
  563.    about 1.25 MBits/s left for video.  The number I usually see though
  564.    is 1.15 MBits/s (maybe you need the rest for the system data
  565.    stream).  You can then calculate the video compression ratio from
  566.    the numbers here to be about 26:1.  If you step back and think
  567.    about that, it's little short of a miracle.  Of course, it's lossy
  568.    compression, but it can be pretty hard sometimes to see the loss,
  569.    if you're comparing the SIF original to the SIF decompressed.  There
  570.    is, however, a very noticeable loss if you're coming from CCIR-601
  571.    and have to decimate to SIF, but that's another matter.  I'm not
  572.    counting that in the 26:1.
  573.  
  574.    The standard also provides for other bit rates ranging from 32Kbits/s
  575.    for a single channel, up to 448 Kbits/s for stereo.
  576.  
  577. Q. What's phase II?
  578. A. As I said, there is a considerable loss of quality in going from
  579.    CCIR-601 to SIF resolution.  For entertainment video, it's simply
  580.    not acceptable.  You want to use more bits and code all or almost
  581.    all the CCIR-601 data.  From subjective testing at the Japan
  582.    meeting in November 1991, it seems that 4 MBits/s can give very
  583.    good quality compared to the original CCIR-601 material.  The
  584.    objective of phase II is to define a bit stream optimized for these
  585.    resolutions and bit rates.
  586.  
  587. Q. Why not just scale up what you're doing with MPEG I?
  588. A. The main difficulty is the interlacing.  The simplest way to extend
  589.    MPEG I to interlaced material is to put the fields together into
  590.    frames (720x486x30/s).  This results in bad motion artifacts that
  591.    stem from the fact that moving objects are in different places
  592.    in the two fields, and so don't line up in the frames.  Compressing
  593.    and decompressing without taking that into account somehow tends to
  594.    muddle the objects in the two different fields.
  595.  
  596.    The other thing you might try is to code the even and odd field
  597.    streams separately.  This avoids the motion artifacts, but as you
  598.    might imagine, doesn't get very good compression since you are not
  599.    using the redundancy between the even and odd fields where there
  600.    is not much motion (which is typically most of image).
  601.  
  602.    Or you can code it as a single stream of fields.  Or you can
  603.    interpolate lines.  Or, etc. etc.  There are many things you can
  604.    try, and the point of MPEG II is to figure out what works well.
  605.    MPEG II is not limited to consider only derivations of MPEG I.
  606.    There were several non-MPEG I-like schemes in the competition in
  607.    November, and some aspects of those algorithms may or may not
  608.    make it into the final standard for entertainment video compression.
  609.  
  610. Q. So what works?
  611. A. Basically, derivations of MPEG I worked quite well, with one that
  612.    used wavelet subband coding instead of DCT's that also worked very
  613.    well.  Also among the worked-very-well's was a scheme that did not
  614.    use B frames at all, just I and P's.  All of them, except maybe one,
  615.    did some sort of adaptive frame/field coding, where a decision is
  616.    made on a macroblock basis as to whether to code that one as one
  617.    frame macroblock or as two field macroblocks.  Some other aspects
  618.    are how to code I-frames--some suggest predicting the even field
  619.    from the odd field.  Or you can predict evens from evens and odds
  620.    or odds from evens and odds or any field from any other field, etc.
  621.  
  622. Q. So what works?
  623. A. Ok, we're not really sure what works best yet.  The next step is
  624.    to define a "test model" to start from, that incorporates most of
  625.    the salient features of the worked-very-well proposals in a
  626.    simple way.  Then experiments will be done on that test model,
  627.    making a mod at a time, and seeing what makes it better and what
  628.    makes it worse.  Example experiments are, B's or no B's, DCT vs.
  629.    wavelets, various field prediction modes, etc.  The requirements,
  630.    such as implementation cost, quality, random access, etc. will all
  631.    feed into this process as well.
  632.  
  633. Q. When will all this be finished?
  634. A. I don't know.  I'd have to hope in about a year or less.
  635.  
  636. Q. How do I join MPEG?
  637. A. You don't join MPEG.  You have to participate in ISO as part of a
  638.    national delegation.  How you get to be part of the national
  639.    delegation is up to each nation.  I only know the U.S., where you
  640.    have to attend the corresponding ANSI meetings to be able to
  641.    attend the ISO meetings.  Your company or institution has to be
  642.    willing to sink some bucks into travel since, naturally, these
  643.    meetings are held all over the world.  (For example, Paris,
  644.    Santa Clara, Kurihama Japan, Singapore, Haifa Israel, Rio de
  645.    Janeiro, London, etc.)
  646.  
  647. Q. Well, then how do I get the documents, like the MPEG I draft?
  648. A. MPEG is a draft ISO standard. It's exact name is ISO CD 11172.
  649.    The draft consists of three parts: System, Video, and Audio. The
  650.    System part (11172-1) deals with synchronization and multiplexing
  651.    of audio-visual information, while the Video (11172-2) and Audio
  652.    part (11172-3) address the video and the audio compression techniques
  653.    respectively.
  654.  
  655.    You may order it from your national standards body (e.g. ANSI in
  656.    the USA) or buy it from companies like
  657.      OMNICOM
  658.      phone +44 438 742424
  659.      FAX +44 438 740154
  660.  
  661. ------------------------------------------------------------------------------
  662.  
  663. Subject: [72] What is wavelet theory?
  664.  
  665.  
  666. Preprints and software are available by anonymous ftp from the
  667. Yale Mathematics Department computer ceres.math.yale.edu[130.132.23.22],
  668. in pub/wavelets and pub/software.
  669.  
  670. epic and hcompress are wavelet coders. (For source code, see item 15
  671. in part one).
  672.  
  673. Bill Press of Harvard/CfA has made some things available for anonymous
  674. ftp on cfata4.harvard.edu [128.103.40.79] in directory /pub. There is
  675. a short TeX article on wavelet theory (wavelet.tex, to be included in
  676. a future edition of Numerical Recipes), some sample wavelet code
  677. (wavelet.f, in FORTRAN - sigh), and a beta version of an astronomical
  678. image compression program which he is currently developing (FITS
  679. format data files only, in fitspress08.tar.Z).
  680.  
  681. A mailing list dedicated to research on wavelets has been set up at the
  682. University of South Carolina. To subscribe to this mailing list, send a
  683. message with "subscribe" as the subject to wavelet@math.scarolina.edu.
  684.  
  685.  
  686. A 5 minute course in wavelet transforms, by Richard Kirk <rak@crosfield.co.uk>:
  687.  
  688. Do you know what a Haar transform is? Its a transform to another orthonormal
  689. space (like the DFT), but the basis functions are a set of square wave bursts
  690. like this...
  691.  
  692.    +--+                         +------+
  693.    +  |  +------------------    +      |      +--------------
  694.       +--+                             +------+
  695.  
  696.          +--+                                 +------+
  697.    ------+  |  +------------    --------------+      |      +
  698.             +--+                                     +------+
  699.  
  700.                +--+             +-------------+
  701.    ------------+  |  +------    +             |             +
  702.                   +--+                        +-------------+
  703.  
  704.                      +--+       +---------------------------+
  705.    ------------------+  |  +    +                           +
  706.                         +--+
  707.  
  708. This is the set of functions for an 8-element 1-D Haar transform. You
  709. can probably see how to extend this to higher orders and higher dimensions
  710. yourself. This is dead easy to calculate, but it is not what is usually
  711. understood by a wavelet transform.
  712.  
  713. If you look at the eight Haar functions you see we have four functions
  714. that code the highest resolution detail, two functions that code the
  715. coarser detail, one function that codes the coarser detail still, and the 
  716. top function that codes the average value for the whole `image'.
  717.  
  718. Haar function can be used to code images instead of the DFT. With bilevel
  719. images (such as text) the result can look better, and it is quicker to code.
  720. Flattish regions, textures, and soft edges in scanned images get a nasty
  721. `blocking' feel to them. This is obvious on hardcopy, but can be disguised on
  722. color CRTs by the effects of the shadow mask. The DCT gives more consistent
  723. results.
  724.  
  725. This connects up with another bit of maths sometimes called Multispectral
  726. Image Analysis, sometimes called Image Pyramids.
  727.  
  728. Suppose you want to produce a discretely sampled image from a continuous 
  729. function. You would do this by effectively `scanning' the function using a
  730. sinc function [ sin(x)/x ] `aperture'. This was proved by Shannon in the 
  731. `forties. You can do the same thing starting with a high resolution
  732. discretely sampled image. You can then get a whole set of images showing 
  733. the edges at different resolutions by differencing the image at one
  734. resolution with another version at another resolution. If you have made this
  735. set of images properly they ought to all add together to give the original 
  736. image.
  737.  
  738. This is an expansion of data. Suppose you started off with a 1K*1K image.
  739. You now may have a 64*64 low resolution image plus difference images at 128*128
  740. 256*256, 512*512 and 1K*1K. 
  741.  
  742. Where has this extra data come from? If you look at the difference images you 
  743. will see there is obviously some redundancy as most of the values are near 
  744. zero. From the way we constructed the levels we know that locally the average
  745. must approach zero in all levels but the top. We could then construct a set of
  746. functions out of the sync functions at any level so that their total value 
  747. at all higher levels is zero. This gives us an orthonormal set of basis 
  748. functions for a transform. The transform resembles the Haar transform a bit,
  749. but has symmetric wave pulses that decay away continuously in either direction
  750. rather than square waves that cut off sharply. This transform is the
  751. wavelet transform ( got to the point at last!! ).
  752.  
  753. These wavelet functions have been likened to the edge detecting functions
  754. believed to be present in the human retina.
  755.  
  756.  
  757. Loren I. Petrich <lip@s1.gov> adds that order 2 or 3 Daubechies
  758. discrete wavelet transforms have a speed comparable to DCT's, and
  759. usually achieve compression a factor of 2 better for the same image
  760. quality than the JPEG 8*8 DCT. (See item 25 in part 1 of this FAQ for
  761. references on fast DCT algorithms.)
  762.  
  763. ------------------------------------------------------------------------------
  764.  
  765. Subject: [73] What is the theoretical compression limit?
  766.  
  767.  
  768. There is no compressor that is guaranteed to compress all possible input
  769. files. If it compresses some files, then it must enlarge some others.
  770. This can be proven by a simple counting argument (see question 9).
  771.  
  772. As an extreme example, the following algorithm achieves optimal
  773. compression for one special input file and enlarges all other files by
  774. only one bit:
  775.  
  776. - if the input data is <insert your favorite one here>, output a single 0 bit
  777. - otherwise output the bit 1 followed by the input data.
  778.  
  779. (You can even output an empty file in the first case if the decompressor
  780. can detect by other means that the input is empty.)
  781.  
  782. The concept of theoretical compression limit is meaningful only
  783. if you have a model for your input data. See question 70 above
  784. for some examples of data models.
  785.  
  786. ------------------------------------------------------------------------------
  787.  
  788. Subject: [74] Introduction to JBIG
  789.  
  790.  
  791. JBIG software and the JBIG specification are available on nic.funet.fi
  792. in /pub/graphics/misc/test-images/jbig.tar.gz.
  793.  
  794.  
  795. A short introduction to JBIG, written by Mark Adler <madler@cco.caltech.edu>:
  796.  
  797.   JBIG losslessly compresses binary (one-bit/pixel) images.  (The B stands
  798.   for bi-level.)  Basically it models the redundancy in the image as the
  799.   correlations of the pixel currently being coded with a set of nearby
  800.   pixels called the template.  An example template might be the two
  801.   pixels preceding this one on the same line, and the five pixels centered
  802.   above this pixel on the previous line.  Note that this choice only
  803.   involves pixels that have already been seen from a scanner.
  804.  
  805.   The current pixel is then arithmetically coded based on the eight-bit
  806.   (including the pixel being coded) state so formed.  So there are (in this
  807.   case) 256 contexts to be coded.  The arithmetic coder and probability
  808.   estimator for the contexts are actually IBM's (patented) Q-coder.  The
  809.   Q-coder uses low precision, rapidly adaptable (those two are related)
  810.   probability estimation combined with a multiply-less arithmetic coder.
  811.   The probability estimation is intimately tied to the interval calculations
  812.   necessary for the arithmetic coding.
  813.  
  814.   JBIG actually goes beyond this and has adaptive templates, and probably
  815.   some other bells and whistles I don't know about.  You can find a
  816.   description of the Q-coder as well as the ancestor of JBIG in the Nov 88
  817.   issue of the IBM Journal of Research and Development.  This is a very
  818.   complete and well written set of five articles that describe the Q-coder
  819.   and a bi-level image coder that uses the Q-coder.
  820.  
  821.   You can use JBIG on grey-scale or even color images by simply applying
  822.   the algorithm one bit-plane at a time.  You would want to recode the
  823.   grey or color levels first though, so that adjacent levels differ in
  824.   only one bit (called Gray-coding).  I hear that this works well up to
  825.   about six bits per pixel, beyond which JPEG's lossless mode works better.
  826.   You need to use the Q-coder with JPEG also to get this performance.
  827.  
  828.   Actually no lossless mode works well beyond six bits per pixel, since
  829.   those low bits tend to be noise, which doesn't compress at all.
  830.  
  831.   Anyway, the intent of JBIG is to replace the current, less effective
  832.   group 3 and 4 fax algorithms.
  833.  
  834.  
  835. Another introduction to JBIG, written by Hank van Bekkem <jbek@oce.nl>:
  836.  
  837.   The following description of the JBIG algorithm is derived from
  838.   experiences with a software implementation I wrote following the
  839.   specifications in the revision 4.1 draft of September 16, 1991. The
  840.   source will not be made available in the public domain, as parts of
  841.   JBIG are patented.
  842.  
  843.   JBIG (Joint Bi-level Image Experts Group) is an experts group of ISO,
  844.   IEC and CCITT (JTC1/SC2/WG9 and SGVIII). Its job is to define a
  845.   compression standard for lossless image coding ([1]). The main
  846.   characteristics of the proposed algorithm are:
  847.   - Compatible progressive/sequential coding. This means that a
  848.     progressively coded image can be decoded sequentially, and the
  849.     other way around.
  850.   - JBIG will be a lossless image compression standard: all bits in
  851.     your images before and after compression and decompression will be
  852.     exactly the same.
  853.  
  854.   In the rest of this text I will first describe the JBIG algorithm in
  855.   a short abstract of the draft. I will conclude by saying something
  856.   about the value of JBIG.
  857.  
  858.  
  859.   JBIG algorithm.
  860.   --------------
  861.  
  862.   JBIG parameter P specifies the number of bits per pixel in the image.
  863.   Its allowable range is 1 through 255, but starting at P=8 or so,
  864.   compression will be more efficient using other algorithms. On the
  865.   other hand, medical images such as chest X-rays are often stored with
  866.   12 bits per pixel, while no distorsion is allowed, so JBIG can
  867.   certainly be of use in this area. To limit the number of bit changes
  868.   between adjacent decimal values (e.g. 127 and 128), it is wise to use
  869.   Gray coding before compressing multi-level images with JBIG. JBIG
  870.   then compresses the image on a bitplane basis, so the rest of this
  871.   text assumes bi-level pixels.
  872.  
  873.   Progressive coding is a way to send an image gradually to a receiver
  874.   instead of all at once. During sending, more detail is sent, and the
  875.   receiver can build the image from low to high detail. JBIG uses
  876.   discrete steps of detail by successively doubling the resolution. The
  877.   sender computes a number of resolution layers D, and transmits these
  878.   starting at the lowest resolution Dl. Resolution reduction uses
  879.   pixels in the high resolution layer and some already computed low
  880.   resolution pixels as an index into a lookup table. The contents of
  881.   this table can be specified by the user.
  882.  
  883.   Compatibility between progressive and sequential coding is achieved
  884.   by dividing an image into stripes. Each stripe is a horizontal bar
  885.   with a user definable height. Each stripe is separately coded and
  886.   transmitted, and the user can define in which order stripes,
  887.   resolutions and bitplanes (if P>1) are intermixed in the coded data.
  888.   A progressive coded image can be decoded sequentially by decoding
  889.   each stripe, beginning by the one at the top of the image, to its
  890.   full resolution, and then proceeding to the next stripe. Progressive
  891.   decoding can be done by decoding only a specific resolution layer
  892.   from all stripes.
  893.  
  894.   After dividing an image into bitplanes, resolution layers and
  895.   stripes, eventually a number of small bi-level bitmaps are left to
  896.   compress. Compression is done using a Q-coder. Reference [2]
  897.   contains a full description, I will only outline the basic principles
  898.   here.
  899.  
  900.   The Q-coder codes bi-level pixels as symbols using the probability of
  901.   occurrence of these symbols in a certain context. JBIG defines two
  902.   kinds of context, one for the lowest resolution layer (the base
  903.   layer), and one for all other layers (differential layers).
  904.   Differential layer contexts contain pixels in the layer to be coded,
  905.   and in the corresponding lower resolution layer.
  906.  
  907.   For each combination of pixel values in a context, the probability
  908.   distribution of black and white pixels can be different. In an all
  909.   white context, the probability of coding a white pixel will be much
  910.   greater than that of coding a black pixel. The Q-coder assigns, just
  911.   like a Huffman coder, more bits to less probable symbols, and so
  912.   achieves compression. The Q-coder can, unlike a Huffmann coder,
  913.   assign one output codebit to more than one input symbol, and thus is
  914.   able to compress bi-level pixels without explicit clustering, as
  915.   would be necessary using a Huffman coder.
  916.  
  917.   Maximum compression will be achieved when all probabilities (one set
  918.   for each combination of pixel values in the context) follow the
  919.   probabilities of the pixels. The Q-coder therefore continuously
  920.   adapts these probabilities to the symbols it sees.
  921.  
  922.  
  923.   JBIG value.
  924.   ----------
  925.  
  926.   In my opinion, JBIG can be regarded as two combined devices:
  927.   - Providing the user the service of sending or storing multiple
  928.     representations of images at different resolutions without any
  929.     extra cost in storage. Differential layer contexts contain pixels
  930.     in two resolution layers, and so enable the Q-coder to effectively
  931.     code the difference in information between the two layers, instead
  932.     of the information contained in every layer. This means that,
  933.     within a margin of approximately 5%, the number of resolution
  934.     layers doesn't effect the compression ratio.
  935.   - Providing the user a very efficient compression algorithm, mainly
  936.     for use with bi-level images. Compared to CCITT Group 4, JBIG is
  937.     approximately 10% to 50% better on text and line art, and even
  938.     better on halftones. JBIG is however, just like Group 4, somewhat
  939.     sensitive to noise in images. This means that the compression ratio
  940.     decreases when the amount of noise in your images increases.
  941.  
  942.   An example of an application would be browsing through an image
  943.   database, e.g. an EDMS (engineering document management system).
  944.   Large A0 size drawings at 300 dpi or so would be stored using five
  945.   resolution layers. The lowest resolution layer would fit on a
  946.   computer screen. Base layer compressed data would be stored at the
  947.   beginning of the compressed file, thus making browsing through large
  948.   numbers of compressed drawings possible by reading and decompressing
  949.   just the first small part of all files. When the user stops browsing,
  950.   the system could automatically start decompressing all remaining
  951.   detail for printing at high resolution.
  952.  
  953.   [1] "Progressive Bi-level Image Compression, Revision 4.1", ISO/IEC
  954.       JTC1/SC2/WG9, CD 11544, September 16, 1991
  955.   [2] "An overview of the basic principles of the Q-coder adaptive
  956.       binary arithmetic coder", W.B. Pennebaker, J.L. Mitchell, G.G.
  957.       Langdon, R.B. Arps, IBM Journal of research and development,
  958.       Vol.32, No.6, November 1988, pp. 771-726 (See also the other
  959.       articles about the Q-coder in this issue)
  960.  
  961. ------------------------------------------------------------------------------
  962.  
  963. Subject: [75] Introduction to JPEG
  964.  
  965. Here is a brief overview of the inner workings of JPEG, plus some
  966. references for more detailed information, written by Tom Lane
  967. <tgl+@cs.cmu.edu>.  Please read item 19 in part 1 first.
  968.  
  969. JPEG works on either full-color or gray-scale images; it does not handle
  970. bilevel (black and white) images, at least not efficiently.  It doesn't
  971. handle colormapped images either; you have to pre-expand those into an
  972. unmapped full-color representation.  JPEG works best on "continuous tone"
  973. images; images with many sudden jumps in color values will not compress well.
  974.  
  975. There are a lot of parameters to the JPEG compression process.  By adjusting
  976. the parameters, you can trade off compressed image size against reconstructed
  977. image quality over a *very* wide range.  You can get image quality ranging
  978. from op-art (at 100x smaller than the original 24-bit image) to quite
  979. indistinguishable from the source (at about 3x smaller).  Usually the
  980. threshold of visible difference from the source image is somewhere around 10x
  981. to 20x smaller than the original, ie, 1 to 2 bits per pixel for color images.
  982. Grayscale requires a little bit less space.
  983.  
  984. JPEG defines a "baseline" lossy algorithm, plus optional extensions for
  985. progressive and hierarchical coding.  There is also a separate lossless
  986. compression mode; this typically gives about 2:1 compression, ie about 12
  987. bits per color pixel.  Most currently available JPEG hardware and software
  988. handles only the baseline mode.
  989.  
  990.  
  991. Here's the outline of the baseline compression algorithm:
  992.  
  993. 1. Transform the image into a suitable color space.  This is a no-op for
  994. grayscale, but for color images you generally want to transform RGB into a
  995. luminance/chrominance color space (YCbCr, YUV, etc).  The luminance component
  996. is grayscale and the other two axes are color information.  The reason for
  997. doing this is that you can afford to lose a lot more information in the
  998. chrominance components than you can in the luminance component; the human eye
  999. is not as sensitive to high-frequency color info as it is to high-frequency
  1000. luminance.  (See any TV system for precedents.)  You don't have to change the
  1001. color space if you don't want to, as the remainder of the algorithm works on
  1002. each color component independently, and doesn't care just what the data is.
  1003. However, compression will be less since you will have to code all the
  1004. components at luminance quality.
  1005.  
  1006. 2. (Optional) Downsample each component by averaging together groups of
  1007. pixels.  The luminance component is left at full resolution, while the color
  1008. components are usually reduced 2:1 horizontally and either 2:1 or 1:1 (no
  1009. change) vertically.  In JPEG-speak these alternatives are usually called
  1010. 2h2v and 2h1v sampling, but you may also see the terms "411" and "422"
  1011. sampling.  This step immediately reduces the data volume by one-half or
  1012. one-third, while having almost no impact on perceived quality.  (Obviously
  1013. this would not be true if you tried it in RGB color space...)  Note that
  1014. downsampling is not applicable to gray-scale data.
  1015.  
  1016. 3. Group the pixel values for each component into 8x8 blocks.  Transform each
  1017. 8x8 block through a discrete cosine transform (DCT); this is a relative of the
  1018. Fourier transform and likewise gives a frequency map, with 8x8 components.
  1019. Thus you now have numbers representing the average value in each block and
  1020. successively higher-frequency changes within the block.  The motivation for
  1021. doing this is that you can now throw away high-frequency information without
  1022. affecting low-frequency information.  (The DCT transform itself is reversible
  1023. except for roundoff error.)  See question 25 for fast DCT algorithms.
  1024.  
  1025. 4. In each block, divide each of the 64 frequency components by a separate
  1026. "quantization coefficient", and round the results to integers.  This is the
  1027. fundamental information-losing step.  A Q.C. of 1 loses no information;
  1028. larger Q.C.s lose successively more info.  The higher frequencies are normally
  1029. reduced much more than the lower.  (All 64 Q.C.s are parameters to the
  1030. compression process; tuning them for best results is a black art.  It seems
  1031. likely that the best values are yet to be discovered.  Most existing coders
  1032. use simple multiples of the example tables given in the JPEG standard.)
  1033.  
  1034. 5. Encode the reduced coefficients using either Huffman or arithmetic coding.
  1035. (Strictly speaking, baseline JPEG only allows Huffman coding; arithmetic
  1036. coding is an optional extension.)   Notice that this step is lossless, so it
  1037. doesn't affect image quality.  The arithmetic coding option uses Q-coding;
  1038. it is identical to the coder used in JBIG (see question 74).  Be aware that
  1039. Q-coding is patented.  Most existing implementations support only the Huffman
  1040. mode, so as to avoid license fees.  The arithmetic mode offers maybe 5 or 10%
  1041. better compression, which isn't enough to justify paying fees.
  1042.  
  1043. 6. Tack on appropriate headers, etc, and output the result.  In an
  1044. "interchange" JPEG file, all of the compression parameters are included
  1045. in the headers so that the decompressor can reverse the process.  For
  1046. specialized applications, the spec permits the parameters to be omitted
  1047. from the file; this saves several hundred bytes of overhead, but it means
  1048. that the decompressor must know what parameters the compressor used.
  1049.  
  1050.  
  1051. The decompression algorithm reverses this process, and typically adds some
  1052. smoothing steps to reduce pixel-to-pixel discontinuities.
  1053.  
  1054.  
  1055. Extensions:
  1056.  
  1057. The progressive mode is intended to support real-time transmission of images.
  1058. It allows the DCT coefficients to be sent incrementally in multiple "scans"
  1059. of the image.  With each scan, the decoder can produce a higher-quality
  1060. rendition of the image.  Thus a low-quality preview can be sent very quickly,
  1061. then refined as time allows.  Notice that the decoder must do essentially a
  1062. full JPEG decode cycle for each scan, so this scheme is useful only with fast
  1063. decoders (meaning dedicated hardware, at least at present).  However, the
  1064. total number of bits sent can actually be somewhat less than is necessary in
  1065. the baseline mode, especially if arithmetic coding is used.  So progressive
  1066. coding might be useful even if the decoder will simply save up the bits and
  1067. make only one output pass.
  1068.  
  1069. The hierarchical mode represents an image at multiple resolutions.  For
  1070. example, one could provide 512x512, 1024x1024, and 2048x2048 versions of the
  1071. image.  The higher-resolution images are coded as differences from the next
  1072. smaller image, and thus require many fewer bits than they would if stored
  1073. independently.  (However, the total number of bits will be greater than that
  1074. needed to store just the highest-resolution frame.)  Note that the individual
  1075. frames in a hierarchical sequence may be coded progressively if desired.
  1076.  
  1077.  
  1078. Lossless JPEG:
  1079.  
  1080. The separate lossless mode does not use DCT, since roundoff errors prevent a
  1081. DCT calculation from being lossless.  For the same reason, one would not
  1082. normally use colorspace conversion or downsampling, although these are
  1083. permitted by the standard.  The lossless mode simply codes the difference
  1084. between each pixel and the "predicted" value for the pixel.  The predicted
  1085. value is a simple function of the already-transmitted pixels just above and
  1086. to the left of the current one (eg, their average; 8 different predictor
  1087. functions are permitted).  The sequence of differences is encoded using the
  1088. same back end (Huffman or arithmetic) used in the lossy mode.
  1089.  
  1090. The main reason for providing a lossless option is that it makes a good
  1091. adjunct to the hierarchical mode: the final scan in a hierarchical sequence
  1092. can be a lossless coding of the remaining differences, to achieve overall
  1093. losslessness.  This isn't quite as useful as it may at first appear, because
  1094. exact losslessness is not guaranteed unless the encoder and decoder have
  1095. identical IDCT implementations (ie identical roundoff errors).
  1096.  
  1097.  
  1098. References:
  1099.  
  1100. For a good technical introduction to JPEG, see:
  1101.     Wallace, Gregory K.  "The JPEG Still Picture Compression Standard",
  1102.     Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
  1103. (Adjacent articles in that issue discuss MPEG motion picture compression,
  1104. applications of JPEG, and related topics.)  If you don't have the CACM issue
  1105. handy, a PostScript file containing a revised version of this article is
  1106. available at ftp.uu.net, graphics/jpeg/wallace.ps.Z.  The file (actually a
  1107. preprint for an article to appear in IEEE Trans. Consum. Elect.) omits the
  1108. sample images that appeared in CACM, but it includes corrections and some
  1109. added material.  Note: the Wallace article is copyright ACM and IEEE, and
  1110. it may not be used for commercial purposes.
  1111.  
  1112. An alternative, more leisurely explanation of JPEG can be found in "The Data
  1113. Compression Book" by Mark Nelson ([Nel 1991], see question 7).  This book
  1114. provides excellent introductions to many data compression methods including
  1115. JPEG, plus sample source code in C.  The JPEG-related source code is far from
  1116. industrial-strength, but it's a pretty good learning tool.
  1117.  
  1118. An excellent textbook about JPEG is "JPEG Still Image Data Compression
  1119. Standard" by William B. Pennebaker and Joan L. Mitchell.  Published by Van
  1120. Nostrand Reinhold, 1993, ISBN 0-442-01272-1.  650 pages, price US$59.95.
  1121. (VNR will accept credit card orders at 800/842-3636, or get your local
  1122. bookstore to order it.)  This book includes the complete text of the ISO
  1123. JPEG standards, DIS 10918-1 and draft DIS 10918-2.  Review by Tom Lane:
  1124. "This is by far the most complete exposition of JPEG in existence.  It's
  1125. written by two people who know what they are talking about: both serve on the
  1126. ISO JPEG standards committee.  If you want to know how JPEG works or why it
  1127. works that way, this is the book to have."
  1128.  
  1129. There are a number of errors in the first printing of the Pennebaker
  1130. & Mitchell book.  An errata list is available at ftp.uu.net:
  1131. graphics/jpeg/pm.errata.  At last report, all were fixed in the
  1132. second printing.
  1133.  
  1134. The official specification of JPEG is not currently available on-line.
  1135. I hear that CCITT specs may be on-line sometime soon, which would change this.
  1136. At the moment, your best bet is to buy the Pennebaker and Mitchell textbook.
  1137.