lib/gifdecomp.c

Go to the documentation of this file.
00001 /* decode.c - An LZW decoder for GIF
00002  * Copyright (C) 1987, by Steven A. Bennett
00003  *
00004  * Permission is given by the author to freely redistribute and include
00005  * this code in any program as long as this credit is given where due.
00006  *
00007  * In accordance with the above, I want to credit Steve Wilhite who wrote
00008  * the code which this is heavily inspired by...
00009  *
00010  * GIF and 'Graphics Interchange Format' are trademarks (tm) of
00011  * Compuserve, Incorporated, an H&R Block Company.
00012  *
00013  * Release Notes: This file contains a decoder routine for GIF images
00014  * which is similar, structurally, to the original routine by Steve Wilhite.
00015  * It is, however, somewhat noticably faster in most cases.
00016  *
00017  */
00018 
00019 #include "common.h"
00020 #include "gifcodes.h"
00021 
00022 static char const rcsid[] = "$Id: gifdecomp.c,v 1.3 2003/05/06 07:33:42 kate Exp $";
00023 
00024 
00025 /* extern int gif_get_byte()
00026  *
00027  *   - This external (machine specific) function is expected to return
00028  * either the next byte from the GIF file, or a negative number, as
00029  * defined in gifcodes.h.
00030  */
00031 extern int gif_get_byte();
00032 
00033 /* extern int gif_out_line(pixels, linelen)
00034  *     UBYTE pixels[];
00035  *     int linelen;
00036  *
00037  *   - This function takes a full line of pixels (one byte per pixel) and
00038  * displays them (or does whatever your program wants with them...).  It
00039  * should return zero, or negative if an error or some other event occurs
00040  * which would require aborting the decode process...  Note that the length
00041  * passed will almost always be equal to the line length passed to the
00042  * decoder function, with the sole exception occurring when an ending code
00043  * occurs in an odd place in the GIF file...  In any case, linelen will be
00044  * equal to the number of pixels passed...
00045  */
00046 extern int gif_out_line();
00047 
00048 /* extern int bad_code_count;
00049  *
00050  * This value is the only other global required by the using program, and
00051  * is incremented each time an out of range code is read by the decoder.
00052  * When this value is non-zero after a decode, your GIF file is probably
00053  * corrupt in some way...
00054  */
00055 int bad_code_count;
00056 
00057 #define MAX_CODES   4095
00058 
00059 /* Static variables */
00060 static WORD curr_size;                     /* The current code size */
00061 static WORD clear;                         /* Value for a clear code */
00062 static WORD ending;                        /* Value for a ending code */
00063 static WORD newcodes;                      /* First available code */
00064 static WORD top_slot;                      /* Highest code for current size */
00065 static WORD slot;                          /* Last read code */
00066 
00067 /* The following static variables are used
00068  * for seperating out codes
00069  */
00070 static WORD navail_bytes = 0;              /* # bytes left in block */
00071 static WORD nbits_left = 0;                /* # bits left in current byte */
00072 static UBYTE b1;                           /* Current byte */
00073 static UBYTE gif_byte_buff[256+3];               /* Current block */
00074 static UBYTE *pbytes;                      /* Pointer to next byte in block */
00075 
00076 static long code_mask[13] = {
00077      0,
00078      0x0001, 0x0003,
00079      0x0007, 0x000F,
00080      0x001F, 0x003F,
00081      0x007F, 0x00FF,
00082      0x01FF, 0x03FF,
00083      0x07FF, 0x0FFF
00084      };
00085 
00086 
00087 /* This function initializes the decoder for reading a new image.
00088  */
00089 static WORD init_exp(size)
00090    WORD size;
00091    {
00092    curr_size = size + 1;
00093    top_slot = 1 << curr_size;
00094    clear = 1 << size;
00095    ending = clear + 1;
00096    slot = newcodes = ending + 1;
00097    navail_bytes = nbits_left = 0;
00098    return(0);
00099    }
00100 
00101 /* get_next_code()
00102  * - gets the next code from the GIF file.  Returns the code, or else
00103  * a negative number in case of file errors...
00104  */
00105 static WORD get_next_code()
00106    {
00107    WORD i, x;
00108    unsigned long ret;
00109 
00110    if (nbits_left == 0)
00111       {
00112       if (navail_bytes <= 0)
00113          {
00114 
00115          /* Out of bytes in current block, so read next block
00116           */
00117          pbytes = gif_byte_buff;
00118          if ((navail_bytes = gif_get_byte()) < 0)
00119             return(navail_bytes);
00120          else if (navail_bytes)
00121             {
00122             for (i = 0; i < navail_bytes; ++i)
00123                {
00124                if ((x = gif_get_byte()) < 0)
00125                   return(x);
00126                gif_byte_buff[i] = x;
00127                }
00128             }
00129          }
00130       b1 = *pbytes++;
00131       nbits_left = 8;
00132       --navail_bytes;
00133       }
00134 
00135    ret = b1 >> (8 - nbits_left);
00136    while (curr_size > nbits_left)
00137       {
00138       if (navail_bytes <= 0)
00139          {
00140 
00141          /* Out of bytes in current block, so read next block
00142           */
00143          pbytes = gif_byte_buff;
00144          if ((navail_bytes = gif_get_byte()) < 0)
00145             return(navail_bytes);
00146          else if (navail_bytes)
00147             {
00148             for (i = 0; i < navail_bytes; ++i)
00149                {
00150                if ((x = gif_get_byte()) < 0)
00151                   return(x);
00152                gif_byte_buff[i] = x;
00153                }
00154             }
00155          }
00156       b1 = *pbytes++;
00157       ret |= b1 << nbits_left;
00158       nbits_left += 8;
00159       --navail_bytes;
00160       }
00161    nbits_left -= curr_size;
00162    ret &= code_mask[curr_size];
00163    return((WORD)(ret));
00164    }
00165 
00166 
00167 
00168 /* WORD decoder(linewidth)
00169  *    WORD linewidth;               * Pixels per line of image *
00170  *
00171  * - This function decodes an LZW image, according to the method used
00172  * in the GIF spec.  Every *linewidth* 'characters' (ie. pixels) decoded
00173  * will generate a call to gif_out_line(), which is a user specific function
00174  * to display a line of pixels.  The function gets it's codes from
00175  * get_next_code() which is responsible for reading blocks of data and
00176  * seperating them into the proper size codes.  Finally, gif_get_byte() is
00177  * the global routine to read the next byte from the GIF file.
00178  *
00179  * It is generally a good idea to have linewidth correspond to the actual
00180  * width of a line (as specified in the Image header) to make your own
00181  * code a bit simpler, but it isn't absolutely necessary.
00182  *
00183  * Returns: 0 if successful, else negative.  (See ERRS.H)
00184  *
00185  */
00186 
00187 static WORD decoder(linewidth,buf,stack,suffix,prefix)
00188    WORD linewidth;
00189    UBYTE *buf;          /* food for gif_line_out, where the pixels go */
00190    UBYTE *stack;        /* Stack for storing pixels backwards */
00191    UBYTE *suffix;       /* Suffix table */
00192    UWORD *prefix;       /* Prefix linked list */
00193    {
00194    register UBYTE *sp, *bufptr;
00195    register WORD code, fc, oc, bufcnt;
00196    WORD c, size, ret;
00197 
00198    /* Initialize for decoding a new image...
00199     */
00200    if ((size = gif_get_byte()) < 0)
00201       return(size);
00202    if (size < 2 || 9 < size)
00203       return(BAD_CODE_SIZE);
00204    init_exp(size);
00205 
00206    /* Initialize in case they forgot to put in a clear code.
00207     * (This shouldn't happen, but we'll try and decode it anyway...)
00208     */
00209    oc = fc = 0;
00210 
00211 
00212    /* Set up the stack pointer and decode buffer pointer
00213     */
00214    sp = stack;
00215    bufptr = buf;
00216    bufcnt = linewidth;
00217 
00218    /* This is the main loop.  For each code we get we pass through the
00219     * linked list of prefix codes, pushing the corresponding 'character' for
00220     * each code onto the stack.  When the list reaches a single 'character'
00221     * we push that on the stack too, and then start unstacking each
00222     * character for output in the correct order.  Special handling is
00223     * included for the clear code, and the whole thing ends when we get
00224     * an ending code.
00225     */
00226    while ((c = get_next_code()) != ending)
00227       {
00228 
00229       /* If we had a file error, return without completing the decode
00230        */
00231       if (c < 0)
00232          {
00233          return(c);
00234          }
00235 
00236       /* If the code is a clear code, reinitialize all necessary items.
00237        */
00238       if (c == clear)
00239          {
00240          curr_size = size + 1;
00241          slot = newcodes;
00242          top_slot = 1 << curr_size;
00243 
00244          /* Continue reading codes until we get a non-clear code
00245           * (Another unlikely, but possible case...)
00246           */
00247          while ((c = get_next_code()) == clear)
00248             ;
00249 
00250          /* If we get an ending code immediately after a clear code
00251           * (Yet another unlikely case), then break out of the loop.
00252           */
00253          if (c == ending)
00254             break;
00255 
00256          /* Finally, if the code is beyond the range of already set codes,
00257           * (This one had better NOT happen...  I have no idea what will
00258           * result from this, but I doubt it will look good...) then set it
00259           * to color zero.
00260           */
00261          if (c >= slot)
00262             c = 0;
00263 
00264          oc = fc = c;
00265 
00266          /* And let us not forget to put the char into the buffer... And
00267           * if, on the off chance, we were exactly one pixel from the end
00268           * of the line, we have to send the buffer to the gif_out_line()
00269           * routine...
00270           */
00271          *bufptr++ = c;
00272          if (--bufcnt == 0)
00273             {
00274             if ((ret = gif_out_line(buf, linewidth)) < 0)
00275                {
00276                return(ret);
00277                }
00278             bufptr = buf;
00279             bufcnt = linewidth;
00280             }
00281          }
00282       else
00283          {
00284 
00285          /* In this case, it's not a clear code or an ending code, so
00286           * it must be a code code...  So we can now decode the code into
00287           * a stack of character codes. (Clear as mud, right?)
00288           */
00289          code = c;
00290 
00291          /* Here we go again with one of those off chances...  If, on the
00292           * off chance, the code we got is beyond the range of those already
00293           * set up (Another thing which had better NOT happen...) we trick
00294           * the decoder into thinking it actually got the last code read.
00295           * (Hmmn... I'm not sure why this works...  But it does...)
00296           */
00297          if (code >= slot)
00298             {
00299             if (code > slot)
00300                ++bad_code_count;
00301             code = oc;
00302             *sp++ = fc;
00303             }
00304 
00305          /* Here we scan back along the linked list of prefixes, pushing
00306           * helpless characters (ie. suffixes) onto the stack as we do so.
00307           */
00308          while (code >= newcodes)
00309             {
00310             *sp++ = suffix[code];
00311             code = prefix[code];
00312             }
00313 
00314          /* Push the last character on the stack, and set up the new
00315           * prefix and suffix, and if the required slot number is greater
00316           * than that allowed by the current bit size, increase the bit
00317           * size.  (NOTE - If we are all full, we *don't* save the new
00318           * suffix and prefix...  I'm not certain if this is correct...
00319           * it might be more proper to overwrite the last code...
00320           */
00321          *sp++ = code;
00322          if (slot < top_slot)
00323             {
00324             suffix[slot] = fc = code;
00325             prefix[slot++] = oc;
00326             oc = c;
00327             }
00328          if (slot >= top_slot)
00329             if (curr_size < 12)
00330                {
00331                top_slot <<= 1;
00332                ++curr_size;
00333                } 
00334 
00335          /* Now that we've pushed the decoded string (in reverse order)
00336           * onto the stack, lets pop it off and put it into our decode
00337           * buffer...  And when the decode buffer is full, write another
00338           * line...
00339           */
00340          while (sp > stack)
00341             {
00342             *bufptr++ = *(--sp);
00343             if (--bufcnt == 0)
00344                {
00345                if ((ret = gif_out_line(buf, linewidth)) < 0)
00346                   {
00347                   return(ret);
00348                   }
00349                bufptr = buf;
00350                bufcnt = linewidth;
00351                }
00352             }
00353          }
00354       }
00355    ret = 0;
00356    if (bufcnt != linewidth)
00357       ret = gif_out_line(buf, (linewidth - bufcnt));
00358    return(ret);
00359    }
00360 
00361 /* basically just allocate memory for buffers and tables, and then
00362    call Steve B.'s decoder */
00363 int gif_decoder(int linewidth)
00364 {
00365 UBYTE *buf, *stack, *suffix;
00366 UWORD *prefix;
00367 int ret;
00368 
00369 ret = OUT_OF_MEMORY;
00370 stack = NULL;
00371 suffix = NULL;
00372 prefix = NULL;
00373 /* stack = suffix = (UBYTE *)prefix = NULL; */
00374 if ((buf = (UBYTE *)needMem(linewidth + 1)) == NULL)
00375         goto OUT;
00376 if ((stack = (UBYTE *)needMem(MAX_CODES+1)) == NULL)
00377         goto OUT;
00378 if ((suffix = (UBYTE *)needMem(MAX_CODES+1)) == NULL)
00379         goto OUT;
00380 if ((prefix = (UWORD *)needMem((MAX_CODES+1)*sizeof(UWORD) )) == NULL)
00381         goto OUT;
00382 ret = decoder(linewidth,buf,stack,suffix,prefix);
00383 OUT:
00384 freeMem(buf);
00385 freeMem(stack);
00386 freeMem(prefix);
00387 freeMem(suffix);
00388 return(ret);
00389 }
00390 
00391 
00392 

Generated on Tue Dec 25 18:39:31 2007 for blat by  doxygen 1.5.2