home *** CD-ROM | disk | FTP | other *** search
/ Fish 'n' More 2 / fishmore-publicdomainlibraryvol.ii1991xetec.iso / dirs / dkbtrace_397.lzh / DKBTrace / DKBSource.LZH / gifdecod.c < prev    next >
C/C++ Source or Header  |  1990-08-26  |  16KB  |  479 lines

  1. /*****************************************************************************
  2. *
  3. *                                   gifdecod.c
  4. *
  5. *   from DKBTrace (c) 1990  David Buck
  6. *
  7. * This software is freely distributable. The source and/or object code may be
  8. * copied or uploaded to communications services so long as this notice remains
  9. * at the top of each file.  If any changes are made to the program, you must
  10. * clearly indicate in the documentation and in the programs startup message
  11. * who it was who made the changes. The documentation should also describe what
  12. * those changes were. This software may not be included in whole or in
  13. * part into any commercial package without the express written consent of the
  14. * author.  It may, however, be included in other public domain or freely
  15. * distributed software so long as the proper credit for the software is given.
  16. *
  17. * This software is provided as is without any guarantees or warranty. Although
  18. * the author has attempted to find and correct any bugs in the software, he
  19. * is not responsible for any damage caused by the use of the software.  The
  20. * author is under no obligation to provide service, corrections, or upgrades
  21. * to this package.
  22. *
  23. * Despite all the legal stuff above, if you do find bugs, I would like to hear
  24. * about them.  Also, if you have any comments or questions, you may contact me
  25. * at the following address:
  26. *
  27. *     David Buck
  28. *     22C Sonnet Cres.
  29. *     Nepean Ontario
  30. *     Canada, K2H 8W7
  31. *
  32. *  I can also be reached on the following bulleton boards:
  33. *
  34. *     ATX              (613) 526-4141
  35. *     OMX              (613) 731-3419
  36. *     Mystic           (613) 731-0088 or (613) 731-6698
  37. *
  38. *  Fidonet:   1:163/109.9
  39. *  Internet:  David_Buck@Carleton.CA
  40. *
  41. *  IBM Port by Aaron A. Collins. Aaron may be reached on the following BBS'es:
  42. *
  43. *     Lattice BBS                      (708) 916-1200
  44. *     The Information Exchange BBS     (708) 945-5575
  45. *     Stillwaters BBS                  (708) 403-2826
  46. *
  47. *****************************************************************************/
  48.  
  49. /*
  50.    This module was freely borrowed from FRACTINT, so here is their entire
  51.    copyright to keep them happy:
  52. */
  53.  
  54. /* DECODER.C - An LZW decoder for GIF
  55.  * Copyright (C) 1987, by Steven A. Bennett
  56.  *
  57.  * Permission is given by the author to freely redistribute and include
  58.  * this code in any program as long as this credit is given where due.
  59.  *
  60.  * In accordance with the above, I want to credit Steve Wilhite who wrote
  61.  * the code which this is heavily inspired by...
  62.  *
  63.  * GIF and 'Graphics Interchange Format' are trademarks (tm) of
  64.  * Compuserve, Incorporated, an H&R Block Company.
  65.  *
  66.  * Release Notes: This file contains a decoder routine for GIF images
  67.  * which is similar, structurally, to the original routine by Steve Wilhite.
  68.  * It is, however, somewhat noticably faster in most cases.
  69.  *
  70.  == This routine was modified for use in FRACTINT in two ways.
  71.  == 
  72.  == 1) The original #includes were folded into the routine strictly to hold
  73.  ==    down the number of files we were dealing with.
  74.  ==
  75.  == 2) The 'stack', 'suffix', 'prefix', and 'buf' arrays were changed from
  76.  ==    static and 'malloc()'ed to external only so that the assembler
  77.  ==    program could use the same array space for several independent
  78.  ==    chunks of code.  Also, 'stack' was renamed to 'dstack' for TASM
  79.  ==    compatibility.
  80.  == 
  81.  == 3) The 'out_line()' external function has been changed to reference 
  82.  ==    '*outln()' for flexibility (in particular, 3D transformations)
  83.  ==
  84.  == 4) A call to 'keypressed()' has been added after the 'outln()' calls
  85.  ==    to check for the presenc of a key-press as a bail-out signal
  86.  ==
  87.  == (Bert Tyler and Timothy Wegner)
  88. */
  89.  
  90. /* 
  91.    This routine was modified for DKBtrace in the following ways:
  92.  
  93.    1)  Removed calls to buzzer() and keypressed() to get rid of ASM files.
  94.  
  95.    2)  The dstack, suffix, and prefix arrays were made STATIC once again.
  96.  
  97.    3)  Added the usual ANSI function prototypes, etc. in the DKB headers.
  98. */
  99.  
  100. #include "frame.h"
  101. #include "dkbproto.h"
  102.  
  103. #define LOCAL static
  104. #define IMPORT extern
  105.  
  106. #define FAST register
  107.  
  108. typedef short WORD;
  109. typedef unsigned short UWORD;
  110. typedef char TEXT;
  111. typedef unsigned char UTINY;
  112. typedef long LONG;
  113. typedef unsigned long ULONG;
  114. typedef int INT;
  115.  
  116.  
  117. /* Various error codes used by decoder
  118.  * and my own routines...   It's okay
  119.  * for you to define whatever you want,
  120.  * as long as it's negative...  It will be
  121.  * returned intact up the various subroutine
  122.  * levels...
  123.  */
  124. #define OUT_OF_MEMORY -10
  125. #define BAD_CODE_SIZE -20
  126. #define READ_ERROR -1
  127. #define WRITE_ERROR -2
  128. #define OPEN_ERROR -3
  129. #define CREATE_ERROR -4
  130.  
  131.  
  132. /* IMPORT INT get_byte()
  133.  *
  134.  *   - This external (machine specific) function is expected to return
  135.  * either the next byte from the GIF file, or a negative number, as
  136.  * defined in ERRS.H.
  137.  */
  138. IMPORT INT get_byte();
  139.  
  140. /* IMPORT INT out_line(pixels, linelen)
  141.  *     UBYTE pixels[];
  142.  *     INT linelen;
  143.  *
  144.  *   - This function takes a full line of pixels (one byte per pixel) and
  145.  * displays them (or does whatever your program wants with them...).  It
  146.  * should return zero, or negative if an error or some other event occurs
  147.  * which would require aborting the decode process...  Note that the length
  148.  * passed will almost always be equal to the line length passed to the
  149.  * decoder function, with the sole exception occurring when an ending code
  150.  * occurs in an odd place in the GIF file...  In any case, linelen will be
  151.  * equal to the number of pixels passed...
  152.  */
  153. IMPORT INT out_line();
  154.  
  155. /* IMPORT INT bad_code_count;
  156.  *
  157.  * This value is the only other global required by the using program, and
  158.  * is incremented each time an out of range code is read by the decoder.
  159.  * When this value is non-zero after a decode, your GIF file is probably
  160.  * corrupt in some way...
  161.  */
  162. INT bad_code_count;
  163.  
  164. #define NULL   0L
  165. #define MAX_CODES   4095
  166.  
  167. /* Static variables */
  168. LOCAL WORD curr_size;                     /* The current code size */
  169. LOCAL WORD clear;                         /* Value for a clear code */
  170. LOCAL WORD ending;                        /* Value for a ending code */
  171. LOCAL WORD newcodes;                      /* First available code */
  172. LOCAL WORD top_slot;                      /* Highest code for current size */
  173. LOCAL WORD slot;                          /* Last read code */
  174.  
  175. /* The following static variables are used
  176.  * for seperating out codes
  177.  */
  178. LOCAL WORD navail_bytes = 0;              /* # bytes left in block */
  179. LOCAL WORD nbits_left = 0;                /* # bits left in current byte */
  180. LOCAL UTINY b1;                           /* Current byte */
  181. LOCAL UTINY byte_buff[257];               /* Current block */
  182. LOCAL UTINY *pbytes;                      /* Pointer to next byte in block */
  183.  
  184. LOCAL LONG code_mask[13] = {
  185.      0,
  186.      0x0001, 0x0003,
  187.      0x0007, 0x000F,
  188.      0x001F, 0x003F,
  189.      0x007F, 0x00FF,
  190.      0x01FF, 0x03FF,
  191.      0x07FF, 0x0FFF
  192.      };
  193.  
  194.  
  195. /* This function initializes the decoder for reading a new image.
  196.  */
  197. LOCAL WORD init_exp(size)
  198.    WORD size;
  199.    {
  200.    curr_size = size + 1;
  201.    top_slot = 1 << curr_size;
  202.    clear = 1 << size;
  203.    ending = clear + 1;
  204.    slot = newcodes = ending + 1;
  205.    navail_bytes = nbits_left = 0;
  206.    return(0);
  207.    }
  208.  
  209. /* get_next_code()
  210.  * - gets the next code from the GIF file.  Returns the code, or else
  211.  * a negative number in case of file errors...
  212.  */
  213. LOCAL WORD get_next_code()
  214.    {
  215.    WORD i, x;
  216.    ULONG ret;
  217.  
  218.    if (nbits_left == 0)
  219.       {
  220.       if (navail_bytes <= 0)
  221.          {
  222.  
  223.          /* Out of bytes in current block, so read next block
  224.           */
  225.          pbytes = byte_buff;
  226.          if ((navail_bytes = get_byte()) < 0)
  227.             return(navail_bytes);
  228.          else if (navail_bytes)
  229.             {
  230.             for (i = 0; i < navail_bytes; ++i)
  231.                {
  232.                if ((x = get_byte()) < 0)
  233.                   return(x);
  234.                byte_buff[i] = x;
  235.                }
  236.             }
  237.          }
  238.       b1 = *pbytes++;
  239.       nbits_left = 8;
  240.       --navail_bytes;
  241.       }
  242.  
  243.    ret = b1 >> (8 - nbits_left);
  244.    while (curr_size > nbits_left)
  245.       {
  246.       if (navail_bytes <= 0)
  247.          {
  248.  
  249.          /* Out of bytes in current block, so read next block
  250.           */
  251.          pbytes = byte_buff;
  252.          if ((navail_bytes = get_byte()) < 0)
  253.             return(navail_bytes);
  254.          else if (navail_bytes)
  255.             {
  256.             for (i = 0; i < navail_bytes; ++i)
  257.                {
  258.                if ((x = get_byte()) < 0)
  259.                   return(x);
  260.                byte_buff[i] = x;
  261.                }
  262.             }
  263.          }
  264.       b1 = *pbytes++;
  265.       ret |= b1 << nbits_left;
  266.       nbits_left += 8;
  267.       --navail_bytes;
  268.       }
  269.    nbits_left -= curr_size;
  270.    ret &= code_mask[curr_size];
  271.    return((WORD)(ret));
  272.    }
  273.  
  274.  
  275. /* The reason we have these seperated like this instead of using
  276.  * a structure like the original Wilhite code did, is because this
  277.  * stuff generally produces significantly faster code when compiled...
  278.  * This code is full of similar speedups...  (For a good book on writing
  279.  * C for speed or for space optomisation, see Efficient C by Tom Plum,
  280.  * published by Plum-Hall Associates...)
  281.  */
  282.  
  283. /*
  284. I removed the LOCAL identifiers in the arrays below and replaced them
  285. with 'extern's so as to declare (and re-use) the space elsewhere.
  286. The arrays are actually declared in the assembler source.
  287.                                                     Bert Tyler
  288. */
  289.  
  290. LOCAL UTINY dstack[MAX_CODES + 1];      /* Stack for storing pixels */
  291. LOCAL UTINY suffix[MAX_CODES + 1];      /* Suffix table */
  292. LOCAL UWORD prefix[MAX_CODES + 1];      /* Prefix linked list */
  293. extern UTINY *decoderline;              /* decoded line goes here */
  294.  
  295. /* WORD decoder(linewidth)
  296.  *    WORD linewidth;               * Pixels per line of image *
  297.  *
  298.  * - This function decodes an LZW image, according to the method used
  299.  * in the GIF spec.  Every *linewidth* "characters" (ie. pixels) decoded
  300.  * will generate a call to out_line(), which is a user specific function
  301.  * to display a line of pixels.  The function gets its codes from
  302.  * get_next_code() which is responsible for reading blocks of data and
  303.  * seperating them into the proper size codes.  Finally, get_byte() is
  304.  * the global routine to read the next byte from the GIF file.
  305.  *
  306.  * It is generally a good idea to have linewidth correspond to the actual
  307.  * width of a line (as specified in the Image header) to make your own
  308.  * code a bit simpler, but it isn't absolutely necessary.
  309.  *
  310.  * Returns: 0 if successful, else negative.  (See ERRS.H)
  311.  *
  312.  */
  313.  
  314. WORD decoder(linewidth)
  315.    WORD linewidth;
  316.    {
  317.    FAST UTINY *sp, *bufptr;
  318.    UTINY *buf;
  319.    FAST WORD code, fc, oc, bufcnt;
  320.    WORD c, size, ret;
  321.  
  322.    /* Initialize for decoding a new image...
  323.     */
  324.    if ((size = get_byte()) < 0)
  325.       return(size);
  326.    if (size < 2 || 9 < size)
  327.       return(BAD_CODE_SIZE);
  328.    init_exp(size);
  329.  
  330.    /* Initialize in case they forgot to put in a clear code.
  331.     * (This shouldn't happen, but we'll try and decode it anyway...)
  332.     */
  333.    oc = fc = 0;
  334.  
  335.    buf = decoderline;
  336.  
  337.    /* Set up the stack pointer and decode buffer pointer
  338.     */
  339.    sp = dstack;
  340.    bufptr = buf;
  341.    bufcnt = linewidth;
  342.  
  343.    /* This is the main loop.  For each code we get we pass through the
  344.     * linked list of prefix codes, pushing the corresponding "character" for
  345.     * each code onto the stack.  When the list reaches a single "character"
  346.     * we push that on the stack too, and then start unstacking each
  347.     * character for output in the correct order.  Special handling is
  348.     * included for the clear code, and the whole thing ends when we get
  349.     * an ending code.
  350.     */
  351.    while ((c = get_next_code()) != ending)
  352.       {
  353.  
  354.       /* If we had a file error, return without completing the decode
  355.        */
  356.       if (c < 0)
  357.          return(0);
  358.  
  359.       /* If the code is a clear code, reinitialize all necessary items.
  360.        */
  361.       if (c == clear)
  362.          {
  363.          curr_size = size + 1;
  364.          slot = newcodes;
  365.          top_slot = 1 << curr_size;
  366.  
  367.          /* Continue reading codes until we get a non-clear code
  368.           * (Another unlikely, but possible case...)
  369.           */
  370.          while ((c = get_next_code()) == clear)
  371.             ;
  372.  
  373.          /* If we get an ending code immediately after a clear code
  374.           * (Yet another unlikely case), then break out of the loop.
  375.           */
  376.          if (c == ending)
  377.             break;
  378.  
  379.          /* Finally, if the code is beyond the range of already set codes,
  380.           * (This one had better NOT happen...  I have no idea what will
  381.           * result from this, but I doubt it will look good...) then set it
  382.           * to color zero.
  383.           */
  384.          if (c >= slot)
  385.             c = 0;
  386.  
  387.          oc = fc = c;
  388.  
  389.          /* And let us not forget to put the char into the buffer... And
  390.           * if, on the off chance, we were exactly one pixel from the end
  391.           * of the line, we have to send the buffer to the out_line()
  392.           * routine...
  393.           */
  394.          *bufptr++ = c;
  395.          if (--bufcnt == 0)
  396.             {
  397.             if ((ret = out_line(buf, linewidth)) < 0)
  398.                return(ret);
  399.             bufptr = buf;
  400.             bufcnt = linewidth;
  401.             }
  402.          }
  403.       else
  404.          {
  405.  
  406.          /* In this case, it's not a clear code or an ending code, so
  407.           * it must be a code code...  So we can now decode the code into
  408.           * a stack of character codes. (Clear as mud, right?)
  409.           */
  410.          code = c;
  411.  
  412.          /* Here we go again with one of those off chances...  If, on the
  413.           * off chance, the code we got is beyond the range of those already
  414.           * set up (Another thing which had better NOT happen...) we trick
  415.           * the decoder into thinking it actually got the last code read.
  416.           * (Hmmn... I'm not sure why this works...  But it does...)
  417.           */
  418.          if (code >= slot)
  419.             {
  420.             if (code > slot)
  421.                ++bad_code_count;
  422.             code = oc;
  423.             *sp++ = fc;
  424.             }
  425.  
  426.          /* Here we scan back along the linked list of prefixes, pushing
  427.           * helpless characters (ie. suffixes) onto the stack as we do so.
  428.           */
  429.          while (code >= newcodes)
  430.             {
  431.             *sp++ = suffix[code];
  432.             code = prefix[code];
  433.             }
  434.  
  435.          /* Push the last character on the stack, and set up the new
  436.           * prefix and suffix, and if the required slot number is greater
  437.           * than that allowed by the current bit size, increase the bit
  438.           * size.  (NOTE - If we are all full, we *don't* save the new
  439.           * suffix and prefix...  I'm not certain if this is correct...
  440.           * it might be more proper to overwrite the last code...
  441.           */
  442.          *sp++ = code;
  443.          if (slot < top_slot)
  444.             {
  445.             suffix[slot] = fc = code;
  446.             prefix[slot++] = oc;
  447.             oc = c;
  448.             }
  449.          if (slot >= top_slot)
  450.             if (curr_size < 12)
  451.                {
  452.                top_slot <<= 1;
  453.                ++curr_size;
  454.                }
  455.  
  456.          /* Now that we've pushed the decoded string (in reverse order)
  457.           * onto the stack, lets pop it off and put it into our decode
  458.           * buffer...  And when the decode buffer is full, write another
  459.           * line...
  460.           */
  461.          while (sp > dstack)
  462.             {
  463.             *bufptr++ = *(--sp);
  464.             if (--bufcnt == 0)
  465.                {
  466.                if ((ret = out_line(buf, linewidth)) < 0)
  467.                   return(ret);
  468.                bufptr = buf;
  469.                bufcnt = linewidth;
  470.                }
  471.             }
  472.          }
  473.       }
  474.    ret = 0;
  475.    if (bufcnt != linewidth)
  476.       ret = out_line(buf, (linewidth - bufcnt));
  477.    return(ret);
  478.    }
  479.