home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / Libraries / MacPNG Library 1.02 / pngMacSrc 1.02 / png.1 / ptot / inflate.c < prev    next >
Encoding:
Text File  |  1995-08-17  |  37.5 KB  |  1,079 lines  |  [TEXT/CWIE]

  1. /* inflate.c -- put in the public domain by Mark Adler
  2.    version c14p, 4 October 1994 */
  3.  
  4. /* You can do whatever you like with this source file, though I would
  5.    prefer that if you modify it and redistribute it that you include
  6.    comments to that effect with your name and the date.  Thank you.
  7.  
  8.    History:
  9.    vers    date          who           what
  10.    ----  ---------  --------------  ------------------------------------
  11.     a    ~~ Feb 92  M. Adler        used full (large, one-step) lookup table
  12.     b1   21 Mar 92  M. Adler        first version with partial lookup tables
  13.     b2   21 Mar 92  M. Adler        fixed bug in fixed-code blocks
  14.     b3   22 Mar 92  M. Adler        sped up match copies, cleaned up some
  15.     b4   25 Mar 92  M. Adler        added prototypes; removed window[] (now
  16.                                     is the responsibility of unzip.h--also
  17.                                     changed name to slide[]), so needs diffs
  18.                                     for unzip.c and unzip.h (this allows
  19.                                     compiling in the small model on MSDOS);
  20.                                     fixed cast of q in huft_build();
  21.     b5   26 Mar 92  M. Adler        got rid of unintended macro recursion.
  22.     b6   27 Mar 92  M. Adler        got rid of nextbyte() routine.  fixed
  23.                                     bug in inflate_fixed().
  24.     c1   30 Mar 92  M. Adler        removed lbits, dbits environment variables.
  25.                                     changed BMAX to 16 for explode.  Removed
  26.                                     OUTB usage, and replaced it with flush()--
  27.                                     this was a 20% speed improvement!  Added
  28.                                     an explode.c (to replace unimplod.c) that
  29.                                     uses the huft routines here.  Removed
  30.                                     register union.
  31.     c2    4 Apr 92  M. Adler        fixed bug for file sizes a multiple of 32k.
  32.     c3   10 Apr 92  M. Adler        reduced memory of code tables made by
  33.                                     huft_build significantly (factor of two to
  34.                                     three).
  35.     c4   15 Apr 92  M. Adler        added NOMEMCPY do kill use of memcpy().
  36.                                     worked around a Turbo C optimization bug.
  37.     c5   21 Apr 92  M. Adler        added the WSIZE #define to allow reducing
  38.                                     the 32K window size for specialized
  39.                                     applications.
  40.     c6   31 May 92  M. Adler        added some typecasts to eliminate warnings
  41.     c7   27 Jun 92  G. Roelofs      added some more typecasts (444:  MSC bug).
  42.     c8    5 Oct 92  J-l. Gailly     added ifdef'd code to deal with PKZIP bug.
  43.     c9    9 Oct 92  M. Adler        removed a memory error message (~line 416).
  44.     c10  17 Oct 92  G. Roelofs      changed ULONG/UWORD/byte to ulg/ush/uch,
  45.                                     removed old inflate, renamed inflate_entry
  46.                                     to inflate, added Mark's fix to a comment.
  47.    c10.5 14 Dec 92  M. Adler        fix up error messages for incomplete trees.
  48.     c11   2 Jan 93  M. Adler        fixed bug in detection of incomplete
  49.                                     tables, and removed assumption that EOB is
  50.                                     the longest code (bad assumption).
  51.     c12   3 Jan 93  M. Adler        make tables for fixed blocks only once.
  52.     c13   5 Jan 93  M. Adler        allow all zero length codes (pkzip 2.04c
  53.                                     outputs one zero length code for an empty
  54.                                     distance tree).
  55.     c14  12 Mar 93  M. Adler        made inflate.c standalone with the
  56.                                     introduction of inflate.h.
  57.    c14b  16 Jul 93  G. Roelofs      added (unsigned) typecast to w at 470.
  58.    c14c  19 Jul 93  J. Bush         changed v[N_MAX], l[288], ll[28x+3x] arrays
  59.                                     to static for Amiga.
  60.    c14d  13 Aug 93  J-l. Gailly     de-complicatified Mark's c[*p++]++ thing.
  61.    c14e   8 Oct 93  G. Roelofs      changed memset() to memzero().
  62.    c14f  22 Oct 93  G. Roelofs      renamed quietflg to qflag; made Trace()
  63.                                     conditional; added inflate_free().
  64.    c14g  28 Oct 93  G. Roelofs      changed l/(lx+1) macro to pointer (Cray bug)
  65.    c14h   7 Dec 93  C. Ghisler      huft_build() optimizations.
  66.    c14i   9 Jan 94  A. Verheijen    set fixed_t{d,l} to NULL after freeing;
  67.                     G. Roelofs      check NEXTBYTE macro for EOF.
  68.    c14j  23 Jan 94  G. Roelofs      removed Ghisler "optimizations"; ifdef'd
  69.                                     EOF check.
  70.    c14k  27 Feb 94  G. Roelofs      added some typecasts to avoid warnings.
  71.    c14l   9 Apr 94  G. Roelofs      fixed split comments on preprocessor lines
  72.                                     to avoid bug in Encore compiler.
  73.    c14m   7 Jul 94  P. Kienitz      modified to allow assembler version of
  74.                                     inflate_codes() (define ASM_INFLATECODES)
  75.    c14n  22 Jul 94  G. Roelofs      changed fprintf to FPRINTF for DLL versions
  76.    c14o  23 Aug 94  C. Spieler      added a newline to a debug statement;
  77.                     G. Roelofs      added another typecast to avoid MSC warning
  78.    c14p   4 Oct 94  G. Roelofs      added (voidp *) cast to free() argument
  79.  */
  80.  
  81.  
  82. /*
  83.    Inflate deflated (PKZIP's method 8 compressed) data.  The compression
  84.    method searches for as much of the current string of bytes (up to a
  85.    length of 258) in the previous 32K bytes.  If it doesn't find any
  86.    matches (of at least length 3), it codes the next byte.  Otherwise, it
  87.    codes the length of the matched string and its distance backwards from
  88.    the current position.  There is a single Huffman code that codes both
  89.    single bytes (called "literals") and match lengths.  A second Huffman
  90.    code codes the distance information, which follows a length code.  Each
  91.    length or distance code actually represents a base value and a number
  92.    of "extra" (sometimes zero) bits to get to add to the base value.  At
  93.    the end of each deflated block is a special end-of-block (EOB) literal/
  94.    length code.  The decoding process is basically: get a literal/length
  95.    code; if EOB then done; if a literal, emit the decoded byte; if a
  96.    length then get the distance and emit the referred-to bytes from the
  97.    sliding window of previously emitted data.
  98.  
  99.    There are (currently) three kinds of inflate blocks: stored, fixed, and
  100.    dynamic.  The compressor outputs a chunk of data at a time and decides
  101.    which method to use on a chunk-by-chunk basis.  A chunk might typically
  102.    be 32K to 64K, uncompressed.  If the chunk is uncompressible, then the
  103.    "stored" method is used.  In this case, the bytes are simply stored as
  104.    is, eight bits per byte, with none of the above coding.  The bytes are
  105.    preceded by a count, since there is no longer an EOB code.
  106.  
  107.    If the data is compressible, then either the fixed or dynamic methods
  108.    are used.  In the dynamic method, the compressed data is preceded by
  109.    an encoding of the literal/length and distance Huffman codes that are
  110.    to be used to decode this block.  The representation is itself Huffman
  111.    coded, and so is preceded by a description of that code.  These code
  112.    descriptions take up a little space, and so for small blocks, there is
  113.    a predefined set of codes, called the fixed codes.  The fixed method is
  114.    used if the block ends up smaller that way (usually for quite small
  115.    chunks); otherwise the dynamic method is used.  In the latter case, the
  116.    codes are customized to the probabilities in the current block and so
  117.    can code it much better than the pre-determined fixed codes can.
  118.  
  119.    The Huffman codes themselves are decoded using a mutli-level table
  120.    lookup, in order to maximize the speed of decoding plus the speed of
  121.    building the decoding tables.  See the comments below that precede the
  122.    lbits and dbits tuning parameters.
  123.  */
  124.  
  125.  
  126. /*
  127.    Notes beyond the 1.93a appnote.txt:
  128.  
  129.    1. Distance pointers never point before the beginning of the output
  130.       stream.
  131.    2. Distance pointers can point back across blocks, up to 32k away.
  132.    3. There is an implied maximum of 7 bits for the bit length table and
  133.       15 bits for the actual data.
  134.    4. If only one code exists, then it is encoded using one bit.  (Zero
  135.       would be more efficient, but perhaps a little confusing.)  If two
  136.       codes exist, they are coded using one bit each (0 and 1).
  137.    5. There is no way of sending zero distance codes--a dummy must be
  138.       sent if there are none.  (History: a pre 2.0 version of PKZIP would
  139.       store blocks with no distance codes, but this was discovered to be
  140.       too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
  141.       zero distance codes, which is sent as one code of zero bits in
  142.       length.
  143.    6. There are up to 286 literal/length codes.  Code 256 represents the
  144.       end-of-block.  Note however that the static length tree defines
  145.       288 codes just to fill out the Huffman codes.  Codes 286 and 287
  146.       cannot be used though, since there is no length base or extra bits
  147.       defined for them.  Similarily, there are up to 30 distance codes.
  148.       However, static trees define 32 codes (all 5 bits) to fill out the
  149.       Huffman codes, but the last two had better not show up in the data.
  150.    7. Unzip can check dynamic Huffman blocks for complete code sets.
  151.       The exception is that a single code would not be complete (see #4).
  152.    8. The five bits following the block type is really the number of
  153.       literal codes sent minus 257.
  154.    9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
  155.       (1+6+6).  Therefore, to output three times the length, you output
  156.       three codes (1+1+1), whereas to output four times the same length,
  157.       you only need two codes (1+3).  Hmm.
  158.   10. In the tree reconstruction algorithm, Code = Code + Increment
  159.       only if BitLength(i) is not zero.  (Pretty obvious.)
  160.   11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
  161.   12. Note: length code 284 can represent 227-258, but length code 285
  162.       really is 258.  The last length deserves its own, short code
  163.       since it gets used a lot in very redundant files.  The length
  164.       258 is special since 258 - 3 (the min match length) is 255.
  165.   13. The literal/length and distance code bit lengths are read as a
  166.       single stream of lengths.  It is possible (and advantageous) for
  167.       a repeat code (16, 17, or 18) to go across the boundary between
  168.       the two sets of lengths.
  169.  */
  170.  
  171.  
  172. #define PKZIP_BUG_WORKAROUND    /* PKZIP 1.93a problem--live with it */
  173.  
  174. /*
  175.     inflate.h must supply the uch slide[WSIZE] array, the voidp typedef
  176.     (void if (void *) is accepted, else char) and the NEXTBYTE,
  177.     FLUSH() and memzero macros.  If the window size is not 32K, it
  178.     should also define WSIZE.  If INFMOD is defined, it can include
  179.     compiled functions to support the NEXTBYTE and/or FLUSH() macros.
  180.     There are defaults for NEXTBYTE and FLUSH() below for use as
  181.     examples of what those functions need to do.  Normally, you would
  182.     also want FLUSH() to compute a crc on the data.  inflate.h also
  183.     needs to provide these typedefs:
  184.  
  185.         typedef unsigned char uch;
  186.         typedef unsigned short ush;
  187.         typedef unsigned long ulg;
  188.  
  189.     This module uses the external functions malloc() and free() (and
  190.     probably memset() or bzero() in the memzero() macro).  Their
  191.     prototypes are normally found in <string.h> and <stdlib.h>.
  192.  */
  193. #define INFMOD          /* tell inflate.h to include code to be compiled */
  194. #include "inflate.h"
  195.  
  196. #ifndef WSIZE           /* default is 32K */
  197. #  define WSIZE 0x8000  /* window size--must be a power of two, and at least */
  198. #endif                  /* 32K for zip's deflate method */
  199.  
  200. #ifndef NEXTBYTE        /* default is to simply get a byte from stdin */
  201. #  define NEXTBYTE getchar()
  202. #endif
  203.  
  204. #ifndef FPRINTF
  205. #  define FPRINTF fprintf
  206. #endif
  207.  
  208. #ifndef FLUSH           /* default is to simply write the buffer to stdout */
  209. #  define FLUSH(n) fwrite(slide, 1, n, stdout)  /* return value not used */
  210. #endif
  211. /* Warning: the fwrite above might not work on 16-bit compilers, since
  212.    0x8000 might be interpreted as -32,768 by the library function. */
  213.  
  214. #ifndef Trace
  215. #  ifdef DEBUG
  216. #    define Trace(x) fprintf x
  217. #  else
  218. #    define Trace(x)
  219. #  endif
  220. #endif
  221.  
  222.  
  223. /* Huffman code lookup table entry--this entry is four bytes for machines
  224.    that have 16-bit pointers (e.g. PC's in the small or medium model).
  225.    Valid extra bits are 0..13.  e == 15 is EOB (end of block), e == 16
  226.    means that v is a literal, 16 < e < 32 means that v is a pointer to
  227.    the next table, which codes e - 16 bits, and lastly e == 99 indicates
  228.    an unused code.  If a code with e == 99 is looked up, this implies an
  229.    error in the data. */
  230. struct huft {
  231.   uch e;                /* number of extra bits or operation */
  232.   uch b;                /* number of bits in this code or subcode */
  233.   union {
  234.     ush n;              /* literal, length base, or distance base */
  235.     struct huft *t;     /* pointer to next level of table */
  236.   } v;
  237. };
  238.  
  239.  
  240. /* Function prototypes */
  241. #ifndef OF
  242. #  ifdef __STDC__
  243. #    define OF(a) a
  244. #  else /* !__STDC__ */
  245. #    define OF(a) ()
  246. #  endif /* ?__STDC__ */
  247. #endif
  248. int huft_build OF((unsigned *, unsigned, unsigned, ush *, ush *,
  249.                    struct huft **, int *));
  250. int huft_free OF((struct huft *));
  251. int inflate_codes OF((struct huft *, struct huft *, int, int));
  252. int inflate_stored OF((void));
  253. int inflate_fixed OF((void));
  254. int inflate_dynamic OF((void));
  255. int inflate_block OF((int *));
  256. int inflate OF((void));
  257. int inflate_free OF((void));
  258.  
  259.  
  260. /* The inflate algorithm uses a sliding 32K byte window on the uncompressed
  261.    stream to find repeated byte strings.  This is implemented here as a
  262.    circular buffer.  The index is updated simply by incrementing and then
  263.    and'ing with 0x7fff (32K-1). */
  264. /* It is left to other modules to supply the 32K area.  It is assumed
  265.    to be usable as if it were declared "uch slide[32768];" or as just
  266.    "uch *slide;" and then malloc'ed in the latter case.  The definition
  267.    must be in unzip.h, included above. */
  268. unsigned wp;            /* current position in slide */
  269.  
  270.  
  271. /* Tables for deflate from PKZIP's appnote.txt. */
  272. static unsigned border[] = {    /* Order of the bit length code lengths */
  273.         16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  274. static ush cplens[] = {         /* Copy lengths for literal codes 257..285 */
  275.         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  276.         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  277.         /* note: see note #13 above about the 258 in this list. */
  278. static ush cplext[] = {         /* Extra bits for literal codes 257..285 */
  279.         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
  280.         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */
  281. static ush cpdist[] = {         /* Copy offsets for distance codes 0..29 */
  282.         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  283.         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  284.         8193, 12289, 16385, 24577};
  285. static ush cpdext[] = {         /* Extra bits for distance codes */
  286.         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
  287.         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  288.         12, 12, 13, 13};
  289.  
  290. /* And'ing with mask[n] masks the lower n bits */
  291. ush mask[] = {
  292.     0x0000,
  293.     0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
  294.     0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
  295. };
  296.  
  297.  
  298. /* Macros for inflate() bit peeking and grabbing.
  299.    The usage is:
  300.    
  301.         NEEDBITS(j)
  302.         x = b & mask[j];
  303.         DUMPBITS(j)
  304.  
  305.    where NEEDBITS makes sure that b has at least j bits in it, and
  306.    DUMPBITS removes the bits from b.  The macros use the variable k
  307.    for the number of bits in b.  Normally, b and k are register
  308.    variables for speed, and are initialized at the begining of a
  309.    routine that uses these macros from a global bit buffer and count.
  310.  
  311.    In order to not ask for more bits than there are in the compressed
  312.    stream, the Huffman tables are constructed to only ask for just
  313.    enough bits to make up the end-of-block code (value 256).  Then no
  314.    bytes need to be "returned" to the buffer at the end of the last
  315.    block.  See the huft_build() routine.
  316.  */
  317.  
  318. ulg bb;                         /* bit buffer */
  319. unsigned bk;                    /* bits in bit buffer */
  320.  
  321. #ifndef CHECK_EOF
  322. #  define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE)<<k;k+=8;}}
  323. #else
  324. #  define NEEDBITS(n) {while(k<(n)){int c=NEXTBYTE;if(c==EOF)return 1;\
  325.     b|=((ulg)c)<<k;k+=8;}}
  326. #endif                      /* Piet Plomp:  change "return 1" to "break" */
  327.  
  328. #define DUMPBITS(n) {b>>=(n);k-=(n);}
  329.  
  330.  
  331. /*
  332.    Huffman code decoding is performed using a multi-level table lookup.
  333.    The fastest way to decode is to simply build a lookup table whose
  334.    size is determined by the longest code.  However, the time it takes
  335.    to build this table can also be a factor if the data being decoded
  336.    is not very long.  The most common codes are necessarily the
  337.    shortest codes, so those codes dominate the decoding time, and hence
  338.    the speed.  The idea is you can have a shorter table that decodes the
  339.    shorter, more probable codes, and then point to subsidiary tables for
  340.    the longer codes.  The time it costs to decode the longer codes is
  341.    then traded against the time it takes to make longer tables.
  342.  
  343.    This results of this trade are in the variables lbits and dbits
  344.    below.  lbits is the number of bits the first level table for literal/
  345.    length codes can decode in one step, and dbits is the same thing for
  346.    the distance codes.  Subsequent tables are also less than or equal to
  347.    those sizes.  These values may be adjusted either when all of the
  348.    codes are shorter than that, in which case the longest code length in
  349.    bits is used, or when the shortest code is *longer* than the requested
  350.    table size, in which case the length of the shortest code in bits is
  351.    used.
  352.  
  353.    There are two different values for the two tables, since they code a
  354.    different number of possibilities each.  The literal/length table
  355.    codes 286 possible values, or in a flat code, a little over eight
  356.    bits.  The distance table codes 30 possible values, or a little less
  357.    than five bits, flat.  The optimum values for speed end up being
  358.    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
  359.    The optimum values may differ though from machine to machine, and
  360.    possibly even between compilers.  Your mileage may vary.
  361.  */
  362.  
  363.  
  364. int lbits = 9;          /* bits in base literal/length lookup table */
  365. int dbits = 6;          /* bits in base distance lookup table */
  366.  
  367.  
  368. /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
  369. #define BMAX 16         /* maximum bit length of any code (16 for explode) */
  370. #define N_MAX 288       /* maximum number of codes in any set */
  371.  
  372.  
  373. unsigned hufts;         /* track memory usage */
  374.  
  375.  
  376. int huft_build(b, n, s, d, e, t, m)
  377. unsigned *b;            /* code lengths in bits (all assumed <= BMAX) */
  378. unsigned n;             /* number of codes (assumed <= N_MAX) */
  379. unsigned s;             /* number of simple-valued codes (0..s-1) */
  380. ush *d;                 /* list of base values for non-simple codes */
  381. ush *e;                 /* list of extra bits for non-simple codes */
  382. struct huft **t;        /* result: starting table */
  383. int *m;                 /* maximum lookup bits, returns actual */
  384. /* Given a list of code lengths and a maximum table size, make a set of
  385.    tables to decode that set of codes.  Return zero on success, one if
  386.    the given code set is incomplete (the tables are still built in this
  387.    case), two if the input is invalid (all zero length codes or an
  388.    oversubscribed set of lengths), and three if not enough memory.
  389.    The code with value 256 is special, and the tables are constructed
  390.    so that no bits beyond that code are fetched when that code is
  391.    decoded. */
  392. {
  393.   unsigned a;                   /* counter for codes of length k */
  394.   unsigned c[BMAX+1];           /* bit length count table */
  395.   unsigned el;                  /* length of EOB code (value 256) */
  396.   unsigned f;                   /* i repeats in table every f entries */
  397.   int g;                        /* maximum code length */
  398.   int h;                        /* table level */
  399.   register unsigned i;          /* counter, current code */
  400.   register unsigned j;          /* counter */
  401.   register int k;               /* number of bits in current code */
  402.   int lx[BMAX+1];               /* memory for l[-1..BMAX-1] */
  403.   int *l = lx+1;                /* stack of bits per table */
  404.   register unsigned *p;         /* pointer into c[], b[], or v[] */
  405.   register struct huft *q;      /* points to current table */
  406.   struct huft r;                /* table entry for structure assignment */
  407.   struct huft *u[BMAX];         /* table stack */
  408.   static unsigned v[N_MAX];     /* values in order of bit length */
  409.   register int w;               /* bits before this table == (l * h) */
  410.   unsigned x[BMAX+1];           /* bit offsets, then code stack */
  411.   unsigned *xp;                 /* pointer into x */
  412.   int y;                        /* number of dummy codes added */
  413.   unsigned z;                   /* number of entries in current table */
  414.  
  415.  
  416.   /* Generate counts for each bit length */
  417.   el = n > 256 ? b[256] : BMAX; /* set length of EOB code, if any */
  418.   memzero((char *)c, sizeof(c));
  419.   p = b;  i = n;
  420.   do {
  421.     c[*p]++; p++;               /* assume all entries <= BMAX */
  422.   } while (--i);
  423.   if (c[0] == n)                /* null input--all zero length codes */
  424.   {
  425.     *t = (struct huft *)NULL;
  426.     *m = 0;
  427.     return 0;
  428.   }
  429.  
  430.  
  431.   /* Find minimum and maximum length, bound *m by those */
  432.   for (j = 1; j <= BMAX; j++)
  433.     if (c[j])
  434.       break;
  435.   k = j;                        /* minimum code length */
  436.   if ((unsigned)*m < j)
  437.     *m = j;
  438.   for (i = BMAX; i; i--)
  439.     if (c[i])
  440.       break;
  441.   g = i;                        /* maximum code length */
  442.   if ((unsigned)*m > i)
  443.     *m = i;
  444.  
  445.  
  446.   /* Adjust last length count to fill out codes, if needed */
  447.   for (y = 1 << j; j < i; j++, y <<= 1)
  448.     if ((y -= c[j]) < 0)
  449.       return 2;                 /* bad input: more codes than bits */
  450.   if ((y -= c[i]) < 0)
  451.     return 2;
  452.   c[i] += y;
  453.  
  454.  
  455.   /* Generate starting offsets into the value table for each length */
  456.   x[1] = j = 0;
  457.   p = c + 1;  xp = x + 2;
  458.   while (--i) {                 /* note that i == g from above */
  459.     *xp++ = (j += *p++);
  460.   }
  461.  
  462.  
  463.   /* Make a table of values in order of bit lengths */
  464.   p = b;  i = 0;
  465.   do {
  466.     if ((j = *p++) != 0)
  467.       v[x[j]++] = i;
  468.   } while (++i < n);
  469.  
  470.  
  471.   /* Generate the Huffman codes and for each, make the table entries */
  472.   x[0] = i = 0;                 /* first Huffman code is zero */
  473.   p = v;                        /* grab values in bit order */
  474.   h = -1;                       /* no tables yet--level -1 */
  475.   w = l[-1] = 0;                /* no bits decoded yet */
  476.   u[0] = (struct huft *)NULL;   /* just to keep compilers happy */
  477.   q = (struct huft *)NULL;      /* ditto */
  478.   z = 0;                        /* ditto */
  479.  
  480.   /* go through the bit lengths (k already is bits in shortest code) */
  481.   for (; k <= g; k++)
  482.   {
  483.     a = c[k];
  484.     while (a--)
  485.     {
  486.       /* here i is the Huffman code of length k bits for value *p */
  487.       /* make tables up to required level */
  488.       while (k > w + l[h])
  489.       {
  490.         w += l[h++];            /* add bits already decoded */
  491.  
  492.         /* compute minimum size table less than or equal to *m bits */
  493.         z = (z = g - w) > (unsigned)*m ? *m : z;        /* upper limit */
  494.         if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
  495.         {                       /* too few codes for k-w bit table */
  496.           f -= a + 1;           /* deduct codes from patterns left */
  497.           xp = c + k;
  498.           while (++j < z)       /* try smaller tables up to z bits */
  499.           {
  500.             if ((f <<= 1) <= *++xp)
  501.               break;            /* enough codes to use up j bits */
  502.             f -= *xp;           /* else deduct codes from patterns */
  503.           }
  504.         }
  505.         if ((unsigned)w + j > el && (unsigned)w < el)
  506.           j = el - w;           /* make EOB code end at table */
  507.         z = 1 << j;             /* table entries for j-bit table */
  508.         l[h] = j;               /* set table size in stack */
  509.  
  510.         /* allocate and link in new table */
  511.         if ((q = (struct huft *)malloc((z + 1)*sizeof(struct huft))) ==
  512.             (struct huft *)NULL)
  513.         {
  514.           if (h)
  515.             huft_free(u[0]);
  516.           return 3;             /* not enough memory */
  517.         }
  518.         hufts += z + 1;         /* track memory usage */
  519.         *t = q + 1;             /* link to list for huft_free() */
  520.         *(t = &(q->v.t)) = (struct huft *)NULL;
  521.         u[h] = ++q;             /* table starts after link */
  522.  
  523.         /* connect to last table, if there is one */
  524.         if (h)
  525.         {
  526.           x[h] = i;             /* save pattern for backing up */
  527.           r.b = (uch)l[h-1];    /* bits to dump before this table */
  528.           r.e = (uch)(16 + j);  /* bits in this table */
  529.           r.v.t = q;            /* pointer to this table */
  530.           j = (i & ((1 << w) - 1)) >> (w - l[h-1]);
  531.           u[h-1][j] = r;        /* connect to last table */
  532.         }
  533.       }
  534.  
  535.       /* set up table entry in r */
  536.       r.b = (uch)(k - w);
  537.       if (p >= v + n)
  538.         r.e = 99;               /* out of values--invalid code */
  539.       else if (*p < s)
  540.       {
  541.         r.e = (uch)(*p < 256 ? 16 : 15);    /* 256 is end-of-block code */
  542.         r.v.n = *p++;           /* simple code is just the value */
  543.       }
  544.       else
  545.       {
  546.         r.e = (uch)e[*p - s];   /* non-simple--look up in lists */
  547.         r.v.n = d[*p++ - s];
  548.       }
  549.  
  550.       /* fill code-like entries with r */
  551.       f = 1 << (k - w);
  552.       for (j = i >> w; j < z; j += f)
  553.         q[j] = r;
  554.  
  555.       /* backwards increment the k-bit code i */
  556.       for (j = 1 << (k - 1); i & j; j >>= 1)
  557.         i ^= j;
  558.       i ^= j;
  559.  
  560.       /* backup over finished tables */
  561.       while ((i & ((1 << w) - 1)) != x[h])
  562.         w -= l[--h];            /* don't need to update q */
  563.     }
  564.   }
  565.  
  566.  
  567.   /* return actual size of base table */
  568.   *m = l[0];
  569.  
  570.  
  571.   /* Return true (1) if we were given an incomplete table */
  572.   return y != 0 && g != 1;
  573. }
  574.  
  575.  
  576.  
  577. int huft_free(t)
  578. struct huft *t;         /* table to free */
  579. /* Free the malloc'ed tables built by huft_build(), which makes a linked
  580.    list of the tables it made, with the links in a dummy first entry of
  581.    each table. */
  582. {
  583.   register struct huft *p, *q;
  584.  
  585.  
  586.   /* Go through linked list, freeing from the malloced (t[-1]) address. */
  587.   p = t;
  588.   while (p != (struct huft *)NULL)
  589.   {
  590.     q = (--p)->v.t;
  591.     free((voidp *)p);
  592.     p = q;
  593.   } 
  594.   return 0;
  595. }
  596.  
  597.  
  598.  
  599. #ifdef ASM_INFLATECODES
  600. #  define inflate_codes(tl,td,bl,bd)  flate_codes(tl,td,bl,bd,(uch *)slide)
  601.    int flate_codes OF((struct huft *, struct huft *, int, int, uch *));
  602.  
  603. #else
  604.  
  605. int inflate_codes(tl, td, bl, bd)
  606. struct huft *tl, *td;   /* literal/length and distance decoder tables */
  607. int bl, bd;             /* number of bits decoded by tl[] and td[] */
  608. /* inflate (decompress) the codes in a deflated (compressed) block.
  609.    Return an error code or zero if it all goes ok. */
  610. {
  611.   register unsigned e;  /* table entry flag/number of extra bits */
  612.   unsigned n, d;        /* length and index for copy */
  613.   unsigned w;           /* current window position */
  614.   struct huft *t;       /* pointer to table entry */
  615.   unsigned ml, md;      /* masks for bl and bd bits */
  616.   register ulg b;       /* bit buffer */
  617.   register unsigned k;  /* number of bits in bit buffer */
  618.  
  619.  
  620.   /* make local copies of globals */
  621.   b = bb;                       /* initialize bit buffer */
  622.   k = bk;
  623.   w = wp;                       /* initialize window position */
  624.  
  625.  
  626.   /* inflate the coded data */
  627.   ml = mask[bl];           /* precompute masks for speed */
  628.   md = mask[bd];
  629.   while (1)                     /* do until end of block */
  630.   {
  631.     NEEDBITS((unsigned)bl)
  632.     if ((e = (t = tl + ((unsigned)b & ml))->e) > 16)
  633.       do {
  634.         if (e == 99)
  635.           return 1;
  636.         DUMPBITS(t->b)
  637.         e -= 16;
  638.         NEEDBITS(e)
  639.       } while ((e = (t = t->v.t + ((unsigned)b & mask[e]))->e) > 16);
  640.     DUMPBITS(t->b)
  641.     if (e == 16)                /* then it's a literal */
  642.     {
  643.       slide[w++] = (uch)t->v.n;
  644.       if (w == WSIZE)
  645.       {
  646.         FLUSH(w);
  647.         w = 0;
  648.       }
  649.     }
  650.     else                        /* it's an EOB or a length */
  651.     {
  652.       /* exit if end of block */
  653.       if (e == 15)
  654.         break;
  655.  
  656.       /* get length of block to copy */
  657.       NEEDBITS(e)
  658.       n = t->v.n + ((unsigned)b & mask[e]);
  659.       DUMPBITS(e);
  660.  
  661.       /* decode distance of block to copy */
  662.       NEEDBITS((unsigned)bd)
  663.       if ((e = (t = td + ((unsigned)b & md))->e) > 16)
  664.         do {
  665.           if (e == 99)
  666.             return 1;
  667.           DUMPBITS(t->b)
  668.           e -= 16;
  669.           NEEDBITS(e)
  670.         } while ((e = (t = t->v.t + ((unsigned)b & mask[e]))->e) > 16);
  671.       DUMPBITS(t->b)
  672.       NEEDBITS(e)
  673.       d = w - t->v.n - ((unsigned)b & mask[e]);
  674.       DUMPBITS(e)
  675.  
  676.       /* do the copy */
  677.       do {
  678.         n -= (e = (e = WSIZE - ((d &= WSIZE-1) > w ? d : w)) > n ? n : e);
  679. #ifndef NOMEMCPY
  680.         if (w - d >= e)         /* (this test assumes unsigned comparison) */
  681.         {
  682.           memcpy(slide + w, slide + d, e);
  683.           w += e;
  684.           d += e;
  685.         }
  686.         else                      /* do it slow to avoid memcpy() overlap */
  687. #endif /* !NOMEMCPY */
  688.           do {
  689.             slide[w++] = slide[d++];
  690.           } while (--e);
  691.         if (w == WSIZE)
  692.         {
  693.           FLUSH(w);
  694.           w = 0;
  695.         }
  696.       } while (n);
  697.     }
  698.   }
  699.  
  700.  
  701.   /* restore the globals from the locals */
  702.   wp = w;                       /* restore global window pointer */
  703.   bb = b;                       /* restore global bit buffer */
  704.   bk = k;
  705.  
  706.  
  707.   /* done */
  708.   return 0;
  709. }
  710.  
  711. #endif /* ASM_INFLATECODES */
  712.  
  713.  
  714.  
  715. int inflate_stored()
  716. /* "decompress" an inflated type 0 (stored) block. */
  717. {
  718.   unsigned n;           /* number of bytes in block */
  719.   unsigned w;           /* current window position */
  720.   register ulg b;       /* bit buffer */
  721.   register unsigned k;  /* number of bits in bit buffer */
  722.  
  723.  
  724.   /* make local copies of globals */
  725.   Trace((stderr, "\nstored block"));
  726.   b = bb;                       /* initialize bit buffer */
  727.   k = bk;
  728.   w = wp;                       /* initialize window position */
  729.  
  730.  
  731.   /* go to byte boundary */
  732.   n = k & 7;
  733.   DUMPBITS(n);
  734.  
  735.  
  736.   /* get the length and its complement */
  737.   NEEDBITS(16)
  738.   n = ((unsigned)b & 0xffff);
  739.   DUMPBITS(16)
  740.   NEEDBITS(16)
  741.   if (n != (unsigned)((~b) & 0xffff))
  742.     return 1;                   /* error in compressed data */
  743.   DUMPBITS(16)
  744.  
  745.  
  746.   /* read and output the compressed data */
  747.   while (n--)
  748.   {
  749.     NEEDBITS(8)
  750.     slide[w++] = (uch)b;
  751.     if (w == WSIZE)
  752.     {
  753.       FLUSH(w);
  754.       w = 0;
  755.     }
  756.     DUMPBITS(8)
  757.   }
  758.  
  759.  
  760.   /* restore the globals from the locals */
  761.   wp = w;                       /* restore global window pointer */
  762.   bb = b;                       /* restore global bit buffer */
  763.   bk = k;
  764.   return 0;
  765. }
  766.  
  767.  
  768. /* Globals for literal tables (built once) */
  769. struct huft *fixed_tl = (struct huft *)NULL;
  770. struct huft *fixed_td;
  771. int fixed_bl, fixed_bd;
  772.  
  773. int inflate_fixed()
  774. /* decompress an inflated type 1 (fixed Huffman codes) block.  We should
  775.    either replace this with a custom decoder, or at least precompute the
  776.    Huffman tables. */
  777. {
  778.   /* if first time, set up tables for fixed blocks */
  779.   Trace((stderr, "\nliteral block"));
  780.   if (fixed_tl == (struct huft *)NULL)
  781.   {
  782.     int i;                /* temporary variable */
  783.     static unsigned l[288]; /* length list for huft_build */
  784.  
  785.     /* literal table */
  786.     for (i = 0; i < 144; i++)
  787.       l[i] = 8;
  788.     for (; i < 256; i++)
  789.       l[i] = 9;
  790.     for (; i < 280; i++)
  791.       l[i] = 7;
  792.     for (; i < 288; i++)          /* make a complete, but wrong code set */
  793.       l[i] = 8;
  794.     fixed_bl = 7;
  795.     if ((i = huft_build(l, 288, 257, cplens, cplext,
  796.                         &fixed_tl, &fixed_bl)) != 0)
  797.     {
  798.       fixed_tl = (struct huft *)NULL;
  799.       return i;
  800.     }
  801.  
  802.     /* distance table */
  803.     for (i = 0; i < 30; i++)      /* make an incomplete code set */
  804.       l[i] = 5;
  805.     fixed_bd = 5;
  806.     if ((i = huft_build(l, 30, 0, cpdist, cpdext, &fixed_td, &fixed_bd)) > 1)
  807.     {
  808.       huft_free(fixed_tl);
  809.       fixed_tl = (struct huft *)NULL;
  810.       return i;
  811.     }
  812.   }
  813.  
  814.  
  815.   /* decompress until an end-of-block code */
  816.   return inflate_codes(fixed_tl, fixed_td, fixed_bl, fixed_bd) != 0;
  817. }
  818.  
  819.  
  820.  
  821. int inflate_dynamic()
  822. /* decompress an inflated type 2 (dynamic Huffman codes) block. */
  823. {
  824.   int i;                /* temporary variables */
  825.   unsigned j;
  826.   unsigned l;           /* last length */
  827.   unsigned m;           /* mask for bit lengths table */
  828.   unsigned n;           /* number of lengths to get */
  829.   struct huft *tl;      /* literal/length code table */
  830.   struct huft *td;      /* distance code table */
  831.   int bl;               /* lookup bits for tl */
  832.   int bd;               /* lookup bits for td */
  833.   unsigned nb;          /* number of bit length codes */
  834.   unsigned nl;          /* number of literal/length codes */
  835.   unsigned nd;          /* number of distance codes */
  836. #ifdef PKZIP_BUG_WORKAROUND
  837.   static unsigned ll[288+32]; /* literal/length and distance code lengths */
  838. #else
  839.   static unsigned ll[286+30]; /* literal/length and distance code lengths */
  840. #endif
  841.   register ulg b;       /* bit buffer */
  842.   register unsigned k;  /* number of bits in bit buffer */
  843.  
  844.  
  845.   /* make local bit buffer */
  846.   Trace((stderr, "\ndynamic block"));
  847.   b = bb;
  848.   k = bk;
  849.  
  850.  
  851.   /* read in table lengths */
  852.   NEEDBITS(5)
  853.   nl = 257 + ((unsigned)b & 0x1f);      /* number of literal/length codes */
  854.   DUMPBITS(5)
  855.   NEEDBITS(5)
  856.   nd = 1 + ((unsigned)b & 0x1f);        /* number of distance codes */
  857.   DUMPBITS(5)
  858.   NEEDBITS(4)
  859.   nb = 4 + ((unsigned)b & 0xf);         /* number of bit length codes */
  860.   DUMPBITS(4)
  861. #ifdef PKZIP_BUG_WORKAROUND
  862.   if (nl > 288 || nd > 32)
  863. #else
  864.   if (nl > 286 || nd > 30)
  865. #endif
  866.     return 1;                   /* bad lengths */
  867.  
  868.  
  869.   /* read in bit-length-code lengths */
  870.   for (j = 0; j < nb; j++)
  871.   {
  872.     NEEDBITS(3)
  873.     ll[border[j]] = (unsigned)b & 7;
  874.     DUMPBITS(3)
  875.   }
  876.   for (; j < 19; j++)
  877.     ll[border[j]] = 0;
  878.  
  879.  
  880.   /* build decoding table for trees--single level, 7 bit lookup */
  881.   bl = 7;
  882.   if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0)
  883.   {
  884.     if (i == 1)
  885.       huft_free(tl);
  886.     return i;                   /* incomplete code set */
  887.   }
  888.  
  889.  
  890.   /* read in literal and distance code lengths */
  891.   n = nl + nd;
  892.   m = mask[bl];
  893.   i = l = 0;
  894.   while ((unsigned)i < n)
  895.   {
  896.     NEEDBITS((unsigned)bl)
  897.     j = (td = tl + ((unsigned)b & m))->b;
  898.     DUMPBITS(j)
  899.     j = td->v.n;
  900.     if (j < 16)                 /* length of code in bits (0..15) */
  901.       ll[i++] = l = j;          /* save last length in l */
  902.     else if (j == 16)           /* repeat last length 3 to 6 times */
  903.     {
  904.       NEEDBITS(2)
  905.       j = 3 + ((unsigned)b & 3);
  906.       DUMPBITS(2)
  907.       if ((unsigned)i + j > n)
  908.         return 1;
  909.       while (j--)
  910.         ll[i++] = l;
  911.     }
  912.     else if (j == 17)           /* 3 to 10 zero length codes */
  913.     {
  914.       NEEDBITS(3)
  915.       j = 3 + ((unsigned)b & 7);
  916.       DUMPBITS(3)
  917.       if ((unsigned)i + j > n)
  918.         return 1;
  919.       while (j--)
  920.         ll[i++] = 0;
  921.       l = 0;
  922.     }
  923.     else                        /* j == 18: 11 to 138 zero length codes */
  924.     {
  925.       NEEDBITS(7)
  926.       j = 11 + ((unsigned)b & 0x7f);
  927.       DUMPBITS(7)
  928.       if ((unsigned)i + j > n)
  929.         return 1;
  930.       while (j--)
  931.         ll[i++] = 0;
  932.       l = 0;
  933.     }
  934.   }
  935.  
  936.  
  937.   /* free decoding table for trees */
  938.   huft_free(tl);
  939.  
  940.  
  941.   /* restore the global bit buffer */
  942.   bb = b;
  943.   bk = k;
  944.  
  945.  
  946.   /* build the decoding tables for literal/length and distance codes */
  947.   bl = lbits;
  948.   if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0)
  949.   {
  950.     if (i == 1 && !qflag) {
  951.       FPRINTF(stderr, "(incomplete l-tree)  ");
  952.       huft_free(tl);
  953.     }
  954.     return i;                   /* incomplete code set */
  955.   }
  956.   bd = dbits;
  957.   if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0)
  958.   {
  959.     if (i == 1 && !qflag) {
  960.       FPRINTF(stderr, "(incomplete d-tree)  ");
  961. #ifdef PKZIP_BUG_WORKAROUND
  962.       i = 0;
  963.     }
  964. #else
  965.       huft_free(td);
  966.     }
  967.     huft_free(tl);
  968.     return i;                   /* incomplete code set */
  969. #endif
  970.   }
  971.  
  972.  
  973.   /* decompress until an end-of-block code */
  974.   if (inflate_codes(tl, td, bl, bd))
  975.     return 1;
  976.  
  977.  
  978.   /* free the decoding tables, return */
  979.   huft_free(tl);
  980.   huft_free(td);
  981.   return 0;
  982. }
  983.  
  984.  
  985.  
  986. int inflate_block(e)
  987. int *e;                 /* last block flag */
  988. /* decompress an inflated block */
  989. {
  990.   unsigned t;           /* block type */
  991.   register ulg b;       /* bit buffer */
  992.   register unsigned k;  /* number of bits in bit buffer */
  993.  
  994.  
  995.   /* make local bit buffer */
  996.   b = bb;
  997.   k = bk;
  998.  
  999.  
  1000.   /* read in last block bit */
  1001.   NEEDBITS(1)
  1002.   *e = (int)b & 1;
  1003.   DUMPBITS(1)
  1004.  
  1005.  
  1006.   /* read in block type */
  1007.   NEEDBITS(2)
  1008.   t = (unsigned)b & 3;
  1009.   DUMPBITS(2)
  1010.  
  1011.  
  1012.   /* restore the global bit buffer */
  1013.   bb = b;
  1014.   bk = k;
  1015.  
  1016.  
  1017.   /* inflate that block type */
  1018.   if (t == 2)
  1019.     return inflate_dynamic();
  1020.   if (t == 0)
  1021.     return inflate_stored();
  1022.   if (t == 1)
  1023.     return inflate_fixed();
  1024.  
  1025.  
  1026.   /* bad block type */
  1027.   return 2;
  1028. }
  1029.  
  1030.  
  1031.  
  1032. int inflate()
  1033. /* decompress an inflated entry */
  1034. {
  1035.   int e;                /* last block flag */
  1036.   int r;                /* result code */
  1037.   unsigned h;           /* maximum struct huft's malloc'ed */
  1038.  
  1039.  
  1040.   /* initialize window, bit buffer */
  1041.   wp = 0;
  1042.   bk = 0;
  1043.   bb = 0;
  1044.  
  1045.  
  1046.   /* decompress until the last block */
  1047.   h = 0;
  1048.   do {
  1049.     hufts = 0;
  1050.     if ((r = inflate_block(&e)) != 0)
  1051.       return r;
  1052.     if (hufts > h)
  1053.       h = hufts;
  1054.   } while (!e);
  1055.  
  1056.  
  1057.   /* flush out slide */
  1058.   FLUSH(wp);
  1059.  
  1060.  
  1061.   /* return success */
  1062.   Trace((stderr, "\n%u bytes in Huffman tables (%d/entry)\n",
  1063.          h * sizeof(struct huft), sizeof(struct huft)));
  1064.   return 0;
  1065. }
  1066.  
  1067.  
  1068.  
  1069. int inflate_free()
  1070. {
  1071.   if (fixed_tl != (struct huft *)NULL)
  1072.   {
  1073.     huft_free(fixed_td);
  1074.     huft_free(fixed_tl);
  1075.     fixed_td = fixed_tl = (struct huft *)NULL;
  1076.   }
  1077.   return 0;
  1078. }
  1079.