home *** CD-ROM | disk | FTP | other *** search
/ PC Extra Super CD 1998 January / PCPLUS131.iso / DJGPP / V2 / DJLSR201.ZIP / src / utils / djtar / unpack.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-11-16  |  8.3 KB  |  241 lines

  1. /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
  2. /* unpack.c -- decompress files in pack format.
  3.  * Copyright (C) 1992-1993 Jean-loup Gailly
  4.  * This is free software; you can redistribute it and/or modify it under the
  5.  * terms of the GNU General Public License, see the file COPYING.
  6.  *
  7.  * Minor changes for DJTAR program, Eli Zaretskii November 1995.
  8.  */
  9.  
  10. #ifdef RCSID
  11. static char rcsid[] = "$Id: unpack.c,v 1.4 1993/06/11 19:25:36 jloup Exp $";
  12. #endif
  13.  
  14. #include "tailor.h"
  15. #include "zread.h"
  16. #include "crypt.h"
  17.  
  18. #define MIN(a,b) ((a) <= (b) ? (a) : (b))
  19. /* The arguments must not have side effects. */
  20.  
  21. #define MAX_BITLEN 25
  22. /* Maximum length of Huffman codes. (Minor modifications to the code
  23.  * would be needed to support 32 bits codes, but pack never generates
  24.  * more than 24 bits anyway.)
  25.  */
  26.  
  27. #define LITERALS 256
  28. /* Number of literals, excluding the End of Block (EOB) code */
  29.  
  30. #define MAX_PEEK 12
  31. /* Maximum number of 'peek' bits used to optimize traversal of the
  32.  * Huffman tree.
  33.  */
  34.  
  35. local ulg orig_len;       /* original uncompressed length */
  36. local int max_len;        /* maximum bit length of Huffman codes */
  37.  
  38. local uch literal[LITERALS];
  39. /* The literal bytes present in the Huffman tree. The EOB code is not
  40.  * represented.
  41.  */
  42.  
  43. local int lit_base[MAX_BITLEN+1];
  44. /* All literals of a given bit length are contiguous in literal[] and
  45.  * have contiguous codes. literal[code+lit_base[len]] is the literal
  46.  * for a code of len bits.
  47.  */
  48.  
  49. local int leaves [MAX_BITLEN+1]; /* Number of leaves for each bit length */
  50. local int parents[MAX_BITLEN+1]; /* Number of parents for each bit length */
  51.  
  52. local int peek_bits; /* Number of peek bits currently used */
  53.  
  54. /* local uch prefix_len[1 << MAX_PEEK]; */
  55. #define prefix_len outbuf
  56. /* For each bit pattern b of peek_bits bits, prefix_len[b] is the length
  57.  * of the Huffman code starting with a prefix of b (upper bits), or 0
  58.  * if all codes of prefix b have more than peek_bits bits. It is not
  59.  * necessary to have a huge table (large MAX_PEEK) because most of the
  60.  * codes encountered in the input stream are short codes (by construction).
  61.  * So for most codes a single lookup will be necessary.
  62.  */
  63. #if (1<<MAX_PEEK) > OUTBUFSIZ
  64.     error cannot overlay prefix_len and outbuf
  65. #endif
  66.  
  67. local ulg bitbuf;
  68. /* Bits are added on the low part of bitbuf and read from the high part. */
  69.  
  70. local int valid;                  /* number of valid bits in bitbuf */
  71. /* all bits above the last valid bit are always zero */
  72.  
  73. /* Set code to the next 'bits' input bits without skipping them. code
  74.  * must be the name of a simple variable and bits must not have side effects.
  75.  * IN assertions: bits <= 25 (so that we still have room for an extra byte
  76.  * when valid is only 24), and mask = (1<<bits)-1.
  77.  */
  78. #define look_bits(code,bits,mask) \
  79. { \
  80.   while (valid < (bits)) bitbuf = (bitbuf<<8) | (ulg)get_byte(), valid += 8; \
  81.   code = (bitbuf >> (valid-(bits))) & (mask); \
  82. }
  83.  
  84. /* Skip the given number of bits (after having peeked at them): */
  85. #define skip_bits(bits)  (valid -= (bits))
  86.  
  87. #define clear_bitbuf() (valid = 0, bitbuf = 0)
  88.  
  89. /* Local functions */
  90.  
  91. local void read_tree  (void);
  92. local void build_tree (void);
  93.  
  94. /* ===========================================================================
  95.  * Read the Huffman tree.
  96.  */
  97. local void read_tree()
  98. {
  99.     int len;  /* bit length */
  100.     int base; /* base offset for a sequence of leaves */
  101.     int n;
  102.  
  103.     /* Read the original input size, MSB first */
  104.     orig_len = 0;
  105.     for (n = 1; n <= 4; n++) orig_len = (orig_len << 8) | (ulg)get_byte();
  106.  
  107.     max_len = (int)get_byte(); /* maximum bit length of Huffman codes */
  108.     if (max_len > MAX_BITLEN) {
  109.     error("invalid compressed data -- Huffman code > 32 bits");
  110.     }
  111.  
  112.     /* Get the number of leaves at each bit length */
  113.     n = 0;
  114.     for (len = 1; len <= max_len; len++) {
  115.     leaves[len] = (int)get_byte();
  116.     n += leaves[len];
  117.     }
  118.     if (n > LITERALS) {
  119.     error("too many leaves in Huffman tree");
  120.     }
  121.     Trace((stderr, "orig_len %ld, max_len %d, leaves %d\n",
  122.        orig_len, max_len, n));
  123.     /* There are at least 2 and at most 256 leaves of length max_len.
  124.      * (Pack arbitrarily rejects empty files and files consisting of
  125.      * a single byte even repeated.) To fit the last leaf count in a
  126.      * byte, it is offset by 2. However, the last literal is the EOB
  127.      * code, and is not transmitted explicitly in the tree, so we must
  128.      * adjust here by one only.
  129.      */
  130.     leaves[max_len]++;
  131.  
  132.     /* Now read the leaves themselves */
  133.     base = 0;
  134.     for (len = 1; len <= max_len; len++) {
  135.     /* Remember where the literals of this length start in literal[] : */
  136.     lit_base[len] = base;
  137.     /* And read the literals: */
  138.     for (n = leaves[len]; n > 0; n--) {
  139.         literal[base++] = (uch)get_byte();
  140.     }
  141.     }
  142.     leaves[max_len]++; /* Now include the EOB code in the Huffman tree */
  143. }
  144.  
  145. /* ===========================================================================
  146.  * Build the Huffman tree and the prefix table.
  147.  */
  148. local void build_tree()
  149. {
  150.     int nodes = 0; /* number of nodes (parents+leaves) at current bit length */
  151.     int len;       /* current bit length */
  152.     uch *prefixp;  /* pointer in prefix_len */
  153.  
  154.     for (len = max_len; len >= 1; len--) {
  155.     /* The number of parent nodes at this level is half the total
  156.      * number of nodes at parent level:
  157.      */
  158.     nodes >>= 1;
  159.     parents[len] = nodes;
  160.     /* Update lit_base by the appropriate bias to skip the parent nodes
  161.      * (which are not represented in the literal array):
  162.      */
  163.     lit_base[len] -= nodes;
  164.     /* Restore nodes to be parents+leaves: */
  165.     nodes += leaves[len];
  166.     }
  167.     /* Construct the prefix table, from shortest leaves to longest ones.
  168.      * The shortest code is all ones, so we start at the end of the table.
  169.      */
  170.     peek_bits = MIN(max_len, MAX_PEEK);
  171.     prefixp = &prefix_len[1<<peek_bits];
  172.     for (len = 1; len <= peek_bits; len++) {
  173.     int prefixes = leaves[len] << (peek_bits-len); /* may be 0 */
  174.     while (prefixes--) *--prefixp = (uch)len;
  175.     }
  176.     /* The length of all other codes is unknown: */
  177.     while (prefixp > prefix_len) *--prefixp = 0;
  178. }
  179.  
  180. /* ===========================================================================
  181.  * Unpack in to out.  This routine does not support the old pack format
  182.  * with magic header \037\037.
  183.  *
  184.  * IN assertions: the buffer inbuf contains already the beginning of
  185.  *   the compressed data, from offsets inptr to insize-1 included.
  186.  *   The magic header has already been checked. The output buffer is cleared.
  187.  */
  188. int unpack(void *in)
  189. {
  190.     int len;                /* Bit length of current code */
  191.     unsigned eob;           /* End Of Block code */
  192.     register unsigned peek; /* lookahead bits */
  193.     unsigned peek_mask;     /* Mask for peek_bits bits */
  194.  
  195.     ifd = in;
  196.  
  197.     read_tree();     /* Read the Huffman tree */
  198.     build_tree();    /* Build the prefix table */
  199.     clear_bitbuf();  /* Initialize bit input */
  200.     peek_mask = (1<<peek_bits)-1;
  201.  
  202.     /* The eob code is the largest code among all leaves of maximal length: */
  203.     eob = leaves[max_len]-1;
  204.     Trace((stderr, "eob %d %x\n", max_len, eob));
  205.  
  206.     /* Decode the input data: */
  207.     for (;;) {
  208.     /* Since eob is the longest code and not shorter than max_len,
  209.          * we can peek at max_len bits without having the risk of reading
  210.          * beyond the end of file.
  211.      */
  212.     look_bits(peek, peek_bits, peek_mask);
  213.     len = prefix_len[peek];
  214.     if (len > 0) {
  215.         peek >>= peek_bits - len; /* discard the extra bits */
  216.     } else {
  217.         /* Code of more than peek_bits bits, we must traverse the tree */
  218.         ulg mask = peek_mask;
  219.         len = peek_bits;
  220.         do {
  221.                 len++, mask = (mask<<1)+1;
  222.         look_bits(peek, len, mask);
  223.         } while (peek < (unsigned)parents[len]);
  224.         /* loop as long as peek is a parent node */
  225.     }
  226.     /* At this point, peek is the next complete code, of len bits */
  227.     if (peek == eob && len == max_len) break; /* end of file? */
  228.     put_ubyte(literal[peek+lit_base[len]]);
  229.     Tracev((stderr,"%02d %04x %c\n", len, peek,
  230.         literal[peek+lit_base[len]]));
  231.     skip_bits(len);
  232.     } /* for (;;) */
  233.  
  234.     flush_window();
  235.     Trace((stderr, "bytes_out %ld\n", bytes_out));
  236.     if (orig_len != (ulg)bytes_out) {
  237.     error("invalid compressed data--length error");
  238.     }
  239.     return OK;
  240. }
  241.