lzw and gif explained----steve blackstock

      i hope this little document will help enlighten those of you out there
who want to know more about the lempel-ziv welch compression algorithm, and,
specifically, the implementation that gif uses.
     before we start, here's a little terminology, for the purposes of this
      "character": a fundamental data element. in normal text files, this is
just a single byte. in raster images, which is what we're interested in, it's
an index that specifies the color of a given pixel. i'll refer to an arbitray
character as "k".
      "charstream": a stream of characters, as in a data file.
      "string": a number of continuous characters, anywhere from one to very
many characters in length. i can specify an arbitrary string as "[...]k".
      "prefix": almost the same as a string, but with the implication that a
prefix immediately precedes a character, and a prefix can have a length of
zero. so, a prefix and a character make up a string. i will refer to an
arbitrary prefix as "[...]".
      "root": a single-character string. for most purposes, this is a
character, but we may occasionally make a distinction. it is [...]k, where
[...] is empty.
      "code": a number, specified by a known number of bits, which maps to a
      "codestream": the output stream of codes, as in the "raster data"
      "entry": a code and its string.
      "string table": a list of entries; usually, but not necessarily, unique.
      that should be enough of that.
     lzw is a way of compressing data that takes advantage of repetition of
strings in the data. since raster data usually contains a lot of this
repetition, lzw is a good way of compressing and decompressing it.
     for the moment, lets consider normal lzw encoding and decoding. gif's
variation on the concept is just an extension from there.
     lzw manipulates three objects in both compression and decompression: the
charstream, the codestream, and the string table. in compression, the
charstream is the input and the codestream is the output. in decompression,
the codestream is the input and the charstream is the output. the string table
is a product of both compression and decompression, but is never passed from
one to the other.
     the first thing we do in lzw compression is initialize our string table.
to do this, we need to choose a code size (how many bits) and know how many
values our characters can possibly take. let's say our code size is 12 bits,
meaning we can store 0->fff, or 4096 entries in our string table. lets also
say that we have 32 possible different characters. (this corresponds to, say,
a picture in which there are 32 different colors possible for each pixel.) to
initialize the table, we set code#0 to character#0, code #1 to character#1,
and so on, until code#31 to character#31. actually, we are specifying that
each code from 0 to 31 maps to a root. there will be no more entries in the
table that have this property.
     now we start compressing data. let's first define something called the
"current prefix". it's just a prefix that we'll store things in and compare
things to now and then. i will refer to it as "[.c.]". initially, the current
prefix has nothing in it. let's also define a "current string", which will be
the current prefix plus the next character in the charstream. i will refer to
the current string as "[.c.]k", where k is some character. ok, look at the
first character in the charstream. call it p. make [.c.]p the current string.
(at this point, of course, it's just the root p.) now search through the
string table to see if [.c.]p appears in it. of course, it does now, because
our string table is initialized to have all roots. so we don't do anything.
now make [.c.]p the current prefix. look at the next character in the
charstream. call it q. add it to the current prefix to form [.c.]q, the
current string. now search through the string table to see if [.c.]q appears
in it. in this case, of course, it doesn't. aha! now we get to do something.
add [.c.]q (which is pq in this case) to the string table for code#32, and
output the code for [.c.] to the codestream. now start over again with the
current prefix being just the root p. keep adding characters to [.c.] to form
[.c.]k, until you can't find [.c.]k in the string table. then output the code
for [.c.] and add [.c.]k to the string table. in pseudo-code, the algorithm
goes something like this:
     [1] initialize string table;
     [2] [.c.] <- empty;
     [3] k <- next character in charstream;
     [4] is [.c.]k in string table?
      (yes: [.c.] <- [.c.]k;
            go to [3];
      (no: add [.c.]k to the string table;
           output the code for [.c.] to the codestream;
           [.c.] <- k;
           go to [3];
       it's as simple as that! of course, when you get to step [3] and there
aren't any more characters left, you just output the code for [.c.] and throw
the table away. you're done.
      wanna do an example? let's pretend we have a four-character alphabet:
a,b,c,d. the charstream looks like abacaba. let's compress it. first, we
initialize our string table to: #0=a, #1=b, #2=c, #3=d. the first character is
a, which is in the string table, so [.c.] becomes a. next we get ab, which is
not in the table, so we output code #0 (for [.c.]),
     and add ab to the string table as code #4. [.c.] becomes b. next we get
[.c.]a = ba, which is not in the string table, so output code #1, and add ba
to the string table as code #5. [.c.] becomes a. next we get ac, which is not
in the string table. output code #0, and add ac to the string table as code
#6. now [.c.] becomes c. next we get [.c.]a = ca, which is not in the table.
output #2 for c, and add ca to table as code#7. now [.c.] becomes a. next we
get ab, which is in the string table, so [.c.] gets ab, and we look at aba,
which is not in the string table, so output the code for ab, which is #4, and
add aba to the string table as code #8. [.c.] becomes a. we can't get any more
characters, so we just output #0 for the code for a, and we're done. so, the
codestream is #0#1#0#2#4#0.
      a few words (four) should be said here about efficiency: use a hashing
strategy. the search through the string table can be computationally
intensive, and some hashing is well worth the effort. also, note that
"straight lzw" compression runs the risk of overflowing the string table -
getting to a code which can't be represented in the number of bits you've set
aside for codes. there are several ways of dealing with this problem, and gif
implements a very clever one, but we'll get to that.
      an important thing to notice is that, at any point during the
compression, if [...]k is in the string table, [...] is there also. this fact
suggests an efficient method for storing strings in the table. rather than
store the entire string of k's in the table, realize that any string can be
expressed as a prefix plus a character: [...]k. if we're about to store [...]k
in the table, we know that [...] is already there, so we can just store the
code for [...] plus the final character k.
      ok, that takes care of compression. decompression is perhaps more
difficult conceptually, but it is really easier to program.
      here's how it goes: we again have to start with an initialized string
table. this table comes from what knowledge we have about the charstream that
we will eventually get, like what possible values the characters can take. in
gif files, this information is in the header as the number of possible pixel
values. the beauty of lzw, though, is that this is all we need to know. we
will build the rest of the string table as we decompress the codestream. the
compression is done in such a way that we will never encounter a code in the
codestream that we can't translate into a string.
      we need to define something called a "current code", which i will refer
to as "<code>", and an "old-code", which i will refer to as "<old>". to start
things off, look at the first code. this is now <code>. this code will be in
the intialized string table as the code for a root. output the root to the
charstream. make this code the old-code <old>. *now look at the next code, and
make it <code>. it is possible that this code will not be in the string table,
but let's assume for now that it is. output the string corresponding to <code>
to the codestream. now find the first character in the string you just
translated. call this k. add this to the prefix [...] generated by <old> to
form a new string [...]k. add this string [...]k to the string table, and set
the old-code <old> to the current code <code>. repeat from where i typed the
asterisk, and you're all set. read this paragraph again if you just skimmed
it!!!  now let's consider the possibility that <code> is not in the string
table. think back to compression, and try to understand what happens when you
have a string like p[...]p[...]pq appear in the charstream. suppose p[...] is
already in the string table, but p[...]p is not. the compressor will parse out
p[...], and find that p[...]p is not in the string table. it will output the
code for p[...], and add p[...]p to the string table. then it will get up to
p[...]p for the next string, and find that p[...]p is in the table, as
     the code just added. so it will output the code for p[...]p if it finds
that p[...]pq is not in the table. the decompressor is always "one step
behind" the compressor. when the decompressor sees the code for p[...]p, it
will not have added that code to it's string table yet because it needed the
beginning character of p[...]p to add to the string for the last code, p[...],
to form the code for p[...]p. however, when a decompressor finds a code that
it doesn't know yet, it will always be the very next one to be added to the
string table. so it can guess at what the string for the code should be, and,
in fact, it will always be correct. if i am a decompressor, and i see
code#124, and yet my string table has entries only up to code#123, i can
figure out what code#124 must be, add it to my string table, and output the
string. if code#123 generated the string, which i will refer to here as a
prefix, [...], then code#124, in this special case, will be [...] plus the
first character of [...]. so just add the first character of [...] to the end
of itself. not too bad.  as an example (and a very common one) of this special
case, let's assume we have a raster image in which the first three pixels have
the same color value. that is, my charstream looks like: qqq.... for the sake
of argument, let's say we have 32 colors, and q is the color#12. the
compressor will generate the code sequence 12,32,.... (if you don't know why,
take a minute to understand it.) remember that #32 is not in the initial
table, which goes from #0 to #31. the decompressor will see #12 and translate
it just fine as color q. then it will see #32 and not yet know what that
means. but if it thinks about it long enough, it can figure out that qq should
be entry#32 in the table and qq should be the next string output.  so the
decompression pseudo-code goes something like:
      [1] initialize string table;
     [2] get first code: <code>;
     [3] output the string for <code> to the charstream;
     [4] <old> = <code>;
     [5] <code> <- next code in codestream;
     [6] does <code> exist in the string table?
      (yes: output the string for <code> to the charstream;
            [...] <- translation for <old>;
            k <- first character of translation for <code>;
            add [...]k to the string table;        <old> <- <code>;  )
      (no: [...] <- translation for <old>;
           k <- first character of [...];
           output [...]k to charstream and add it to string table;
           <old> <- <code>
     [7] go to [5];
      again, when you get to step [5] and there are no more codes, you're
finished.  outputting of strings, and finding of initial characters in strings
are efficiency problems all to themselves, but i'm not going to suggest ways
to do them here. half the fun of programming is figuring these things out!
      now for the gif variations on the theme. in part of the header of a gif
file, there is a field, in the raster data stream, called "code size". this is
a very misleading name for the field, but we have to live with it. what it is
really is the "root size". the actual size, in bits, of the compression codes
actually changes during compression/decompression, and i will refer to that
size here as the "compression size". the initial table is just the codes for
all the roots, as usual, but two special codes are added on top of those.
suppose you have a "code size", which is usually the number of bits per pixel
in the image, of n. if the number of bits/pixel is one, then n must be 2: the
roots take up slots #0 and #1 in the initial table, and the two special codes
will take up slots #4 and #5. in any other case, n is the number of bits per
pixel, and the roots take up slots #0 through #(2**n-1), and the special codes
are (2**n) and (2**n + 1). the initial compression size will be n+1 bits per
code. if you're encoding, you output the codes (n+1) bits at a time to start
with, and if you're decoding, you grab (n+1) bits from the codestream at a
time.  as for the special codes: <cc> or the clear code, is (2**n), and <eoi>,
or end-of-information, is (2**n + 1). <cc> tells the compressor to re-
initialize the string table, and to reset the compression size to (n+1). <eoi>
means there's no more in the codestream.  if you're encoding or decoding, you
should start adding things to the string table at <cc> + 2. if you're
encoding, you should output <cc> as the very first code, and then whenever
after that you reach code #4095 (hex fff), because gif does not allow
compression sizes to be greater than 12 bits. if you're decoding, you should
reinitialize your string table when you observe <cc>.  the variable
compression sizes are really no big deal. if you're encoding, you start with a
compression size of (n+1) bits, and, whenever you output the code
(2**(compression size)-1), you bump the compression size up one bit. so the
next code you output will be one bit longer. remember that the largest
compression size is 12 bits, corresponding to a code of 4095. if you get that
far, you must output <cc> as the next code, and start over.  if you're
decoding, you must increase your compression size as soon as you write entry
#(2**(compression size) - 1) to the string table. the next code you read will
be one bit longer. don't make the mistake of waiting until you need to add the
code (2**compression size) to the table. you'll have already missed a bit from
the last code.  the packaging of codes into a bitsream for the raster data is
also a potential stumbling block for the novice encoder or decoder. the lowest
order bit in the code should coincide with the lowest available bit in the
first available byte in the codestream. for example, if you're starting with
5-bit compression codes, and your first three codes are, say, <abcde>,
<fghij>, <klmno>, where e, j, and o are bit#0, then your codestream will start
off like:
       byte#0: hijabcde
       byte#1: .klmnofg
      so the differences between straight lzw and gif lzw are: two additional
special codes and variable compression sizes. if you understand lzw, and you
understand those variations, you understand it all!
      just as sort of a p.s., you may have noticed that a compressor has a
little bit of flexibility at compression time. i specified a "greedy" approach
to the compression, grabbing as many characters as possible before outputting
codes. this is, in fact, the standard lzw way of doing things, and it will
yield the best compression ratio. but there's no rule saying you can't stop
anywhere along the line and just output the code for the current prefix,
whether it's already in the table or not, and add that string plus the next
character to the string table. there are various reasons for wanting to do
this, especially if the strings get extremely long and make hashing difficult.
if you need to, do it.
      hope this helps out.----steve blackstock